hikaru-core


Namehikaru-core JSON
Version 1.1.2 PyPI version JSON
download
home_pagehttps://github.com/haxsaw/hikaru
SummaryHikaru allows you to smoothly move between Kubernetes YAML, Python objects, and Python source, in any direction. Hikaru-core provides the basic machinery for all Hikaru model packages to work with Kubernetes.
upload_time2024-04-15 17:41:32
maintainerNone
docs_urlNone
authorTom Carroll
requires_pythonNone
licenseMIT
keywords kubernetes modelling yaml json modeling translate translator reformatter transform
VCS
bugtrack_url
requirements hikaru-model-25 hikaru-model-26 hikaru-model-27 hikaru-model-28 hikaru-codegen
Travis-CI
coveralls test coverage No coveralls.
            
.. |travis| image:: https://travis-ci.com/haxsaw/hikaru.svg?branch=dev
    :target: https://app.travis-ci.com/github/haxsaw/hikaru

.. |license| image:: https://img.shields.io/github/license/haxsaw/hikaru
   :alt: GitHub license   :target: https://github.com/haxsaw/hikaru/blob/main/LICENSE

.. |versions| image:: https://img.shields.io/pypi/pyversions/hikaru
   :alt: PyPI - Python Version

.. |coverage| image:: https://codecov.io/gh/haxsaw/hikaru/branch/dev/graph/badge.svg?token=QOFGNVHGNP
   :target: https://codecov.io/gh/haxsaw/hikaru

.. |logo| image:: hikaru-core-logo.png
   :alt: Hikaru

|logo|


Version 1.1.2

|travis|   |license|   |versions|   |coverage|

`Try it: see Hikaru convert your K8s YAML <http://www.incisivetech.co.uk/try-hikaru.html>`_

`Release notes <https://github.com/haxsaw/hikaru/blob/main/release_notes.rst>`_

`Full documentation at Read the Docs <https://hikaru.readthedocs.io/en/latest/index.html>`_

Hikaru is a collection of tools that allow you to work with Kubernetes resources from within Python in
a variety of ways:

- Hikaru provides type-annotated classes that model all of the Kubernetes resources in Python
  and supports CRUD operations on those classes to manage their lifecycle in your Kubernetes cluster.
- Hikaru also provides tooling to shift formats for these objects, allowing you to turn K8s YAML
  into Python objects, JSON, or Python dicts, and vice-versa. It can also generate Python source code for K8s
  objects loaded from non-Python sources.
- Hikaru also supports a number of features that aid in the management of
  your objects such as searching for specific fields or diffing two instances of a K8s resource.
- Hikaru includes support for creating 'watches' on your objects, providing a means to monitor events
  on your provisioned K8s resources.
- Hikaru provides support for creation of CRDs which support all the above features such as CRUD operations
  and watches.
- Finally, Hikaru includes a facility to specify a collection of
  resources as an 'application', similar in spirit to a Helm chart, and provides the same CRUD,
  watch, and management capabilities on the entire application as it does on single resource objects
  (full format shifting support to come).

The ``hikaru-core`` package provides all the base machinery to support the above capabilities but
does not include any of the Kubernetes model objects, nor does it include the support to generate
Python source code from in-memory Hikaru objects.

- For model objects, install one of the ``hikaru-model-*`` packages. The ``hikaru-core`` package is
  is a requirement for all model packages, so you will automatically get ``hikaru-core`` when you
  install a model. You may install as many model releases into the same Python instance as you wish, but
  you will need to indicate to Hikaru which release should be used when create objects from a
  cluster or other sources.
- For source code generation capabilities, you'll need to install the ``hikaru-codegen`` package.

For convenience, a meta-package simply named ``hikaru`` exists which installs ``hikaru-core``,
the four most recent model packages, and the code generation package. If you don't need all of those
capabilities it is best to install just the model package you need.

That means that you probably don't need to ever install just ``hikaru-core`` on its own, although that's all
that's required if you just want to work with fully custom CRDs.

From Python
~~~~~~~~~~~

Hikaru uses type-annotated Python dataclasses to represent each of the
kinds of objects defined in the Kubernetes API, so when used with an
IDE that understands Python type annotations, Hikaru enables the IDE to
provide the user direct assistance as to what parameters are available,
what type each parameter must be, and which parameters are optional. Assembled
Hikaru object can be rendered into YAML that can be processed by regular
Kubernetes tools.

From YAML
~~~~~~~~~

But you don’t have to start with authoring Python: you can use Hikaru to
parse Kubernetes YAML into these same Python objects, at which point you
can inspect the created objects, modify them and re-generate new YAML,
or even have Hikaru emit Python source
code that will re-create the same structure but from the Python
interface.

From JSON
~~~~~~~~~

You can also process JSON or Python dict representations of Kubernetes configs
into the corresponding Python objects

To YAML, Python, or JSON
~~~~~~~~~~~~~~~~~~~~~~~~

Hikaru can output a Python Kubernetes object as Python source code,
YAML, JSON, or a Python dict, and go back to any of these representations, allowing you
to shift easily between representational formats for various purposes.

Supports multiple versions of Kubernetes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Hikaru allows you to use multiple releases of the Kubernetes client, providing
appropriate bindings/methods/attributes for every object in each version of a
release.

Direct Kubernetes via CRUD or low-level methods
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

You can use Hikaru objects to interact with a Kubernetes system. Hikaru wraps the Kubernetes
Python client and maps API operations on to the Hikaru model they involve. For example, you
can now create a Pod directly from a Pod object. Hikaru supports a higher-level CRUD-style
set of methods as well as all the operations defined in the Swagger API specification.

Hikaru can work with any Kubernetes-compliant system such as `K3s <https://k3s.io/>`_
and `minikube <https://minikube.sigs.k8s.io/docs/>`_.

Monitor Kubernetes activities with watches
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Hikaru provides an abstraction on over the K8s `watch` APIs, which allow you to easily
create code that receives events for all activites carried out in your K8s cluster on
a per-kind basis. Or, you can create a watch container that multiplexes the output
from individual watches into a single stream.

Create Custom Resource Definitions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

As of release 1.0.0, Hikaru supports the creation of CRDs that integrate with the rest
of Hikaru. Automatically generate schema from a Hikaru class, define CRDs to
Kubernetes, manage CRD instances with CRUD methods, and create watchers that allow
you to build your own controllers for your CRDs.

Model entire applications
-------------------------

Hikaru provides an Application base class that can be derived from to allow the creation
of sets of resources that comprise the infra for an application system. This Application model
can be inspected, provisioned into a cluster, read from a cluster, and watched, just like
with individual Hikaru K8s objects.

Integrate your own subclasses
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

You can not only in create your own subclasses of Hikaru document classes for your own
use, but you can also register these classes with Hikaru and it will make instances
of your classes when Hikaru encounters the relevant ``apiVersion`` and ``kind``
values. So for example, you can create your own ``MyPod`` subclass of ``Pod``, and
Hikaru will instantiate your subclass when reading Pod YAML.

Alternative to templating for customisation
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Using Hikaru, you can assemble Kubernetes objects using previously
defined libraries of objects in Python, craft replacements procedurally, or
even tweak the values of an existing object and turn it back into YAML.

Build models for uses other than controlling systems
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

You can use Hikaru in the process of issuing instructions to Kubernetes,
but the same Hikaru models can be used as high-fidelity replicas of the
YAML for other processes as well.

Type checking, diffing, merging, and inspection
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Hikaru supports a number of other operations on the Python objects it defines. For
example, you can check the types of all attributes in a config against the defined
types for each attribute, you can diff two configs to see where they aren't the same,
and you can search through a config for specific values and contained objects.

API coverage
~~~~~~~~~~~~

Hikaru supports all objects in the OpenAPI swagger spec for
the Kubernetes API **v 1.26**, and has initial support for methods on those objects
from the same swagger spec. Additionally, it defines some higher-level CRUD-style
methods on top of these foundation methods.

Usage examples
~~~~~~~~~~~~~~

To create Python objects from a Kubernetes YAML source, use ``load_full_yaml()``:

.. code:: python

   from hikaru import load_full_yaml  # or just 'from hikaru import *'

   docs = load_full_yaml(stream=open("test.yaml", "r"))
   p = docs[0]

``load_full_yaml()`` loads every Kubernetes YAML document in a YAML file and returns
a list of the resulting Hikaru objects found. You can then use the YAML
property names to navigate the resulting object. If you assert that an
object is of a known object type, your IDE can provide you assistance in
navigation:

.. code:: python

   from hikaru.model.rel_1_16 import Pod
   assert isinstance(p, Pod)
   print(p.metadata.labels["lab2"])
   print(p.spec.containers[0].ports[0].containerPort)
   for k, v in p.metadata.labels.items():
       print(f"key:{k} value:{v}")


You can create Hikaru representations of Kubernetes objects in Python:

.. code:: python

   from hikaru.model.rel_1_16 import Pod, PodSpec, Container, ObjectMeta
   x = Pod(apiVersion='v1', kind='Pod',
           metadata=ObjectMeta(name='hello-kiamol-3'),
           spec=PodSpec(
               containers=[Container(name='web', image='kiamol/ch02-hello-kiamol') ]
                )
       )


…and then render it in YAML:

.. code:: python

   from hikaru import get_yaml
   print(get_yaml(x))

…which yields:

.. code:: yaml

   ---
   apiVersion: v1
   kind: Pod
   metadata:
     name: hello-kiamol-3
   spec:
     containers:
       - name: web
         image: kiamol/ch02-hello-kiamol

If you use Hikaru to parse this back in as Python objects, you can then
ask Hikaru to output Python source code that will re-create it (thus
providing a migration path):

.. code:: python

   from hikaru import get_python_source, load_full_yaml
   docs = load_full_yaml(path="to/the/above.yaml")
   print(get_python_source(docs[0], assign_to='x', style="black"))

...which results in:

.. code:: python

    x = Pod(
        apiVersion="v1",
        kind="Pod",
        metadata=ObjectMeta(name="hello-kiamol-3"),
        spec=PodSpec(containers=[Container(name="web", image="kiamol/ch02-hello-kiamol")]),
    )

...and then turn it into real Kubernetes resources using the CRUD methods:

.. code:: python

	x.create(namespace='my-namespace')

...or read an existing object back in:

.. code:: python

	p = Pod().read(name='hello-kiamol-3', namespace='my-namespace')

...or use a Hikaru object as a context manager to automatically perform updates:

.. code:: python

	with Pod().read(name='hello-kiamol-3', namespace='my-namespace') as p:
		p.metadata.labels["new-label"] = 'some-value'
		# and other changes

	# when the 'with' ends, the context manager sends an update()

It is entirely possible to load YAML into Python, tailor it, and then
send it back to YAML; Hikaru can round-trip YAML through Python and
then back to the equivalent YAML.

The pieces of complex objects can be created separately and even stored
in a standard components library module for assembly later, or returned as the
value of a factory function, as opposed to using a templating system to piece
text files together:

.. code:: python

   from component_lib import web_container, lb_container
   from hikaru.model.rel_1_16 import Pod, ObjectMeta, PodSpec
   # make an ObjectMeta instance here called "om"
   p = Pod(apiVersion="v1", kind="Pod",
           metadata=om,
           spec=PodSpec(containers=[web_container, lb_container])
           )

You can also transform Hikaru objects into Python dicts:

.. code:: python

    from pprint import pprint
    pprint(get_clean_dict(x))

...which yields:

.. code:: python

    {'apiVersion': 'v1',
     'kind': 'Pod',
     'metadata': {'name': 'hello-kiamol-3'},
     'spec': {'containers': [{'image': 'kiamol/ch02-hello-kiamol', 'name': 'web'}]}}

...and go back into Hikaru objects. You can also render Hikaru objects as
JSON:

.. code:: python

    from hikaru import *
    print(get_json(x))

...which outputs the similar:

.. code:: json

    {"apiVersion": "v1", "kind": "Pod", "metadata": {"name": "hello-kiamol-3"}, "spec": {"containers": [{"name": "web", "image": "kiamol/ch02-hello-kiamol"}]}}

Hikaru lets you go from JSON back to Hikaru objects as well.

Hikaru objects can be tested for equivalence with ‘==’, and you can also
easily create deep copies of entire object structures with dup(). This
latter is useful in cases where you have a component that you want to
use multiple times in a model but need it slightly tweaked in each use;
a shared instance can’t have different values at each use, so it’s easy
to make a copy that can be customised in isolation.

Finally, every Hikaru object that holds other properties and objects
have methods that allow you to search the entire collection of objects.
This lets you find various objects of interest for review and checking
against policies and conventions. For example, if we had a Pod ‘p’ that was
pulled in with load_full_yaml(), we could examine all of the Container objects
with:

.. code:: python

   containers = p.find_by_name("containers")
   for c in containers:
       # check what you want...


Or you can get all of the ExecAction object (the value of ‘exec’
properties) that are part the second container’s lifecycle’s httpGet
property like so:

.. code:: python

   execs = p.find_by_name("exec", following='containers.1.lifecycle.httpGet')

These queries result in a list of ``CatalogEntry`` objects, which are
named tuples that provide the path to the found element. You can acquire
the actual element for inspection with the ``object_at_path()`` method:

.. code:: python

   o = p.object_at_path(execs[0].path)

This makes it easy to scan for specific items in a config under
automated control.

Future work
~~~~~~~~~~~

With basic support of managing Kubernetes resources in place, other directions
are being considered such as event/watch support and bringing in support for
additional releases of Kubernetes.

About
~~~~~

Hikaru is Mr. Sulu’s first name, a famed fictional helmsman.



            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/haxsaw/hikaru",
    "name": "hikaru-core",
    "maintainer": null,
    "docs_url": null,
    "requires_python": null,
    "maintainer_email": null,
    "keywords": "Kubernetes, modelling, YAML, JSON, modeling, translate, translator, reformatter, transform",
    "author": "Tom Carroll",
    "author_email": "tcarroll@incisivetech.co.uk",
    "download_url": "https://github.com/haxsaw/hikaru/archive/1.1.2.tar.gz",
    "platform": null,
    "description": "\n.. |travis| image:: https://travis-ci.com/haxsaw/hikaru.svg?branch=dev\n    :target: https://app.travis-ci.com/github/haxsaw/hikaru\n\n.. |license| image:: https://img.shields.io/github/license/haxsaw/hikaru\n   :alt: GitHub license   :target: https://github.com/haxsaw/hikaru/blob/main/LICENSE\n\n.. |versions| image:: https://img.shields.io/pypi/pyversions/hikaru\n   :alt: PyPI - Python Version\n\n.. |coverage| image:: https://codecov.io/gh/haxsaw/hikaru/branch/dev/graph/badge.svg?token=QOFGNVHGNP\n   :target: https://codecov.io/gh/haxsaw/hikaru\n\n.. |logo| image:: hikaru-core-logo.png\n   :alt: Hikaru\n\n|logo|\n\n\nVersion 1.1.2\n\n|travis|   |license|   |versions|   |coverage|\n\n`Try it: see Hikaru convert your K8s YAML <http://www.incisivetech.co.uk/try-hikaru.html>`_\n\n`Release notes <https://github.com/haxsaw/hikaru/blob/main/release_notes.rst>`_\n\n`Full documentation at Read the Docs <https://hikaru.readthedocs.io/en/latest/index.html>`_\n\nHikaru is a collection of tools that allow you to work with Kubernetes resources from within Python in\na variety of ways:\n\n- Hikaru provides type-annotated classes that model all of the Kubernetes resources in Python\n  and supports CRUD operations on those classes to manage their lifecycle in your Kubernetes cluster.\n- Hikaru also provides tooling to shift formats for these objects, allowing you to turn K8s YAML\n  into Python objects, JSON, or Python dicts, and vice-versa. It can also generate Python source code for K8s\n  objects loaded from non-Python sources.\n- Hikaru also supports a number of features that aid in the management of\n  your objects such as searching for specific fields or diffing two instances of a K8s resource.\n- Hikaru includes support for creating 'watches' on your objects, providing a means to monitor events\n  on your provisioned K8s resources.\n- Hikaru provides support for creation of CRDs which support all the above features such as CRUD operations\n  and watches.\n- Finally, Hikaru includes a facility to specify a collection of\n  resources as an 'application', similar in spirit to a Helm chart, and provides the same CRUD,\n  watch, and management capabilities on the entire application as it does on single resource objects\n  (full format shifting support to come).\n\nThe ``hikaru-core`` package provides all the base machinery to support the above capabilities but\ndoes not include any of the Kubernetes model objects, nor does it include the support to generate\nPython source code from in-memory Hikaru objects.\n\n- For model objects, install one of the ``hikaru-model-*`` packages. The ``hikaru-core`` package is\n  is a requirement for all model packages, so you will automatically get ``hikaru-core`` when you\n  install a model. You may install as many model releases into the same Python instance as you wish, but\n  you will need to indicate to Hikaru which release should be used when create objects from a\n  cluster or other sources.\n- For source code generation capabilities, you'll need to install the ``hikaru-codegen`` package.\n\nFor convenience, a meta-package simply named ``hikaru`` exists which installs ``hikaru-core``,\nthe four most recent model packages, and the code generation package. If you don't need all of those\ncapabilities it is best to install just the model package you need.\n\nThat means that you probably don't need to ever install just ``hikaru-core`` on its own, although that's all\nthat's required if you just want to work with fully custom CRDs.\n\nFrom Python\n~~~~~~~~~~~\n\nHikaru uses type-annotated Python dataclasses to represent each of the\nkinds of objects defined in the Kubernetes API, so when used with an\nIDE that understands Python type annotations, Hikaru enables the IDE to\nprovide the user direct assistance as to what parameters are available,\nwhat type each parameter must be, and which parameters are optional. Assembled\nHikaru object can be rendered into YAML that can be processed by regular\nKubernetes tools.\n\nFrom YAML\n~~~~~~~~~\n\nBut you don\u2019t have to start with authoring Python: you can use Hikaru to\nparse Kubernetes YAML into these same Python objects, at which point you\ncan inspect the created objects, modify them and re-generate new YAML,\nor even have Hikaru emit Python source\ncode that will re-create the same structure but from the Python\ninterface.\n\nFrom JSON\n~~~~~~~~~\n\nYou can also process JSON or Python dict representations of Kubernetes configs\ninto the corresponding Python objects\n\nTo YAML, Python, or JSON\n~~~~~~~~~~~~~~~~~~~~~~~~\n\nHikaru can output a Python Kubernetes object as Python source code,\nYAML, JSON, or a Python dict, and go back to any of these representations, allowing you\nto shift easily between representational formats for various purposes.\n\nSupports multiple versions of Kubernetes\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nHikaru allows you to use multiple releases of the Kubernetes client, providing\nappropriate bindings/methods/attributes for every object in each version of a\nrelease.\n\nDirect Kubernetes via CRUD or low-level methods\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nYou can use Hikaru objects to interact with a Kubernetes system. Hikaru wraps the Kubernetes\nPython client and maps API operations on to the Hikaru model they involve. For example, you\ncan now create a Pod directly from a Pod object. Hikaru supports a higher-level CRUD-style\nset of methods as well as all the operations defined in the Swagger API specification.\n\nHikaru can work with any Kubernetes-compliant system such as `K3s <https://k3s.io/>`_\nand `minikube <https://minikube.sigs.k8s.io/docs/>`_.\n\nMonitor Kubernetes activities with watches\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nHikaru provides an abstraction on over the K8s `watch` APIs, which allow you to easily\ncreate code that receives events for all activites carried out in your K8s cluster on\na per-kind basis. Or, you can create a watch container that multiplexes the output\nfrom individual watches into a single stream.\n\nCreate Custom Resource Definitions\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nAs of release 1.0.0, Hikaru supports the creation of CRDs that integrate with the rest\nof Hikaru. Automatically generate schema from a Hikaru class, define CRDs to\nKubernetes, manage CRD instances with CRUD methods, and create watchers that allow\nyou to build your own controllers for your CRDs.\n\nModel entire applications\n-------------------------\n\nHikaru provides an Application base class that can be derived from to allow the creation\nof sets of resources that comprise the infra for an application system. This Application model\ncan be inspected, provisioned into a cluster, read from a cluster, and watched, just like\nwith individual Hikaru K8s objects.\n\nIntegrate your own subclasses\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nYou can not only in create your own subclasses of Hikaru document classes for your own\nuse, but you can also register these classes with Hikaru and it will make instances\nof your classes when Hikaru encounters the relevant ``apiVersion`` and ``kind``\nvalues. So for example, you can create your own ``MyPod`` subclass of ``Pod``, and\nHikaru will instantiate your subclass when reading Pod YAML.\n\nAlternative to templating for customisation\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nUsing Hikaru, you can assemble Kubernetes objects using previously\ndefined libraries of objects in Python, craft replacements procedurally, or\neven tweak the values of an existing object and turn it back into YAML.\n\nBuild models for uses other than controlling systems\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nYou can use Hikaru in the process of issuing instructions to Kubernetes,\nbut the same Hikaru models can be used as high-fidelity replicas of the\nYAML for other processes as well.\n\nType checking, diffing, merging, and inspection\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nHikaru supports a number of other operations on the Python objects it defines. For\nexample, you can check the types of all attributes in a config against the defined\ntypes for each attribute, you can diff two configs to see where they aren't the same,\nand you can search through a config for specific values and contained objects.\n\nAPI coverage\n~~~~~~~~~~~~\n\nHikaru supports all objects in the OpenAPI swagger spec for\nthe Kubernetes API **v 1.26**, and has initial support for methods on those objects\nfrom the same swagger spec. Additionally, it defines some higher-level CRUD-style\nmethods on top of these foundation methods.\n\nUsage examples\n~~~~~~~~~~~~~~\n\nTo create Python objects from a Kubernetes YAML source, use ``load_full_yaml()``:\n\n.. code:: python\n\n   from hikaru import load_full_yaml  # or just 'from hikaru import *'\n\n   docs = load_full_yaml(stream=open(\"test.yaml\", \"r\"))\n   p = docs[0]\n\n``load_full_yaml()`` loads every Kubernetes YAML document in a YAML file and returns\na list of the resulting Hikaru objects found. You can then use the YAML\nproperty names to navigate the resulting object. If you assert that an\nobject is of a known object type, your IDE can provide you assistance in\nnavigation:\n\n.. code:: python\n\n   from hikaru.model.rel_1_16 import Pod\n   assert isinstance(p, Pod)\n   print(p.metadata.labels[\"lab2\"])\n   print(p.spec.containers[0].ports[0].containerPort)\n   for k, v in p.metadata.labels.items():\n       print(f\"key:{k} value:{v}\")\n\n\nYou can create Hikaru representations of Kubernetes objects in Python:\n\n.. code:: python\n\n   from hikaru.model.rel_1_16 import Pod, PodSpec, Container, ObjectMeta\n   x = Pod(apiVersion='v1', kind='Pod',\n           metadata=ObjectMeta(name='hello-kiamol-3'),\n           spec=PodSpec(\n               containers=[Container(name='web', image='kiamol/ch02-hello-kiamol') ]\n                )\n       )\n\n\n\u2026and then render it in YAML:\n\n.. code:: python\n\n   from hikaru import get_yaml\n   print(get_yaml(x))\n\n\u2026which yields:\n\n.. code:: yaml\n\n   ---\n   apiVersion: v1\n   kind: Pod\n   metadata:\n     name: hello-kiamol-3\n   spec:\n     containers:\n       - name: web\n         image: kiamol/ch02-hello-kiamol\n\nIf you use Hikaru to parse this back in as Python objects, you can then\nask Hikaru to output Python source code that will re-create it (thus\nproviding a migration path):\n\n.. code:: python\n\n   from hikaru import get_python_source, load_full_yaml\n   docs = load_full_yaml(path=\"to/the/above.yaml\")\n   print(get_python_source(docs[0], assign_to='x', style=\"black\"))\n\n...which results in:\n\n.. code:: python\n\n    x = Pod(\n        apiVersion=\"v1\",\n        kind=\"Pod\",\n        metadata=ObjectMeta(name=\"hello-kiamol-3\"),\n        spec=PodSpec(containers=[Container(name=\"web\", image=\"kiamol/ch02-hello-kiamol\")]),\n    )\n\n...and then turn it into real Kubernetes resources using the CRUD methods:\n\n.. code:: python\n\n\tx.create(namespace='my-namespace')\n\n...or read an existing object back in:\n\n.. code:: python\n\n\tp = Pod().read(name='hello-kiamol-3', namespace='my-namespace')\n\n...or use a Hikaru object as a context manager to automatically perform updates:\n\n.. code:: python\n\n\twith Pod().read(name='hello-kiamol-3', namespace='my-namespace') as p:\n\t\tp.metadata.labels[\"new-label\"] = 'some-value'\n\t\t# and other changes\n\n\t# when the 'with' ends, the context manager sends an update()\n\nIt is entirely possible to load YAML into Python, tailor it, and then\nsend it back to YAML; Hikaru can round-trip YAML through Python and\nthen back to the equivalent YAML.\n\nThe pieces of complex objects can be created separately and even stored\nin a standard components library module for assembly later, or returned as the\nvalue of a factory function, as opposed to using a templating system to piece\ntext files together:\n\n.. code:: python\n\n   from component_lib import web_container, lb_container\n   from hikaru.model.rel_1_16 import Pod, ObjectMeta, PodSpec\n   # make an ObjectMeta instance here called \"om\"\n   p = Pod(apiVersion=\"v1\", kind=\"Pod\",\n           metadata=om,\n           spec=PodSpec(containers=[web_container, lb_container])\n           )\n\nYou can also transform Hikaru objects into Python dicts:\n\n.. code:: python\n\n    from pprint import pprint\n    pprint(get_clean_dict(x))\n\n...which yields:\n\n.. code:: python\n\n    {'apiVersion': 'v1',\n     'kind': 'Pod',\n     'metadata': {'name': 'hello-kiamol-3'},\n     'spec': {'containers': [{'image': 'kiamol/ch02-hello-kiamol', 'name': 'web'}]}}\n\n...and go back into Hikaru objects. You can also render Hikaru objects as\nJSON:\n\n.. code:: python\n\n    from hikaru import *\n    print(get_json(x))\n\n...which outputs the similar:\n\n.. code:: json\n\n    {\"apiVersion\": \"v1\", \"kind\": \"Pod\", \"metadata\": {\"name\": \"hello-kiamol-3\"}, \"spec\": {\"containers\": [{\"name\": \"web\", \"image\": \"kiamol/ch02-hello-kiamol\"}]}}\n\nHikaru lets you go from JSON back to Hikaru objects as well.\n\nHikaru objects can be tested for equivalence with \u2018==\u2019, and you can also\neasily create deep copies of entire object structures with dup(). This\nlatter is useful in cases where you have a component that you want to\nuse multiple times in a model but need it slightly tweaked in each use;\na shared instance can\u2019t have different values at each use, so it\u2019s easy\nto make a copy that can be customised in isolation.\n\nFinally, every Hikaru object that holds other properties and objects\nhave methods that allow you to search the entire collection of objects.\nThis lets you find various objects of interest for review and checking\nagainst policies and conventions. For example, if we had a Pod \u2018p\u2019 that was\npulled in with load_full_yaml(), we could examine all of the Container objects\nwith:\n\n.. code:: python\n\n   containers = p.find_by_name(\"containers\")\n   for c in containers:\n       # check what you want...\n\n\nOr you can get all of the ExecAction object (the value of \u2018exec\u2019\nproperties) that are part the second container\u2019s lifecycle\u2019s httpGet\nproperty like so:\n\n.. code:: python\n\n   execs = p.find_by_name(\"exec\", following='containers.1.lifecycle.httpGet')\n\nThese queries result in a list of ``CatalogEntry`` objects, which are\nnamed tuples that provide the path to the found element. You can acquire\nthe actual element for inspection with the ``object_at_path()`` method:\n\n.. code:: python\n\n   o = p.object_at_path(execs[0].path)\n\nThis makes it easy to scan for specific items in a config under\nautomated control.\n\nFuture work\n~~~~~~~~~~~\n\nWith basic support of managing Kubernetes resources in place, other directions\nare being considered such as event/watch support and bringing in support for\nadditional releases of Kubernetes.\n\nAbout\n~~~~~\n\nHikaru is Mr. Sulu\u2019s first name, a famed fictional helmsman.\n\n\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Hikaru allows you to smoothly move between Kubernetes YAML, Python objects, and Python source, in any direction. Hikaru-core provides the basic machinery for all Hikaru model packages to work with Kubernetes.",
    "version": "1.1.2",
    "project_urls": {
        "Download": "https://github.com/haxsaw/hikaru/archive/1.1.2.tar.gz",
        "Homepage": "https://github.com/haxsaw/hikaru"
    },
    "split_keywords": [
        "kubernetes",
        " modelling",
        " yaml",
        " json",
        " modeling",
        " translate",
        " translator",
        " reformatter",
        " transform"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "7b58cc7bf7f66864c4eb1d1078aba4d984d2ff92dd29624b19d6533cda55f7ce",
                "md5": "bc5882a7c9e0b3624c76a7eb56c38f45",
                "sha256": "fed33f866170c42efb597aa9fd365095a19b688bb30f02bdb418f5723d47a48d"
            },
            "downloads": -1,
            "filename": "hikaru_core-1.1.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "bc5882a7c9e0b3624c76a7eb56c38f45",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 83891,
            "upload_time": "2024-04-15T17:41:32",
            "upload_time_iso_8601": "2024-04-15T17:41:32.668531Z",
            "url": "https://files.pythonhosted.org/packages/7b/58/cc7bf7f66864c4eb1d1078aba4d984d2ff92dd29624b19d6533cda55f7ce/hikaru_core-1.1.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-04-15 17:41:32",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "haxsaw",
    "github_project": "hikaru",
    "travis_ci": true,
    "coveralls": false,
    "github_actions": false,
    "requirements": [
        {
            "name": "hikaru-model-25",
            "specs": [
                [
                    ">=",
                    "1.1.0"
                ]
            ]
        },
        {
            "name": "hikaru-model-26",
            "specs": [
                [
                    ">=",
                    "1.1.0"
                ]
            ]
        },
        {
            "name": "hikaru-model-27",
            "specs": [
                [
                    ">=",
                    "1.1.0"
                ]
            ]
        },
        {
            "name": "hikaru-model-28",
            "specs": [
                [
                    ">=",
                    "1.1.0"
                ]
            ]
        },
        {
            "name": "hikaru-codegen",
            "specs": [
                [
                    ">=",
                    "1.1.0"
                ]
            ]
        }
    ],
    "lcname": "hikaru-core"
}
        
Elapsed time: 0.21137s