| 1 |
.. _provisioning: |
| 2 |
|
| 3 |
Customizing the kernel's runtime environment |
| 4 |
============================================ |
| 5 |
|
| 6 |
Kernel Provisioning |
| 7 |
~~~~~~~~~~~~~~~~~~~ |
| 8 |
|
| 9 |
Introduced in the 7.0 release, Kernel Provisioning enables the ability |
| 10 |
for third parties to manage the lifecycle of a kernel's runtime |
| 11 |
environment. By implementing and configuring a *kernel provisioner*, |
| 12 |
third parties now have the ability to provision kernels for different |
| 13 |
environments, typically managed by resource managers like Kubernetes, |
| 14 |
Hadoop YARN, Slurm, etc. For example, a *Kubernetes Provisioner* would |
| 15 |
be responsible for launching a kernel within its own Kubernetes pod, |
| 16 |
communicating the kernel's connection information back to the |
| 17 |
application (residing in a separate pod), and terminating the pod upon |
| 18 |
the kernel's termination. In essence, a kernel provisioner is an |
| 19 |
*abstraction layer* between the ``KernelManager`` and today's kernel |
| 20 |
*process* (i.e., ``Popen``). |
| 21 |
|
| 22 |
The kernel manager and kernel provisioner relationship |
| 23 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 24 |
|
| 25 |
Prior to this enhancement, the only extension point for customizing a |
| 26 |
kernel's behavior could occur by subclassing ``KernelManager``. This |
| 27 |
proved to be a limitation because the Jupyter framework allows for a |
| 28 |
single ``KernelManager`` class at any time. While applications could |
| 29 |
introduce a ``KernelManager`` subclass of their own, that |
| 30 |
``KernelManager`` was then tied directly to *that* application and |
| 31 |
thereby not usable as a ``KernelManager`` in another application. As a |
| 32 |
result, we consider the ``KernelManager`` class to be an |
| 33 |
*application-owned entity* upon which application-specific behaviors can |
| 34 |
be implemented. |
| 35 |
|
| 36 |
Kernel provisioners, on the other hand, are contained within the |
| 37 |
``KernelManager`` (i.e., a *has-a* relationship) and applications are |
| 38 |
agnostic as to what *kind* of provisioner is in use other than what is |
| 39 |
conveyed via the kernel's specification (kernelspec). All kernel |
| 40 |
interactions still occur via the ``KernelManager`` and ``KernelClient`` |
| 41 |
classes within ``jupyter_client`` and potentially subclassed by the |
| 42 |
application. |
| 43 |
|
| 44 |
Kernel provisioners are not related in any way to the ``KernelManager`` |
| 45 |
instance that controls their lifecycle, nor do they have any affinity to |
| 46 |
the application within which they are used. They merely provide a |
| 47 |
vehicle by which authors can extend the landscape in which a kernel can |
| 48 |
reside, while not side-effecting the application. That said, some kernel |
| 49 |
provisioners may introduce requirements on the application. For example |
| 50 |
(and completely hypothetically speaking), a ``SlurmProvisioner`` may |
| 51 |
impose the constraint that the server (``jupyter_client``) resides on an |
| 52 |
edge node of the Slurm cluster. These kinds of requirements can be |
| 53 |
mitigated by leveraging applications like `Jupyter Kernel Gateway <https://github.com/jupyter/kernel_gateway>`_ or |
| 54 |
`Jupyter Enterprise Gateway <https://github.com/jupyter/enterprise_gateway>`_ |
| 55 |
where the gateway server resides on the edge |
| 56 |
node of (or within) the cluster, etc. |
| 57 |
|
| 58 |
Discovery |
| 59 |
~~~~~~~~~ |
| 60 |
|
| 61 |
Kernel provisioning does not alter today's kernel discovery mechanism |
| 62 |
that utilizes well-known directories of ``kernel.json`` files. Instead, |
| 63 |
it optionally extends the current ``metadata`` stanza within the |
| 64 |
``kernel.json`` to include the specification of the kernel provisioner |
| 65 |
name, along with an optional ``config`` stanza, consisting of |
| 66 |
provisioner-specific configuration items. For example, a container-based |
| 67 |
provisioner will likely need to specify the image name in this section. |
| 68 |
The important point is that the content of this section is |
| 69 |
provisioner-specific. |
| 70 |
|
| 71 |
.. code:: JSON |
| 72 |
|
| 73 |
"metadata": { |
| 74 |
"kernel_provisioner": { |
| 75 |
"provisioner_name": "k8s-provisioner", |
| 76 |
"config": { |
| 77 |
"image_name": "my_docker_org/kernel:2.1.5", |
| 78 |
"max_cpus": 4 |
| 79 |
} |
| 80 |
} |
| 81 |
}, |
| 82 |
|
| 83 |
Kernel provisioner authors implement their provisioners by deriving from |
| 84 |
:class:`KernelProvisionerBase` and expose their provisioner for consumption |
| 85 |
via entry-points: |
| 86 |
|
| 87 |
.. code:: |
| 88 |
|
| 89 |
'jupyter_client.kernel_provisioners': [ |
| 90 |
'k8s-provisioner = my_package:K8sProvisioner', |
| 91 |
], |
| 92 |
|
| 93 |
Backwards Compatibility |
| 94 |
~~~~~~~~~~~~~~~~~~~~~~~ |
| 95 |
|
| 96 |
Prior to this release, no ``kernel.json`` (kernelspec) will contain a |
| 97 |
provisioner entry, yet the framework is now based on using provisioners. |
| 98 |
As a result, when a ``kernel_provisioner`` stanza is **not** present in |
| 99 |
a selected kernelspec, jupyter client will, by default, use the built-in |
| 100 |
``LocalProvisioner`` implementation as its provisioner. This provisioner |
| 101 |
retains today's local kernel functionality. It can also be subclassed |
| 102 |
for those provisioner authors wanting to extend the functionality of |
| 103 |
local kernels. The result of launching a kernel in this manner is |
| 104 |
equivalent to the following stanza existing in the ``kernel.json`` file: |
| 105 |
|
| 106 |
.. code:: JSON |
| 107 |
|
| 108 |
"metadata": { |
| 109 |
"kernel_provisioner": { |
| 110 |
"provisioner_name": "local-provisioner", |
| 111 |
"config": { |
| 112 |
} |
| 113 |
} |
| 114 |
}, |
| 115 |
|
| 116 |
Should a given installation wish to use a *different* provisioner as |
| 117 |
their "default provisioner" (including subclasses of |
| 118 |
``LocalProvisioner``), they can do so by specifying a value for |
| 119 |
``KernelProvisionerFactory.default_provisioner_name``. |
| 120 |
|
| 121 |
Implementing a custom provisioner |
| 122 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 123 |
|
| 124 |
The impact of Kernel Provisioning is that it enables the ability to |
| 125 |
implement custom kernel provisioners to manage a kernel's lifecycle |
| 126 |
within any runtime environment. There are currently two approaches by |
| 127 |
which that can be accomplished, extending the ``KernelProvisionerBase`` |
| 128 |
class or extending the built-in class - ``LocalProvisioner``. As more |
| 129 |
provisioners are introduced, some may be implemented in an abstract |
| 130 |
sense, from which specific implementations can be authored. |
| 131 |
|
| 132 |
Extending ``LocalProvisioner`` |
| 133 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 134 |
|
| 135 |
If you're interested in running kernels locally and yet adjust their |
| 136 |
behavior, there's a good chance you can simply extend |
| 137 |
``LocalProvisioner`` via subclassing. This amounts to deriving from |
| 138 |
``LocalProvisioner`` and overriding appropriate methods to provide your |
| 139 |
custom functionality. |
| 140 |
|
| 141 |
In this example, RBACProvisioner will verify whether the current user is |
| 142 |
in the role meant for this kernel by calling a method implemented within *this* |
| 143 |
provisioner. If the user is not in the role, an exception will be thrown. |
| 144 |
|
| 145 |
.. code:: python |
| 146 |
|
| 147 |
class RBACProvisioner(LocalProvisioner): |
| 148 |
role: str = Unicode(config=True) |
| 149 |
|
| 150 |
async def pre_launch(self, **kwargs: Any) -> Dict[str, Any]: |
| 151 |
if not self.user_in_role(self.role): |
| 152 |
raise PermissionError( |
| 153 |
f"User is not in role {self.role} and " f"cannot launch this kernel." |
| 154 |
) |
| 155 |
|
| 156 |
return await super().pre_launch(**kwargs) |
| 157 |
|
| 158 |
It is important to note *when* it's necessary to call the superclass in |
| 159 |
a given method - since the operations it performs may be critical to the |
| 160 |
kernel's management. As a result, you'll likely need to become familiar |
| 161 |
with how ``LocalProvisioner`` operates. |
| 162 |
|
| 163 |
Extending ``KernelProvisionerBase`` |
| 164 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 165 |
|
| 166 |
If you'd like to launch your kernel in an environment other than the |
| 167 |
local server, then you will need to consider subclassing :class:`KernelProvisionerBase` |
| 168 |
directly. This will allow you to implement the various kernel process |
| 169 |
controls relative to your target environment. For instance, if you |
| 170 |
wanted to have your kernel hosted in a Hadoop YARN cluster, you will |
| 171 |
need to implement process-control methods like :meth:`poll` and :meth:`wait` |
| 172 |
to use the YARN REST API. Or, similarly, a Kubernetes-based provisioner |
| 173 |
would need to implement the process-control methods using the Kubernetes client |
| 174 |
API, etc. |
| 175 |
|
| 176 |
By modeling the :class:`KernelProvisionerBase` methods after :class:`subprocess.Popen` |
| 177 |
a natural mapping between today's kernel lifecycle management takes place. This, |
| 178 |
coupled with the ability to add configuration directly into the ``config:`` stanza |
| 179 |
of the ``kernel_provisioner`` metadata, allows for things like endpoint address, |
| 180 |
image names, namespaces, hosts lists, etc. to be specified relative to your |
| 181 |
kernel provisioner implementation. |
| 182 |
|
| 183 |
The ``kernel_id`` corresponding to the launched kernel and used by the |
| 184 |
kernel manager is now available *prior* to the kernel's launch. This |
| 185 |
enables provisioners with a unique *key* they can use to discover and |
| 186 |
control their kernel when launched into resource-managed clusters such |
| 187 |
as Hadoop YARN or Kubernetes. |
| 188 |
|
| 189 |
.. tip:: |
| 190 |
Use ``kernel_id`` as a discovery mechanism from your provisioner! |
| 191 |
|
| 192 |
Here's a prototyped implementation of a couple of the abstract methods |
| 193 |
of :class:`KernelProvisionerBase` for use in an Hadoop YARN cluster to |
| 194 |
help illustrate a provisioner's implementation. Note that the built-in |
| 195 |
implementation of :class:`LocalProvisioner` can also be used as a reference. |
| 196 |
|
| 197 |
Notice the internal method ``_get_application_id()``. This method is |
| 198 |
what the provisioner uses to determine if the YARN application (i.e., |
| 199 |
the kernel) is still running within the cluster. Although the provisioner |
| 200 |
doesn't dictate the application id, the application id is |
| 201 |
discovered via the application *name* which is a function of ``kernel_id``. |
| 202 |
|
| 203 |
.. code:: python |
| 204 |
|
| 205 |
async def poll(self) -> Optional[int]: |
| 206 |
"""Submitting a new kernel/app to YARN will take a while to be ACCEPTED. |
| 207 |
Thus application ID will probably not be available immediately for poll. |
| 208 |
So will regard the application as RUNNING when application ID still in |
| 209 |
ACCEPTED or SUBMITTED state. |
| 210 |
|
| 211 |
:return: None if the application's ID is available and state is |
| 212 |
ACCEPTED/SUBMITTED/RUNNING. Otherwise 0. |
| 213 |
""" |
| 214 |
result = 0 |
| 215 |
if self._get_application_id(): |
| 216 |
state = self._query_app_state_by_id(self.application_id) |
| 217 |
if state in YarnProvisioner.initial_states: |
| 218 |
result = None |
| 219 |
|
| 220 |
return result |
| 221 |
|
| 222 |
|
| 223 |
async def send_signal(self, signum): |
| 224 |
"""Currently only support 0 as poll and other as kill. |
| 225 |
|
| 226 |
:param signum |
| 227 |
:return: |
| 228 |
""" |
| 229 |
if signum == 0: |
| 230 |
return await self.poll() |
| 231 |
elif signum == signal.SIGKILL: |
| 232 |
return await self.kill() |
| 233 |
else: |
| 234 |
return await super().send_signal(signum) |
| 235 |
|
| 236 |
Notice how in some cases we can compose provisioner methods to implement others. For |
| 237 |
example, since sending a signal number of 0 is tantamount to polling the process, we |
| 238 |
go ahead and call :meth:`poll` to handle ``signum`` of 0 and :meth:`kill` to handle |
| 239 |
``SIGKILL`` requests. |
| 240 |
|
| 241 |
Here we see how ``_get_application_id`` uses the ``kernel_id`` to acquire the application |
| 242 |
id - which is the *primary id* for controlling YARN application lifecycles. Since startup |
| 243 |
in resource-managed clusters can tend to take much longer than local kernels, you'll typically |
| 244 |
need a polling or notification mechanism within your provisioner. In addition, your |
| 245 |
provisioner will be asked by the ``KernelManager`` what is an acceptable startup time. |
| 246 |
This answer is implemented in the provisioner via the :meth:`get_shutdown_wait_time` method. |
| 247 |
|
| 248 |
.. code:: python |
| 249 |
|
| 250 |
def _get_application_id(self, ignore_final_states: bool = False) -> str: |
| 251 |
if not self.application_id: |
| 252 |
app = self._query_app_by_name(self.kernel_id) |
| 253 |
state_condition = True |
| 254 |
if type(app) is dict: |
| 255 |
state = app.get("state") |
| 256 |
self.last_known_state = state |
| 257 |
|
| 258 |
if ignore_final_states: |
| 259 |
state_condition = state not in YarnProvisioner.final_states |
| 260 |
|
| 261 |
if len(app.get("id", "")) > 0 and state_condition: |
| 262 |
self.application_id = app["id"] |
| 263 |
self.log.info( |
| 264 |
f"ApplicationID: '{app['id']}' assigned for " |
| 265 |
f"KernelID: '{self.kernel_id}', state: {state}." |
| 266 |
) |
| 267 |
if not self.application_id: |
| 268 |
self.log.debug( |
| 269 |
f"ApplicationID not yet assigned for KernelID: " |
| 270 |
f"'{self.kernel_id}' - retrying..." |
| 271 |
) |
| 272 |
return self.application_id |
| 273 |
|
| 274 |
|
| 275 |
def get_shutdown_wait_time(self, recommended: Optional[float] = 5.0) -> float: |
| 276 |
if recommended < yarn_shutdown_wait_time: |
| 277 |
recommended = yarn_shutdown_wait_time |
| 278 |
self.log.debug( |
| 279 |
f"{type(self).__name__} shutdown wait time adjusted to " |
| 280 |
f"{recommended} seconds." |
| 281 |
) |
| 282 |
|
| 283 |
return recommended |
| 284 |
|
| 285 |
Registering your custom provisioner |
| 286 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 287 |
|
| 288 |
Once your custom provisioner has been authored, it needs to be exposed |
| 289 |
as an |
| 290 |
`entry point <https://packaging.python.org/specifications/entry-points/>`_. |
| 291 |
To do this add the following to your ``setup.py`` (or equivalent) in its |
| 292 |
``entry_points`` stanza using the group name |
| 293 |
``jupyter_client.kernel_provisioners``: |
| 294 |
|
| 295 |
:: |
| 296 |
|
| 297 |
'jupyter_client.kernel_provisioners': [ |
| 298 |
'rbac-provisioner = acme.rbac.provisioner:RBACProvisioner', |
| 299 |
], |
| 300 |
|
| 301 |
where: |
| 302 |
|
| 303 |
- ``rbac-provisioner`` is the *name* of your provisioner and what will |
| 304 |
be referenced within the ``kernel.json`` file |
| 305 |
- ``acme.rbac.provisioner`` identifies the provisioner module name, and |
| 306 |
- ``RBACProvisioner`` is custom provisioner object name |
| 307 |
(implementation) that (directly or indirectly) derives from |
| 308 |
``KernelProvisionerBase`` |
| 309 |
|
| 310 |
Deploying your custom provisioner |
| 311 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 312 |
|
| 313 |
The final step in getting your custom provisioner deployed is to add a |
| 314 |
``kernel_provisioner`` stanza to the appropriate ``kernel.json`` files. |
| 315 |
This can be accomplished manually or programmatically (in which some |
| 316 |
tooling is implemented to create the appropriate ``kernel.json`` file). |
| 317 |
In either case, the end result is the same - a ``kernel.json`` file with |
| 318 |
the appropriate stanza within ``metadata``. The *vision* is that kernel |
| 319 |
provisioner packages will include an application that creates kernel |
| 320 |
specifications (i.e., ``kernel.json`` et. al.) pertaining to that |
| 321 |
provisioner. |
| 322 |
|
| 323 |
Following on the previous example of ``RBACProvisioner``, one would find |
| 324 |
the following ``kernel.json`` file in directory |
| 325 |
``/usr/local/share/jupyter/kernels/rbac_kernel``: |
| 326 |
|
| 327 |
.. code:: JSON |
| 328 |
|
| 329 |
{ |
| 330 |
"argv": ["python", "-m", "ipykernel_launcher", "-f", "{connection_file}"], |
| 331 |
"env": {}, |
| 332 |
"display_name": "RBAC Kernel", |
| 333 |
"language": "python", |
| 334 |
"interrupt_mode": "signal", |
| 335 |
"metadata": { |
| 336 |
"kernel_provisioner": { |
| 337 |
"provisioner_name": "rbac-provisioner", |
| 338 |
"config": { |
| 339 |
"role": "data_scientist" |
| 340 |
} |
| 341 |
} |
| 342 |
} |
| 343 |
} |
| 344 |
|
| 345 |
Listing available kernel provisioners |
| 346 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 347 |
To confirm that your custom provisioner is available for use, |
| 348 |
the ``jupyter kernelspec`` command has been extended to include |
| 349 |
a ``provisioners`` sub-command. As a result, running ``jupyter kernelspec provisioners`` |
| 350 |
will list the available provisioners by name followed by their module and object |
| 351 |
names (colon-separated): |
| 352 |
|
| 353 |
.. code:: bash |
| 354 |
|
| 355 |
$ jupyter kernelspec provisioners |
| 356 |
|
| 357 |
Available kernel provisioners: |
| 358 |
local-provisioner jupyter_client.provisioning:LocalProvisioner |
| 359 |
rbac-provisioner acme.rbac.provisioner:RBACProvisioner |