]> git.proxmox.com Git - ceph.git/blame - ceph/src/pybind/mgr/dashboard/HACKING.rst
import 15.2.4
[ceph.git] / ceph / src / pybind / mgr / dashboard / HACKING.rst
CommitLineData
11fdf7f2
TL
1Ceph Dashboard Developer Documentation
2======================================
31f18b77 3
11fdf7f2 4.. contents:: Table of Contents
31f18b77 5
11fdf7f2
TL
6Frontend Development
7--------------------
31f18b77 8
11fdf7f2
TL
9Before you can start the dashboard from within a development environment, you
10will need to generate the frontend code and either use a compiled and running
11Ceph cluster (e.g. started by ``vstart.sh``) or the standalone development web
12server.
31f18b77 13
11fdf7f2
TL
14The 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.
31f18b77 16
11fdf7f2
TL
17Prerequisites
18~~~~~~~~~~~~~
31f18b77 19
11fdf7f2
TL
20 * Node 8.9.0 or higher
21 * NPM 5.7.0 or higher
31f18b77 22
11fdf7f2
TL
23nodeenv:
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.
31f18b77 27
11fdf7f2
TL
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``.
31f18b77 31
11fdf7f2 32 Once you finish, you can simply run ``deactivate`` and exit the virtualenv.
31f18b77 33
11fdf7f2
TL
34Angular 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.
31f18b77 38
11fdf7f2
TL
39Package installation
40~~~~~~~~~~~~~~~~~~~~
31f18b77 41
11fdf7f2
TL
42Run ``npm install`` in directory ``src/pybind/mgr/dashboard/frontend`` to
43install the required packages locally.
31f18b77 44
11fdf7f2
TL
45Setting up a Development Server
46~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
31f18b77 47
11fdf7f2 48Create the ``proxy.conf.json`` file based on ``proxy.conf.json.sample``.
31f18b77 49
11fdf7f2
TL
50Run ``npm start`` for a dev server.
51Navigate to ``http://localhost:4200/``. The app will automatically
52reload if you change any of the source files.
31f18b77 53
11fdf7f2
TL
54Code Scaffolding
55~~~~~~~~~~~~~~~~
56
57Run ``ng generate component component-name`` to generate a new
58component. You can also use
59``ng generate directive|pipe|service|class|guard|interface|enum|module``.
60
61Build the Project
62~~~~~~~~~~~~~~~~~
63
64Run ``npm run build`` to build the project. The build artifacts will be
9f95a23c
TL
65stored in the ``dist/`` directory. Use the ``--prod`` flag for a
66production build (``npm run build -- --prod``). Navigate to ``https://localhost:8443``.
11fdf7f2 67
81eedcae
TL
68Build the Code Documentation
69~~~~~~~~~~~~~~~~~~~~~~~~~~~~
70
71Run ``npm run doc-build`` to generate code docs in the ``documentation/``
72directory. To make them accesible locally for a web browser, run
73``npm run doc-serve`` and they will become available at ``http://localhost:8444``.
74With ``npm run compodoc -- <opts>`` you may
9f95a23c 75`fully configure it <https://compodoc.app/guides/usage.html>`_.
81eedcae 76
11fdf7f2
TL
77Code linting and formatting
78~~~~~~~~~~~~~~~~~~~~~~~~~~~~
79
80We use the following tools to lint and format the code in all our TS, SCSS and
81HTML files:
82
83- `codelyzer <http://codelyzer.com/>`_
84- `html-linter <https://github.com/chinchiheather/html-linter>`_
85- `Prettier <https://prettier.io/>`_
86- `TSLint <https://palantir.github.io/tslint/>`_
87
88We added 2 npm scripts to help run these tools:
89
90- ``npm run lint``, will check frontend files against all linters
91- ``npm run fix``, will try to fix all the detected linting errors
92
93Writing Unit Tests
94~~~~~~~~~~~~~~~~~~
95
96To write unit tests most efficient we have a small collection of tools,
97we use within test suites.
98
99Those tools can be found under
100``src/pybind/mgr/dashboard/frontend/src/testing/``, especially take
101a look at ``unit-test-helper.ts``.
102
103There you will be able to find:
104
105``configureTestBed`` that replaces the initial ``TestBed``
106methods. It takes the same arguments as ``TestBed.configureTestingModule``.
107Using it will run your tests a lot faster in development, as it doesn't
108recreate everything from scratch on every test. To use the default behaviour
109pass ``true`` as the second argument.
110
111``PermissionHelper`` to help determine if
112the correct actions are shown based on the current permissions and selection
113in a list.
114
115``FormHelper`` which makes testing a form a lot easier
116with a few simple methods. It allows you to set a control or multiple
117controls, expect if a control is valid or has an error or just do both with
118one method. Additional you can expect a template element or multiple elements
119to be visible in the rendered template.
120
121Running Unit Tests
122~~~~~~~~~~~~~~~~~~
123
124Create ``unit-test-configuration.ts`` file based on
125``unit-test-configuration.ts.sample`` in directory
126``src/pybind/mgr/dashboard/frontend/src``.
127
128Run ``npm run test`` to execute the unit tests via `Jest
129<https://facebook.github.io/jest/>`_.
130
131If you get errors on all tests, it could be because `Jest
9f95a23c 132<https://facebook.github.io/jest/>`__ or something else was updated.
11fdf7f2
TL
133There are a few ways how you can try to resolve this:
134
135- Remove all modules with ``rm -rf dist node_modules`` and run ``npm install``
136 again in order to reinstall them
137- Clear the cache of jest by running ``npx jest --clearCache``
138
9f95a23c
TL
139Running End-to-End (E2E) Tests
140~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
11fdf7f2 141
e306af50 142We use `Cypress <https://www.cypress.io/>`__ to run our frontend E2E tests.
11fdf7f2 143
e306af50
TL
144E2E Prerequisites
145.................
146
147You need to previously build the frontend.
148
149In some environments, depending on your user permissions and the CYPRESS_CACHE_FOLDER,
150you might need to run ``npm ci`` with the ``--unsafe-perm`` flag.
151
152You might need to install additional packages to be able to run Cypress.
153Please run ``npx cypress verify`` to verify it.
154
155run-frontend-e2e-tests.sh
156.........................
157
158Our ``run-frontend-e2e-tests.sh`` script is the go to solution when you wish to
159do a full scale e2e run.
160It will verify if everything needed is installed, start a new vstart cluster
161and run the full test suite.
11fdf7f2 162
9f95a23c 163Start all frontend E2E tests by running::
11fdf7f2
TL
164
165 $ ./run-frontend-e2e-tests.sh
31f18b77 166
9f95a23c 167Report:
e306af50
TL
168 You can follow the e2e report on the terminal and you can find the screenshots
169 of failed test cases by opening the following directory::
9f95a23c 170
e306af50 171 src/pybind/mgr/dashboard/frontend/cypress/screenshots/
9f95a23c 172
11fdf7f2
TL
173Device:
174 You can force the script to use a specific device with the ``-d`` flag::
31f18b77 175
e306af50 176 $ ./run-frontend-e2e-tests.sh -d <chrome|chromium|electron|docker>
31f18b77 177
11fdf7f2 178Remote:
e306af50 179 By default this script will stop and start a new vstart cluster.
11fdf7f2 180 If you want to run the tests outside the ceph environment, you will need to
e306af50
TL
181 manually define the dashboard url using ``-r`` and, optionally, credentials
182 (``-u``, ``-p``)::
11fdf7f2 183
9f95a23c 184 $ ./run-frontend-e2e-tests.sh -r <DASHBOARD_URL> -u <E2E_LOGIN_USER> -p <E2E_LOGIN_PWD>
11fdf7f2
TL
185
186Note:
187 When using docker, as your device, you might need to run the script with sudo
188 permissions.
189
e306af50
TL
190Other running options
191.....................
9f95a23c 192
e306af50
TL
193During active development, it is not recommended to run the previous script,
194as it is not prepared for constant file changes.
195Instead you should use one of the following commands:
196
197- ``npm run e2e`` - This will run ``ng serve`` and open the Cypress Test Runner.
198- ``npm run e2e:ci`` - This will run ``ng serve`` and run the Cypress Test Runner once.
199- ``npx cypress run`` - This calls cypress directly and will run the Cypress Test Runner.
200 You need to have a running frontend server.
201- ``npx cypress open`` - This calls cypress directly and will open the Cypress Test Runner.
202 You need to have a running frontend server.
203
204Calling Cypress directly has the advantage that you can use any of the available
205`flags <https://docs.cypress.io/guides/guides/command-line.html#cypress-run>`__
206to customize your test run and you don't need to start a frontend server each time.
207
208Using one of the ``open`` commands, will open a cypress application where you
209can see all the test files you have and run each individually.
210This is going to be run in watch mode, so if you make any changes to test files,
211it will retrigger the test run.
212This cannot be used inside docker, as it requires X11 environment to be able to open.
213
214By default Cypress will look for the web page at ``https://localhost:4200/``.
215If you are serving it in a different URL you will need to configure it by
216exporting the environment variable CYPRESS_BASE_URL with the new value.
217E.g.: ``CYPRESS_BASE_URL=https://localhost:41076/ npx cypress open``
218
219CYPRESS_CACHE_FOLDER
220.....................
9f95a23c 221
e306af50
TL
222When installing cypress via npm, a binary of the cypress app will also be
223downloaded and stored in a cache folder.
224This removes the need to download it every time you run ``npm ci`` or even when
225using cypress in a separate project.
9f95a23c 226
e306af50
TL
227By default Cypress uses ~/.cache to store the binary.
228To prevent changes to the user home directory, we have changed this folder to
229``/ceph/build/src/pybind/mgr/dashboard/cypress``, so when you build ceph or run
230``run-frontend-e2e-tests.sh`` this is the directory Cypress will use.
11fdf7f2 231
e306af50
TL
232When using any other command to install or run cypress,
233it will go back to the default directory. It is recommended that you export the
234CYPRESS_CACHE_FOLDER environment variable with a fixed directory, so you always
235use the same directory no matter which command you use.
9f95a23c 236
e306af50
TL
237
238Writing End-to-End Tests
239~~~~~~~~~~~~~~~~~~~~~~~~
9f95a23c
TL
240
241The PagerHelper class
242.....................
243
244The ``PageHelper`` class is supposed to be used for general purpose code that
245can be used on various pages or suites.
246
247Examples are
248
e306af50
TL
249- ``navigateTo()`` - Navigates to a specific page and waits for it to load
250- ``getFirstTableCell()`` - returns the first table cell. You can also pass a
251 string with the desired content and it will return the first cell that
252 contains it.
9f95a23c 253- ``getTabsCount()`` - returns the amount of tabs
9f95a23c
TL
254
255Every method that could be useful on several pages belongs there. Also, methods
256which enhance the derived classes of the PageHelper belong there. A good
257example for such a case is the ``restrictTo()`` decorator. It ensures that a
258method implemented in a subclass of PageHelper is called on the correct page.
259It will also show a developer-friendly warning if this is not the case.
260
261Subclasses of PageHelper
262........................
263
264Helper Methods
265""""""""""""""
266
267In order to make code reusable which is specific for a particular suite, make
268sure to put it in a derived class of the ``PageHelper``. For instance, when
269talking about the pool suite, such methods would be ``create()``, ``exist()``
270and ``delete()``. These methods are specific to a pool but are useful for other
271suites.
272
e306af50
TL
273Methods that return HTML elements which can only be found on a specific page,
274should be either implemented in the helper methods of the subclass of PageHelper
275or as own methods of the subclass of PageHelper.
9f95a23c
TL
276
277Using PageHelpers
278"""""""""""""""""
279
e306af50
TL
280In any suite, an instance of the specific ``Helper`` class should be
281instantiated and called directly.
9f95a23c
TL
282
283.. code:: TypeScript
284
e306af50
TL
285 const pools = new PoolPageHelper();
286
9f95a23c 287 it('should create a pool', () => {
e306af50
TL
288 pools.exist(poolName, false);
289 pools.navigateTo('create');
290 pools.create(poolName, 8);
291 pools.exist(poolName, true);
9f95a23c
TL
292 });
293
294Code Style
295..........
296
e306af50
TL
297Please refer to the official `Cypress Core Concepts
298<https://docs.cypress.io/guides/core-concepts/introduction-to-cypress.html#Cypress-Can-Be-Simple-Sometimes>`__
299for a better insight on how to write and structure tests.
9f95a23c
TL
300
301``describe()`` vs ``it()``
302""""""""""""""""""""""""""
303
e306af50
TL
304Both ``describe()`` and ``it()`` are function blocks, meaning that any
305executable code necessary for the test can be contained in either block.
306However, Typescript scoping rules still apply, therefore any variables declared
307in a ``describe`` are available to the ``it()`` blocks inside of it.
9f95a23c 308
e306af50
TL
309``describe()`` typically are containers for tests, allowing you to break tests
310into multiple parts. Likewise, any setup that must be made before your tests are
311run can be initialized within the ``describe()`` block. Here is an example:
9f95a23c
TL
312
313.. code:: TypeScript
314
315 describe('create, edit & delete image test', () => {
316 const poolName = 'e2e_images_pool';
317
e306af50
TL
318 before(() => {
319 cy.login();
320 pools.navigateTo('create');
321 pools.create(poolName, 8, 'rbd');
322 pools.exist(poolName, true);
323 });
324
325 beforeEach(() => {
326 cy.login();
9f95a23c
TL
327 images.navigateTo();
328 });
329
e306af50
TL
330 //...
331
332 });
333
9f95a23c 334As shown, we can initiate the variable ``poolName`` as well as run commands
e306af50
TL
335before our test suite begins (creating a pool). ``describe()`` block messages
336should include what the test suite is.
9f95a23c 337
e306af50
TL
338``it()`` blocks typically are parts of an overarching test. They contain the
339functionality of the test suite, each performing individual roles.
340Here is an example:
9f95a23c
TL
341
342.. code:: TypeScript
343
e306af50
TL
344 describe('create, edit & delete image test', () => {
345 //...
346
347 it('should create image', () => {
348 images.createImage(imageName, poolName, '1');
349 images.getFirstTableCell(imageName).should('exist');
350 });
351
352 it('should edit image', () => {
353 images.editImage(imageName, poolName, newImageName, '2');
354 images.getFirstTableCell(newImageName).should('exist');
355 });
356
357 //...
9f95a23c 358 });
9f95a23c 359
e306af50
TL
360As shown from the previous example, our ``describe()`` test suite is to create,
361edit and delete an image. Therefore, each ``it()`` completes one of these steps,
362one for creating, one for editing, and so on. Likewise, every ``it()`` blocks
363message should be in lowercase and written so long as "it" can be the prefix of
364the message. For example, ``it('edits the test image' () => ...)`` vs.
365``it('image edit test' () => ...)``. As shown, the first example makes
366grammatical sense with ``it()`` as the prefix whereas the second message does
367not. ``it()`` should describe what the individual test is doing and what it
368expects to happen.
9f95a23c
TL
369
370Differences between Frontend Unit Tests and End-to-End (E2E) Tests / FAQ
371~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
372
373General introduction about testing and E2E/unit tests
374
375
376What are E2E/unit tests designed for?
377.....................................
378
379E2E test:
380
9f95a23c
TL
381It requires a fully functional system and tests the interaction of all components
382of the application (Ceph, back-end, front-end).
383E2E tests are designed to mimic the behavior of the user when interacting with the application
384- for example when it comes to workflows like creating/editing/deleting an item.
385Also the tests should verify that certain items are displayed as a user would see them
386when clicking through the UI (for example a menu entry or a pool that has been
387created during a test and the pool and its properties should be displayed in the table).
388
389Angular Unit Tests:
390
391Unit tests, as the name suggests, are tests for smaller units of the code.
392Those tests are designed for testing all kinds of Angulars' components (e.g. services, pipes etc.).
393They do not require a connection to the backend, hence those tests are independent of it.
394The expected data of the backend is mocked in the frontend and by using this data
395the functionality of the frontend can be tested without having to have real data from the backend.
396As previously mentioned, data is either mocked or, in a simple case, contains a static input,
397a function call and an expected static output.
398More complex examples include the state of a component (attributes of the component class),
399that define how the output changes according to the given input.
400
401Which E2E/unit tests are considered to be valid?
402................................................
403
404This is not easy to answer, but new tests that are written in the same way as already existing
405dashboard tests should generally be considered valid.
406Unit tests should focus on the component to be tested.
407This is either an Angular component, directive, service, pipe, etc.
408
409E2E tests should focus on testing the functionality of the whole application.
410Approximately a third of the overall E2E tests should verify the correctness
411of user visible elements.
412
413How should an E2E/unit test look like?
414......................................
415
416Unit tests should focus on the described purpose
417and shouldn't try to test other things in the same `it` block.
418
419E2E tests should contain a description that either verifies
420the correctness of a user visible element or a complete process
421like for example the creation/validation/deletion of a pool.
422
423What should an E2E/unit test cover?
424...................................
425
426E2E tests should mostly, but not exclusively, cover interaction with the backend.
427This way the interaction with the backend is utilized to write integration tests.
428
429A unit test should mostly cover critical or complex functionality
430of a component (Angular Components, Services, Pipes, Directives, etc).
431
432What should an E2E/unit test NOT cover?
433.......................................
434
435Avoid duplicate testing: do not write E2E tests for what's already
436been covered as frontend-unit tests and vice versa.
437It may not be possible to completely avoid an overlap.
438
439Unit tests should not be used to extensively click through components and E2E tests
440shouldn't be used to extensively test a single component of Angular.
441
442Best practices/guideline
443........................
444
445As a general guideline we try to follow the 70/20/10 approach - 70% unit tests,
44620% integration tests and 10% end-to-end tests.
447For further information please refer to `this document
448<https://testing.googleblog.com/2015/04/just-say-no-to-more-end-to-end-tests.html>`__
449and the included "Testing Pyramid".
11fdf7f2
TL
450
451Further Help
452~~~~~~~~~~~~
453
454To get more help on the Angular CLI use ``ng help`` or go check out the
455`Angular CLI
456README <https://github.com/angular/angular-cli/blob/master/README.md>`__.
457
458Example of a Generator
459~~~~~~~~~~~~~~~~~~~~~~
31f18b77
FG
460
461::
462
11fdf7f2
TL
463 # Create module 'Core'
464 src/app> ng generate module core -m=app --routing
465
466 # Create module 'Auth' under module 'Core'
467 src/app/core> ng generate module auth -m=core --routing
468 or, alternatively:
469 src/app> ng generate module core/auth -m=core --routing
470
471 # Create component 'Login' under module 'Auth'
472 src/app/core/auth> ng generate component login -m=core/auth
473 or, alternatively:
474 src/app> ng generate component core/auth/login -m=core/auth
475
476Frontend Typescript Code Style Guide Recommendations
477~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
478
479Group the imports based on its source and separate them with a blank
480line.
481
482The source groups can be either from Angular, external or internal.
483
484Example:
485
486.. code:: javascript
487
488 import { Component } from '@angular/core';
489 import { Router } from '@angular/router';
490
494da23a 491 import { ToastrManager } from 'ngx-toastr';
11fdf7f2
TL
492
493 import { Credentials } from '../../../shared/models/credentials.model';
494 import { HostService } from './services/host.service';
495
496Frontend components
497~~~~~~~~~~~~~~~~~~~
498
499There are several components that can be reused on different pages.
500This components are declared on the components module:
501`src/pybind/mgr/dashboard/frontend/src/app/shared/components`.
502
503Helper
9f95a23c 504~~~~~~
11fdf7f2
TL
505
506This component should be used to provide additional information to the user.
507
508Example:
509
510.. code:: html
511
512 <cd-helper>
513 Some <strong>helper</strong> html text
514 </cd-helper>
515
516Terminology and wording
517~~~~~~~~~~~~~~~~~~~~~~~
518
519Instead of using the Ceph component names, the approach
520suggested is to use the logical/generic names (Block over RBD, Filesystem over
521CephFS, Object over RGW). Nevertheless, as Ceph-Dashboard cannot completely hide
522the Ceph internals, some Ceph-specific names might remain visible.
523
524Regarding the wording for action labels and other textual elements (form titles,
525buttons, etc.), the chosen approach is to follow `these guidelines
526<https://www.patternfly.org/styles/terminology-and-wording/#terminology-and-wording-for-action-labels>`_.
527As a rule of thumb, 'Create' and 'Delete' are the proper wording for most forms,
528instead of 'Add' and 'Remove', unless some already created item is either added
529or removed to/from a set of items (e.g.: 'Add permission' to a user vs. 'Create
530(new) permission').
31f18b77 531
11fdf7f2
TL
532In order to enforce the use of this wording, a service ``ActionLabelsI18n`` has
533been created, which provides translated labels for use in UI elements.
494da23a 534
11fdf7f2
TL
535Frontend branding
536~~~~~~~~~~~~~~~~~
31f18b77 537
11fdf7f2
TL
538Every vendor can customize the 'Ceph dashboard' to his needs. No matter if
539logo, HTML-Template or TypeScript, every file inside the frontend folder can be
540replaced.
31f18b77 541
11fdf7f2
TL
542To replace files, open ``./frontend/angular.json`` and scroll to the section
543``fileReplacements`` inside the production configuration. Here you can add the
544files you wish to brand. We recommend to place the branded version of a file in
545the same directory as the original one and to add a ``.brand`` to the file
546name, right in front of the file extension. A ``fileReplacement`` could for
547example look like this:
31f18b77 548
11fdf7f2 549.. code:: javascript
31f18b77 550
11fdf7f2
TL
551 {
552 "replace": "src/app/core/auth/login/login.component.html",
553 "with": "src/app/core/auth/login/login.component.brand.html"
554 }
555
556To serve or build the branded user interface run:
557
558 $ npm run start -- --prod
559
560or
561
562 $ npm run build -- --prod
563
564Unfortunately it's currently not possible to use multiple configurations when
565serving or building the UI at the same time. That means a configuration just
566for the branding ``fileReplacements`` is not an option, because you want to use
567the production configuration anyway
568(https://github.com/angular/angular-cli/issues/10612).
569Furthermore it's also not possible to use glob expressions for
570``fileReplacements``. As long as the feature hasn't been implemented, you have
571to add the file replacements manually to the angular.json file
572(https://github.com/angular/angular-cli/issues/12354).
573
574Nevertheless you should stick to the suggested naming scheme because it makes
575it easier for you to use glob expressions once it's supported in the future.
576
577To change the variable defaults you can overwrite them in the file
578``./frontend/src/vendor.variables.scss``. Just reassign the variable you want
579to change, for example ``$color-primary: teal;``
580To overwrite or extend the default CSS, you can add your own styles in
581``./frontend/src/vendor.overrides.scss``.
582
583I18N
31f18b77
FG
584----
585
11fdf7f2
TL
586How to extract messages from source code?
587~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
588
589To extract the I18N messages from the templates and the TypeScript files just
590run the following command in ``src/pybind/mgr/dashboard/frontend``::
591
eafe8130 592 $ npm run i18n:extract
11fdf7f2
TL
593
594This will extract all marked messages from the HTML templates first and then
595add all marked strings from the TypeScript files to the translation template.
596Since the extraction from TypeScript files is still not supported by Angular
597itself, we are using the
598`ngx-translator <https://github.com/ngx-translate/i18n-polyfill>`_ extractor to
599parse the TypeScript files.
600
601When the command ran successfully, it should have created or updated the file
602``src/locale/messages.xlf``.
603
81eedcae
TL
604The file isn't tracked by git, you can just use it to start with the
605translation offline or add/update the resource files on transifex.
11fdf7f2
TL
606
607Supported languages
608~~~~~~~~~~~~~~~~~~~
609
81eedcae
TL
610All our supported languages should be registered in both exports in
611``supported-languages.enum.ts`` and have a corresponding test in
612``language-selector.component.spec.ts``.
613
614The ``SupportedLanguages`` enum will provide the list for the default language selection.
615
616The ``languageBootstrapMapping`` variable will provide the
617`language support <https://github.com/valor-software/ngx-bootstrap/tree/development/src/chronos/i18n>`_
618for ngx-bootstrap components like the
619`date picker <https://valor-software.com/ngx-bootstrap/#/datepicker#locales>`_.
11fdf7f2
TL
620
621Translating process
622~~~~~~~~~~~~~~~~~~~
623
624To facilitate the translation process of the dashboard we are using a web tool
625called `transifex <https://www.transifex.com/>`_.
626
627If you wish to help translating to any language just go to our `transifex
628project page <https://www.transifex.com/ceph/ceph-dashboard/>`_, join the
629project and you can start translating immediately.
630
631All translations will then be reviewed and later pushed upstream.
632
633Updating translated messages
634~~~~~~~~~~~~~~~~~~~~~~~~~~~~
635
636Any time there are new messages translated and reviewed in a specific language
637we should update the translation file upstream.
638
eafe8130
TL
639To do that, check the settings in the i18n config file
640``src/pybind/mgr/dashboard/frontend/i18n.config.json``:: and make sure that the
641organization is *ceph*, the project is *ceph-dashboard* and the resource is
642the one you want to pull from and push to e.g. *Master:master*. To find a list
9f95a23c 643of avaiable resources visit `<https://www.transifex.com/ceph/ceph-dashboard/content/>`_.
eafe8130 644
9f95a23c 645After you checked the config go to the directory ``src/pybind/mgr/dashboard/frontend`` and run::
eafe8130
TL
646
647 $ npm run i18n
648
649This command will extract all marked messages from the HTML templates and
650TypeScript files. Once the source file has been created it will push it to
651transifex and pull the latest translations. It will also fill all the
652untranslated strings with the source string.
653The tool will ask you for an api token, unless you added it by running:
654
655 $ npm run i18n:token
656
9f95a23c 657To create a transifex api token visit `<https://www.transifex.com/user/settings/api/>`_.
11fdf7f2 658
eafe8130
TL
659After the command ran successfully, build the UI and check if everything is
660working as expected. You also might want to run the frontend tests.
11fdf7f2
TL
661
662Suggestions
663~~~~~~~~~~~
664
665Strings need to start and end in the same line as the element:
666
9f95a23c 667.. code-block:: html
11fdf7f2
TL
668
669 <!-- avoid -->
670 <span i18n>
671 Foo
672 </span>
673
674 <!-- recommended -->
675 <span i18n>Foo</span>
676
677
678 <!-- avoid -->
679 <span i18n>
680 Foo bar baz.
681 Foo bar baz.
682 </span>
683
684 <!-- recommended -->
685 <span i18n>Foo bar baz.
686 Foo bar baz.</span>
687
688Isolated interpolations should not be translated:
689
9f95a23c 690.. code-block:: html
11fdf7f2
TL
691
692 <!-- avoid -->
693 <span i18n>{{ foo }}</span>
694
695 <!-- recommended -->
696 <span>{{ foo }}</span>
697
698Interpolations used in a sentence should be kept in the translation:
699
9f95a23c 700.. code-block:: html
11fdf7f2
TL
701
702 <!-- recommended -->
703 <span i18n>There are {{ x }} OSDs.</span>
704
705Remove elements that are outside the context of the translation:
706
9f95a23c 707.. code-block:: html
11fdf7f2
TL
708
709 <!-- avoid -->
710 <label i18n>
711 Profile
712 <span class="required"></span>
713 </label>
714
715 <!-- recommended -->
716 <label>
717 <ng-container i18n>Profile<ng-container>
718 <span class="required"></span>
719 </label>
720
721Keep elements that affect the sentence:
722
9f95a23c 723.. code-block:: html
11fdf7f2
TL
724
725 <!-- recommended -->
726 <span i18n>Profile <b>foo</b> will be removed.</span>
727
728Backend Development
729-------------------
730
731The Python backend code of this module requires a number of Python modules to be
732installed. They are listed in file ``requirements.txt``. Using `pip
733<https://pypi.python.org/pypi/pip>`_ you may install all required dependencies
734by issuing ``pip install -r requirements.txt`` in directory
735``src/pybind/mgr/dashboard``.
736
737If you're using the `ceph-dev-docker development environment
738<https://github.com/ricardoasmarques/ceph-dev-docker/>`_, simply run
739``./install_deps.sh`` from the toplevel directory to install them.
740
741Unit Testing
742~~~~~~~~~~~~
743
744In dashboard we have two different kinds of backend tests:
745
7461. Unit tests based on ``tox``
7472. API tests based on Teuthology.
748
749Unit tests based on tox
750~~~~~~~~~~~~~~~~~~~~~~~~
751
752We included a ``tox`` configuration file that will run the unit tests under
753Python 2 or 3, as well as linting tools to guarantee the uniformity of code.
754
755You need to install ``tox`` and ``coverage`` before running it. To install the
756packages in your system, either install it via your operating system's package
757management tools, e.g. by running ``dnf install python-tox python-coverage`` on
758Fedora Linux.
759
760Alternatively, you can use Python's native package installation method::
761
762 $ pip install tox
763 $ pip install coverage
764
9f95a23c 765To run the tests, run ``src/script/run_tox.sh`` in the dashboard directory (where
11fdf7f2
TL
766``tox.ini`` is located)::
767
768 ## Run Python 2+3 tests+lint commands:
9f95a23c 769 $ ../../../script/run_tox.sh --tox-env py27,py3,lint,check
11fdf7f2
TL
770
771 ## Run Python 3 tests+lint commands:
9f95a23c 772 $ ../../../script/run_tox.sh --tox-env py3,lint,check
11fdf7f2
TL
773
774 ## Run Python 3 arbitrary command (e.g. 1 single test):
9f95a23c 775 $ ../../../script/run_tox.sh --tox-env py3 "" tests/test_rgw_client.py::RgwClientTest::test_ssl_verify
11fdf7f2 776
9f95a23c 777You can also run tox instead of ``run_tox.sh``::
11fdf7f2
TL
778
779 ## Run Python 3 tests command:
9f95a23c 780 $ tox -e py3
11fdf7f2
TL
781
782 ## Run Python 3 arbitrary command (e.g. 1 single test):
9f95a23c
TL
783 $ tox -e py3 tests/test_rgw_client.py::RgwClientTest::test_ssl_verify
784
785Python files can be automatically fixed and formatted according to PEP8
786standards by using ``run_tox.sh --tox-env fix`` or ``tox -e fix``.
11fdf7f2
TL
787
788We also collect coverage information from the backend code when you run tests. You can check the
789coverage information provided by the tox output, or by running the following
790command after tox has finished successfully::
791
792 $ coverage html
793
794This command will create a directory ``htmlcov`` with an HTML representation of
795the code coverage of the backend.
796
797API tests based on Teuthology
798~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
799
800How to run existing API tests:
801 To run the API tests against a real Ceph cluster, we leverage the Teuthology
802 framework. This has the advantage of catching bugs originated from changes in
803 the internal Ceph code.
804
805 Our ``run-backend-api-tests.sh`` script will start a ``vstart`` Ceph cluster
806 before running the Teuthology tests, and then it stops the cluster after the
807 tests are run. Of course this implies that you have built/compiled Ceph
808 previously.
809
810 Start all dashboard tests by running::
811
812 $ ./run-backend-api-tests.sh
813
814 Or, start one or multiple specific tests by specifying the test name::
815
816 $ ./run-backend-api-tests.sh tasks.mgr.dashboard.test_pool.PoolTest
817
818 Or, ``source`` the script and run the tests manually::
819
820 $ source run-backend-api-tests.sh
821 $ run_teuthology_tests [tests]...
822 $ cleanup_teuthology
823
824How to write your own tests:
825 There are two possible ways to write your own API tests:
826
827 The first is by extending one of the existing test classes in the
828 ``qa/tasks/mgr/dashboard`` directory.
829
830 The second way is by adding your own API test module if you're creating a new
831 controller for example. To do so you'll just need to add the file containing
832 your new test class to the ``qa/tasks/mgr/dashboard`` directory and implement
833 all your tests here.
834
835 .. note:: Don't forget to add the path of the newly created module to
836 ``modules`` section in ``qa/suites/rados/mgr/tasks/dashboard.yaml``.
837
838 Short example: Let's assume you created a new controller called
839 ``my_new_controller.py`` and the related test module
840 ``test_my_new_controller.py``. You'll need to add
841 ``tasks.mgr.dashboard.test_my_new_controller`` to the ``modules`` section in
842 the ``dashboard.yaml`` file.
843
844 Also, if you're removing test modules please keep in mind to remove the
845 related section. Otherwise the Teuthology test run will fail.
846
847 Please run your API tests on your dev environment (as explained above)
848 before submitting a pull request. Also make sure that a full QA run in
849 Teuthology/sepia lab (based on your changes) has completed successfully
850 before it gets merged. You don't need to schedule the QA run yourself, just
851 add the 'needs-qa' label to your pull request as soon as you think it's ready
852 for merging (e.g. make check was successful, the pull request is approved and
853 all comments have been addressed). One of the developers who has access to
854 Teuthology/the sepia lab will take care of it and report the result back to
855 you.
856
857
858How to add a new controller?
859~~~~~~~~~~~~~~~~~~~~~~~~~~~~
860
861A controller is a Python class that extends from the ``BaseController`` class
862and is decorated with either the ``@Controller``, ``@ApiController`` or
863``@UiApiController`` decorators. The Python class must be stored inside a Python
864file located under the ``controllers`` directory. The Dashboard module will
865automatically load your new controller upon start.
866
867``@ApiController`` and ``@UiApiController`` are both specializations of the
868``@Controller`` decorator.
869
870The ``@ApiController`` should be used for controllers that provide an API-like
871REST interface and the ``@UiApiController`` should be used for endpoints consumed
872by the UI but that are not part of the 'public' API. For any other kinds of
873controllers the ``@Controller`` decorator should be used.
874
875A controller has a URL prefix path associated that is specified in the
876controller decorator, and all endpoints exposed by the controller will share
877the same URL prefix path.
878
879A controller's endpoint is exposed by implementing a method on the controller
880class decorated with the ``@Endpoint`` decorator.
881
882For example create a file ``ping.py`` under ``controllers`` directory with the
883following code:
884
885.. code-block:: python
886
887 from ..tools import Controller, ApiController, UiApiController, BaseController, Endpoint
888
889 @Controller('/ping')
890 class Ping(BaseController):
891 @Endpoint()
892 def hello(self):
893 return {'msg': "Hello"}
894
895 @ApiController('/ping')
896 class ApiPing(BaseController):
897 @Endpoint()
898 def hello(self):
899 return {'msg': "Hello"}
900
901 @UiApiController('/ping')
902 class UiApiPing(BaseController):
903 @Endpoint()
904 def hello(self):
905 return {'msg': "Hello"}
906
907The ``hello`` endpoint of the ``Ping`` controller can be reached by the
908following URL: https://mgr_hostname:8443/ping/hello using HTTP GET requests.
909As you can see the controller URL path ``/ping`` is concatenated to the
910method name ``hello`` to generate the endpoint's URL.
911
912In the case of the ``ApiPing`` controller, the ``hello`` endpoint can be
913reached by the following URL: https://mgr_hostname:8443/api/ping/hello using a
914HTTP GET request.
915The API controller URL path ``/ping`` is prefixed by the ``/api`` path and then
916concatenated to the method name ``hello`` to generate the endpoint's URL.
917Internally, the ``@ApiController`` is actually calling the ``@Controller``
918decorator by passing an additional decorator parameter called ``base_url``::
919
920 @ApiController('/ping') <=> @Controller('/ping', base_url="/api")
921
922``UiApiPing`` works in a similar way than the ``ApiPing``, but the URL will be
923prefixed by ``/ui-api``: https://mgr_hostname:8443/ui-api/ping/hello. ``UiApiPing`` is
924also a ``@Controller`` extension::
925
926 @UiApiController('/ping') <=> @Controller('/ping', base_url="/ui-api")
927
928The ``@Endpoint`` decorator also supports many parameters to customize the
929endpoint:
930
931* ``method="GET"``: the HTTP method allowed to access this endpoint.
932* ``path="/<method_name>"``: the URL path of the endpoint, excluding the
933 controller URL path prefix.
934* ``path_params=[]``: list of method parameter names that correspond to URL
935 path parameters. Can only be used when ``method in ['POST', 'PUT']``.
936* ``query_params=[]``: list of method parameter names that correspond to URL
937 query parameters.
938* ``json_response=True``: indicates if the endpoint response should be
939 serialized in JSON format.
940* ``proxy=False``: indicates if the endpoint should be used as a proxy.
941
942An endpoint method may have parameters declared. Depending on the HTTP method
943defined for the endpoint the method parameters might be considered either
944path parameters, query parameters, or body parameters.
945
946For ``GET`` and ``DELETE`` methods, the method's non-optional parameters are
947considered path parameters by default. Optional parameters are considered
948query parameters. By specifying the ``query_parameters`` in the endpoint
949decorator it is possible to make a non-optional parameter to be a query
950parameter.
951
952For ``POST`` and ``PUT`` methods, all method parameters are considered
953body parameters by default. To override this default, one can use the
954``path_params`` and ``query_params`` to specify which method parameters are
9f95a23c 955path and query parameters respectively.
11fdf7f2
TL
956Body parameters are decoded from the request body, either from a form format, or
957from a dictionary in JSON format.
958
959Let's use an example to better understand the possible ways to customize an
960endpoint:
961
962.. code-block:: python
963
964 from ..tools import Controller, BaseController, Endpoint
965
966 @Controller('/ping')
967 class Ping(BaseController):
968
969 # URL: /ping/{key}?opt1=...&opt2=...
970 @Endpoint(path="/", query_params=['opt1'])
971 def index(self, key, opt1, opt2=None):
9f95a23c 972 """..."""
11fdf7f2
TL
973
974 # URL: /ping/{key}?opt1=...&opt2=...
975 @Endpoint(query_params=['opt1'])
976 def __call__(self, key, opt1, opt2=None):
9f95a23c 977 """..."""
11fdf7f2
TL
978
979 # URL: /ping/post/{key1}/{key2}
980 @Endpoint('POST', path_params=['key1', 'key2'])
981 def post(self, key1, key2, data1, data2=None):
9f95a23c 982 """..."""
11fdf7f2
TL
983
984
985In the above example we see how the ``path`` option can be used to override the
986generated endpoint URL in order to not use the method's name in the URL. In the
987``index`` method we set the ``path`` to ``"/"`` to generate an endpoint that is
988accessible by the root URL of the controller.
989
990An alternative approach to generate an endpoint that is accessible through just
991the controller's path URL is by using the ``__call__`` method, as we show in
992the above example.
993
994From the third method you can see that the path parameters are collected from
995the URL by parsing the list of values separated by slashes ``/`` that come
996after the URL path ``/ping`` for ``index`` method case, and ``/ping/post`` for
997the ``post`` method case.
998
999Defining path parameters in endpoints's URLs using python methods's parameters
1000is very easy but it is still a bit strict with respect to the position of these
1001parameters in the URL structure.
1002Sometimes we may want to explicitly define a URL scheme that
1003contains path parameters mixed with static parts of the URL.
1004Our controller infrastructure also supports the declaration of URL paths with
1005explicit path parameters at both the controller level and method level.
1006
1007Consider the following example:
1008
1009.. code-block:: python
1010
1011 from ..tools import Controller, BaseController, Endpoint
1012
1013 @Controller('/ping/{node}/stats')
1014 class Ping(BaseController):
1015
1016 # URL: /ping/{node}/stats/{date}/latency?unit=...
1017 @Endpoint(path="/{date}/latency")
1018 def latency(self, node, date, unit="ms"):
9f95a23c 1019 """ ..."""
11fdf7f2
TL
1020
1021In this example we explicitly declare a path parameter ``{node}`` in the
1022controller URL path, and a path parameter ``{date}`` in the ``latency``
1023method. The endpoint for the ``latency`` method is then accessible through
1024the URL: https://mgr_hostname:8443/ping/{node}/stats/{date}/latency .
1025
1026For a full set of examples on how to use the ``@Endpoint``
1027decorator please check the unit test file: ``tests/test_controllers.py``.
1028There you will find many examples of how to customize endpoint methods.
1029
1030
1031Implementing Proxy Controller
1032~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1033
1034Sometimes you might need to relay some requests from the Dashboard frontend
1035directly to an external service.
1036For that purpose we provide a decorator called ``@Proxy``.
1037(As a concrete example, check the ``controllers/rgw.py`` file where we
1038implemented an RGW Admin Ops proxy.)
1039
1040
1041The ``@Proxy`` decorator is a wrapper of the ``@Endpoint`` decorator that
1042already customizes the endpoint for working as a proxy.
1043A proxy endpoint works by capturing the URL path that follows the controller
1044URL prefix path, and does not do any decoding of the request body.
1045
1046Example:
1047
1048.. code-block:: python
1049
1050 from ..tools import Controller, BaseController, Proxy
1051
1052 @Controller('/foo/proxy')
1053 class FooServiceProxy(BaseController):
1054
1055 @Proxy()
1056 def proxy(self, path, **params):
9f95a23c
TL
1057 """
1058 if requested URL is "/foo/proxy/access/service?opt=1"
1059 then path is "access/service" and params is {'opt': '1'}
1060 """
11fdf7f2
TL
1061
1062
1063How does the RESTController work?
1064~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1065
1066We also provide a simple mechanism to create REST based controllers using the
1067``RESTController`` class. Any class which inherits from ``RESTController`` will,
1068by default, return JSON.
1069
1070The ``RESTController`` is basically an additional abstraction layer which eases
1071and unifies the work with collections. A collection is just an array of objects
1072with a specific type. ``RESTController`` enables some default mappings of
1073request types and given parameters to specific method names. This may sound
1074complicated at first, but it's fairly easy. Lets have look at the following
1075example:
1076
1077.. code-block:: python
1078
1079 import cherrypy
1080 from ..tools import ApiController, RESTController
1081
1082 @ApiController('ping')
1083 class Ping(RESTController):
1084 def list(self):
1085 return {"msg": "Hello"}
1086
1087 def get(self, id):
1088 return self.objects[id]
1089
1090In this case, the ``list`` method is automatically used for all requests to
1091``api/ping`` where no additional argument is given and where the request type
1092is ``GET``. If the request is given an additional argument, the ID in our
1093case, it won't map to ``list`` anymore but to ``get`` and return the element
1094with the given ID (assuming that ``self.objects`` has been filled before). The
1095same applies to other request types:
1096
1097+--------------+------------+----------------+-------------+
1098| Request type | Arguments | Method | Status Code |
1099+==============+============+================+=============+
1100| GET | No | list | 200 |
1101+--------------+------------+----------------+-------------+
1102| PUT | No | bulk_set | 200 |
1103+--------------+------------+----------------+-------------+
1104| POST | No | create | 201 |
1105+--------------+------------+----------------+-------------+
1106| DELETE | No | bulk_delete | 204 |
1107+--------------+------------+----------------+-------------+
1108| GET | Yes | get | 200 |
1109+--------------+------------+----------------+-------------+
1110| PUT | Yes | set | 200 |
1111+--------------+------------+----------------+-------------+
1112| DELETE | Yes | delete | 204 |
1113+--------------+------------+----------------+-------------+
1114
1115How to use a custom API endpoint in a RESTController?
1116~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1117
1118If you don't have any access restriction you can use ``@Endpoint``. If you
1119have set a permission scope to restrict access to your endpoints,
1120``@Endpoint`` will fail, as it doesn't know which permission property should be
1121used. To use a custom endpoint inside a restricted ``RESTController`` use
1122``@RESTController.Collection`` instead. You can also choose
1123``@RESTController.Resource`` if you have set a ``RESOURCE_ID`` in your
1124``RESTController`` class.
1125
1126.. code-block:: python
1127
1128 import cherrypy
1129 from ..tools import ApiController, RESTController
1130
1131 @ApiController('ping', Scope.Ping)
1132 class Ping(RESTController):
1133 RESOURCE_ID = 'ping'
1134
1135 @RESTController.Resource('GET')
1136 def some_get_endpoint(self):
1137 return {"msg": "Hello"}
1138
1139 @RESTController.Collection('POST')
1140 def some_post_endpoint(self, **data):
1141 return {"msg": data}
1142
1143Both decorators also support four parameters to customize the
1144endpoint:
1145
1146* ``method="GET"``: the HTTP method allowed to access this endpoint.
1147* ``path="/<method_name>"``: the URL path of the endpoint, excluding the
1148 controller URL path prefix.
1149* ``status=200``: set the HTTP status response code
1150* ``query_params=[]``: list of method parameter names that correspond to URL
1151 query parameters.
1152
1153How to restrict access to a controller?
1154~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1155
1156All controllers require authentication by default.
1157If you require that the controller can be accessed without authentication,
1158then you can add the parameter ``secure=False`` to the controller decorator.
1159
1160Example:
1161
1162.. code-block:: python
1163
1164 import cherrypy
1165 from . import ApiController, RESTController
1166
1167
1168 @ApiController('ping', secure=False)
1169 class Ping(RESTController):
1170 def list(self):
1171 return {"msg": "Hello"}
1172
9f95a23c
TL
1173How to create a dedicated UI endpoint which uses the 'public' API?
1174~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1175
1176Sometimes we want to combine multiple calls into one single call
1177to save bandwidth or for other performance reasons.
1178In order to achieve that, we first have to create an ``@UiApiController`` which
1179is used for endpoints consumed by the UI but that are not part of the
1180'public' API. Let the ui class inherit from the REST controller class.
1181Now you can use all methods from the api controller.
1182
1183Example:
1184
1185.. code-block:: python
1186
1187 import cherrypy
1188 from . import UiApiController, ApiController, RESTController
1189
1190
1191 @ApiController('ping', secure=False) # /api/ping
1192 class Ping(RESTController):
1193 def list(self):
1194 return self._list()
1195
1196 def _list(self): # To not get in conflict with the JSON wrapper
1197 return [1,2,3]
1198
1199
1200 @UiApiController('ping', secure=False) # /ui-api/ping
1201 class PingUi(Ping):
1202 def list(self):
1203 return self._list() + [4, 5, 6]
11fdf7f2
TL
1204
1205How to access the manager module instance from a controller?
1206~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1207
1208We provide the manager module instance as a global variable that can be
9f95a23c 1209imported in any module.
11fdf7f2
TL
1210
1211Example:
1212
1213.. code-block:: python
1214
9f95a23c 1215 import logging
11fdf7f2 1216 import cherrypy
9f95a23c 1217 from .. import mgr
11fdf7f2
TL
1218 from ..tools import ApiController, RESTController
1219
9f95a23c 1220 logger = logging.getLogger(__name__)
11fdf7f2
TL
1221
1222 @ApiController('servers')
1223 class Servers(RESTController):
1224 def list(self):
1225 logger.debug('Listing available servers')
1226 return {'servers': mgr.list_servers()}
1227
1228
1229How to write a unit test for a controller?
1230~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1231
1232We provide a test helper class called ``ControllerTestCase`` to easily create
1233unit tests for your controller.
1234
1235If we want to write a unit test for the above ``Ping`` controller, create a
1236``test_ping.py`` file under the ``tests`` directory with the following code:
1237
1238.. code-block:: python
1239
1240 from .helper import ControllerTestCase
1241 from .controllers.ping import Ping
1242
1243
1244 class PingTest(ControllerTestCase):
1245 @classmethod
1246 def setup_test(cls):
1247 Ping._cp_config['tools.authenticate.on'] = False
1248 cls.setup_controllers([Ping])
1249
1250 def test_ping(self):
1251 self._get("/api/ping")
1252 self.assertStatus(200)
1253 self.assertJsonBody({'msg': 'Hello'})
1254
1255The ``ControllerTestCase`` class starts by initializing a CherryPy webserver.
1256Then it will call the ``setup_test()`` class method where we can explicitly
1257load the controllers that we want to test. In the above example we are only
1258loading the ``Ping`` controller. We can also disable authentication of a
1259controller at this stage, as depicted in the example.
1260
1261
1262How to listen for manager notifications in a controller?
1263~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1264
1265The manager notifies the modules of several types of cluster events, such
1266as cluster logging event, etc...
1267
1268Each module has a "global" handler function called ``notify`` that the manager
1269calls to notify the module. But this handler function must not block or spend
1270too much time processing the event notification.
1271For this reason we provide a notification queue that controllers can register
1272themselves with to receive cluster notifications.
1273
1274The example below represents a controller that implements a very simple live
1275log viewer page:
1276
1277.. code-block:: python
1278
1279 from __future__ import absolute_import
1280
1281 import collections
1282
1283 import cherrypy
1284
1285 from ..tools import ApiController, BaseController, NotificationQueue
1286
1287
1288 @ApiController('livelog')
1289 class LiveLog(BaseController):
1290 log_buffer = collections.deque(maxlen=1000)
1291
1292 def __init__(self):
1293 super(LiveLog, self).__init__()
1294 NotificationQueue.register(self.log, 'clog')
1295
1296 def log(self, log_struct):
1297 self.log_buffer.appendleft(log_struct)
1298
1299 @cherrypy.expose
1300 def default(self):
1301 ret = '<html><meta http-equiv="refresh" content="2" /><body>'
1302 for l in self.log_buffer:
1303 ret += "{}<br>".format(l)
1304 ret += "</body></html>"
1305 return ret
1306
1307As you can see above, the ``NotificationQueue`` class provides a register
1308method that receives the function as its first argument, and receives the
1309"notification type" as the second argument.
1310You can omit the second argument of the ``register`` method, and in that case
1311you are registering to listen all notifications of any type.
1312
1313Here is an list of notification types (these might change in the future) that
1314can be used:
1315
1316* ``clog``: cluster log notifications
1317* ``command``: notification when a command issued by ``MgrModule.send_command``
1318 completes
1319* ``perf_schema_update``: perf counters schema update
1320* ``mon_map``: monitor map update
1321* ``fs_map``: cephfs map update
1322* ``osd_map``: OSD map update
1323* ``service_map``: services (RGW, RBD-Mirror, etc.) map update
1324* ``mon_status``: monitor status regular update
1325* ``health``: health status regular update
1326* ``pg_summary``: regular update of PG status information
1327
1328
1329How to write a unit test when a controller accesses a Ceph module?
1330~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1331
1332Consider the following example that implements a controller that retrieves the
1333list of RBD images of the ``rbd`` pool:
1334
1335.. code-block:: python
1336
1337 import rbd
1338 from .. import mgr
1339 from ..tools import ApiController, RESTController
1340
1341
1342 @ApiController('rbdimages')
1343 class RbdImages(RESTController):
1344 def __init__(self):
1345 self.ioctx = mgr.rados.open_ioctx('rbd')
1346 self.rbd = rbd.RBD()
1347
1348 def list(self):
1349 return [{'name': n} for n in self.rbd.list(self.ioctx)]
1350
1351In the example above, we want to mock the return value of the ``rbd.list``
1352function, so that we can test the JSON response of the controller.
1353
1354The unit test code will look like the following:
1355
1356.. code-block:: python
1357
1358 import mock
1359 from .helper import ControllerTestCase
1360
1361
1362 class RbdImagesTest(ControllerTestCase):
1363 @mock.patch('rbd.RBD.list')
1364 def test_list(self, rbd_list_mock):
1365 rbd_list_mock.return_value = ['img1', 'img2']
1366 self._get('/api/rbdimages')
1367 self.assertJsonBody([{'name': 'img1'}, {'name': 'img2'}])
1368
1369
1370
1371How to add a new configuration setting?
1372~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1373
1374If you need to store some configuration setting for a new feature, we already
1375provide an easy mechanism for you to specify/use the new config setting.
1376
1377For instance, if you want to add a new configuration setting to hold the
1378email address of the dashboard admin, just add a setting name as a class
1379attribute to the ``Options`` class in the ``settings.py`` file::
1380
1381 # ...
1382 class Options(object):
1383 # ...
1384
1385 ADMIN_EMAIL_ADDRESS = ('admin@admin.com', str)
1386
1387The value of the class attribute is a pair composed by the default value for that
1388setting, and the python type of the value.
1389
1390By declaring the ``ADMIN_EMAIL_ADDRESS`` class attribute, when you restart the
1391dashboard module, you will automatically gain two additional CLI commands to
1392get and set that setting::
1393
1394 $ ceph dashboard get-admin-email-address
1395 $ ceph dashboard set-admin-email-address <value>
1396
1397To access, or modify the config setting value from your Python code, either
1398inside a controller or anywhere else, you just need to import the ``Settings``
1399class and access it like this:
1400
1401.. code-block:: python
1402
1403 from settings import Settings
1404
1405 # ...
1406 tmp_var = Settings.ADMIN_EMAIL_ADDRESS
1407
1408 # ....
1409 Settings.ADMIN_EMAIL_ADDRESS = 'myemail@admin.com'
1410
1411The settings management implementation will make sure that if you change a
1412setting value from the Python code you will see that change when accessing
1413that setting from the CLI and vice-versa.
1414
1415
1416How to run a controller read-write operation asynchronously?
1417~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1418
1419Some controllers might need to execute operations that alter the state of the
1420Ceph cluster. These operations might take some time to execute and to maintain
1421a good user experience in the Web UI, we need to run those operations
1422asynchronously and return immediately to frontend some information that the
1423operations are running in the background.
1424
1425To help in the development of the above scenario we added the support for
1426asynchronous tasks. To trigger the execution of an asynchronous task we must
1427use the following class method of the ``TaskManager`` class::
1428
1429 from ..tools import TaskManager
1430 # ...
1431 TaskManager.run(name, metadata, func, args, kwargs)
1432
1433* ``name`` is a string that can be used to group tasks. For instance
1434 for RBD image creation tasks we could specify ``"rbd/create"`` as the
1435 name, or similarly ``"rbd/remove"`` for RBD image removal tasks.
1436
1437* ``metadata`` is a dictionary where we can store key-value pairs that
1438 characterize the task. For instance, when creating a task for creating
1439 RBD images we can specify the metadata argument as
1440 ``{'pool_name': "rbd", image_name': "test-img"}``.
1441
1442* ``func`` is the python function that implements the operation code, which
1443 will be executed asynchronously.
1444
1445* ``args`` and ``kwargs`` are the positional and named arguments that will be
1446 passed to ``func`` when the task manager starts its execution.
1447
1448The ``TaskManager.run`` method triggers the asynchronous execution of function
1449``func`` and returns a ``Task`` object.
1450The ``Task`` provides the public method ``Task.wait(timeout)``, which can be
1451used to wait for the task to complete up to a timeout defined in seconds and
1452provided as an argument. If no argument is provided the ``wait`` method
1453blocks until the task is finished.
1454
1455The ``Task.wait`` is very useful for tasks that usually are fast to execute but
1456that sometimes may take a long time to run.
1457The return value of the ``Task.wait`` method is a pair ``(state, value)``
1458where ``state`` is a string with following possible values:
1459
1460* ``VALUE_DONE = "done"``
1461* ``VALUE_EXECUTING = "executing"``
1462
1463The ``value`` will store the result of the execution of function ``func`` if
1464``state == VALUE_DONE``. If ``state == VALUE_EXECUTING`` then
1465``value == None``.
1466
1467The pair ``(name, metadata)`` should unequivocally identify the task being
1468run, which means that if you try to trigger a new task that matches the same
1469``(name, metadata)`` pair of the currently running task, then the new task
1470is not created and you get the task object of the current running task.
1471
1472For instance, consider the following example:
1473
1474.. code-block:: python
1475
1476 task1 = TaskManager.run("dummy/task", {'attr': 2}, func)
1477 task2 = TaskManager.run("dummy/task", {'attr': 2}, func)
1478
1479If the second call to ``TaskManager.run`` executes while the first task is
1480still executing then it will return the same task object:
1481``assert task1 == task2``.
1482
1483
1484How to get the list of executing and finished asynchronous tasks?
1485~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1486
1487The list of executing and finished tasks is included in the ``Summary``
1488controller, which is already polled every 5 seconds by the dashboard frontend.
1489But we also provide a dedicated controller to get the same list of executing
1490and finished tasks.
1491
1492The ``Task`` controller exposes the ``/api/task`` endpoint that returns the
1493list of executing and finished tasks. This endpoint accepts the ``name``
1494parameter that accepts a glob expression as its value.
1495For instance, an HTTP GET request of the URL ``/api/task?name=rbd/*``
1496will return all executing and finished tasks which name starts with ``rbd/``.
1497
1498To prevent the finished tasks list from growing unbounded, we will always
1499maintain the 10 most recent finished tasks, and the remaining older finished
1500tasks will be removed when reaching a TTL of 1 minute. The TTL is calculated
1501using the timestamp when the task finished its execution. After a minute, when
1502the finished task information is retrieved, either by the summary controller or
1503by the task controller, it is automatically deleted from the list and it will
1504not be included in further task queries.
1505
1506Each executing task is represented by the following dictionary::
1507
1508 {
1509 'name': "name", # str
1510 'metadata': { }, # dict
1511 'begin_time': "2018-03-14T15:31:38.423605Z", # str (ISO 8601 format)
1512 'progress': 0 # int (percentage)
1513 }
1514
1515Each finished task is represented by the following dictionary::
1516
1517 {
1518 'name': "name", # str
1519 'metadata': { }, # dict
1520 'begin_time': "2018-03-14T15:31:38.423605Z", # str (ISO 8601 format)
1521 'end_time': "2018-03-14T15:31:39.423605Z", # str (ISO 8601 format)
1522 'duration': 0.0, # float
1523 'progress': 0 # int (percentage)
1524 'success': True, # bool
1525 'ret_value': None, # object, populated only if 'success' == True
1526 'exception': None, # str, populated only if 'success' == False
1527 }
1528
1529
1530How to use asynchronous APIs with asynchronous tasks?
1531~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1532
1533The ``TaskManager.run`` method as described in a previous section, is well
1534suited for calling blocking functions, as it runs the function inside a newly
1535created thread. But sometimes we want to call some function of an API that is
1536already asynchronous by nature.
1537
1538For these cases we want to avoid creating a new thread for just running a
1539non-blocking function, and want to leverage the asynchronous nature of the
1540function. The ``TaskManager.run`` is already prepared to be used with
1541non-blocking functions by passing an object of the type ``TaskExecutor`` as an
1542additional parameter called ``executor``. The full method signature of
1543``TaskManager.run``::
1544
1545 TaskManager.run(name, metadata, func, args=None, kwargs=None, executor=None)
1546
1547
1548The ``TaskExecutor`` class is responsible for code that executes a given task
1549function, and defines three methods that can be overridden by
1550subclasses::
1551
1552 def init(self, task)
1553 def start(self)
1554 def finish(self, ret_value, exception)
1555
1556The ``init`` method is called before the running the task function, and
1557receives the task object (of class ``Task``).
1558
1559The ``start`` method runs the task function. The default implementation is to
1560run the task function in the current thread context.
1561
1562The ``finish`` method should be called when the task function finishes with
1563either the ``ret_value`` populated with the result of the execution, or with
1564an exception object in the case that execution raised an exception.
1565
1566To leverage the asynchronous nature of a non-blocking function, the developer
1567should implement a custom executor by creating a subclass of the
1568``TaskExecutor`` class, and provide an instance of the custom executor class
1569as the ``executor`` parameter of the ``TaskManager.run``.
1570
1571To better understand the expressive power of executors, we write a full example
1572of use a custom executor to execute the ``MgrModule.send_command`` asynchronous
1573function:
1574
1575.. code-block:: python
1576
1577 import json
1578 from mgr_module import CommandResult
1579 from .. import mgr
1580 from ..tools import ApiController, RESTController, NotificationQueue, \
1581 TaskManager, TaskExecutor
1582
1583
1584 class SendCommandExecutor(TaskExecutor):
1585 def __init__(self):
1586 super(SendCommandExecutor, self).__init__()
1587 self.tag = None
1588 self.result = None
1589
1590 def init(self, task):
1591 super(SendCommandExecutor, self).init(task)
1592
1593 # we need to listen for 'command' events to know when the command
1594 # finishes
1595 NotificationQueue.register(self._handler, 'command')
1596
1597 # store the CommandResult object to retrieve the results
1598 self.result = self.task.fn_args[0]
1599 if len(self.task.fn_args) > 4:
1600 # the user specified a tag for the command, so let's use it
1601 self.tag = self.task.fn_args[4]
1602 else:
1603 # let's generate a unique tag for the command
1604 self.tag = 'send_command_{}'.format(id(self))
1605 self.task.fn_args.append(self.tag)
1606
1607 def _handler(self, data):
1608 if data == self.tag:
1609 # the command has finished, notifying the task with the result
1610 self.finish(self.result.wait(), None)
1611 # deregister listener to avoid memory leaks
1612 NotificationQueue.deregister(self._handler, 'command')
1613
1614
1615 @ApiController('test')
1616 class Test(RESTController):
1617
1618 def _run_task(self, osd_id):
1619 task = TaskManager.run("test/task", {}, mgr.send_command,
1620 [CommandResult(''), 'osd', osd_id,
1621 json.dumps({'prefix': 'perf histogram dump'})],
1622 executor=SendCommandExecutor())
1623 return task.wait(1.0)
1624
1625 def get(self, osd_id):
1626 status, value = self._run_task(osd_id)
1627 return {'status': status, 'value': value}
1628
1629
1630The above ``SendCommandExecutor`` executor class can be used for any call to
1631``MgrModule.send_command``. This means that we should need just one custom
1632executor class implementation for each non-blocking API that we use in our
1633controllers.
1634
1635The default executor, used when no executor object is passed to
1636``TaskManager.run``, is the ``ThreadedExecutor``. You can check its
1637implementation in the ``tools.py`` file.
1638
1639
1640How to update the execution progress of an asynchronous task?
1641~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1642
1643The asynchronous tasks infrastructure provides support for updating the
1644execution progress of an executing task.
1645The progress can be updated from within the code the task is executing, which
1646usually is the place where we have the progress information available.
1647
1648To update the progress from within the task code, the ``TaskManager`` class
1649provides a method to retrieve the current task object::
1650
1651 TaskManager.current_task()
1652
1653The above method is only available when using the default executor
1654``ThreadedExecutor`` for executing the task.
1655The ``current_task()`` method returns the current ``Task`` object. The
1656``Task`` object provides two public methods to update the execution progress
1657value: the ``set_progress(percentage)``, and the ``inc_progress(delta)``
1658methods.
1659
1660The ``set_progress`` method receives as argument an integer value representing
1661the absolute percentage that we want to set to the task.
1662
1663The ``inc_progress`` method receives as argument an integer value representing
1664the delta we want to increment to the current execution progress percentage.
1665
1666Take the following example of a controller that triggers a new task and
1667updates its progress:
1668
1669.. code-block:: python
1670
1671 from __future__ import absolute_import
1672 import random
1673 import time
1674 import cherrypy
1675 from ..tools import TaskManager, ApiController, BaseController
1676
1677
1678 @ApiController('dummy_task')
1679 class DummyTask(BaseController):
1680 def _dummy(self):
1681 top = random.randrange(100)
1682 for i in range(top):
1683 TaskManager.current_task().set_progress(i*100/top)
1684 # or TaskManager.current_task().inc_progress(100/top)
1685 time.sleep(1)
1686 return "finished"
1687
1688 @cherrypy.expose
1689 @cherrypy.tools.json_out()
1690 def default(self):
1691 task = TaskManager.run("dummy/task", {}, self._dummy)
1692 return task.wait(5) # wait for five seconds
1693
1694
1695How to deal with asynchronous tasks in the front-end?
1696~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1697
1698All executing and most recently finished asynchronous tasks are displayed on
1699"Background-Tasks" and if finished on "Recent-Notifications" in the menu bar.
1700For each task a operation name for three states (running, success and failure),
1701a function that tells who is involved and error descriptions, if any, have to
1702be provided. This can be achieved by appending
1703``TaskManagerMessageService.messages``. This has to be done to achieve
1704consistency among all tasks and states.
1705
1706Operation Object
1707 Ensures consistency among all tasks. It consists of three verbs for each
1708 different state f.e.
1709 ``{running: 'Creating', failure: 'create', success: 'Created'}``.
1710
1711#. Put running operations in present participle f.e. ``'Updating'``.
1712#. Failed messages always start with ``'Failed to '`` and should be continued
1713 with the operation in present tense f.e. ``'update'``.
1714#. Put successful operations in past tense f.e. ``'Updated'``.
1715
1716Involves Function
1717 Ensures consistency among all messages of a task, it resembles who's
1718 involved by the operation. It's a function that returns a string which
1719 takes the metadata from the task to return f.e.
1720 ``"RBD 'somePool/someImage'"``.
1721
1722Both combined create the following messages:
1723
1724* Failure => ``"Failed to create RBD 'somePool/someImage'"``
1725* Running => ``"Creating RBD 'somePool/someImage'"``
1726* Success => ``"Created RBD 'somePool/someImage'"``
1727
1728For automatic task handling use ``TaskWrapperService.wrapTaskAroundCall``.
1729
1730If for some reason ``wrapTaskAroundCall`` is not working for you,
1731you have to subscribe to your asynchronous task manually through
1732``TaskManagerService.subscribe``, and provide it with a callback,
1733in case of a success to notify the user. A notification can
1734be triggered with ``NotificationService.notifyTask``. It will use
1735``TaskManagerMessageService.messages`` to display a message based on the state
1736of a task.
1737
1738Notifications of API errors are handled by ``ApiInterceptorService``.
1739
1740Usage example:
1741
1742.. code-block:: javascript
1743
1744 export class TaskManagerMessageService {
1745 // ...
1746 messages = {
1747 // Messages for task 'rbd/create'
1748 'rbd/create': new TaskManagerMessage(
1749 // Message prefixes
1750 ['create', 'Creating', 'Created'],
1751 // Message suffix
1752 (metadata) => `RBD '${metadata.pool_name}/${metadata.image_name}'`,
1753 (metadata) => ({
1754 // Error code and description
1755 '17': `Name is already used by RBD '${metadata.pool_name}/${
1756 metadata.image_name}'.`
1757 })
1758 ),
1759 // ...
1760 };
1761 // ...
1762 }
1763
1764 export class RBDFormComponent {
1765 // ...
1766 createAction() {
1767 const request = this.createRequest();
1768 // Subscribes to 'call' with submitted 'task' and handles notifications
1769 return this.taskWrapper.wrapTaskAroundCall({
1770 task: new FinishedTask('rbd/create', {
1771 pool_name: request.pool_name,
1772 image_name: request.name
1773 }),
1774 call: this.rbdService.create(request)
1775 });
1776 }
1777 // ...
1778 }
1779
1780
1781REST API documentation
1782~~~~~~~~~~~~~~~~~~~~~~
1783There is an automatically generated Swagger UI page for documentation of the REST
1784API endpoints.However, by default it is not very detailed. There are two
1785decorators that can be used to add more information:
1786
1787* ``@EndpointDoc()`` for documentation of endpoints. It has four optional arguments
9f95a23c
TL
1788 (explained below): ``description``, ``group``, ``parameters`` and
1789 ``responses``.
494da23a 1790* ``@ControllerDoc()`` for documentation of controller or group associated with
9f95a23c
TL
1791 the endpoints. It only takes the two first arguments: ``description`` and
1792 ``group``.
11fdf7f2
TL
1793
1794
1795``description``: A a string with a short (1-2 sentences) description of the object.
1796
1797
1798``group``: By default, an endpoint is grouped together with other endpoints
1799within the same controller class. ``group`` is a string that can be used to
494da23a 1800assign an endpoint or all endpoints in a class to another controller or a
11fdf7f2
TL
1801conceived group name.
1802
1803
1804``parameters``: A dict used to describe path, query or request body parameters.
1805By default, all parameters for an endpoint are listed on the Swagger UI page,
1806including information of whether the parameter is optional/required and default
1807values. However, there will be no description of the parameter and the parameter
1808type will only be displayed in some cases.
1809When adding information, each parameters should be described as in the example
1810below. Note that the parameter type should be expressed as a built-in python
1811type and not as a string. Allowed values are ``str``, ``int``, ``bool``, ``float``.
1812
1813.. code-block:: python
1814
1815 @EndpointDoc(parameters={'my_string': (str, 'Description of my_string')})
9f95a23c 1816 def method(my_string): pass
11fdf7f2
TL
1817
1818For body parameters, more complex cases are possible. If the parameter is a
1819dictionary, the type should be replaced with a ``dict`` containing its nested
1820parameters. When describing nested parameters, the same format as other
1821parameters is used. However, all nested parameters are set as required by default.
1822If the nested parameter is optional this must be specified as for ``item2`` in
1823the example below. If a nested parameters is set to optional, it is also
1824possible to specify the default value (this will not be provided automatically
1825for nested parameters).
1826
1827.. code-block:: python
1828
1829 @EndpointDoc(parameters={
1830 'my_dictionary': ({
1831 'item1': (str, 'Description of item1'),
1832 'item2': (str, 'Description of item2', True), # item2 is optional
1833 'item3': (str, 'Description of item3', True, 'foo'), # item3 is optional with 'foo' as default value
1834 }, 'Description of my_dictionary')})
9f95a23c 1835 def method(my_dictionary): pass
494da23a 1836
11fdf7f2
TL
1837If the parameter is a ``list`` of primitive types, the type should be
1838surrounded with square brackets.
1839
1840.. code-block:: python
1841
1842 @EndpointDoc(parameters={'my_list': ([int], 'Description of my_list')})
9f95a23c 1843 def method(my_list): pass
11fdf7f2
TL
1844
1845If the parameter is a ``list`` with nested parameters, the nested parameters
1846should be placed in a dictionary and surrounded with square brackets.
1847
1848.. code-block:: python
1849
1850 @EndpointDoc(parameters={
1851 'my_list': ([{
1852 'list_item': (str, 'Description of list_item'),
1853 'list_item2': (str, 'Description of list_item2')
1854 }], 'Description of my_list')})
9f95a23c 1855 def method(my_list): pass
11fdf7f2
TL
1856
1857
1858``responses``: A dict used for describing responses. Rules for describing
1859responses are the same as for request body parameters, with one difference:
1860responses also needs to be assigned to the related response code as in the
1861example below:
1862
1863.. code-block:: python
1864
1865 @EndpointDoc(responses={
9f95a23c
TL
1866 '400':{'my_response': (str, 'Description of my_response')}})
1867 def method(): pass
11fdf7f2
TL
1868
1869
1870Error Handling in Python
1871~~~~~~~~~~~~~~~~~~~~~~~~
1872
1873Good error handling is a key requirement in creating a good user experience
1874and providing a good API.
1875
1876Dashboard code should not duplicate C++ code. Thus, if error handling in C++
1877is sufficient to provide good feedback, a new wrapper to catch these errors
1878is not necessary. On the other hand, input validation is the best place to
1879catch errors and generate the best error messages. If required, generate
1880errors as soon as possible.
1881
1882The backend provides few standard ways of returning errors.
1883
1884First, there is a generic Internal Server Error::
1885
1886 Status Code: 500
1887 {
1888 "version": <cherrypy version, e.g. 13.1.0>,
1889 "detail": "The server encountered an unexpected condition which prevented it from fulfilling the request.",
1890 }
1891
1892
1893For errors generated by the backend, we provide a standard error
1894format::
1895
1896 Status Code: 400
1897 {
1898 "detail": str(e), # E.g. "[errno -42] <some error message>"
1899 "component": "rbd", # this can be null to represent a global error code
1900 "code": "3", # Or a error name, e.g. "code": "some_error_key"
1901 }
1902
1903
1904In case, the API Endpoints uses @ViewCache to temporarily cache results,
1905the error looks like so::
1906
1907 Status Code 400
1908 {
1909 "detail": str(e), # E.g. "[errno -42] <some error message>"
1910 "component": "rbd", # this can be null to represent a global error code
1911 "code": "3", # Or a error name, e.g. "code": "some_error_key"
1912 'status': 3, # Indicating the @ViewCache error status
1913 }
1914
1915In case, the API Endpoints uses a task the error looks like so::
1916
1917 Status Code 400
1918 {
1919 "detail": str(e), # E.g. "[errno -42] <some error message>"
1920 "component": "rbd", # this can be null to represent a global error code
1921 "code": "3", # Or a error name, e.g. "code": "some_error_key"
1922 "task": { # Information about the task itself
1923 "name": "taskname",
1924 "metadata": {...}
1925 }
1926 }
1927
1928
1929Our WebUI should show errors generated by the API to the user. Especially
1930field-related errors in wizards and dialogs or show non-intrusive notifications.
1931
1932Handling exceptions in Python should be an exception. In general, we
1933should have few exception handlers in our project. Per default, propagate
1934errors to the API, as it will take care of all exceptions anyway. In general,
1935log the exception by adding ``logger.exception()`` with a description to the
1936handler.
1937
1938We need to distinguish between user errors from internal errors and
1939programming errors. Using different exception types will ease the
1940task for the API layer and for the user interface:
1941
1942Standard Python errors, like ``SystemError``, ``ValueError`` or ``KeyError``
1943will end up as internal server errors in the API.
1944
1945In general, do not ``return`` error responses in the REST API. They will be
1946returned by the error handler. Instead, raise the appropriate exception.
1947
1948Plug-ins
1949~~~~~~~~
1950
1951New functionality can be provided by means of a plug-in architecture. Among the
1952benefits this approach brings in, loosely coupled development is one of the most
1953notable. As the Ceph Dashboard grows in feature richness, its code-base becomes
1954more and more complex. The hook-based nature of a plug-in architecture allows to
1955extend functionality in a controlled manner, and isolate the scope of the
1956changes.
1957
1958Ceph Dashboard relies on `Pluggy <https://pluggy.readthedocs.io>`_ to provide
1959for plug-ing support. On top of pluggy, an interface-based approach has been
1960implemented, with some safety checks (method override and abstract method
1961checks).
1962
1963In order to create a new plugin, the following steps are required:
1964
1965#. Add a new file under ``src/pybind/mgr/dashboard/plugins``.
1966#. Import the ``PLUGIN_MANAGER`` instance and the ``Interfaces``.
92f5a8d4
TL
1967#. Create a class extending the desired interfaces. The plug-in library will
1968 check if all the methods of the interfaces have been properly overridden.
11fdf7f2 1969#. Register the plugin in the ``PLUGIN_MANAGER`` instance.
92f5a8d4
TL
1970#. Import the plug-in from within the Ceph Dashboard ``module.py`` (currently no
1971 dynamic loading is implemented).
11fdf7f2 1972
92f5a8d4 1973The available Mixins (helpers) are:
11fdf7f2
TL
1974
1975- ``CanMgr``: provides the plug-in with access to the ``mgr`` instance under ``self.mgr``.
92f5a8d4
TL
1976
1977The available Interfaces are:
1978
1979- ``Initializable``: requires overriding ``init()`` hook. This method is run at
1980 the very beginning of the dashboard module, right after all imports have been
1981 performed.
1982- ``Setupable``: requires overriding ``setup()`` hook. This method is run in the
1983 Ceph Dashboard ``serve()`` method, right after CherryPy has been configured,
1984 but before it is started. It's a placeholder for the plug-in initialization
1985 logic.
1986- ``HasOptions``: requires overriding ``get_options()`` hook by returning a list
1987 of ``Options()``. The options returned here are added to the
1988 ``MODULE_OPTIONS``.
1989- ``HasCommands``: requires overriding ``register_commands()`` hook by defining
1990 the commands the plug-in can handle and decorating them with ``@CLICommand``.
1991 The commands can be optionally returned, so that they can be invoked
1992 externally (which makes unit testing easier).
1993- ``HasControllers``: requires overriding ``get_controllers()`` hook by defining
1994 and returning the controllers as usual.
1995- ``FilterRequest.BeforeHandler``: requires overriding
1996 ``filter_request_before_handler()`` hook. This method receives a
1997 ``cherrypy.request`` object for processing. A usual implementation of this
9f95a23c 1998 method will allow some requests to pass or will raise a ``cherrypy.HTTPError``
92f5a8d4 1999 based on the ``request`` metadata and other conditions.
11fdf7f2
TL
2000
2001New interfaces and hooks should be added as soon as they are required to
2002implement new functionality. The above list only comprises the hooks needed for
2003the existing plugins.
2004
2005A sample plugin implementation would look like this:
2006
2007.. code-block:: python
2008
2009 # src/pybind/mgr/dashboard/plugins/mute.py
2010
2011 from . import PLUGIN_MANAGER as PM
2012 from . import interfaces as I
2013
2014 from mgr_module import CLICommand, Option
2015 import cherrypy
2016
2017 @PM.add_plugin
9f95a23c
TL
2018 class Mute(I.CanMgr, I.Setupable, I.HasOptions, I.HasCommands,
2019 I.FilterRequest.BeforeHandler, I.HasControllers):
11fdf7f2
TL
2020 @PM.add_hook
2021 def get_options(self):
2022 return [Option('mute', default=False, type='bool')]
2023
2024 @PM.add_hook
2025 def setup(self):
92f5a8d4 2026 self.mute = self.mgr.get_module_option('mute')
11fdf7f2
TL
2027
2028 @PM.add_hook
2029 def register_commands(self):
2030 @CLICommand("dashboard mute")
2031 def _(mgr):
2032 self.mute = True
92f5a8d4 2033 self.mgr.set_module_option('mute', True)
11fdf7f2
TL
2034 return 0
2035
2036 @PM.add_hook
2037 def filter_request_before_handler(self, request):
2038 if self.mute:
2039 raise cherrypy.HTTPError(500, "I'm muted :-x")
31f18b77 2040
11fdf7f2
TL
2041 @PM.add_hook
2042 def get_controllers(self):
2043 from ..controllers import ApiController, RESTController
31f18b77 2044
11fdf7f2
TL
2045 @ApiController('/mute')
2046 class MuteController(RESTController):
2047 def get(_):
2048 return self.mute
31f18b77 2049
92f5a8d4
TL
2050 return [MuteController]
2051
2052
2053Additionally, a helper for creating plugins ``SimplePlugin`` is provided. It
2054facilitates the basic tasks (Options, Commands, and common Mixins). The previous
2055plugin could be rewritten like this:
2056
2057.. code-block:: python
9f95a23c 2058
92f5a8d4
TL
2059 from . import PLUGIN_MANAGER as PM
2060 from . import interfaces as I
2061 from .plugin import SimplePlugin as SP
2062
2063 import cherrypy
2064
2065 @PM.add_plugin
2066 class Mute(SP, I.Setupable, I.FilterRequest.BeforeHandler, I.HasControllers):
2067 OPTIONS = [
2068 SP.Option('mute', default=False, type='bool')
2069 ]
2070
2071 def shut_up(self):
2072 self.set_option('mute', True)
2073 self.mute = True
2074 return 0
2075
2076 COMMANDS = [
2077 SP.Command("dashboard mute", handler=shut_up)
2078 ]
2079
2080 @PM.add_hook
2081 def setup(self):
2082 self.mute = self.get_option('mute')
2083
2084 @PM.add_hook
2085 def filter_request_before_handler(self, request):
2086 if self.mute:
2087 raise cherrypy.HTTPError(500, "I'm muted :-x")
2088
2089 @PM.add_hook
2090 def get_controllers(self):
2091 from ..controllers import ApiController, RESTController
2092
2093 @ApiController('/mute')
2094 class MuteController(RESTController):
2095 def get(_):
2096 return self.mute
2097
2098 return [MuteController]
2099
2100