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