1 Ceph Dashboard Developer Documentation
2 ======================================
4 .. contents:: Table of Contents
9 Before you can start the dashboard from within a development environment, you
10 will need to generate the frontend code and either use a compiled and running
11 Ceph cluster (e.g. started by ``vstart.sh``) or the standalone development web
14 The build process is based on `Node.js <https://nodejs.org/>`_ and requires the
15 `Node Package Manager <https://www.npmjs.com/>`_ ``npm`` to be installed.
20 * Node 8.9.0 or higher
24 During Ceph's build we create a virtualenv with ``node`` and ``npm``
25 installed, which can be used as an alternative to installing node/npm in your
28 If you want to use the node installed in the virtualenv you just need to
29 activate the virtualenv before you run any npm commands. To activate it run
30 ``. build/src/pybind/mgr/dashboard/node-env/bin/activate``.
32 Once you finish, you can simply run ``deactivate`` and exit the virtualenv.
35 If you do not have the `Angular CLI <https://github.com/angular/angular-cli>`_
36 installed globally, then you need to execute ``ng`` commands with an
37 additional ``npm run`` before it.
42 Run ``npm install`` in directory ``src/pybind/mgr/dashboard/frontend`` to
43 install the required packages locally.
45 Setting up a Development Server
46 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
48 Create the ``proxy.conf.json`` file based on ``proxy.conf.json.sample``.
50 Run ``npm start`` for a dev server.
51 Navigate to ``http://localhost:4200/``. The app will automatically
52 reload if you change any of the source files.
57 Run ``ng generate component component-name`` to generate a new
58 component. You can also use
59 ``ng generate directive|pipe|service|class|guard|interface|enum|module``.
64 Run ``npm run build`` to build the project. The build artifacts will be
65 stored in the ``dist/`` directory. Use the ``-prod`` flag for a
66 production build. Navigate to ``https://localhost:8443``.
68 Code linting and formatting
69 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
71 We use the following tools to lint and format the code in all our TS, SCSS and
74 - `codelyzer <http://codelyzer.com/>`_
75 - `html-linter <https://github.com/chinchiheather/html-linter>`_
76 - `Prettier <https://prettier.io/>`_
77 - `TSLint <https://palantir.github.io/tslint/>`_
79 We added 2 npm scripts to help run these tools:
81 - ``npm run lint``, will check frontend files against all linters
82 - ``npm run fix``, will try to fix all the detected linting errors
87 To write unit tests most efficient we have a small collection of tools,
88 we use within test suites.
90 Those tools can be found under
91 ``src/pybind/mgr/dashboard/frontend/src/testing/``, especially take
92 a look at ``unit-test-helper.ts``.
94 There you will be able to find:
96 ``configureTestBed`` that replaces the initial ``TestBed``
97 methods. It takes the same arguments as ``TestBed.configureTestingModule``.
98 Using it will run your tests a lot faster in development, as it doesn't
99 recreate everything from scratch on every test. To use the default behaviour
100 pass ``true`` as the second argument.
102 ``PermissionHelper`` to help determine if
103 the correct actions are shown based on the current permissions and selection
106 ``FormHelper`` which makes testing a form a lot easier
107 with a few simple methods. It allows you to set a control or multiple
108 controls, expect if a control is valid or has an error or just do both with
109 one method. Additional you can expect a template element or multiple elements
110 to be visible in the rendered template.
115 Create ``unit-test-configuration.ts`` file based on
116 ``unit-test-configuration.ts.sample`` in directory
117 ``src/pybind/mgr/dashboard/frontend/src``.
119 Run ``npm run test`` to execute the unit tests via `Jest
120 <https://facebook.github.io/jest/>`_.
122 If you get errors on all tests, it could be because `Jest
123 <https://facebook.github.io/jest/>`_ or something else was updated.
124 There are a few ways how you can try to resolve this:
126 - Remove all modules with ``rm -rf dist node_modules`` and run ``npm install``
127 again in order to reinstall them
128 - Clear the cache of jest by running ``npx jest --clearCache``
130 Running End-to-End Tests
131 ~~~~~~~~~~~~~~~~~~~~~~~~
133 We use `Protractor <http://www.protractortest.org/>`__ to run our frontend e2e
136 Our ``run-frontend-e2e-tests.sh`` script will check if Chrome or Docker is
137 installed and run the tests if either is found.
139 Start all frontend e2e tests by running::
141 $ ./run-frontend-e2e-tests.sh
144 You can force the script to use a specific device with the ``-d`` flag::
146 $ ./run-frontend-e2e-tests.sh -d <chrome|docker>
149 If you want to run the tests outside the ceph environment, you will need to
150 manually define the dashboard url using ``-r``::
152 $ ./run-frontend-e2e-tests.sh -r <DASHBOARD_URL>
155 When using docker, as your device, you might need to run the script with sudo
158 Writing End-to-End Tests
159 ~~~~~~~~~~~~~~~~~~~~~~~~
161 When writing e2e tests you don't want to recompile every time from scratch to
162 try out if your test has succeeded. As usual you have your development server
163 open (``npm start``) which already has compiled all files. To attach
164 `Protractor <http://www.protractortest.org/>`__ to this process, instead of
165 spinning up it's own server, you can use ``npm run e2e -- --dev-server-target``
166 or just ``npm run e2e:dev`` which is equivalent.
171 To get more help on the Angular CLI use ``ng help`` or go check out the
173 README <https://github.com/angular/angular-cli/blob/master/README.md>`__.
175 Example of a Generator
176 ~~~~~~~~~~~~~~~~~~~~~~
180 # Create module 'Core'
181 src/app> ng generate module core -m=app --routing
183 # Create module 'Auth' under module 'Core'
184 src/app/core> ng generate module auth -m=core --routing
186 src/app> ng generate module core/auth -m=core --routing
188 # Create component 'Login' under module 'Auth'
189 src/app/core/auth> ng generate component login -m=core/auth
191 src/app> ng generate component core/auth/login -m=core/auth
193 Frontend Typescript Code Style Guide Recommendations
194 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
196 Group the imports based on its source and separate them with a blank
199 The source groups can be either from Angular, external or internal.
205 import { Component } from '@angular/core';
206 import { Router } from '@angular/router';
208 import { ToastsManager } from 'ng2-toastr';
210 import { Credentials } from '../../../shared/models/credentials.model';
211 import { HostService } from './services/host.service';
216 There are several components that can be reused on different pages.
217 This components are declared on the components module:
218 `src/pybind/mgr/dashboard/frontend/src/app/shared/components`.
223 This component should be used to provide additional information to the user.
230 Some <strong>helper</strong> html text
233 Terminology and wording
234 ~~~~~~~~~~~~~~~~~~~~~~~
236 Instead of using the Ceph component names, the approach
237 suggested is to use the logical/generic names (Block over RBD, Filesystem over
238 CephFS, Object over RGW). Nevertheless, as Ceph-Dashboard cannot completely hide
239 the Ceph internals, some Ceph-specific names might remain visible.
241 Regarding the wording for action labels and other textual elements (form titles,
242 buttons, etc.), the chosen approach is to follow `these guidelines
243 <https://www.patternfly.org/styles/terminology-and-wording/#terminology-and-wording-for-action-labels>`_.
244 As a rule of thumb, 'Create' and 'Delete' are the proper wording for most forms,
245 instead of 'Add' and 'Remove', unless some already created item is either added
246 or removed to/from a set of items (e.g.: 'Add permission' to a user vs. 'Create
249 In order to enforce the use of this wording, a service ``ActionLabelsI18n`` has
250 been created, which provides translated labels for use in UI elements.
255 Every vendor can customize the 'Ceph dashboard' to his needs. No matter if
256 logo, HTML-Template or TypeScript, every file inside the frontend folder can be
259 To replace files, open ``./frontend/angular.json`` and scroll to the section
260 ``fileReplacements`` inside the production configuration. Here you can add the
261 files you wish to brand. We recommend to place the branded version of a file in
262 the same directory as the original one and to add a ``.brand`` to the file
263 name, right in front of the file extension. A ``fileReplacement`` could for
264 example look like this:
269 "replace": "src/app/core/auth/login/login.component.html",
270 "with": "src/app/core/auth/login/login.component.brand.html"
273 To serve or build the branded user interface run:
275 $ npm run start -- --prod
279 $ npm run build -- --prod
281 Unfortunately it's currently not possible to use multiple configurations when
282 serving or building the UI at the same time. That means a configuration just
283 for the branding ``fileReplacements`` is not an option, because you want to use
284 the production configuration anyway
285 (https://github.com/angular/angular-cli/issues/10612).
286 Furthermore it's also not possible to use glob expressions for
287 ``fileReplacements``. As long as the feature hasn't been implemented, you have
288 to add the file replacements manually to the angular.json file
289 (https://github.com/angular/angular-cli/issues/12354).
291 Nevertheless you should stick to the suggested naming scheme because it makes
292 it easier for you to use glob expressions once it's supported in the future.
294 To change the variable defaults you can overwrite them in the file
295 ``./frontend/src/vendor.variables.scss``. Just reassign the variable you want
296 to change, for example ``$color-primary: teal;``
297 To overwrite or extend the default CSS, you can add your own styles in
298 ``./frontend/src/vendor.overrides.scss``.
303 How to extract messages from source code?
304 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
306 To extract the I18N messages from the templates and the TypeScript files just
307 run the following command in ``src/pybind/mgr/dashboard/frontend``::
311 This will extract all marked messages from the HTML templates first and then
312 add all marked strings from the TypeScript files to the translation template.
313 Since the extraction from TypeScript files is still not supported by Angular
314 itself, we are using the
315 `ngx-translator <https://github.com/ngx-translate/i18n-polyfill>`_ extractor to
316 parse the TypeScript files.
318 When the command ran successfully, it should have created or updated the file
319 ``src/locale/messages.xlf``.
321 To make sure this file is always up to date in master branch, we added a
322 validation in ``run-frontend-unittests.sh`` that will fail if it finds
323 uncommitted translations.
328 All our supported languages should be registeredd in
329 ``supported-languages.enum.ts``, this will then provide that list to both the
330 language selectors in the frontend.
335 To facilitate the translation process of the dashboard we are using a web tool
336 called `transifex <https://www.transifex.com/>`_.
338 If you wish to help translating to any language just go to our `transifex
339 project page <https://www.transifex.com/ceph/ceph-dashboard/>`_, join the
340 project and you can start translating immediately.
342 All translations will then be reviewed and later pushed upstream.
344 Updating translated messages
345 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
347 Any time there are new messages translated and reviewed in a specific language
348 we should update the translation file upstream.
350 To do that, we need to download the language xlf file from transifex and replace
351 the current one in the repository. Since Angular doesn't support missing
352 translations, we need to do an extra step and fill all the untranslated strings
353 with the source string.
355 Each language file should be placed in ``src/locale/messages.<locale-id>.xlf``.
356 For example, the path for german would be ``src/locale/messages.de-DE.xlf``.
357 ``<locale-id>`` should match the id previouisly inserted in
358 ``supported-languages.enum.ts``.
363 Strings need to start and end in the same line as the element:
373 <span i18n>Foo</span>
383 <span i18n>Foo bar baz.
386 Isolated interpolations should not be translated:
391 <span i18n>{{ foo }}</span>
394 <span>{{ foo }}</span>
396 Interpolations used in a sentence should be kept in the translation:
401 <span i18n>There are {{ x }} OSDs.</span>
403 Remove elements that are outside the context of the translation:
410 <span class="required"></span>
415 <ng-container i18n>Profile<ng-container>
416 <span class="required"></span>
419 Keep elements that affect the sentence:
424 <span i18n>Profile <b>foo</b> will be removed.</span>
429 The Python backend code of this module requires a number of Python modules to be
430 installed. They are listed in file ``requirements.txt``. Using `pip
431 <https://pypi.python.org/pypi/pip>`_ you may install all required dependencies
432 by issuing ``pip install -r requirements.txt`` in directory
433 ``src/pybind/mgr/dashboard``.
435 If you're using the `ceph-dev-docker development environment
436 <https://github.com/ricardoasmarques/ceph-dev-docker/>`_, simply run
437 ``./install_deps.sh`` from the toplevel directory to install them.
442 In dashboard we have two different kinds of backend tests:
444 1. Unit tests based on ``tox``
445 2. API tests based on Teuthology.
447 Unit tests based on tox
448 ~~~~~~~~~~~~~~~~~~~~~~~~
450 We included a ``tox`` configuration file that will run the unit tests under
451 Python 2 or 3, as well as linting tools to guarantee the uniformity of code.
453 You need to install ``tox`` and ``coverage`` before running it. To install the
454 packages in your system, either install it via your operating system's package
455 management tools, e.g. by running ``dnf install python-tox python-coverage`` on
458 Alternatively, you can use Python's native package installation method::
461 $ pip install coverage
463 To run the tests, run ``run-tox.sh`` in the dashboard directory (where
464 ``tox.ini`` is located)::
466 ## Run Python 2+3 tests+lint commands:
469 ## Run Python 3 tests+lint commands:
470 $ WITH_PYTHON2=OFF ./run-tox.sh
472 ## Run Python 3 arbitrary command (e.g. 1 single test):
473 $ WITH_PYTHON2=OFF ./run-tox.sh pytest tests/test_rgw_client.py::RgwClientTest::test_ssl_verify
475 You can also run tox instead of ``run-tox.sh``::
477 ## Run Python 3 tests command:
478 $ CEPH_BUILD_DIR=.tox tox -e py3-cov
480 ## Run Python 3 arbitrary command (e.g. 1 single test):
481 $ CEPH_BUILD_DIR=.tox tox -e py3-run pytest tests/test_rgw_client.py::RgwClientTest::test_ssl_verify
483 We also collect coverage information from the backend code when you run tests. You can check the
484 coverage information provided by the tox output, or by running the following
485 command after tox has finished successfully::
489 This command will create a directory ``htmlcov`` with an HTML representation of
490 the code coverage of the backend.
492 API tests based on Teuthology
493 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
495 How to run existing API tests:
496 To run the API tests against a real Ceph cluster, we leverage the Teuthology
497 framework. This has the advantage of catching bugs originated from changes in
498 the internal Ceph code.
500 Our ``run-backend-api-tests.sh`` script will start a ``vstart`` Ceph cluster
501 before running the Teuthology tests, and then it stops the cluster after the
502 tests are run. Of course this implies that you have built/compiled Ceph
505 Start all dashboard tests by running::
507 $ ./run-backend-api-tests.sh
509 Or, start one or multiple specific tests by specifying the test name::
511 $ ./run-backend-api-tests.sh tasks.mgr.dashboard.test_pool.PoolTest
513 Or, ``source`` the script and run the tests manually::
515 $ source run-backend-api-tests.sh
516 $ run_teuthology_tests [tests]...
519 How to write your own tests:
520 There are two possible ways to write your own API tests:
522 The first is by extending one of the existing test classes in the
523 ``qa/tasks/mgr/dashboard`` directory.
525 The second way is by adding your own API test module if you're creating a new
526 controller for example. To do so you'll just need to add the file containing
527 your new test class to the ``qa/tasks/mgr/dashboard`` directory and implement
530 .. note:: Don't forget to add the path of the newly created module to
531 ``modules`` section in ``qa/suites/rados/mgr/tasks/dashboard.yaml``.
533 Short example: Let's assume you created a new controller called
534 ``my_new_controller.py`` and the related test module
535 ``test_my_new_controller.py``. You'll need to add
536 ``tasks.mgr.dashboard.test_my_new_controller`` to the ``modules`` section in
537 the ``dashboard.yaml`` file.
539 Also, if you're removing test modules please keep in mind to remove the
540 related section. Otherwise the Teuthology test run will fail.
542 Please run your API tests on your dev environment (as explained above)
543 before submitting a pull request. Also make sure that a full QA run in
544 Teuthology/sepia lab (based on your changes) has completed successfully
545 before it gets merged. You don't need to schedule the QA run yourself, just
546 add the 'needs-qa' label to your pull request as soon as you think it's ready
547 for merging (e.g. make check was successful, the pull request is approved and
548 all comments have been addressed). One of the developers who has access to
549 Teuthology/the sepia lab will take care of it and report the result back to
553 How to add a new controller?
554 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
556 A controller is a Python class that extends from the ``BaseController`` class
557 and is decorated with either the ``@Controller``, ``@ApiController`` or
558 ``@UiApiController`` decorators. The Python class must be stored inside a Python
559 file located under the ``controllers`` directory. The Dashboard module will
560 automatically load your new controller upon start.
562 ``@ApiController`` and ``@UiApiController`` are both specializations of the
563 ``@Controller`` decorator.
565 The ``@ApiController`` should be used for controllers that provide an API-like
566 REST interface and the ``@UiApiController`` should be used for endpoints consumed
567 by the UI but that are not part of the 'public' API. For any other kinds of
568 controllers the ``@Controller`` decorator should be used.
570 A controller has a URL prefix path associated that is specified in the
571 controller decorator, and all endpoints exposed by the controller will share
572 the same URL prefix path.
574 A controller's endpoint is exposed by implementing a method on the controller
575 class decorated with the ``@Endpoint`` decorator.
577 For example create a file ``ping.py`` under ``controllers`` directory with the
580 .. code-block:: python
582 from ..tools import Controller, ApiController, UiApiController, BaseController, Endpoint
585 class Ping(BaseController):
588 return {'msg': "Hello"}
590 @ApiController('/ping')
591 class ApiPing(BaseController):
594 return {'msg': "Hello"}
596 @UiApiController('/ping')
597 class UiApiPing(BaseController):
600 return {'msg': "Hello"}
602 The ``hello`` endpoint of the ``Ping`` controller can be reached by the
603 following URL: https://mgr_hostname:8443/ping/hello using HTTP GET requests.
604 As you can see the controller URL path ``/ping`` is concatenated to the
605 method name ``hello`` to generate the endpoint's URL.
607 In the case of the ``ApiPing`` controller, the ``hello`` endpoint can be
608 reached by the following URL: https://mgr_hostname:8443/api/ping/hello using a
610 The API controller URL path ``/ping`` is prefixed by the ``/api`` path and then
611 concatenated to the method name ``hello`` to generate the endpoint's URL.
612 Internally, the ``@ApiController`` is actually calling the ``@Controller``
613 decorator by passing an additional decorator parameter called ``base_url``::
615 @ApiController('/ping') <=> @Controller('/ping', base_url="/api")
617 ``UiApiPing`` works in a similar way than the ``ApiPing``, but the URL will be
618 prefixed by ``/ui-api``: https://mgr_hostname:8443/ui-api/ping/hello. ``UiApiPing`` is
619 also a ``@Controller`` extension::
621 @UiApiController('/ping') <=> @Controller('/ping', base_url="/ui-api")
623 The ``@Endpoint`` decorator also supports many parameters to customize the
626 * ``method="GET"``: the HTTP method allowed to access this endpoint.
627 * ``path="/<method_name>"``: the URL path of the endpoint, excluding the
628 controller URL path prefix.
629 * ``path_params=[]``: list of method parameter names that correspond to URL
630 path parameters. Can only be used when ``method in ['POST', 'PUT']``.
631 * ``query_params=[]``: list of method parameter names that correspond to URL
633 * ``json_response=True``: indicates if the endpoint response should be
634 serialized in JSON format.
635 * ``proxy=False``: indicates if the endpoint should be used as a proxy.
637 An endpoint method may have parameters declared. Depending on the HTTP method
638 defined for the endpoint the method parameters might be considered either
639 path parameters, query parameters, or body parameters.
641 For ``GET`` and ``DELETE`` methods, the method's non-optional parameters are
642 considered path parameters by default. Optional parameters are considered
643 query parameters. By specifying the ``query_parameters`` in the endpoint
644 decorator it is possible to make a non-optional parameter to be a query
647 For ``POST`` and ``PUT`` methods, all method parameters are considered
648 body parameters by default. To override this default, one can use the
649 ``path_params`` and ``query_params`` to specify which method parameters are
650 path and query parameters respectivelly.
651 Body parameters are decoded from the request body, either from a form format, or
652 from a dictionary in JSON format.
654 Let's use an example to better understand the possible ways to customize an
657 .. code-block:: python
659 from ..tools import Controller, BaseController, Endpoint
662 class Ping(BaseController):
664 # URL: /ping/{key}?opt1=...&opt2=...
665 @Endpoint(path="/", query_params=['opt1'])
666 def index(self, key, opt1, opt2=None):
669 # URL: /ping/{key}?opt1=...&opt2=...
670 @Endpoint(query_params=['opt1'])
671 def __call__(self, key, opt1, opt2=None):
674 # URL: /ping/post/{key1}/{key2}
675 @Endpoint('POST', path_params=['key1', 'key2'])
676 def post(self, key1, key2, data1, data2=None):
680 In the above example we see how the ``path`` option can be used to override the
681 generated endpoint URL in order to not use the method's name in the URL. In the
682 ``index`` method we set the ``path`` to ``"/"`` to generate an endpoint that is
683 accessible by the root URL of the controller.
685 An alternative approach to generate an endpoint that is accessible through just
686 the controller's path URL is by using the ``__call__`` method, as we show in
689 From the third method you can see that the path parameters are collected from
690 the URL by parsing the list of values separated by slashes ``/`` that come
691 after the URL path ``/ping`` for ``index`` method case, and ``/ping/post`` for
692 the ``post`` method case.
694 Defining path parameters in endpoints's URLs using python methods's parameters
695 is very easy but it is still a bit strict with respect to the position of these
696 parameters in the URL structure.
697 Sometimes we may want to explicitly define a URL scheme that
698 contains path parameters mixed with static parts of the URL.
699 Our controller infrastructure also supports the declaration of URL paths with
700 explicit path parameters at both the controller level and method level.
702 Consider the following example:
704 .. code-block:: python
706 from ..tools import Controller, BaseController, Endpoint
708 @Controller('/ping/{node}/stats')
709 class Ping(BaseController):
711 # URL: /ping/{node}/stats/{date}/latency?unit=...
712 @Endpoint(path="/{date}/latency")
713 def latency(self, node, date, unit="ms"):
716 In this example we explicitly declare a path parameter ``{node}`` in the
717 controller URL path, and a path parameter ``{date}`` in the ``latency``
718 method. The endpoint for the ``latency`` method is then accessible through
719 the URL: https://mgr_hostname:8443/ping/{node}/stats/{date}/latency .
721 For a full set of examples on how to use the ``@Endpoint``
722 decorator please check the unit test file: ``tests/test_controllers.py``.
723 There you will find many examples of how to customize endpoint methods.
726 Implementing Proxy Controller
727 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
729 Sometimes you might need to relay some requests from the Dashboard frontend
730 directly to an external service.
731 For that purpose we provide a decorator called ``@Proxy``.
732 (As a concrete example, check the ``controllers/rgw.py`` file where we
733 implemented an RGW Admin Ops proxy.)
736 The ``@Proxy`` decorator is a wrapper of the ``@Endpoint`` decorator that
737 already customizes the endpoint for working as a proxy.
738 A proxy endpoint works by capturing the URL path that follows the controller
739 URL prefix path, and does not do any decoding of the request body.
743 .. code-block:: python
745 from ..tools import Controller, BaseController, Proxy
747 @Controller('/foo/proxy')
748 class FooServiceProxy(BaseController):
751 def proxy(self, path, **params):
752 # if requested URL is "/foo/proxy/access/service?opt=1"
753 # then path is "access/service" and params is {'opt': '1'}
757 How does the RESTController work?
758 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
760 We also provide a simple mechanism to create REST based controllers using the
761 ``RESTController`` class. Any class which inherits from ``RESTController`` will,
762 by default, return JSON.
764 The ``RESTController`` is basically an additional abstraction layer which eases
765 and unifies the work with collections. A collection is just an array of objects
766 with a specific type. ``RESTController`` enables some default mappings of
767 request types and given parameters to specific method names. This may sound
768 complicated at first, but it's fairly easy. Lets have look at the following
771 .. code-block:: python
774 from ..tools import ApiController, RESTController
776 @ApiController('ping')
777 class Ping(RESTController):
779 return {"msg": "Hello"}
782 return self.objects[id]
784 In this case, the ``list`` method is automatically used for all requests to
785 ``api/ping`` where no additional argument is given and where the request type
786 is ``GET``. If the request is given an additional argument, the ID in our
787 case, it won't map to ``list`` anymore but to ``get`` and return the element
788 with the given ID (assuming that ``self.objects`` has been filled before). The
789 same applies to other request types:
791 +--------------+------------+----------------+-------------+
792 | Request type | Arguments | Method | Status Code |
793 +==============+============+================+=============+
794 | GET | No | list | 200 |
795 +--------------+------------+----------------+-------------+
796 | PUT | No | bulk_set | 200 |
797 +--------------+------------+----------------+-------------+
798 | POST | No | create | 201 |
799 +--------------+------------+----------------+-------------+
800 | DELETE | No | bulk_delete | 204 |
801 +--------------+------------+----------------+-------------+
802 | GET | Yes | get | 200 |
803 +--------------+------------+----------------+-------------+
804 | PUT | Yes | set | 200 |
805 +--------------+------------+----------------+-------------+
806 | DELETE | Yes | delete | 204 |
807 +--------------+------------+----------------+-------------+
809 How to use a custom API endpoint in a RESTController?
810 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
812 If you don't have any access restriction you can use ``@Endpoint``. If you
813 have set a permission scope to restrict access to your endpoints,
814 ``@Endpoint`` will fail, as it doesn't know which permission property should be
815 used. To use a custom endpoint inside a restricted ``RESTController`` use
816 ``@RESTController.Collection`` instead. You can also choose
817 ``@RESTController.Resource`` if you have set a ``RESOURCE_ID`` in your
818 ``RESTController`` class.
820 .. code-block:: python
823 from ..tools import ApiController, RESTController
825 @ApiController('ping', Scope.Ping)
826 class Ping(RESTController):
829 @RESTController.Resource('GET')
830 def some_get_endpoint(self):
831 return {"msg": "Hello"}
833 @RESTController.Collection('POST')
834 def some_post_endpoint(self, **data):
837 Both decorators also support four parameters to customize the
840 * ``method="GET"``: the HTTP method allowed to access this endpoint.
841 * ``path="/<method_name>"``: the URL path of the endpoint, excluding the
842 controller URL path prefix.
843 * ``status=200``: set the HTTP status response code
844 * ``query_params=[]``: list of method parameter names that correspond to URL
847 How to restrict access to a controller?
848 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
850 All controllers require authentication by default.
851 If you require that the controller can be accessed without authentication,
852 then you can add the parameter ``secure=False`` to the controller decorator.
856 .. code-block:: python
859 from . import ApiController, RESTController
862 @ApiController('ping', secure=False)
863 class Ping(RESTController):
865 return {"msg": "Hello"}
868 How to access the manager module instance from a controller?
869 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
871 We provide the manager module instance as a global variable that can be
872 imported in any module. We also provide a logger instance in the same way.
876 .. code-block:: python
879 from .. import logger, mgr
880 from ..tools import ApiController, RESTController
883 @ApiController('servers')
884 class Servers(RESTController):
886 logger.debug('Listing available servers')
887 return {'servers': mgr.list_servers()}
890 How to write a unit test for a controller?
891 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
893 We provide a test helper class called ``ControllerTestCase`` to easily create
894 unit tests for your controller.
896 If we want to write a unit test for the above ``Ping`` controller, create a
897 ``test_ping.py`` file under the ``tests`` directory with the following code:
899 .. code-block:: python
901 from .helper import ControllerTestCase
902 from .controllers.ping import Ping
905 class PingTest(ControllerTestCase):
908 Ping._cp_config['tools.authenticate.on'] = False
909 cls.setup_controllers([Ping])
912 self._get("/api/ping")
913 self.assertStatus(200)
914 self.assertJsonBody({'msg': 'Hello'})
916 The ``ControllerTestCase`` class starts by initializing a CherryPy webserver.
917 Then it will call the ``setup_test()`` class method where we can explicitly
918 load the controllers that we want to test. In the above example we are only
919 loading the ``Ping`` controller. We can also disable authentication of a
920 controller at this stage, as depicted in the example.
923 How to listen for manager notifications in a controller?
924 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
926 The manager notifies the modules of several types of cluster events, such
927 as cluster logging event, etc...
929 Each module has a "global" handler function called ``notify`` that the manager
930 calls to notify the module. But this handler function must not block or spend
931 too much time processing the event notification.
932 For this reason we provide a notification queue that controllers can register
933 themselves with to receive cluster notifications.
935 The example below represents a controller that implements a very simple live
938 .. code-block:: python
940 from __future__ import absolute_import
946 from ..tools import ApiController, BaseController, NotificationQueue
949 @ApiController('livelog')
950 class LiveLog(BaseController):
951 log_buffer = collections.deque(maxlen=1000)
954 super(LiveLog, self).__init__()
955 NotificationQueue.register(self.log, 'clog')
957 def log(self, log_struct):
958 self.log_buffer.appendleft(log_struct)
962 ret = '<html><meta http-equiv="refresh" content="2" /><body>'
963 for l in self.log_buffer:
964 ret += "{}<br>".format(l)
965 ret += "</body></html>"
968 As you can see above, the ``NotificationQueue`` class provides a register
969 method that receives the function as its first argument, and receives the
970 "notification type" as the second argument.
971 You can omit the second argument of the ``register`` method, and in that case
972 you are registering to listen all notifications of any type.
974 Here is an list of notification types (these might change in the future) that
977 * ``clog``: cluster log notifications
978 * ``command``: notification when a command issued by ``MgrModule.send_command``
980 * ``perf_schema_update``: perf counters schema update
981 * ``mon_map``: monitor map update
982 * ``fs_map``: cephfs map update
983 * ``osd_map``: OSD map update
984 * ``service_map``: services (RGW, RBD-Mirror, etc.) map update
985 * ``mon_status``: monitor status regular update
986 * ``health``: health status regular update
987 * ``pg_summary``: regular update of PG status information
990 How to write a unit test when a controller accesses a Ceph module?
991 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
993 Consider the following example that implements a controller that retrieves the
994 list of RBD images of the ``rbd`` pool:
996 .. code-block:: python
1000 from ..tools import ApiController, RESTController
1003 @ApiController('rbdimages')
1004 class RbdImages(RESTController):
1006 self.ioctx = mgr.rados.open_ioctx('rbd')
1007 self.rbd = rbd.RBD()
1010 return [{'name': n} for n in self.rbd.list(self.ioctx)]
1012 In the example above, we want to mock the return value of the ``rbd.list``
1013 function, so that we can test the JSON response of the controller.
1015 The unit test code will look like the following:
1017 .. code-block:: python
1020 from .helper import ControllerTestCase
1023 class RbdImagesTest(ControllerTestCase):
1024 @mock.patch('rbd.RBD.list')
1025 def test_list(self, rbd_list_mock):
1026 rbd_list_mock.return_value = ['img1', 'img2']
1027 self._get('/api/rbdimages')
1028 self.assertJsonBody([{'name': 'img1'}, {'name': 'img2'}])
1032 How to add a new configuration setting?
1033 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1035 If you need to store some configuration setting for a new feature, we already
1036 provide an easy mechanism for you to specify/use the new config setting.
1038 For instance, if you want to add a new configuration setting to hold the
1039 email address of the dashboard admin, just add a setting name as a class
1040 attribute to the ``Options`` class in the ``settings.py`` file::
1043 class Options(object):
1046 ADMIN_EMAIL_ADDRESS = ('admin@admin.com', str)
1048 The value of the class attribute is a pair composed by the default value for that
1049 setting, and the python type of the value.
1051 By declaring the ``ADMIN_EMAIL_ADDRESS`` class attribute, when you restart the
1052 dashboard module, you will automatically gain two additional CLI commands to
1053 get and set that setting::
1055 $ ceph dashboard get-admin-email-address
1056 $ ceph dashboard set-admin-email-address <value>
1058 To access, or modify the config setting value from your Python code, either
1059 inside a controller or anywhere else, you just need to import the ``Settings``
1060 class and access it like this:
1062 .. code-block:: python
1064 from settings import Settings
1067 tmp_var = Settings.ADMIN_EMAIL_ADDRESS
1070 Settings.ADMIN_EMAIL_ADDRESS = 'myemail@admin.com'
1072 The settings management implementation will make sure that if you change a
1073 setting value from the Python code you will see that change when accessing
1074 that setting from the CLI and vice-versa.
1077 How to run a controller read-write operation asynchronously?
1078 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1080 Some controllers might need to execute operations that alter the state of the
1081 Ceph cluster. These operations might take some time to execute and to maintain
1082 a good user experience in the Web UI, we need to run those operations
1083 asynchronously and return immediately to frontend some information that the
1084 operations are running in the background.
1086 To help in the development of the above scenario we added the support for
1087 asynchronous tasks. To trigger the execution of an asynchronous task we must
1088 use the following class method of the ``TaskManager`` class::
1090 from ..tools import TaskManager
1092 TaskManager.run(name, metadata, func, args, kwargs)
1094 * ``name`` is a string that can be used to group tasks. For instance
1095 for RBD image creation tasks we could specify ``"rbd/create"`` as the
1096 name, or similarly ``"rbd/remove"`` for RBD image removal tasks.
1098 * ``metadata`` is a dictionary where we can store key-value pairs that
1099 characterize the task. For instance, when creating a task for creating
1100 RBD images we can specify the metadata argument as
1101 ``{'pool_name': "rbd", image_name': "test-img"}``.
1103 * ``func`` is the python function that implements the operation code, which
1104 will be executed asynchronously.
1106 * ``args`` and ``kwargs`` are the positional and named arguments that will be
1107 passed to ``func`` when the task manager starts its execution.
1109 The ``TaskManager.run`` method triggers the asynchronous execution of function
1110 ``func`` and returns a ``Task`` object.
1111 The ``Task`` provides the public method ``Task.wait(timeout)``, which can be
1112 used to wait for the task to complete up to a timeout defined in seconds and
1113 provided as an argument. If no argument is provided the ``wait`` method
1114 blocks until the task is finished.
1116 The ``Task.wait`` is very useful for tasks that usually are fast to execute but
1117 that sometimes may take a long time to run.
1118 The return value of the ``Task.wait`` method is a pair ``(state, value)``
1119 where ``state`` is a string with following possible values:
1121 * ``VALUE_DONE = "done"``
1122 * ``VALUE_EXECUTING = "executing"``
1124 The ``value`` will store the result of the execution of function ``func`` if
1125 ``state == VALUE_DONE``. If ``state == VALUE_EXECUTING`` then
1128 The pair ``(name, metadata)`` should unequivocally identify the task being
1129 run, which means that if you try to trigger a new task that matches the same
1130 ``(name, metadata)`` pair of the currently running task, then the new task
1131 is not created and you get the task object of the current running task.
1133 For instance, consider the following example:
1135 .. code-block:: python
1137 task1 = TaskManager.run("dummy/task", {'attr': 2}, func)
1138 task2 = TaskManager.run("dummy/task", {'attr': 2}, func)
1140 If the second call to ``TaskManager.run`` executes while the first task is
1141 still executing then it will return the same task object:
1142 ``assert task1 == task2``.
1145 How to get the list of executing and finished asynchronous tasks?
1146 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1148 The list of executing and finished tasks is included in the ``Summary``
1149 controller, which is already polled every 5 seconds by the dashboard frontend.
1150 But we also provide a dedicated controller to get the same list of executing
1153 The ``Task`` controller exposes the ``/api/task`` endpoint that returns the
1154 list of executing and finished tasks. This endpoint accepts the ``name``
1155 parameter that accepts a glob expression as its value.
1156 For instance, an HTTP GET request of the URL ``/api/task?name=rbd/*``
1157 will return all executing and finished tasks which name starts with ``rbd/``.
1159 To prevent the finished tasks list from growing unbounded, we will always
1160 maintain the 10 most recent finished tasks, and the remaining older finished
1161 tasks will be removed when reaching a TTL of 1 minute. The TTL is calculated
1162 using the timestamp when the task finished its execution. After a minute, when
1163 the finished task information is retrieved, either by the summary controller or
1164 by the task controller, it is automatically deleted from the list and it will
1165 not be included in further task queries.
1167 Each executing task is represented by the following dictionary::
1170 'name': "name", # str
1171 'metadata': { }, # dict
1172 'begin_time': "2018-03-14T15:31:38.423605Z", # str (ISO 8601 format)
1173 'progress': 0 # int (percentage)
1176 Each finished task is represented by the following dictionary::
1179 'name': "name", # str
1180 'metadata': { }, # dict
1181 'begin_time': "2018-03-14T15:31:38.423605Z", # str (ISO 8601 format)
1182 'end_time': "2018-03-14T15:31:39.423605Z", # str (ISO 8601 format)
1183 'duration': 0.0, # float
1184 'progress': 0 # int (percentage)
1185 'success': True, # bool
1186 'ret_value': None, # object, populated only if 'success' == True
1187 'exception': None, # str, populated only if 'success' == False
1191 How to use asynchronous APIs with asynchronous tasks?
1192 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1194 The ``TaskManager.run`` method as described in a previous section, is well
1195 suited for calling blocking functions, as it runs the function inside a newly
1196 created thread. But sometimes we want to call some function of an API that is
1197 already asynchronous by nature.
1199 For these cases we want to avoid creating a new thread for just running a
1200 non-blocking function, and want to leverage the asynchronous nature of the
1201 function. The ``TaskManager.run`` is already prepared to be used with
1202 non-blocking functions by passing an object of the type ``TaskExecutor`` as an
1203 additional parameter called ``executor``. The full method signature of
1204 ``TaskManager.run``::
1206 TaskManager.run(name, metadata, func, args=None, kwargs=None, executor=None)
1209 The ``TaskExecutor`` class is responsible for code that executes a given task
1210 function, and defines three methods that can be overridden by
1213 def init(self, task)
1215 def finish(self, ret_value, exception)
1217 The ``init`` method is called before the running the task function, and
1218 receives the task object (of class ``Task``).
1220 The ``start`` method runs the task function. The default implementation is to
1221 run the task function in the current thread context.
1223 The ``finish`` method should be called when the task function finishes with
1224 either the ``ret_value`` populated with the result of the execution, or with
1225 an exception object in the case that execution raised an exception.
1227 To leverage the asynchronous nature of a non-blocking function, the developer
1228 should implement a custom executor by creating a subclass of the
1229 ``TaskExecutor`` class, and provide an instance of the custom executor class
1230 as the ``executor`` parameter of the ``TaskManager.run``.
1232 To better understand the expressive power of executors, we write a full example
1233 of use a custom executor to execute the ``MgrModule.send_command`` asynchronous
1236 .. code-block:: python
1239 from mgr_module import CommandResult
1241 from ..tools import ApiController, RESTController, NotificationQueue, \
1242 TaskManager, TaskExecutor
1245 class SendCommandExecutor(TaskExecutor):
1247 super(SendCommandExecutor, self).__init__()
1251 def init(self, task):
1252 super(SendCommandExecutor, self).init(task)
1254 # we need to listen for 'command' events to know when the command
1256 NotificationQueue.register(self._handler, 'command')
1258 # store the CommandResult object to retrieve the results
1259 self.result = self.task.fn_args[0]
1260 if len(self.task.fn_args) > 4:
1261 # the user specified a tag for the command, so let's use it
1262 self.tag = self.task.fn_args[4]
1264 # let's generate a unique tag for the command
1265 self.tag = 'send_command_{}'.format(id(self))
1266 self.task.fn_args.append(self.tag)
1268 def _handler(self, data):
1269 if data == self.tag:
1270 # the command has finished, notifying the task with the result
1271 self.finish(self.result.wait(), None)
1272 # deregister listener to avoid memory leaks
1273 NotificationQueue.deregister(self._handler, 'command')
1276 @ApiController('test')
1277 class Test(RESTController):
1279 def _run_task(self, osd_id):
1280 task = TaskManager.run("test/task", {}, mgr.send_command,
1281 [CommandResult(''), 'osd', osd_id,
1282 json.dumps({'prefix': 'perf histogram dump'})],
1283 executor=SendCommandExecutor())
1284 return task.wait(1.0)
1286 def get(self, osd_id):
1287 status, value = self._run_task(osd_id)
1288 return {'status': status, 'value': value}
1291 The above ``SendCommandExecutor`` executor class can be used for any call to
1292 ``MgrModule.send_command``. This means that we should need just one custom
1293 executor class implementation for each non-blocking API that we use in our
1296 The default executor, used when no executor object is passed to
1297 ``TaskManager.run``, is the ``ThreadedExecutor``. You can check its
1298 implementation in the ``tools.py`` file.
1301 How to update the execution progress of an asynchronous task?
1302 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1304 The asynchronous tasks infrastructure provides support for updating the
1305 execution progress of an executing task.
1306 The progress can be updated from within the code the task is executing, which
1307 usually is the place where we have the progress information available.
1309 To update the progress from within the task code, the ``TaskManager`` class
1310 provides a method to retrieve the current task object::
1312 TaskManager.current_task()
1314 The above method is only available when using the default executor
1315 ``ThreadedExecutor`` for executing the task.
1316 The ``current_task()`` method returns the current ``Task`` object. The
1317 ``Task`` object provides two public methods to update the execution progress
1318 value: the ``set_progress(percentage)``, and the ``inc_progress(delta)``
1321 The ``set_progress`` method receives as argument an integer value representing
1322 the absolute percentage that we want to set to the task.
1324 The ``inc_progress`` method receives as argument an integer value representing
1325 the delta we want to increment to the current execution progress percentage.
1327 Take the following example of a controller that triggers a new task and
1328 updates its progress:
1330 .. code-block:: python
1332 from __future__ import absolute_import
1336 from ..tools import TaskManager, ApiController, BaseController
1339 @ApiController('dummy_task')
1340 class DummyTask(BaseController):
1342 top = random.randrange(100)
1343 for i in range(top):
1344 TaskManager.current_task().set_progress(i*100/top)
1345 # or TaskManager.current_task().inc_progress(100/top)
1350 @cherrypy.tools.json_out()
1352 task = TaskManager.run("dummy/task", {}, self._dummy)
1353 return task.wait(5) # wait for five seconds
1356 How to deal with asynchronous tasks in the front-end?
1357 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1359 All executing and most recently finished asynchronous tasks are displayed on
1360 "Background-Tasks" and if finished on "Recent-Notifications" in the menu bar.
1361 For each task a operation name for three states (running, success and failure),
1362 a function that tells who is involved and error descriptions, if any, have to
1363 be provided. This can be achieved by appending
1364 ``TaskManagerMessageService.messages``. This has to be done to achieve
1365 consistency among all tasks and states.
1368 Ensures consistency among all tasks. It consists of three verbs for each
1369 different state f.e.
1370 ``{running: 'Creating', failure: 'create', success: 'Created'}``.
1372 #. Put running operations in present participle f.e. ``'Updating'``.
1373 #. Failed messages always start with ``'Failed to '`` and should be continued
1374 with the operation in present tense f.e. ``'update'``.
1375 #. Put successful operations in past tense f.e. ``'Updated'``.
1378 Ensures consistency among all messages of a task, it resembles who's
1379 involved by the operation. It's a function that returns a string which
1380 takes the metadata from the task to return f.e.
1381 ``"RBD 'somePool/someImage'"``.
1383 Both combined create the following messages:
1385 * Failure => ``"Failed to create RBD 'somePool/someImage'"``
1386 * Running => ``"Creating RBD 'somePool/someImage'"``
1387 * Success => ``"Created RBD 'somePool/someImage'"``
1389 For automatic task handling use ``TaskWrapperService.wrapTaskAroundCall``.
1391 If for some reason ``wrapTaskAroundCall`` is not working for you,
1392 you have to subscribe to your asynchronous task manually through
1393 ``TaskManagerService.subscribe``, and provide it with a callback,
1394 in case of a success to notify the user. A notification can
1395 be triggered with ``NotificationService.notifyTask``. It will use
1396 ``TaskManagerMessageService.messages`` to display a message based on the state
1399 Notifications of API errors are handled by ``ApiInterceptorService``.
1403 .. code-block:: javascript
1405 export class TaskManagerMessageService {
1408 // Messages for task 'rbd/create'
1409 'rbd/create': new TaskManagerMessage(
1411 ['create', 'Creating', 'Created'],
1413 (metadata) => `RBD '${metadata.pool_name}/${metadata.image_name}'`,
1415 // Error code and description
1416 '17': `Name is already used by RBD '${metadata.pool_name}/${
1417 metadata.image_name}'.`
1425 export class RBDFormComponent {
1428 const request = this.createRequest();
1429 // Subscribes to 'call' with submitted 'task' and handles notifications
1430 return this.taskWrapper.wrapTaskAroundCall({
1431 task: new FinishedTask('rbd/create', {
1432 pool_name: request.pool_name,
1433 image_name: request.name
1435 call: this.rbdService.create(request)
1442 REST API documentation
1443 ~~~~~~~~~~~~~~~~~~~~~~
1444 There is an automatically generated Swagger UI page for documentation of the REST
1445 API endpoints.However, by default it is not very detailed. There are two
1446 decorators that can be used to add more information:
1448 * ``@EndpointDoc()`` for documentation of endpoints. It has four optional arguments
1449 (explained below): ``description``, ``group``, ``parameters`` and``responses``.
1450 * ``@ControllerDoc()`` for documentation of controller or group associated with
1451 the endpoints. It only takes the two first arguments: ``description`` and``group``.
1454 ``description``: A a string with a short (1-2 sentences) description of the object.
1457 ``group``: By default, an endpoint is grouped together with other endpoints
1458 within the same controller class. ``group`` is a string that can be used to
1459 assign an endpoint or all endpoints in a class to another controller or a
1460 conceived group name.
1463 ``parameters``: A dict used to describe path, query or request body parameters.
1464 By default, all parameters for an endpoint are listed on the Swagger UI page,
1465 including information of whether the parameter is optional/required and default
1466 values. However, there will be no description of the parameter and the parameter
1467 type will only be displayed in some cases.
1468 When adding information, each parameters should be described as in the example
1469 below. Note that the parameter type should be expressed as a built-in python
1470 type and not as a string. Allowed values are ``str``, ``int``, ``bool``, ``float``.
1472 .. code-block:: python
1474 @EndpointDoc(parameters={'my_string': (str, 'Description of my_string')})
1476 For body parameters, more complex cases are possible. If the parameter is a
1477 dictionary, the type should be replaced with a ``dict`` containing its nested
1478 parameters. When describing nested parameters, the same format as other
1479 parameters is used. However, all nested parameters are set as required by default.
1480 If the nested parameter is optional this must be specified as for ``item2`` in
1481 the example below. If a nested parameters is set to optional, it is also
1482 possible to specify the default value (this will not be provided automatically
1483 for nested parameters).
1485 .. code-block:: python
1487 @EndpointDoc(parameters={
1489 'item1': (str, 'Description of item1'),
1490 'item2': (str, 'Description of item2', True), # item2 is optional
1491 'item3': (str, 'Description of item3', True, 'foo'), # item3 is optional with 'foo' as default value
1492 }, 'Description of my_dictionary')})
1494 If the parameter is a ``list`` of primitive types, the type should be
1495 surrounded with square brackets.
1497 .. code-block:: python
1499 @EndpointDoc(parameters={'my_list': ([int], 'Description of my_list')})
1501 If the parameter is a ``list`` with nested parameters, the nested parameters
1502 should be placed in a dictionary and surrounded with square brackets.
1504 .. code-block:: python
1506 @EndpointDoc(parameters={
1508 'list_item': (str, 'Description of list_item'),
1509 'list_item2': (str, 'Description of list_item2')
1510 }], 'Description of my_list')})
1513 ``responses``: A dict used for describing responses. Rules for describing
1514 responses are the same as for request body parameters, with one difference:
1515 responses also needs to be assigned to the related response code as in the
1518 .. code-block:: python
1520 @EndpointDoc(responses={
1521 '400':{'my_response': (str, 'Description of my_response')}
1524 Error Handling in Python
1525 ~~~~~~~~~~~~~~~~~~~~~~~~
1527 Good error handling is a key requirement in creating a good user experience
1528 and providing a good API.
1530 Dashboard code should not duplicate C++ code. Thus, if error handling in C++
1531 is sufficient to provide good feedback, a new wrapper to catch these errors
1532 is not necessary. On the other hand, input validation is the best place to
1533 catch errors and generate the best error messages. If required, generate
1534 errors as soon as possible.
1536 The backend provides few standard ways of returning errors.
1538 First, there is a generic Internal Server Error::
1542 "version": <cherrypy version, e.g. 13.1.0>,
1543 "detail": "The server encountered an unexpected condition which prevented it from fulfilling the request.",
1547 For errors generated by the backend, we provide a standard error
1552 "detail": str(e), # E.g. "[errno -42] <some error message>"
1553 "component": "rbd", # this can be null to represent a global error code
1554 "code": "3", # Or a error name, e.g. "code": "some_error_key"
1558 In case, the API Endpoints uses @ViewCache to temporarily cache results,
1559 the error looks like so::
1563 "detail": str(e), # E.g. "[errno -42] <some error message>"
1564 "component": "rbd", # this can be null to represent a global error code
1565 "code": "3", # Or a error name, e.g. "code": "some_error_key"
1566 'status': 3, # Indicating the @ViewCache error status
1569 In case, the API Endpoints uses a task the error looks like so::
1573 "detail": str(e), # E.g. "[errno -42] <some error message>"
1574 "component": "rbd", # this can be null to represent a global error code
1575 "code": "3", # Or a error name, e.g. "code": "some_error_key"
1576 "task": { # Information about the task itself
1583 Our WebUI should show errors generated by the API to the user. Especially
1584 field-related errors in wizards and dialogs or show non-intrusive notifications.
1586 Handling exceptions in Python should be an exception. In general, we
1587 should have few exception handlers in our project. Per default, propagate
1588 errors to the API, as it will take care of all exceptions anyway. In general,
1589 log the exception by adding ``logger.exception()`` with a description to the
1592 We need to distinguish between user errors from internal errors and
1593 programming errors. Using different exception types will ease the
1594 task for the API layer and for the user interface:
1596 Standard Python errors, like ``SystemError``, ``ValueError`` or ``KeyError``
1597 will end up as internal server errors in the API.
1599 In general, do not ``return`` error responses in the REST API. They will be
1600 returned by the error handler. Instead, raise the appropriate exception.
1605 New functionality can be provided by means of a plug-in architecture. Among the
1606 benefits this approach brings in, loosely coupled development is one of the most
1607 notable. As the Ceph Dashboard grows in feature richness, its code-base becomes
1608 more and more complex. The hook-based nature of a plug-in architecture allows to
1609 extend functionality in a controlled manner, and isolate the scope of the
1612 Ceph Dashboard relies on `Pluggy <https://pluggy.readthedocs.io>`_ to provide
1613 for plug-ing support. On top of pluggy, an interface-based approach has been
1614 implemented, with some safety checks (method override and abstract method
1617 In order to create a new plugin, the following steps are required:
1619 #. Add a new file under ``src/pybind/mgr/dashboard/plugins``.
1620 #. Import the ``PLUGIN_MANAGER`` instance and the ``Interfaces``.
1621 #. Create a class extending the desired interfaces. The plug-in library will check if all the methods of the interfaces have been properly overridden.
1622 #. Register the plugin in the ``PLUGIN_MANAGER`` instance.
1623 #. Import the plug-in from within the Ceph Dashboard ``module.py`` (currently no dynamic loading is implemented).
1625 The available interfaces are the following:
1627 - ``CanMgr``: provides the plug-in with access to the ``mgr`` instance under ``self.mgr``.
1628 - ``CanLog``: provides the plug-in with access to the Ceph Dashboard logger under ``self.log``.
1629 - ``Setupable``: requires overriding ``setup()`` hook. This method is run in the Ceph Dashboard ``serve()`` method, right after CherryPy has been configured, but before it is started. It's a placeholder for the plug-in initialization logic.
1630 - ``HasOptions``: requires overriding ``get_options()`` hook by returning a list of ``Options()``. The options returned here are added to the ``MODULE_OPTIONS``.
1631 - ``HasCommands``: requires overriding ``register_commands()`` hook by defining the commands the plug-in can handle and decorating them with ``@CLICommand`. The commands can be optionally returned, so that they can be invoked externally (which makes unit testing easier).
1632 - ``HasControllers``: requires overriding ``get_controllers()`` hook by defining and returning the controllers as usual.
1633 - ``FilterRequest.BeforeHandler``: requires overriding ``filter_request_before_handler()`` hook. This method receives a ``cherrypy.request`` object for processing. A usual implementation of this method will allow some requests to pass or will raise a ``cherrypy.HTTPError` based on the ``request`` metadata and other conditions.
1635 New interfaces and hooks should be added as soon as they are required to
1636 implement new functionality. The above list only comprises the hooks needed for
1637 the existing plugins.
1639 A sample plugin implementation would look like this:
1641 .. code-block:: python
1643 # src/pybind/mgr/dashboard/plugins/mute.py
1645 from . import PLUGIN_MANAGER as PM
1646 from . import interfaces as I
1648 from mgr_module import CLICommand, Option
1652 class Mute(I.CanMgr, I.CanLog, I.Setupable, I.HasOptions,
1653 I.HasCommands, I.FilterRequest.BeforeHandler,
1656 def get_options(self):
1657 return [Option('mute', default=False, type='bool')]
1661 self.mute = self.mgr.get_module_options('mute')
1664 def register_commands(self):
1665 @CLICommand("dashboard mute")
1668 self.mgr.set_module_options('mute', True)
1672 def filter_request_before_handler(self, request):
1674 raise cherrypy.HTTPError(500, "I'm muted :-x")
1677 def get_controllers(self):
1678 from ..controllers import ApiController, RESTController
1680 @ApiController('/mute')
1681 class MuteController(RESTController):
1685 return [FeatureTogglesEndpoint]