]> git.proxmox.com Git - ceph.git/blob - ceph/src/pybind/mgr/dashboard/HACKING.rst
update sources to ceph Nautilus 14.2.1
[ceph.git] / ceph / src / pybind / mgr / dashboard / HACKING.rst
1 Ceph Dashboard Developer Documentation
2 ======================================
3
4 .. contents:: Table of Contents
5
6 Frontend Development
7 --------------------
8
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
12 server.
13
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.
16
17 Prerequisites
18 ~~~~~~~~~~~~~
19
20 * Node 8.9.0 or higher
21 * NPM 5.7.0 or higher
22
23 nodeenv:
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
26 system.
27
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``.
31
32 Once you finish, you can simply run ``deactivate`` and exit the virtualenv.
33
34 Angular CLI:
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.
38
39 Package installation
40 ~~~~~~~~~~~~~~~~~~~~
41
42 Run ``npm install`` in directory ``src/pybind/mgr/dashboard/frontend`` to
43 install the required packages locally.
44
45 Setting up a Development Server
46 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
47
48 Create the ``proxy.conf.json`` file based on ``proxy.conf.json.sample``.
49
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.
53
54 Code Scaffolding
55 ~~~~~~~~~~~~~~~~
56
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``.
60
61 Build the Project
62 ~~~~~~~~~~~~~~~~~
63
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``.
67
68 Code linting and formatting
69 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
70
71 We use the following tools to lint and format the code in all our TS, SCSS and
72 HTML files:
73
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/>`_
78
79 We added 2 npm scripts to help run these tools:
80
81 - ``npm run lint``, will check frontend files against all linters
82 - ``npm run fix``, will try to fix all the detected linting errors
83
84 Writing Unit Tests
85 ~~~~~~~~~~~~~~~~~~
86
87 To write unit tests most efficient we have a small collection of tools,
88 we use within test suites.
89
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``.
93
94 There you will be able to find:
95
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.
101
102 ``PermissionHelper`` to help determine if
103 the correct actions are shown based on the current permissions and selection
104 in a list.
105
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.
111
112 Running Unit Tests
113 ~~~~~~~~~~~~~~~~~~
114
115 Create ``unit-test-configuration.ts`` file based on
116 ``unit-test-configuration.ts.sample`` in directory
117 ``src/pybind/mgr/dashboard/frontend/src``.
118
119 Run ``npm run test`` to execute the unit tests via `Jest
120 <https://facebook.github.io/jest/>`_.
121
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:
125
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``
129
130 Running End-to-End Tests
131 ~~~~~~~~~~~~~~~~~~~~~~~~
132
133 We use `Protractor <http://www.protractortest.org/>`__ to run our frontend e2e
134 tests.
135
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.
138
139 Start all frontend e2e tests by running::
140
141 $ ./run-frontend-e2e-tests.sh
142
143 Device:
144 You can force the script to use a specific device with the ``-d`` flag::
145
146 $ ./run-frontend-e2e-tests.sh -d <chrome|docker>
147
148 Remote:
149 If you want to run the tests outside the ceph environment, you will need to
150 manually define the dashboard url using ``-r``::
151
152 $ ./run-frontend-e2e-tests.sh -r <DASHBOARD_URL>
153
154 Note:
155 When using docker, as your device, you might need to run the script with sudo
156 permissions.
157
158 Writing End-to-End Tests
159 ~~~~~~~~~~~~~~~~~~~~~~~~
160
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.
167
168 Further Help
169 ~~~~~~~~~~~~
170
171 To get more help on the Angular CLI use ``ng help`` or go check out the
172 `Angular CLI
173 README <https://github.com/angular/angular-cli/blob/master/README.md>`__.
174
175 Example of a Generator
176 ~~~~~~~~~~~~~~~~~~~~~~
177
178 ::
179
180 # Create module 'Core'
181 src/app> ng generate module core -m=app --routing
182
183 # Create module 'Auth' under module 'Core'
184 src/app/core> ng generate module auth -m=core --routing
185 or, alternatively:
186 src/app> ng generate module core/auth -m=core --routing
187
188 # Create component 'Login' under module 'Auth'
189 src/app/core/auth> ng generate component login -m=core/auth
190 or, alternatively:
191 src/app> ng generate component core/auth/login -m=core/auth
192
193 Frontend Typescript Code Style Guide Recommendations
194 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
195
196 Group the imports based on its source and separate them with a blank
197 line.
198
199 The source groups can be either from Angular, external or internal.
200
201 Example:
202
203 .. code:: javascript
204
205 import { Component } from '@angular/core';
206 import { Router } from '@angular/router';
207
208 import { ToastsManager } from 'ng2-toastr';
209
210 import { Credentials } from '../../../shared/models/credentials.model';
211 import { HostService } from './services/host.service';
212
213 Frontend components
214 ~~~~~~~~~~~~~~~~~~~
215
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`.
219
220 Helper
221 ......
222
223 This component should be used to provide additional information to the user.
224
225 Example:
226
227 .. code:: html
228
229 <cd-helper>
230 Some <strong>helper</strong> html text
231 </cd-helper>
232
233 Terminology and wording
234 ~~~~~~~~~~~~~~~~~~~~~~~
235
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.
240
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
247 (new) permission').
248
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.
251
252 Frontend branding
253 ~~~~~~~~~~~~~~~~~
254
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
257 replaced.
258
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:
265
266 .. code:: javascript
267
268 {
269 "replace": "src/app/core/auth/login/login.component.html",
270 "with": "src/app/core/auth/login/login.component.brand.html"
271 }
272
273 To serve or build the branded user interface run:
274
275 $ npm run start -- --prod
276
277 or
278
279 $ npm run build -- --prod
280
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).
290
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.
293
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``.
299
300 I18N
301 ----
302
303 How to extract messages from source code?
304 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
305
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``::
308
309 $ npm run i18n
310
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.
317
318 When the command ran successfully, it should have created or updated the file
319 ``src/locale/messages.xlf``.
320
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.
324
325 Supported languages
326 ~~~~~~~~~~~~~~~~~~~
327
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.
331
332 Translating process
333 ~~~~~~~~~~~~~~~~~~~
334
335 To facilitate the translation process of the dashboard we are using a web tool
336 called `transifex <https://www.transifex.com/>`_.
337
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.
341
342 All translations will then be reviewed and later pushed upstream.
343
344 Updating translated messages
345 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
346
347 Any time there are new messages translated and reviewed in a specific language
348 we should update the translation file upstream.
349
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.
354
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``.
359
360 Suggestions
361 ~~~~~~~~~~~
362
363 Strings need to start and end in the same line as the element:
364
365 .. code-block:: xml
366
367 <!-- avoid -->
368 <span i18n>
369 Foo
370 </span>
371
372 <!-- recommended -->
373 <span i18n>Foo</span>
374
375
376 <!-- avoid -->
377 <span i18n>
378 Foo bar baz.
379 Foo bar baz.
380 </span>
381
382 <!-- recommended -->
383 <span i18n>Foo bar baz.
384 Foo bar baz.</span>
385
386 Isolated interpolations should not be translated:
387
388 .. code-block:: xml
389
390 <!-- avoid -->
391 <span i18n>{{ foo }}</span>
392
393 <!-- recommended -->
394 <span>{{ foo }}</span>
395
396 Interpolations used in a sentence should be kept in the translation:
397
398 .. code-block:: xml
399
400 <!-- recommended -->
401 <span i18n>There are {{ x }} OSDs.</span>
402
403 Remove elements that are outside the context of the translation:
404
405 .. code-block:: xml
406
407 <!-- avoid -->
408 <label i18n>
409 Profile
410 <span class="required"></span>
411 </label>
412
413 <!-- recommended -->
414 <label>
415 <ng-container i18n>Profile<ng-container>
416 <span class="required"></span>
417 </label>
418
419 Keep elements that affect the sentence:
420
421 .. code-block:: xml
422
423 <!-- recommended -->
424 <span i18n>Profile <b>foo</b> will be removed.</span>
425
426 Backend Development
427 -------------------
428
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``.
434
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.
438
439 Unit Testing
440 ~~~~~~~~~~~~
441
442 In dashboard we have two different kinds of backend tests:
443
444 1. Unit tests based on ``tox``
445 2. API tests based on Teuthology.
446
447 Unit tests based on tox
448 ~~~~~~~~~~~~~~~~~~~~~~~~
449
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.
452
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
456 Fedora Linux.
457
458 Alternatively, you can use Python's native package installation method::
459
460 $ pip install tox
461 $ pip install coverage
462
463 To run the tests, run ``run-tox.sh`` in the dashboard directory (where
464 ``tox.ini`` is located)::
465
466 ## Run Python 2+3 tests+lint commands:
467 $ ./run-tox.sh
468
469 ## Run Python 3 tests+lint commands:
470 $ WITH_PYTHON2=OFF ./run-tox.sh
471
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
474
475 You can also run tox instead of ``run-tox.sh``::
476
477 ## Run Python 3 tests command:
478 $ CEPH_BUILD_DIR=.tox tox -e py3-cov
479
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
482
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::
486
487 $ coverage html
488
489 This command will create a directory ``htmlcov`` with an HTML representation of
490 the code coverage of the backend.
491
492 API tests based on Teuthology
493 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
494
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.
499
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
503 previously.
504
505 Start all dashboard tests by running::
506
507 $ ./run-backend-api-tests.sh
508
509 Or, start one or multiple specific tests by specifying the test name::
510
511 $ ./run-backend-api-tests.sh tasks.mgr.dashboard.test_pool.PoolTest
512
513 Or, ``source`` the script and run the tests manually::
514
515 $ source run-backend-api-tests.sh
516 $ run_teuthology_tests [tests]...
517 $ cleanup_teuthology
518
519 How to write your own tests:
520 There are two possible ways to write your own API tests:
521
522 The first is by extending one of the existing test classes in the
523 ``qa/tasks/mgr/dashboard`` directory.
524
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
528 all your tests here.
529
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``.
532
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.
538
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.
541
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
550 you.
551
552
553 How to add a new controller?
554 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
555
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.
561
562 ``@ApiController`` and ``@UiApiController`` are both specializations of the
563 ``@Controller`` decorator.
564
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.
569
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.
573
574 A controller's endpoint is exposed by implementing a method on the controller
575 class decorated with the ``@Endpoint`` decorator.
576
577 For example create a file ``ping.py`` under ``controllers`` directory with the
578 following code:
579
580 .. code-block:: python
581
582 from ..tools import Controller, ApiController, UiApiController, BaseController, Endpoint
583
584 @Controller('/ping')
585 class Ping(BaseController):
586 @Endpoint()
587 def hello(self):
588 return {'msg': "Hello"}
589
590 @ApiController('/ping')
591 class ApiPing(BaseController):
592 @Endpoint()
593 def hello(self):
594 return {'msg': "Hello"}
595
596 @UiApiController('/ping')
597 class UiApiPing(BaseController):
598 @Endpoint()
599 def hello(self):
600 return {'msg': "Hello"}
601
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.
606
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
609 HTTP GET request.
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``::
614
615 @ApiController('/ping') <=> @Controller('/ping', base_url="/api")
616
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::
620
621 @UiApiController('/ping') <=> @Controller('/ping', base_url="/ui-api")
622
623 The ``@Endpoint`` decorator also supports many parameters to customize the
624 endpoint:
625
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
632 query parameters.
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.
636
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.
640
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
645 parameter.
646
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.
653
654 Let's use an example to better understand the possible ways to customize an
655 endpoint:
656
657 .. code-block:: python
658
659 from ..tools import Controller, BaseController, Endpoint
660
661 @Controller('/ping')
662 class Ping(BaseController):
663
664 # URL: /ping/{key}?opt1=...&opt2=...
665 @Endpoint(path="/", query_params=['opt1'])
666 def index(self, key, opt1, opt2=None):
667 # ...
668
669 # URL: /ping/{key}?opt1=...&opt2=...
670 @Endpoint(query_params=['opt1'])
671 def __call__(self, key, opt1, opt2=None):
672 # ...
673
674 # URL: /ping/post/{key1}/{key2}
675 @Endpoint('POST', path_params=['key1', 'key2'])
676 def post(self, key1, key2, data1, data2=None):
677 # ...
678
679
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.
684
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
687 the above example.
688
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.
693
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.
701
702 Consider the following example:
703
704 .. code-block:: python
705
706 from ..tools import Controller, BaseController, Endpoint
707
708 @Controller('/ping/{node}/stats')
709 class Ping(BaseController):
710
711 # URL: /ping/{node}/stats/{date}/latency?unit=...
712 @Endpoint(path="/{date}/latency")
713 def latency(self, node, date, unit="ms"):
714 # ...
715
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 .
720
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.
724
725
726 Implementing Proxy Controller
727 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
728
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.)
734
735
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.
740
741 Example:
742
743 .. code-block:: python
744
745 from ..tools import Controller, BaseController, Proxy
746
747 @Controller('/foo/proxy')
748 class FooServiceProxy(BaseController):
749
750 @Proxy()
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'}
754 # ...
755
756
757 How does the RESTController work?
758 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
759
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.
763
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
769 example:
770
771 .. code-block:: python
772
773 import cherrypy
774 from ..tools import ApiController, RESTController
775
776 @ApiController('ping')
777 class Ping(RESTController):
778 def list(self):
779 return {"msg": "Hello"}
780
781 def get(self, id):
782 return self.objects[id]
783
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:
790
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 +--------------+------------+----------------+-------------+
808
809 How to use a custom API endpoint in a RESTController?
810 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
811
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.
819
820 .. code-block:: python
821
822 import cherrypy
823 from ..tools import ApiController, RESTController
824
825 @ApiController('ping', Scope.Ping)
826 class Ping(RESTController):
827 RESOURCE_ID = 'ping'
828
829 @RESTController.Resource('GET')
830 def some_get_endpoint(self):
831 return {"msg": "Hello"}
832
833 @RESTController.Collection('POST')
834 def some_post_endpoint(self, **data):
835 return {"msg": data}
836
837 Both decorators also support four parameters to customize the
838 endpoint:
839
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
845 query parameters.
846
847 How to restrict access to a controller?
848 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
849
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.
853
854 Example:
855
856 .. code-block:: python
857
858 import cherrypy
859 from . import ApiController, RESTController
860
861
862 @ApiController('ping', secure=False)
863 class Ping(RESTController):
864 def list(self):
865 return {"msg": "Hello"}
866
867
868 How to access the manager module instance from a controller?
869 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
870
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.
873
874 Example:
875
876 .. code-block:: python
877
878 import cherrypy
879 from .. import logger, mgr
880 from ..tools import ApiController, RESTController
881
882
883 @ApiController('servers')
884 class Servers(RESTController):
885 def list(self):
886 logger.debug('Listing available servers')
887 return {'servers': mgr.list_servers()}
888
889
890 How to write a unit test for a controller?
891 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
892
893 We provide a test helper class called ``ControllerTestCase`` to easily create
894 unit tests for your controller.
895
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:
898
899 .. code-block:: python
900
901 from .helper import ControllerTestCase
902 from .controllers.ping import Ping
903
904
905 class PingTest(ControllerTestCase):
906 @classmethod
907 def setup_test(cls):
908 Ping._cp_config['tools.authenticate.on'] = False
909 cls.setup_controllers([Ping])
910
911 def test_ping(self):
912 self._get("/api/ping")
913 self.assertStatus(200)
914 self.assertJsonBody({'msg': 'Hello'})
915
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.
921
922
923 How to listen for manager notifications in a controller?
924 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
925
926 The manager notifies the modules of several types of cluster events, such
927 as cluster logging event, etc...
928
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.
934
935 The example below represents a controller that implements a very simple live
936 log viewer page:
937
938 .. code-block:: python
939
940 from __future__ import absolute_import
941
942 import collections
943
944 import cherrypy
945
946 from ..tools import ApiController, BaseController, NotificationQueue
947
948
949 @ApiController('livelog')
950 class LiveLog(BaseController):
951 log_buffer = collections.deque(maxlen=1000)
952
953 def __init__(self):
954 super(LiveLog, self).__init__()
955 NotificationQueue.register(self.log, 'clog')
956
957 def log(self, log_struct):
958 self.log_buffer.appendleft(log_struct)
959
960 @cherrypy.expose
961 def default(self):
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>"
966 return ret
967
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.
973
974 Here is an list of notification types (these might change in the future) that
975 can be used:
976
977 * ``clog``: cluster log notifications
978 * ``command``: notification when a command issued by ``MgrModule.send_command``
979 completes
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
988
989
990 How to write a unit test when a controller accesses a Ceph module?
991 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
992
993 Consider the following example that implements a controller that retrieves the
994 list of RBD images of the ``rbd`` pool:
995
996 .. code-block:: python
997
998 import rbd
999 from .. import mgr
1000 from ..tools import ApiController, RESTController
1001
1002
1003 @ApiController('rbdimages')
1004 class RbdImages(RESTController):
1005 def __init__(self):
1006 self.ioctx = mgr.rados.open_ioctx('rbd')
1007 self.rbd = rbd.RBD()
1008
1009 def list(self):
1010 return [{'name': n} for n in self.rbd.list(self.ioctx)]
1011
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.
1014
1015 The unit test code will look like the following:
1016
1017 .. code-block:: python
1018
1019 import mock
1020 from .helper import ControllerTestCase
1021
1022
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'}])
1029
1030
1031
1032 How to add a new configuration setting?
1033 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1034
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.
1037
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::
1041
1042 # ...
1043 class Options(object):
1044 # ...
1045
1046 ADMIN_EMAIL_ADDRESS = ('admin@admin.com', str)
1047
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.
1050
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::
1054
1055 $ ceph dashboard get-admin-email-address
1056 $ ceph dashboard set-admin-email-address <value>
1057
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:
1061
1062 .. code-block:: python
1063
1064 from settings import Settings
1065
1066 # ...
1067 tmp_var = Settings.ADMIN_EMAIL_ADDRESS
1068
1069 # ....
1070 Settings.ADMIN_EMAIL_ADDRESS = 'myemail@admin.com'
1071
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.
1075
1076
1077 How to run a controller read-write operation asynchronously?
1078 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1079
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.
1085
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::
1089
1090 from ..tools import TaskManager
1091 # ...
1092 TaskManager.run(name, metadata, func, args, kwargs)
1093
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.
1097
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"}``.
1102
1103 * ``func`` is the python function that implements the operation code, which
1104 will be executed asynchronously.
1105
1106 * ``args`` and ``kwargs`` are the positional and named arguments that will be
1107 passed to ``func`` when the task manager starts its execution.
1108
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.
1115
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:
1120
1121 * ``VALUE_DONE = "done"``
1122 * ``VALUE_EXECUTING = "executing"``
1123
1124 The ``value`` will store the result of the execution of function ``func`` if
1125 ``state == VALUE_DONE``. If ``state == VALUE_EXECUTING`` then
1126 ``value == None``.
1127
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.
1132
1133 For instance, consider the following example:
1134
1135 .. code-block:: python
1136
1137 task1 = TaskManager.run("dummy/task", {'attr': 2}, func)
1138 task2 = TaskManager.run("dummy/task", {'attr': 2}, func)
1139
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``.
1143
1144
1145 How to get the list of executing and finished asynchronous tasks?
1146 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1147
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
1151 and finished tasks.
1152
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/``.
1158
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.
1166
1167 Each executing task is represented by the following dictionary::
1168
1169 {
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)
1174 }
1175
1176 Each finished task is represented by the following dictionary::
1177
1178 {
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
1188 }
1189
1190
1191 How to use asynchronous APIs with asynchronous tasks?
1192 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1193
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.
1198
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``::
1205
1206 TaskManager.run(name, metadata, func, args=None, kwargs=None, executor=None)
1207
1208
1209 The ``TaskExecutor`` class is responsible for code that executes a given task
1210 function, and defines three methods that can be overridden by
1211 subclasses::
1212
1213 def init(self, task)
1214 def start(self)
1215 def finish(self, ret_value, exception)
1216
1217 The ``init`` method is called before the running the task function, and
1218 receives the task object (of class ``Task``).
1219
1220 The ``start`` method runs the task function. The default implementation is to
1221 run the task function in the current thread context.
1222
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.
1226
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``.
1231
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
1234 function:
1235
1236 .. code-block:: python
1237
1238 import json
1239 from mgr_module import CommandResult
1240 from .. import mgr
1241 from ..tools import ApiController, RESTController, NotificationQueue, \
1242 TaskManager, TaskExecutor
1243
1244
1245 class SendCommandExecutor(TaskExecutor):
1246 def __init__(self):
1247 super(SendCommandExecutor, self).__init__()
1248 self.tag = None
1249 self.result = None
1250
1251 def init(self, task):
1252 super(SendCommandExecutor, self).init(task)
1253
1254 # we need to listen for 'command' events to know when the command
1255 # finishes
1256 NotificationQueue.register(self._handler, 'command')
1257
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]
1263 else:
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)
1267
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')
1274
1275
1276 @ApiController('test')
1277 class Test(RESTController):
1278
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)
1285
1286 def get(self, osd_id):
1287 status, value = self._run_task(osd_id)
1288 return {'status': status, 'value': value}
1289
1290
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
1294 controllers.
1295
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.
1299
1300
1301 How to update the execution progress of an asynchronous task?
1302 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1303
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.
1308
1309 To update the progress from within the task code, the ``TaskManager`` class
1310 provides a method to retrieve the current task object::
1311
1312 TaskManager.current_task()
1313
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)``
1319 methods.
1320
1321 The ``set_progress`` method receives as argument an integer value representing
1322 the absolute percentage that we want to set to the task.
1323
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.
1326
1327 Take the following example of a controller that triggers a new task and
1328 updates its progress:
1329
1330 .. code-block:: python
1331
1332 from __future__ import absolute_import
1333 import random
1334 import time
1335 import cherrypy
1336 from ..tools import TaskManager, ApiController, BaseController
1337
1338
1339 @ApiController('dummy_task')
1340 class DummyTask(BaseController):
1341 def _dummy(self):
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)
1346 time.sleep(1)
1347 return "finished"
1348
1349 @cherrypy.expose
1350 @cherrypy.tools.json_out()
1351 def default(self):
1352 task = TaskManager.run("dummy/task", {}, self._dummy)
1353 return task.wait(5) # wait for five seconds
1354
1355
1356 How to deal with asynchronous tasks in the front-end?
1357 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1358
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.
1366
1367 Operation Object
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'}``.
1371
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'``.
1376
1377 Involves Function
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'"``.
1382
1383 Both combined create the following messages:
1384
1385 * Failure => ``"Failed to create RBD 'somePool/someImage'"``
1386 * Running => ``"Creating RBD 'somePool/someImage'"``
1387 * Success => ``"Created RBD 'somePool/someImage'"``
1388
1389 For automatic task handling use ``TaskWrapperService.wrapTaskAroundCall``.
1390
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
1397 of a task.
1398
1399 Notifications of API errors are handled by ``ApiInterceptorService``.
1400
1401 Usage example:
1402
1403 .. code-block:: javascript
1404
1405 export class TaskManagerMessageService {
1406 // ...
1407 messages = {
1408 // Messages for task 'rbd/create'
1409 'rbd/create': new TaskManagerMessage(
1410 // Message prefixes
1411 ['create', 'Creating', 'Created'],
1412 // Message suffix
1413 (metadata) => `RBD '${metadata.pool_name}/${metadata.image_name}'`,
1414 (metadata) => ({
1415 // Error code and description
1416 '17': `Name is already used by RBD '${metadata.pool_name}/${
1417 metadata.image_name}'.`
1418 })
1419 ),
1420 // ...
1421 };
1422 // ...
1423 }
1424
1425 export class RBDFormComponent {
1426 // ...
1427 createAction() {
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
1434 }),
1435 call: this.rbdService.create(request)
1436 });
1437 }
1438 // ...
1439 }
1440
1441
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:
1447
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``.
1452
1453
1454 ``description``: A a string with a short (1-2 sentences) description of the object.
1455
1456
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.
1461
1462
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``.
1471
1472 .. code-block:: python
1473
1474 @EndpointDoc(parameters={'my_string': (str, 'Description of my_string')})
1475
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).
1484
1485 .. code-block:: python
1486
1487 @EndpointDoc(parameters={
1488 'my_dictionary': ({
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')})
1493
1494 If the parameter is a ``list`` of primitive types, the type should be
1495 surrounded with square brackets.
1496
1497 .. code-block:: python
1498
1499 @EndpointDoc(parameters={'my_list': ([int], 'Description of my_list')})
1500
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.
1503
1504 .. code-block:: python
1505
1506 @EndpointDoc(parameters={
1507 'my_list': ([{
1508 'list_item': (str, 'Description of list_item'),
1509 'list_item2': (str, 'Description of list_item2')
1510 }], 'Description of my_list')})
1511
1512
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
1516 example below:
1517
1518 .. code-block:: python
1519
1520 @EndpointDoc(responses={
1521 '400':{'my_response': (str, 'Description of my_response')}
1522
1523
1524 Error Handling in Python
1525 ~~~~~~~~~~~~~~~~~~~~~~~~
1526
1527 Good error handling is a key requirement in creating a good user experience
1528 and providing a good API.
1529
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.
1535
1536 The backend provides few standard ways of returning errors.
1537
1538 First, there is a generic Internal Server Error::
1539
1540 Status Code: 500
1541 {
1542 "version": <cherrypy version, e.g. 13.1.0>,
1543 "detail": "The server encountered an unexpected condition which prevented it from fulfilling the request.",
1544 }
1545
1546
1547 For errors generated by the backend, we provide a standard error
1548 format::
1549
1550 Status Code: 400
1551 {
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"
1555 }
1556
1557
1558 In case, the API Endpoints uses @ViewCache to temporarily cache results,
1559 the error looks like so::
1560
1561 Status Code 400
1562 {
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
1567 }
1568
1569 In case, the API Endpoints uses a task the error looks like so::
1570
1571 Status Code 400
1572 {
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
1577 "name": "taskname",
1578 "metadata": {...}
1579 }
1580 }
1581
1582
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.
1585
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
1590 handler.
1591
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:
1595
1596 Standard Python errors, like ``SystemError``, ``ValueError`` or ``KeyError``
1597 will end up as internal server errors in the API.
1598
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.
1601
1602 Plug-ins
1603 ~~~~~~~~
1604
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
1610 changes.
1611
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
1615 checks).
1616
1617 In order to create a new plugin, the following steps are required:
1618
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).
1624
1625 The available interfaces are the following:
1626
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.
1634
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.
1638
1639 A sample plugin implementation would look like this:
1640
1641 .. code-block:: python
1642
1643 # src/pybind/mgr/dashboard/plugins/mute.py
1644
1645 from . import PLUGIN_MANAGER as PM
1646 from . import interfaces as I
1647
1648 from mgr_module import CLICommand, Option
1649 import cherrypy
1650
1651 @PM.add_plugin
1652 class Mute(I.CanMgr, I.CanLog, I.Setupable, I.HasOptions,
1653 I.HasCommands, I.FilterRequest.BeforeHandler,
1654 I.HasControllers):
1655 @PM.add_hook
1656 def get_options(self):
1657 return [Option('mute', default=False, type='bool')]
1658
1659 @PM.add_hook
1660 def setup(self):
1661 self.mute = self.mgr.get_module_options('mute')
1662
1663 @PM.add_hook
1664 def register_commands(self):
1665 @CLICommand("dashboard mute")
1666 def _(mgr):
1667 self.mute = True
1668 self.mgr.set_module_options('mute', True)
1669 return 0
1670
1671 @PM.add_hook
1672 def filter_request_before_handler(self, request):
1673 if self.mute:
1674 raise cherrypy.HTTPError(500, "I'm muted :-x")
1675
1676 @PM.add_hook
1677 def get_controllers(self):
1678 from ..controllers import ApiController, RESTController
1679
1680 @ApiController('/mute')
1681 class MuteController(RESTController):
1682 def get(_):
1683 return self.mute
1684
1685 return [FeatureTogglesEndpoint]