]> git.proxmox.com Git - ceph.git/blob - ceph/doc/dev/developer_guide/dash-devel.rst
add stop-gap to fix compat with CPUs not supporting SSE 4.1
[ceph.git] / ceph / doc / dev / developer_guide / dash-devel.rst
1 .. _dashdevel:
2
3 Ceph Dashboard Developer Documentation
4 ======================================
5
6 .. contents:: Table of Contents
7
8 Feature Design
9 --------------
10
11 To promote collaboration on new Ceph Dashboard features, the first step is
12 the definition of a design document. These documents then form the basis of
13 implementation scope and permit wider participation in the evolution of the
14 Ceph Dashboard UI.
15
16 .. toctree::
17 :maxdepth: 1
18 :caption: Design Documents:
19
20 UI Design Goals <../dashboard/ui_goals>
21
22
23 Preliminary Steps
24 -----------------
25
26 The following documentation chapters expect a running Ceph cluster and at
27 least a running ``dashboard`` manager module (with few exceptions). This
28 chapter gives an introduction on how to set up such a system for development,
29 without the need to set up a full-blown production environment. All options
30 introduced in this chapter are based on a so called ``vstart`` environment.
31
32 .. note::
33
34 Every ``vstart`` environment needs Ceph `to be compiled`_ from its GitHub
35 repository, though Docker environments simplify that step by providing a
36 shell script that contains those instructions.
37
38 One exception to this rule are the `build-free`_ capabilities of
39 `ceph-dev`_. See below for more information.
40
41 .. _to be compiled: https://docs.ceph.com/docs/master/install/build-ceph/
42
43 vstart
44 ~~~~~~
45
46 "vstart" is actually a shell script in the ``src/`` directory of the Ceph
47 repository (``src/vstart.sh``). It is used to start a single node Ceph
48 cluster on the machine where it is executed. Several required and some
49 optional Ceph internal services are started automatically when it is used to
50 start a Ceph cluster. vstart is the basis for the three most commonly used
51 development environments in Ceph Dashboard.
52
53 You can read more about vstart in :ref:`Deploying a development cluster
54 <dev_deploying_a_development_cluster>`. Additional information for developers
55 can also be found in the `Developer Guide`_.
56
57 .. _Developer Guide: https://docs.ceph.com/docs/master/dev/quick_guide/
58
59 Host-based vs Docker-based Development Environments
60 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
61
62 This document introduces you to three different development environments, all
63 based on vstart. Those are:
64
65 - vstart running on your host system
66
67 - vstart running in a Docker environment
68
69 * ceph-dev-docker_
70 * ceph-dev_
71
72 Besides their independent development branches and sometimes slightly
73 different approaches, they also differ with respect to their underlying
74 operating systems.
75
76 ========= ====================== ========
77 Release ceph-dev-docker ceph-dev
78 ========= ====================== ========
79 Mimic openSUSE Leap 15 CentOS 7
80 Nautilus openSUSE Leap 15 CentOS 7
81 Octopus openSUSE Leap 15.2 CentOS 8
82 --------- ---------------------- --------
83 Master openSUSE Tumbleweed CentOS 8
84 ========= ====================== ========
85
86 .. note::
87
88 Independently of which of these environments you will choose, you need to
89 compile Ceph in that environment. If you compiled Ceph on your host system,
90 you would have to recompile it on Docker to be able to switch to a Docker
91 based solution. The same is true vice versa. If you previously used a
92 Docker development environment and compiled Ceph there and you now want to
93 switch to your host system, you will also need to recompile Ceph (or
94 compile Ceph using another separate repository).
95
96 `ceph-dev`_ is an exception to this rule as one of the options it provides
97 is `build-free`_. This is accomplished through a Ceph installation using
98 RPM system packages. You will still be able to work with a local GitHub
99 repository like you are used to.
100
101
102 Development environment on your host system
103 ...........................................
104
105 - No need to learn or have experience with Docker, jump in right away.
106
107 - Limited amount of scripts to support automation (like Ceph compilation).
108
109 - No pre-configured easy-to-start services (Prometheus, Grafana, etc).
110
111 - Limited amount of host operating systems supported, depending on which
112 Ceph version is supposed to be used.
113
114 - Dependencies need to be installed on your host.
115
116 - You might find yourself in the situation where you need to upgrade your
117 host operating system (for instance due to a change of the GCC version used
118 to compile Ceph).
119
120
121 Development environments based on Docker
122 ........................................
123
124 - Some overhead in learning Docker if you are not used to it yet.
125
126 - Both Docker projects provide you with scripts that help you getting started
127 and automate recurring tasks.
128
129 - Both Docker environments come with partly pre-configured external services
130 which can be used to attach to or complement Ceph Dashboard features, like
131
132 - Prometheus
133 - Grafana
134 - Node-Exporter
135 - Shibboleth
136 - HAProxy
137
138 - Works independently of the operating system you use on your host.
139
140
141 .. _build-free: https://github.com/rhcs-dashboard/ceph-dev#quick-install-rpm-based
142
143 vstart on your host system
144 ~~~~~~~~~~~~~~~~~~~~~~~~~~
145
146 The vstart script is usually called from your `build/` directory like so:
147
148 .. code::
149
150 ../src/vstart.sh -n -d
151
152 In this case ``-n`` ensures that a new vstart cluster is created and that a
153 possibly previously created cluster isn't re-used. ``-d`` enables debug
154 messages in log files. There are several more options to chose from. You can
155 get a list using the ``--help`` argument.
156
157 At the end of the output of vstart, there should be information about the
158 dashboard and its URLs::
159
160 vstart cluster complete. Use stop.sh to stop. See out/* (e.g. 'tail -f out/????') for debug output.
161
162 dashboard urls: https://192.168.178.84:41259, https://192.168.178.84:43259, https://192.168.178.84:45259
163 w/ user/pass: admin / admin
164 restful urls: https://192.168.178.84:42259, https://192.168.178.84:44259, https://192.168.178.84:46259
165 w/ user/pass: admin / 598da51f-8cd1-4161-a970-b2944d5ad200
166
167 During development (especially in backend development), you also want to
168 check on occasions if the dashboard manager module is still running. To do so
169 you can call `./bin/ceph mgr services` manually. It will list all the URLs of
170 successfully enabled services. Only URLs of services which are available over
171 HTTP(S) will be listed there. Ceph Dashboard is one of these services. It
172 should look similar to the following output:
173
174 .. code::
175
176 $ ./bin/ceph mgr services
177 {
178 "dashboard": "https://home:41931/",
179 "restful": "https://home:42931/"
180 }
181
182 By default, this environment uses a randomly chosen port for Ceph Dashboard
183 and you need to use this command to find out which one it has become.
184
185 Docker
186 ~~~~~~
187
188 Docker development environments usually ship with a lot of useful scripts.
189 ``ceph-dev-docker`` for instance contains a file called `start-ceph.sh`,
190 which cleans up log files, always starts a Rados Gateway service, sets some
191 Ceph Dashboard configuration options and automatically runs a frontend proxy,
192 all before or after starting up your vstart cluster.
193
194 Instructions on how to use those environments are contained in their
195 respective repository README files.
196
197 - ceph-dev-docker_
198 - ceph-dev_
199
200 .. _ceph-dev-docker: https://github.com/ricardoasmarques/ceph-dev-docker
201 .. _ceph-dev: https://github.com/rhcs-dashboard/ceph-dev
202
203 Frontend Development
204 --------------------
205
206 Before you can start the dashboard from within a development environment, you
207 will need to generate the frontend code and either use a compiled and running
208 Ceph cluster (e.g. started by ``vstart.sh``) or the standalone development web
209 server.
210
211 The build process is based on `Node.js <https://nodejs.org/>`_ and requires the
212 `Node Package Manager <https://www.npmjs.com/>`_ ``npm`` to be installed.
213
214 Prerequisites
215 ~~~~~~~~~~~~~
216
217 * Node 14.15.0 or higher
218 * NPM 6.14.9 or higher
219
220 nodeenv:
221 During Ceph's build we create a virtualenv with ``node`` and ``npm``
222 installed, which can be used as an alternative to installing node/npm in your
223 system.
224
225 If you want to use the node installed in the virtualenv you just need to
226 activate the virtualenv before you run any npm commands. To activate it run
227 ``. build/src/pybind/mgr/dashboard/node-env/bin/activate``.
228
229 Once you finish, you can simply run ``deactivate`` and exit the virtualenv.
230
231 Angular CLI:
232 If you do not have the `Angular CLI <https://github.com/angular/angular-cli>`_
233 installed globally, then you need to execute ``ng`` commands with an
234 additional ``npm run`` before it.
235
236 Package installation
237 ~~~~~~~~~~~~~~~~~~~~
238
239 Run ``npm ci`` in directory ``src/pybind/mgr/dashboard/frontend`` to
240 install the required packages locally.
241
242 Adding or updating packages
243 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
244
245 Run the following commands to add/update a package::
246
247 npm install <PACKAGE_NAME>
248 npm ci
249
250 Setting up a Development Server
251 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
252
253 Create the ``proxy.conf.json`` file based on ``proxy.conf.json.sample``.
254
255 Run ``npm start`` for a dev server.
256 Navigate to ``http://localhost:4200/``. The app will automatically
257 reload if you change any of the source files.
258
259 Code Scaffolding
260 ~~~~~~~~~~~~~~~~
261
262 Run ``ng generate component component-name`` to generate a new
263 component. You can also use
264 ``ng generate directive|pipe|service|class|guard|interface|enum|module``.
265
266 Build the Project
267 ~~~~~~~~~~~~~~~~~
268
269 Run ``npm run build`` to build the project. The build artifacts will be
270 stored in the ``dist/`` directory. Use the ``--prod`` flag for a
271 production build (``npm run build -- --prod``). Navigate to ``https://localhost:8443``.
272
273 Build the Code Documentation
274 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
275
276 Run ``npm run doc-build`` to generate code docs in the ``documentation/``
277 directory. To make them accessible locally for a web browser, run
278 ``npm run doc-serve`` and they will become available at ``http://localhost:8444``.
279 With ``npm run compodoc -- <opts>`` you may
280 `fully configure it <https://compodoc.app/guides/usage.html>`_.
281
282 Code linting and formatting
283 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
284
285 We use the following tools to lint and format the code in all our TS, SCSS and
286 HTML files:
287
288 - `codelyzer <http://codelyzer.com/>`_
289 - `html-linter <https://github.com/chinchiheather/html-linter>`_
290 - `htmllint-cli <https://github.com/htmllint/htmllint-cli>`_
291 - `Prettier <https://prettier.io/>`_
292 - `ESLint <https://eslint.org/>`_
293 - `stylelint <https://stylelint.io/>`_
294
295 We added 2 npm scripts to help run these tools:
296
297 - ``npm run lint``, will check frontend files against all linters
298 - ``npm run fix``, will try to fix all the detected linting errors
299
300 Ceph Dashboard and Bootstrap
301 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
302
303 Currently we are using Bootstrap on the Ceph Dashboard as a CSS framework. This means that most of our SCSS and HTML
304 code can make use of all the utilities and other advantages Bootstrap is offering. In the past we often have used our
305 own custom styles and this lead to more and more variables with a single use and double defined variables which
306 sometimes are forgotten to be removed or it led to styling be inconsistent because people forgot to change a color or to
307 adjust a custom SCSS class.
308
309 To get the current version of Bootstrap used inside Ceph please refer to the ``package.json`` and search for:
310
311 - ``bootstrap``: For the Bootstrap version used.
312 - ``@ng-bootstrap``: For the version of the Angular bindings which we are using.
313
314 So for the future please do the following when visiting a component:
315
316 - Does this HTML/SCSS code use custom code? - If yes: Is it needed? --> Clean it up before changing the things you want
317 to fix or change.
318 - If you are creating a new component: Please make use of Bootstrap as much as reasonably possible! Don't try to
319 reinvent the wheel.
320 - If possible please look up if Bootstrap has guidelines on how to extend it properly to do achieve what you want to
321 achieve.
322
323 The more bootstrap alike our code is the easier it is to theme, to maintain and the less bugs we will have. Also since
324 Bootstrap is a framework which tries to have usability and user experience in mind we increase both points
325 exponentially. The biggest benefit of all is that there is less code for us to maintain which makes it easier to read
326 for beginners and even more easy for people how are already familiar with the code.
327
328 Writing Unit Tests
329 ~~~~~~~~~~~~~~~~~~
330
331 To write unit tests most efficient we have a small collection of tools,
332 we use within test suites.
333
334 Those tools can be found under
335 ``src/pybind/mgr/dashboard/frontend/src/testing/``, especially take
336 a look at ``unit-test-helper.ts``.
337
338 There you will be able to find:
339
340 ``configureTestBed`` that replaces the initial ``TestBed``
341 methods. It takes the same arguments as ``TestBed.configureTestingModule``.
342 Using it will run your tests a lot faster in development, as it doesn't
343 recreate everything from scratch on every test. To use the default behaviour
344 pass ``true`` as the second argument.
345
346 ``PermissionHelper`` to help determine if
347 the correct actions are shown based on the current permissions and selection
348 in a list.
349
350 ``FormHelper`` which makes testing a form a lot easier
351 with a few simple methods. It allows you to set a control or multiple
352 controls, expect if a control is valid or has an error or just do both with
353 one method. Additional you can expect a template element or multiple elements
354 to be visible in the rendered template.
355
356 Running Unit Tests
357 ~~~~~~~~~~~~~~~~~~
358
359 Run ``npm run test`` to execute the unit tests via `Jest
360 <https://facebook.github.io/jest/>`_.
361
362 If you get errors on all tests, it could be because `Jest
363 <https://facebook.github.io/jest/>`__ or something else was updated.
364 There are a few ways how you can try to resolve this:
365
366 - Remove all modules with ``rm -rf dist node_modules`` and run ``npm install``
367 again in order to reinstall them
368 - Clear the cache of jest by running ``npx jest --clearCache``
369
370 Running End-to-End (E2E) Tests
371 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
372
373 We use `Cypress <https://www.cypress.io/>`__ to run our frontend E2E tests.
374
375 E2E Prerequisites
376 .................
377
378 You need to previously build the frontend.
379
380 In some environments, depending on your user permissions and the CYPRESS_CACHE_FOLDER,
381 you might need to run ``npm ci`` with the ``--unsafe-perm`` flag.
382
383 You might need to install additional packages to be able to run Cypress.
384 Please run ``npx cypress verify`` to verify it.
385
386 run-frontend-e2e-tests.sh
387 .........................
388
389 Our ``run-frontend-e2e-tests.sh`` script is the go to solution when you wish to
390 do a full scale e2e run.
391 It will verify if everything needed is installed, start a new vstart cluster
392 and run the full test suite.
393
394 Start all frontend E2E tests with::
395
396 $ cd src/pybind/mgr/dashboard
397 $ ./run-frontend-e2e-tests.sh
398
399 Report:
400 You can follow the e2e report on the terminal and you can find the screenshots
401 of failed test cases by opening the following directory::
402
403 src/pybind/mgr/dashboard/frontend/cypress/screenshots/
404
405 Device:
406 You can force the script to use a specific device with the ``-d`` flag::
407
408 $ ./run-frontend-e2e-tests.sh -d <chrome|chromium|electron|docker>
409
410 Remote:
411 By default this script will stop and start a new vstart cluster.
412 If you want to run the tests outside the ceph environment, you will need to
413 manually define the dashboard url using ``-r`` and, optionally, credentials
414 (``-u``, ``-p``)::
415
416 $ ./run-frontend-e2e-tests.sh -r <DASHBOARD_URL> -u <E2E_LOGIN_USER> -p <E2E_LOGIN_PWD>
417
418 Note:
419 When using docker, as your device, you might need to run the script with sudo
420 permissions.
421
422 run-cephadm-e2e-tests.sh
423 .........................
424
425 ``run-cephadm-e2e-tests.sh`` runs a subset of E2E tests to verify that the Dashboard and cephadm as
426 Orchestrator backend behave correctly.
427
428 Prerequisites: you need to install `KCLI
429 <https://kcli.readthedocs.io/en/latest/>`_ and Node.js in your local machine.
430
431 Configure KCLI plan requirements::
432
433 $ sudo chown -R $(id -un) /var/lib/libvirt/images
434 $ mkdir -p /var/lib/libvirt/images/ceph-dashboard
435 $ kcli create pool -p /var/lib/libvirt/images/ceph-dashboard ceph-dashboard
436 $ kcli create network -c 192.168.100.0/24 ceph-dashboard
437
438 Note:
439 This script is aimed to be run as jenkins job so the cleanup is triggered only in a jenkins
440 environment. In local, the user will shutdown the cluster when desired (i.e. after debugging).
441
442 Start E2E tests by running::
443
444 $ cd <your/ceph/repo/dir>
445 $ sudo chown -R $(id -un) src/pybind/mgr/dashboard/frontend/{dist,node_modules,src/environments}
446 $ ./src/pybind/mgr/dashboard/ci/cephadm/run-cephadm-e2e-tests.sh
447
448 Note:
449 In fedora 35, there can occur a permission error when trying to mount the shared_folders. This can be
450 fixed by running::
451
452 $ sudo setfacl -R -m u:qemu:rwx <abs-path-to-your-user-home>
453
454 or also by setting the appropriate permission to your $HOME directory
455
456 You can also start a cluster in development mode (so the frontend build starts in watch mode and you
457 only have to reload the page for the changes to be reflected) by running::
458
459 $ ./src/pybind/mgr/dashboard/ci/cephadm/start-cluster.sh --dev-mode
460
461 Note:
462 Add ``--expanded`` if you need a cluster ready to deploy services (one with enough monitor
463 daemons spread across different hosts and enough OSDs).
464
465 Test your changes by running:
466
467 $ ./src/pybind/mgr/dashboard/ci/cephadm/run-cephadm-e2e-tests.sh
468
469 Shutdown the cluster by running:
470
471 $ kcli delete plan -y ceph
472 $ # In development mode, also kill the npm build watch process (e.g., pkill -f "ng build")
473
474 Other running options
475 .....................
476
477 During active development, it is not recommended to run the previous script,
478 as it is not prepared for constant file changes.
479 Instead you should use one of the following commands:
480
481 - ``npm run e2e`` - This will run ``ng serve`` and open the Cypress Test Runner.
482 - ``npm run e2e:ci`` - This will run ``ng serve`` and run the Cypress Test Runner once.
483 - ``npx cypress run`` - This calls cypress directly and will run the Cypress Test Runner.
484 You need to have a running frontend server.
485 - ``npx cypress open`` - This calls cypress directly and will open the Cypress Test Runner.
486 You need to have a running frontend server.
487
488 Calling Cypress directly has the advantage that you can use any of the available
489 `flags <https://docs.cypress.io/guides/guides/command-line.html#cypress-run>`__
490 to customize your test run and you don't need to start a frontend server each time.
491
492 Using one of the ``open`` commands, will open a cypress application where you
493 can see all the test files you have and run each individually.
494 This is going to be run in watch mode, so if you make any changes to test files,
495 it will retrigger the test run.
496 This cannot be used inside docker, as it requires X11 environment to be able to open.
497
498 By default Cypress will look for the web page at ``https://localhost:4200/``.
499 If you are serving it in a different URL you will need to configure it by
500 exporting the environment variable CYPRESS_BASE_URL with the new value.
501 E.g.: ``CYPRESS_BASE_URL=https://localhost:41076/ npx cypress open``
502
503 CYPRESS_CACHE_FOLDER
504 .....................
505
506 When installing cypress via npm, a binary of the cypress app will also be
507 downloaded and stored in a cache folder.
508 This removes the need to download it every time you run ``npm ci`` or even when
509 using cypress in a separate project.
510
511 By default Cypress uses ~/.cache to store the binary.
512 To prevent changes to the user home directory, we have changed this folder to
513 ``/ceph/build/src/pybind/mgr/dashboard/cypress``, so when you build ceph or run
514 ``run-frontend-e2e-tests.sh`` this is the directory Cypress will use.
515
516 When using any other command to install or run cypress,
517 it will go back to the default directory. It is recommended that you export the
518 CYPRESS_CACHE_FOLDER environment variable with a fixed directory, so you always
519 use the same directory no matter which command you use.
520
521
522 Writing End-to-End Tests
523 ~~~~~~~~~~~~~~~~~~~~~~~~
524
525 The PagerHelper class
526 .....................
527
528 The ``PageHelper`` class is supposed to be used for general purpose code that
529 can be used on various pages or suites.
530
531 Examples are
532
533 - ``navigateTo()`` - Navigates to a specific page and waits for it to load
534 - ``getFirstTableCell()`` - returns the first table cell. You can also pass a
535 string with the desired content and it will return the first cell that
536 contains it.
537 - ``getTabsCount()`` - returns the amount of tabs
538
539 Every method that could be useful on several pages belongs there. Also, methods
540 which enhance the derived classes of the PageHelper belong there. A good
541 example for such a case is the ``restrictTo()`` decorator. It ensures that a
542 method implemented in a subclass of PageHelper is called on the correct page.
543 It will also show a developer-friendly warning if this is not the case.
544
545 Subclasses of PageHelper
546 ........................
547
548 Helper Methods
549 """"""""""""""
550
551 In order to make code reusable which is specific for a particular suite, make
552 sure to put it in a derived class of the ``PageHelper``. For instance, when
553 talking about the pool suite, such methods would be ``create()``, ``exist()``
554 and ``delete()``. These methods are specific to a pool but are useful for other
555 suites.
556
557 Methods that return HTML elements which can only be found on a specific page,
558 should be either implemented in the helper methods of the subclass of PageHelper
559 or as own methods of the subclass of PageHelper.
560
561 Using PageHelpers
562 """""""""""""""""
563
564 In any suite, an instance of the specific ``Helper`` class should be
565 instantiated and called directly.
566
567 .. code:: TypeScript
568
569 const pools = new PoolPageHelper();
570
571 it('should create a pool', () => {
572 pools.exist(poolName, false);
573 pools.navigateTo('create');
574 pools.create(poolName, 8);
575 pools.exist(poolName, true);
576 });
577
578 Code Style
579 ..........
580
581 Please refer to the official `Cypress Core Concepts
582 <https://docs.cypress.io/guides/core-concepts/introduction-to-cypress.html#Cypress-Can-Be-Simple-Sometimes>`__
583 for a better insight on how to write and structure tests.
584
585 ``describe()`` vs ``it()``
586 """"""""""""""""""""""""""
587
588 Both ``describe()`` and ``it()`` are function blocks, meaning that any
589 executable code necessary for the test can be contained in either block.
590 However, Typescript scoping rules still apply, therefore any variables declared
591 in a ``describe`` are available to the ``it()`` blocks inside of it.
592
593 ``describe()`` typically are containers for tests, allowing you to break tests
594 into multiple parts. Likewise, any setup that must be made before your tests are
595 run can be initialized within the ``describe()`` block. Here is an example:
596
597 .. code:: TypeScript
598
599 describe('create, edit & delete image test', () => {
600 const poolName = 'e2e_images_pool';
601
602 before(() => {
603 cy.login();
604 pools.navigateTo('create');
605 pools.create(poolName, 8, 'rbd');
606 pools.exist(poolName, true);
607 });
608
609 beforeEach(() => {
610 cy.login();
611 images.navigateTo();
612 });
613
614 //...
615
616 });
617
618 As shown, we can initiate the variable ``poolName`` as well as run commands
619 before our test suite begins (creating a pool). ``describe()`` block messages
620 should include what the test suite is.
621
622 ``it()`` blocks typically are parts of an overarching test. They contain the
623 functionality of the test suite, each performing individual roles.
624 Here is an example:
625
626 .. code:: TypeScript
627
628 describe('create, edit & delete image test', () => {
629 //...
630
631 it('should create image', () => {
632 images.createImage(imageName, poolName, '1');
633 images.getFirstTableCell(imageName).should('exist');
634 });
635
636 it('should edit image', () => {
637 images.editImage(imageName, poolName, newImageName, '2');
638 images.getFirstTableCell(newImageName).should('exist');
639 });
640
641 //...
642 });
643
644 As shown from the previous example, our ``describe()`` test suite is to create,
645 edit and delete an image. Therefore, each ``it()`` completes one of these steps,
646 one for creating, one for editing, and so on. Likewise, every ``it()`` blocks
647 message should be in lowercase and written so long as "it" can be the prefix of
648 the message. For example, ``it('edits the test image' () => ...)`` vs.
649 ``it('image edit test' () => ...)``. As shown, the first example makes
650 grammatical sense with ``it()`` as the prefix whereas the second message does
651 not. ``it()`` should describe what the individual test is doing and what it
652 expects to happen.
653
654
655 Visual Regression Testing
656 ~~~~~~~~~~~~~~~~~~~~~~~~~
657
658 For visual regression testing, we use `Applitools Eyes <https://applitools.com/products-eyes/>`_
659 an AI powered automated visual regression testing tool.
660 Applitools integrates with our existing Cypress E2E tests.
661 The tests currently are located at: ``ceph/src/pybind/mgr/dashboard/frontend/cypress/integration/visualTests`` and
662 follow the naming convention: ``<component-name>.vrt-spec.ts``.
663
664 Running Visual Regression Tests Locally
665 .......................................
666
667 To run the tests locally, you'll need an Applitools API key, if you don't have one, you can sign up
668 for a free account. After obtaining the API key, export it as an environment variable: ``APPLITOOLS_API_KEY``.
669
670 Now you can run the tests like normal cypress E2E tests, using either ``npx cypress open`` or in headless mode by running ``npx cypress run``.
671
672 Capturing Screenshots
673 .....................
674
675 Baseline screenshots are the screenshots against which checkpoint screenshots
676 (or the screenshots from your feature branch) will be tested.
677
678 To capture baseline screenshots, you can run the tests against the master branch,
679 and then switch to your feature branch and run the tests again to capture checkpoint screenshots.
680
681 Now to see your screenshots, login to applitools.com and on the landing page you'll be greeted with
682 applitools eyes test runner, where you can see all your screenshots. And if there's any visual regression or difference (diff) between your baseline and checkpoint screenshots, they'll be highlighted with a mask over the diff.
683
684 Writing More Visual Regression Tests
685 ....................................
686
687 Please refer to `Applitools's official cypress sdk documentation <https://www.npmjs.com/package/@applitools/eyes-cypress#usage>`_ to write more tests.
688
689 Visual Regression Tests In Jenkins
690 ..................................
691
692 Currently, all visual regression tests are being run under `ceph dashboard tests <https://jenkins.ceph.com/job/ceph-dashboard-pull-requests>`_ GitHub check in the Jenkins job.
693
694 Accepting or Rejecting Differences
695 ..................................
696
697 Currently, only the ceph dashboard team has read and write access to the applitools test runner. If any differences are reported by the tests, and you want to accept them and update the baseline screenshots, or if the differences are due to a genuine regression you can fail them. To perform the above actions, please follow `this <https://applitools.com/docs/topics/test-manager/pages/page-test-results/tm-accepting-and-rejecting-steps.html>`_ guide.
698
699 Debugging Regressions
700 .....................
701
702 If you're running the tests locally and regressions are reported, you can take advantage of `Applitools's Root Cause Analysis feature <https://applitools.com/docs/topics/test-manager/viewers/root-cause-analysis.html>`_ to find the cause of the regression.
703
704
705 Differences between Frontend Unit Tests and End-to-End (E2E) Tests / FAQ
706 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
707
708 General introduction about testing and E2E/unit tests
709
710
711 What are E2E/unit tests designed for?
712 .....................................
713
714 E2E test:
715
716 It requires a fully functional system and tests the interaction of all components
717 of the application (Ceph, back-end, front-end).
718 E2E tests are designed to mimic the behavior of the user when interacting with the application
719 - for example when it comes to workflows like creating/editing/deleting an item.
720 Also the tests should verify that certain items are displayed as a user would see them
721 when clicking through the UI (for example a menu entry or a pool that has been
722 created during a test and the pool and its properties should be displayed in the table).
723
724 Angular Unit Tests:
725
726 Unit tests, as the name suggests, are tests for smaller units of the code.
727 Those tests are designed for testing all kinds of Angular components (e.g. services, pipes etc.).
728 They do not require a connection to the backend, hence those tests are independent of it.
729 The expected data of the backend is mocked in the frontend and by using this data
730 the functionality of the frontend can be tested without having to have real data from the backend.
731 As previously mentioned, data is either mocked or, in a simple case, contains a static input,
732 a function call and an expected static output.
733 More complex examples include the state of a component (attributes of the component class),
734 that define how the output changes according to the given input.
735
736 Which E2E/unit tests are considered to be valid?
737 ................................................
738
739 This is not easy to answer, but new tests that are written in the same way as already existing
740 dashboard tests should generally be considered valid.
741 Unit tests should focus on the component to be tested.
742 This is either an Angular component, directive, service, pipe, etc.
743
744 E2E tests should focus on testing the functionality of the whole application.
745 Approximately a third of the overall E2E tests should verify the correctness
746 of user visible elements.
747
748 How should an E2E/unit test look like?
749 ......................................
750
751 Unit tests should focus on the described purpose
752 and shouldn't try to test other things in the same `it` block.
753
754 E2E tests should contain a description that either verifies
755 the correctness of a user visible element or a complete process
756 like for example the creation/validation/deletion of a pool.
757
758 What should an E2E/unit test cover?
759 ...................................
760
761 E2E tests should mostly, but not exclusively, cover interaction with the backend.
762 This way the interaction with the backend is utilized to write integration tests.
763
764 A unit test should mostly cover critical or complex functionality
765 of a component (Angular Components, Services, Pipes, Directives, etc).
766
767 What should an E2E/unit test NOT cover?
768 .......................................
769
770 Avoid duplicate testing: do not write E2E tests for what's already
771 been covered as frontend-unit tests and vice versa.
772 It may not be possible to completely avoid an overlap.
773
774 Unit tests should not be used to extensively click through components and E2E tests
775 shouldn't be used to extensively test a single component of Angular.
776
777 Best practices/guideline
778 ........................
779
780 As a general guideline we try to follow the 70/20/10 approach - 70% unit tests,
781 20% integration tests and 10% end-to-end tests.
782 For further information please refer to `this document
783 <https://testing.googleblog.com/2015/04/just-say-no-to-more-end-to-end-tests.html>`__
784 and the included "Testing Pyramid".
785
786 Further Help
787 ~~~~~~~~~~~~
788
789 To get more help on the Angular CLI use ``ng help`` or go check out the
790 `Angular CLI
791 README <https://github.com/angular/angular-cli/blob/master/README.md>`__.
792
793 Example of a Generator
794 ~~~~~~~~~~~~~~~~~~~~~~
795
796 ::
797
798 # Create module 'Core'
799 src/app> ng generate module core -m=app --routing
800
801 # Create module 'Auth' under module 'Core'
802 src/app/core> ng generate module auth -m=core --routing
803 or, alternatively:
804 src/app> ng generate module core/auth -m=core --routing
805
806 # Create component 'Login' under module 'Auth'
807 src/app/core/auth> ng generate component login -m=core/auth
808 or, alternatively:
809 src/app> ng generate component core/auth/login -m=core/auth
810
811 Frontend Typescript Code Style Guide Recommendations
812 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
813
814 Group the imports based on its source and separate them with a blank
815 line.
816
817 The source groups can be either from Angular, external or internal.
818
819 Example:
820
821 .. code:: javascript
822
823 import { Component } from '@angular/core';
824 import { Router } from '@angular/router';
825
826 import { ToastrManager } from 'ngx-toastr';
827
828 import { Credentials } from '../../../shared/models/credentials.model';
829 import { HostService } from './services/host.service';
830
831 Frontend components
832 ~~~~~~~~~~~~~~~~~~~
833
834 There are several components that can be reused on different pages.
835 This components are declared on the components module:
836 `src/pybind/mgr/dashboard/frontend/src/app/shared/components`.
837
838 Helper
839 ~~~~~~
840
841 This component should be used to provide additional information to the user.
842
843 Example:
844
845 .. code:: html
846
847 <cd-helper>
848 Some <strong>helper</strong> html text
849 </cd-helper>
850
851 Terminology and wording
852 ~~~~~~~~~~~~~~~~~~~~~~~
853
854 Instead of using the Ceph component names, the approach
855 suggested is to use the logical/generic names (Block over RBD, Filesystem over
856 CephFS, Object over RGW). Nevertheless, as Ceph-Dashboard cannot completely hide
857 the Ceph internals, some Ceph-specific names might remain visible.
858
859 Regarding the wording for action labels and other textual elements (form titles,
860 buttons, etc.), the chosen approach is to follow `these guidelines
861 <https://www.patternfly.org/styles/terminology-and-wording/#terminology-and-wording-for-action-labels>`_.
862 As a rule of thumb, 'Create' and 'Delete' are the proper wording for most forms,
863 instead of 'Add' and 'Remove', unless some already created item is either added
864 or removed to/from a set of items (e.g.: 'Add permission' to a user vs. 'Create
865 (new) permission').
866
867 In order to enforce the use of this wording, a service ``ActionLabelsI18n`` has
868 been created, which provides translated labels for use in UI elements.
869
870 Frontend branding
871 ~~~~~~~~~~~~~~~~~
872
873 Every vendor can customize the 'Ceph dashboard' to his needs. No matter if
874 logo, HTML-Template or TypeScript, every file inside the frontend folder can be
875 replaced.
876
877 To replace files, open ``./frontend/angular.json`` and scroll to the section
878 ``fileReplacements`` inside the production configuration. Here you can add the
879 files you wish to brand. We recommend to place the branded version of a file in
880 the same directory as the original one and to add a ``.brand`` to the file
881 name, right in front of the file extension. A ``fileReplacement`` could for
882 example look like this:
883
884 .. code:: javascript
885
886 {
887 "replace": "src/app/core/auth/login/login.component.html",
888 "with": "src/app/core/auth/login/login.component.brand.html"
889 }
890
891 To serve or build the branded user interface run:
892
893 $ npm run start -- --prod
894
895 or
896
897 $ npm run build -- --prod
898
899 Unfortunately it's currently not possible to use multiple configurations when
900 serving or building the UI at the same time. That means a configuration just
901 for the branding ``fileReplacements`` is not an option, because you want to use
902 the production configuration anyway
903 (https://github.com/angular/angular-cli/issues/10612).
904 Furthermore it's also not possible to use glob expressions for
905 ``fileReplacements``. As long as the feature hasn't been implemented, you have
906 to add the file replacements manually to the angular.json file
907 (https://github.com/angular/angular-cli/issues/12354).
908
909 Nevertheless you should stick to the suggested naming scheme because it makes
910 it easier for you to use glob expressions once it's supported in the future.
911
912 To change the variable defaults or add your own ones you can overwrite them in
913 ``./frontend/src/styles/vendor/_variables.scss``.
914 Just reassign the variable you want to change, for example ``$color-primary: teal;``
915 To overwrite or extend the default CSS, you can add your own styles in
916 ``./frontend/src/styles/vendor/_style-overrides.scss``.
917
918 UI Style Guide
919 ~~~~~~~~~~~~~~
920
921 The style guide is created to document Ceph Dashboard standards and maintain
922 consistency across the project. Its an effort to make it easier for
923 contributors to process designing and deciding mockups and designs for
924 Dashboard.
925
926 The development environment for Ceph Dashboard has live reloading enabled so
927 any changes made in UI are reflected in open browser windows. Ceph Dashboard
928 uses Bootstrap as the main third-party CSS library.
929
930 Avoid duplication of code. Be consistent with the existing UI by reusing
931 existing SCSS declarations as much as possible.
932
933 Always check for existing code similar to what you want to write.
934 You should always try to keep the same look-and-feel as the existing code.
935
936 Colors
937 ......
938
939 All the colors used in Ceph Dashboard UI are listed in
940 `frontend/src/styles/defaults/_bootstrap-defaults.scss`. If using new color
941 always define color variables in the `_bootstrap-defaults.scss` and
942 use the variable instead of hard coded color values so that changes to the
943 color are reflected in similar UI elements.
944
945 The main color for the Ceph Dashboard is `$primary`. The primary color is
946 used in navigation components and as the `$border-color` for input components of
947 form.
948
949 The secondary color is `$secondary` and is the background color for Ceph
950 Dashboard.
951
952 Buttons
953 .......
954
955 Buttons are used for performing actions such as: “Submit”, “Edit, “Create" and
956 “Update”.
957
958 **Forms:** When using to submit forms anywhere in the Dashboard, the main action
959 button should use the `cd-submit-button` component and the secondary button should
960 use `cd-back-button` component. The text on the action button should be same as the
961 form title and follow a title case. The text on the secondary button should be
962 `Cancel`. `Perform action` button should always be on right while `Cancel`
963 button should always be on left.
964
965 **Modals**: The main action button should use the `cd-submit-button` component and
966 the secondary button should use `cd-back-button` component. The text on the action
967 button should follow a title case and correspond to the action to be performed.
968 The text on the secondary button should be `Close`.
969
970 **Disclosure Button:** Disclosure buttons should be used to allow users to
971 display and hide additional content in the interface.
972
973 **Action Button**: Use the action button to perform actions such as edit or update
974 a component. All action button should have an icon corresponding to the actions they
975 perform and button text should follow title case. The button color should be the
976 same as the form's main button color.
977
978 **Drop Down Buttons:** Use dropdown buttons to display predefined lists of
979 actions. All drop down buttons have icons corresponding to the action they
980 perform.
981
982 Links
983 .....
984
985 Use text hyperlinks as navigation to guide users to a new page in the application
986 or to anchor users to a section within a page. The color of the hyperlinks
987 should be `$primary`.
988
989 Forms
990 .....
991
992 Mark invalid form fields with red outline and show a meaningful error message.
993 Use red as font color for message and be as specific as possible.
994 `This field is required.` should be the exact error message for required fields.
995 Mark valid forms with a green outline and a green tick at the end of the form.
996 Sections should not have a bigger header than the parent.
997
998 Modals
999 ......
1000
1001 Blur any interface elements in the background to bring the modal content into
1002 focus. The heading of the modal should reflect the action it can perform and
1003 should be clearly mentioned at the top of the modal. Use `cd-back-button`
1004 component in the footer for closing the modal.
1005
1006 Icons
1007 .....
1008
1009 We use `Fork Awesome <https://forkaweso.me/Fork-Awesome/>`_ classes for icons.
1010 We have a list of used icons in `src/app/shared/enum/icons.enum.ts`, these
1011 should be referenced in the HTML, so its easier to change them later. When
1012 icons are next to text, they should be center-aligned horizontally. If icons
1013 are stacked, they should also be center-aligned vertically. Use small icons
1014 with buttons. For notifications use large icons.
1015
1016 Navigation
1017 ..........
1018
1019 For local navigation use tabs. For overall navigation use expandable vertical
1020 navigation to collapse and expand items as needed.
1021
1022 Alerts and notifications
1023 ........................
1024
1025 Default notification should have `text-info` color. Success notification should
1026 have `text-success` color. Failure notification should have `text-danger` color.
1027
1028 Error Handling
1029 ~~~~~~~~~~~~~~
1030
1031 For handling front-end errors, there is a generic Error Component which can be
1032 found in ``./src/pybind/mgr/dashboard/frontend/src/app/core/error``. For
1033 reporting a new error, you can simply extend the ``DashboardError`` class
1034 in ``error.ts`` file and add specific header and message for the new error. Some
1035 generic error classes are already in place such as ``DashboardNotFoundError``
1036 and ``DashboardForbiddenError`` which can be called and reused in different
1037 scenarios.
1038
1039 For example - ``throw new DashboardNotFoundError()``.
1040
1041 Internationalization (i18n)
1042 ---------------------------
1043
1044 How to extract messages from source code?
1045 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1046
1047 To extract the I18N messages from the templates and the TypeScript files just
1048 run the following command in ``src/pybind/mgr/dashboard/frontend``::
1049
1050 $ npm run i18n:extract
1051
1052 This will extract all marked messages from the HTML templates first and then
1053 add all marked strings from the TypeScript files to the translation template.
1054 Since the extraction from TypeScript files is still not supported by Angular
1055 itself, we are using the
1056 `ngx-translator <https://github.com/ngx-translate/i18n-polyfill>`_ extractor to
1057 parse the TypeScript files.
1058
1059 When the command ran successfully, it should have created or updated the file
1060 ``src/locale/messages.xlf``.
1061
1062 The file isn't tracked by git, you can just use it to start with the
1063 translation offline or add/update the resource files on transifex.
1064
1065 Supported languages
1066 ~~~~~~~~~~~~~~~~~~~
1067
1068 All our supported languages should be registered in both exports in
1069 ``supported-languages.enum.ts`` and have a corresponding test in
1070 ``language-selector.component.spec.ts``.
1071
1072 The ``SupportedLanguages`` enum will provide the list for the default language selection.
1073
1074 Translating process
1075 ~~~~~~~~~~~~~~~~~~~
1076
1077 To facilitate the translation process of the dashboard we are using a web tool
1078 called `transifex <https://www.transifex.com/>`_.
1079
1080 If you wish to help translating to any language just go to our `transifex
1081 project page <https://www.transifex.com/ceph/ceph-dashboard/>`_, join the
1082 project and you can start translating immediately.
1083
1084 All translations will then be reviewed and later pushed upstream.
1085
1086 Updating translated messages
1087 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1088
1089 Any time there are new messages translated and reviewed in a specific language
1090 we should update the translation file upstream.
1091
1092 To do that, check the settings in the i18n config file
1093 ``src/pybind/mgr/dashboard/frontend/i18n.config.json``:: and make sure that the
1094 organization is *ceph*, the project is *ceph-dashboard* and the resource is
1095 the one you want to pull from and push to e.g. *Master:master*. To find a list
1096 of available resources visit `<https://www.transifex.com/ceph/ceph-dashboard/content/>`_.
1097
1098 After you checked the config go to the directory ``src/pybind/mgr/dashboard/frontend`` and run::
1099
1100 $ npm run i18n
1101
1102 This command will extract all marked messages from the HTML templates and
1103 TypeScript files. Once the source file has been created it will push it to
1104 transifex and pull the latest translations. It will also fill all the
1105 untranslated strings with the source string.
1106 The tool will ask you for an api token, unless you added it by running:
1107
1108 $ npm run i18n:token
1109
1110 To create a transifex api token visit `<https://www.transifex.com/user/settings/api/>`_.
1111
1112 After the command ran successfully, build the UI and check if everything is
1113 working as expected. You also might want to run the frontend tests.
1114
1115 Add a new release resource to transifex
1116 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1117
1118 In order to organize the translations, we create a
1119 `transifex resource <https://www.transifex.com/ceph/ceph-dashboard/content/>`_
1120 for every Ceph release. This means, once a new version has been released, the
1121 ``src/pybind/mgr/dashboard/frontend/i18n.config.json`` needs to be updated on
1122 the release branch.
1123
1124 Please replace::
1125
1126 "resource": "Master:master"
1127
1128 by::
1129
1130 "resource": "<Release-name>:<release-name>"
1131
1132 E.g. the resource definition for the pacific release::
1133
1134 "resource": "Pacific:pacific"
1135
1136 Note:
1137 The first part of the resource definition (before the colon) needs to be
1138 written with a capital letter.
1139
1140 Suggestions
1141 ~~~~~~~~~~~
1142
1143 Strings need to start and end in the same line as the element:
1144
1145 .. code-block:: html
1146
1147 <!-- avoid -->
1148 <span i18n>
1149 Foo
1150 </span>
1151
1152 <!-- recommended -->
1153 <span i18n>Foo</span>
1154
1155
1156 <!-- avoid -->
1157 <span i18n>
1158 Foo bar baz.
1159 Foo bar baz.
1160 </span>
1161
1162 <!-- recommended -->
1163 <span i18n>Foo bar baz.
1164 Foo bar baz.</span>
1165
1166 Isolated interpolations should not be translated:
1167
1168 .. code-block:: html
1169
1170 <!-- avoid -->
1171 <span i18n>{{ foo }}</span>
1172
1173 <!-- recommended -->
1174 <span>{{ foo }}</span>
1175
1176 Interpolations used in a sentence should be kept in the translation:
1177
1178 .. code-block:: html
1179
1180 <!-- recommended -->
1181 <span i18n>There are {{ x }} OSDs.</span>
1182
1183 Remove elements that are outside the context of the translation:
1184
1185 .. code-block:: html
1186
1187 <!-- avoid -->
1188 <label i18n>
1189 Profile
1190 <span class="required"></span>
1191 </label>
1192
1193 <!-- recommended -->
1194 <label>
1195 <ng-container i18n>Profile<ng-container>
1196 <span class="required"></span>
1197 </label>
1198
1199 Keep elements that affect the sentence:
1200
1201 .. code-block:: html
1202
1203 <!-- recommended -->
1204 <span i18n>Profile <b>foo</b> will be removed.</span>
1205
1206
1207 .. _accessibility:
1208
1209 Accessibility
1210 -------------
1211
1212 Many parts of the Ceph Dashboard are modeled on `Web Content Accessibility Guidelines (WCAG) 2.1 <https://www.w3.org/TR/WCAG21/>`_ level A accessibility conformance guidelines.
1213 By implementing accessibility best practices, you are improving the usability of the Ceph Dashboard for blind and visually impaired users.
1214
1215 Summary
1216 ~~~~~~~
1217
1218 A few things you should check before introducing a new code change include:
1219
1220 1) Add `ARIA labels and descriptions <https://www.w3.org/TR/wai-aria/>`_ to actionable HTML elements.
1221 2) Don't forget to tag ARIA labels/descriptions or any user-readable text for translation (i18n-title, i18n-aria-label...).
1222 3) Add `ARIA roles <https://www.w3.org/TR/wai-aria/#usage_intro>`_ to tag HTML elements that behave different from their intended behaviour (<a> tags behaving as <buttons>) or that provide extended behaviours (roles).
1223 4) Avoid poor `color contrast choices <https://www.w3.org/TR/WCAG21/#contrast-minimum>`_ (foreground-background) when styling a component. Here are some :ref:`tools <color-contrast-checkers>` you can use.
1224 5) When testing menus or dropdowns, be sure to scan them with an :ref:`accessibility checker <accessibility-checkers>` in both opened and closed states. Sometimes issues are hidden when menus are closed.
1225
1226 .. _accessibility-checkers:
1227
1228 Accessibility checkers
1229 ~~~~~~~~~~~~~~~~~~~~~~
1230
1231 During development, you can test the accessibility compliance of your features using one of the tools below:
1232
1233 - `Accessibility insights plugin <https://accessibilityinsights.io/downloads/>`_
1234 - `Site Improve plugin <https://www.siteimprove.com/integrations/browser-extensions/>`_
1235 - `Axe devtools <https://www.deque.com/axe/devtools/>`_
1236
1237 Testing with two or more of these tools can greatly improve the detection of accessibility violations.
1238
1239 .. _color-contrast-checkers:
1240
1241 Color contrast checkers
1242 ~~~~~~~~~~~~~~~~~~~~~~~
1243
1244 When adding new colors, making sure they are accessible is also important. Here are some tools which can help with color contrast testing:
1245
1246 - `Accessible web color-contrast checker <https://accessibleweb.com/color-contrast-checker/>`_
1247 - `Colorsafe generator <https://colorsafe.co/>`_
1248
1249 Accessibility linters
1250 ~~~~~~~~~~~~~~~~~~~~~
1251
1252 If you use VSCode, you may install the `axe accessibility linter <https://marketplace.visualstudio.com/items?itemName=deque-systems.vscode-axe-linter>`_,
1253 which can help you catch and fix potential issues during development.
1254
1255 Accessibility testing
1256 ~~~~~~~~~~~~~~~~~~~~~
1257
1258 Our e2e testing suite, which is based on Cypress, supports the addition of accessibility tests using `axe-core <https://github.com/dequelabs/axe-core>`_
1259 and `cypress-axe <https://github.com/component-driven/cypress-axe>`_. A custom Cypress command, `cy.checkAccessibility`, can also be used directly.
1260 This is a great way to prevent accessibility regressions on high impact components.
1261
1262 Tests can be found under the `a11y folder <./src/pybind/mgr/dashboard/frontend/cypress/integration/a11y>`_ in the dashboard. Here is an example:
1263
1264 .. code:: TypeScript
1265
1266 describe('Navigation accessibility', { retries: 0 }, () => {
1267 const shared = new NavigationPageHelper();
1268
1269 beforeEach(() => {
1270 cy.login();
1271 shared.navigateTo();
1272 });
1273
1274 it('top-nav should have no accessibility violations', () => {
1275 cy.injectAxe();
1276 cy.checkAccessibility('.cd-navbar-top');
1277 });
1278
1279 it('sidebar should have no accessibility violations', () => {
1280 cy.injectAxe();
1281 cy.checkAccessibility('nav[id=sidebar]');
1282 });
1283
1284 });
1285
1286 Additional guidelines
1287 ~~~~~~~~~~~~~~~~~~~~~
1288
1289 If you're unsure about which UI pattern to follow in order to implement an accessibility fix, `patternfly <https://www.patternfly.org/v4/accessibility/accessibility-fundamentals>`_ guidelines can be used.
1290
1291 Backend Development
1292 -------------------
1293
1294 The Python backend code of this module requires a number of Python modules to be
1295 installed. They are listed in file ``requirements.txt``. Using `pip
1296 <https://pypi.python.org/pypi/pip>`_ you may install all required dependencies
1297 by issuing ``pip install -r requirements.txt`` in directory
1298 ``src/pybind/mgr/dashboard``.
1299
1300 If you're using the `ceph-dev-docker development environment
1301 <https://github.com/ricardoasmarques/ceph-dev-docker/>`_, simply run
1302 ``./install_deps.sh`` from the toplevel directory to install them.
1303
1304 Unit Testing
1305 ~~~~~~~~~~~~
1306
1307 In dashboard we have two different kinds of backend tests:
1308
1309 1. Unit tests based on ``tox``
1310 2. API tests based on Teuthology.
1311
1312 Unit tests based on tox
1313 ~~~~~~~~~~~~~~~~~~~~~~~~
1314
1315 We included a ``tox`` configuration file that will run the unit tests under
1316 Python 3, as well as linting tools to guarantee the uniformity of code.
1317
1318 You need to install ``tox`` and ``coverage`` before running it. To install the
1319 packages in your system, either install it via your operating system's package
1320 management tools, e.g. by running ``dnf install python-tox python-coverage`` on
1321 Fedora Linux.
1322
1323 Alternatively, you can use Python's native package installation method::
1324
1325 $ pip install tox
1326 $ pip install coverage
1327
1328 To run the tests, run ``src/script/run_tox.sh`` in the dashboard directory (where
1329 ``tox.ini`` is located)::
1330
1331 ## Run Python 3 tests+lint commands:
1332 $ ../../../script/run_tox.sh --tox-env py3,lint,check
1333
1334 ## Run Python 3 arbitrary command (e.g. 1 single test):
1335 $ ../../../script/run_tox.sh --tox-env py3 "" tests/test_rgw_client.py::RgwClientTest::test_ssl_verify
1336
1337 You can also run tox instead of ``run_tox.sh``::
1338
1339 ## Run Python 3 tests command:
1340 $ tox -e py3
1341
1342 ## Run Python 3 arbitrary command (e.g. 1 single test):
1343 $ tox -e py3 tests/test_rgw_client.py::RgwClientTest::test_ssl_verify
1344
1345 Python files can be automatically fixed and formatted according to PEP8
1346 standards by using ``run_tox.sh --tox-env fix`` or ``tox -e fix``.
1347
1348 We also collect coverage information from the backend code when you run tests. You can check the
1349 coverage information provided by the tox output, or by running the following
1350 command after tox has finished successfully::
1351
1352 $ coverage html
1353
1354 This command will create a directory ``htmlcov`` with an HTML representation of
1355 the code coverage of the backend.
1356
1357 API tests based on Teuthology
1358 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1359
1360 How to run existing API tests:
1361 To run the API tests against a real Ceph cluster, we leverage the Teuthology
1362 framework. This has the advantage of catching bugs originated from changes in
1363 the internal Ceph code.
1364
1365 Our ``run-backend-api-tests.sh`` script will start a ``vstart`` Ceph cluster
1366 before running the Teuthology tests, and then it stops the cluster after the
1367 tests are run. Of course this implies that you have built/compiled Ceph
1368 previously.
1369
1370 Start all dashboard tests by running::
1371
1372 $ ./run-backend-api-tests.sh
1373
1374 Or, start one or multiple specific tests by specifying the test name::
1375
1376 $ ./run-backend-api-tests.sh tasks.mgr.dashboard.test_pool.PoolTest
1377
1378 Or, ``source`` the script and run the tests manually::
1379
1380 $ source run-backend-api-tests.sh
1381 $ run_teuthology_tests [tests]...
1382 $ cleanup_teuthology
1383
1384 How to write your own tests:
1385 There are two possible ways to write your own API tests:
1386
1387 The first is by extending one of the existing test classes in the
1388 ``qa/tasks/mgr/dashboard`` directory.
1389
1390 The second way is by adding your own API test module if you're creating a new
1391 controller for example. To do so you'll just need to add the file containing
1392 your new test class to the ``qa/tasks/mgr/dashboard`` directory and implement
1393 all your tests here.
1394
1395 .. note:: Don't forget to add the path of the newly created module to
1396 ``modules`` section in ``qa/suites/rados/mgr/tasks/dashboard.yaml``.
1397
1398 Short example: Let's assume you created a new controller called
1399 ``my_new_controller.py`` and the related test module
1400 ``test_my_new_controller.py``. You'll need to add
1401 ``tasks.mgr.dashboard.test_my_new_controller`` to the ``modules`` section in
1402 the ``dashboard.yaml`` file.
1403
1404 Also, if you're removing test modules please keep in mind to remove the
1405 related section. Otherwise the Teuthology test run will fail.
1406
1407 Please run your API tests on your dev environment (as explained above)
1408 before submitting a pull request. Also make sure that a full QA run in
1409 Teuthology/sepia lab (based on your changes) has completed successfully
1410 before it gets merged. You don't need to schedule the QA run yourself, just
1411 add the 'needs-qa' label to your pull request as soon as you think it's ready
1412 for merging (e.g. make check was successful, the pull request is approved and
1413 all comments have been addressed). One of the developers who has access to
1414 Teuthology/the sepia lab will take care of it and report the result back to
1415 you.
1416
1417
1418 How to add a new controller?
1419 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1420
1421 A controller is a Python class that extends from the ``BaseController`` class
1422 and is decorated with either the ``@Controller``, ``@ApiController`` or
1423 ``@UiApiController`` decorators. The Python class must be stored inside a Python
1424 file located under the ``controllers`` directory. The Dashboard module will
1425 automatically load your new controller upon start.
1426
1427 ``@ApiController`` and ``@UiApiController`` are both specializations of the
1428 ``@Controller`` decorator.
1429
1430 The ``@ApiController`` should be used for controllers that provide an API-like
1431 REST interface and the ``@UiApiController`` should be used for endpoints consumed
1432 by the UI but that are not part of the 'public' API. For any other kinds of
1433 controllers the ``@Controller`` decorator should be used.
1434
1435 A controller has a URL prefix path associated that is specified in the
1436 controller decorator, and all endpoints exposed by the controller will share
1437 the same URL prefix path.
1438
1439 A controller's endpoint is exposed by implementing a method on the controller
1440 class decorated with the ``@Endpoint`` decorator.
1441
1442 For example create a file ``ping.py`` under ``controllers`` directory with the
1443 following code:
1444
1445 .. code-block:: python
1446
1447 from ..tools import Controller, ApiController, UiApiController, BaseController, Endpoint
1448
1449 @Controller('/ping')
1450 class Ping(BaseController):
1451 @Endpoint()
1452 def hello(self):
1453 return {'msg': "Hello"}
1454
1455 @ApiController('/ping')
1456 class ApiPing(BaseController):
1457 @Endpoint()
1458 def hello(self):
1459 return {'msg': "Hello"}
1460
1461 @UiApiController('/ping')
1462 class UiApiPing(BaseController):
1463 @Endpoint()
1464 def hello(self):
1465 return {'msg': "Hello"}
1466
1467 The ``hello`` endpoint of the ``Ping`` controller can be reached by the
1468 following URL: https://mgr_hostname:8443/ping/hello using HTTP GET requests.
1469 As you can see the controller URL path ``/ping`` is concatenated to the
1470 method name ``hello`` to generate the endpoint's URL.
1471
1472 In the case of the ``ApiPing`` controller, the ``hello`` endpoint can be
1473 reached by the following URL: https://mgr_hostname:8443/api/ping/hello using a
1474 HTTP GET request.
1475 The API controller URL path ``/ping`` is prefixed by the ``/api`` path and then
1476 concatenated to the method name ``hello`` to generate the endpoint's URL.
1477 Internally, the ``@ApiController`` is actually calling the ``@Controller``
1478 decorator by passing an additional decorator parameter called ``base_url``::
1479
1480 @ApiController('/ping') <=> @Controller('/ping', base_url="/api")
1481
1482 ``UiApiPing`` works in a similar way than the ``ApiPing``, but the URL will be
1483 prefixed by ``/ui-api``: https://mgr_hostname:8443/ui-api/ping/hello. ``UiApiPing`` is
1484 also a ``@Controller`` extension::
1485
1486 @UiApiController('/ping') <=> @Controller('/ping', base_url="/ui-api")
1487
1488 The ``@Endpoint`` decorator also supports many parameters to customize the
1489 endpoint:
1490
1491 * ``method="GET"``: the HTTP method allowed to access this endpoint.
1492 * ``path="/<method_name>"``: the URL path of the endpoint, excluding the
1493 controller URL path prefix.
1494 * ``path_params=[]``: list of method parameter names that correspond to URL
1495 path parameters. Can only be used when ``method in ['POST', 'PUT']``.
1496 * ``query_params=[]``: list of method parameter names that correspond to URL
1497 query parameters.
1498 * ``json_response=True``: indicates if the endpoint response should be
1499 serialized in JSON format.
1500 * ``proxy=False``: indicates if the endpoint should be used as a proxy.
1501
1502 An endpoint method may have parameters declared. Depending on the HTTP method
1503 defined for the endpoint the method parameters might be considered either
1504 path parameters, query parameters, or body parameters.
1505
1506 For ``GET`` and ``DELETE`` methods, the method's non-optional parameters are
1507 considered path parameters by default. Optional parameters are considered
1508 query parameters. By specifying the ``query_parameters`` in the endpoint
1509 decorator it is possible to make a non-optional parameter to be a query
1510 parameter.
1511
1512 For ``POST`` and ``PUT`` methods, all method parameters are considered
1513 body parameters by default. To override this default, one can use the
1514 ``path_params`` and ``query_params`` to specify which method parameters are
1515 path and query parameters respectively.
1516 Body parameters are decoded from the request body, either from a form format, or
1517 from a dictionary in JSON format.
1518
1519 Let's use an example to better understand the possible ways to customize an
1520 endpoint:
1521
1522 .. code-block:: python
1523
1524 from ..tools import Controller, BaseController, Endpoint
1525
1526 @Controller('/ping')
1527 class Ping(BaseController):
1528
1529 # URL: /ping/{key}?opt1=...&opt2=...
1530 @Endpoint(path="/", query_params=['opt1'])
1531 def index(self, key, opt1, opt2=None):
1532 """..."""
1533
1534 # URL: /ping/{key}?opt1=...&opt2=...
1535 @Endpoint(query_params=['opt1'])
1536 def __call__(self, key, opt1, opt2=None):
1537 """..."""
1538
1539 # URL: /ping/post/{key1}/{key2}
1540 @Endpoint('POST', path_params=['key1', 'key2'])
1541 def post(self, key1, key2, data1, data2=None):
1542 """..."""
1543
1544
1545 In the above example we see how the ``path`` option can be used to override the
1546 generated endpoint URL in order to not use the method's name in the URL. In the
1547 ``index`` method we set the ``path`` to ``"/"`` to generate an endpoint that is
1548 accessible by the root URL of the controller.
1549
1550 An alternative approach to generate an endpoint that is accessible through just
1551 the controller's path URL is by using the ``__call__`` method, as we show in
1552 the above example.
1553
1554 From the third method you can see that the path parameters are collected from
1555 the URL by parsing the list of values separated by slashes ``/`` that come
1556 after the URL path ``/ping`` for ``index`` method case, and ``/ping/post`` for
1557 the ``post`` method case.
1558
1559 Defining path parameters in endpoints's URLs using python methods's parameters
1560 is very easy but it is still a bit strict with respect to the position of these
1561 parameters in the URL structure.
1562 Sometimes we may want to explicitly define a URL scheme that
1563 contains path parameters mixed with static parts of the URL.
1564 Our controller infrastructure also supports the declaration of URL paths with
1565 explicit path parameters at both the controller level and method level.
1566
1567 Consider the following example:
1568
1569 .. code-block:: python
1570
1571 from ..tools import Controller, BaseController, Endpoint
1572
1573 @Controller('/ping/{node}/stats')
1574 class Ping(BaseController):
1575
1576 # URL: /ping/{node}/stats/{date}/latency?unit=...
1577 @Endpoint(path="/{date}/latency")
1578 def latency(self, node, date, unit="ms"):
1579 """ ..."""
1580
1581 In this example we explicitly declare a path parameter ``{node}`` in the
1582 controller URL path, and a path parameter ``{date}`` in the ``latency``
1583 method. The endpoint for the ``latency`` method is then accessible through
1584 the URL: https://mgr_hostname:8443/ping/{node}/stats/{date}/latency .
1585
1586 For a full set of examples on how to use the ``@Endpoint``
1587 decorator please check the unit test file: ``tests/test_controllers.py``.
1588 There you will find many examples of how to customize endpoint methods.
1589
1590
1591 Implementing Proxy Controller
1592 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1593
1594 Sometimes you might need to relay some requests from the Dashboard frontend
1595 directly to an external service.
1596 For that purpose we provide a decorator called ``@Proxy``.
1597 (As a concrete example, check the ``controllers/rgw.py`` file where we
1598 implemented an RGW Admin Ops proxy.)
1599
1600
1601 The ``@Proxy`` decorator is a wrapper of the ``@Endpoint`` decorator that
1602 already customizes the endpoint for working as a proxy.
1603 A proxy endpoint works by capturing the URL path that follows the controller
1604 URL prefix path, and does not do any decoding of the request body.
1605
1606 Example:
1607
1608 .. code-block:: python
1609
1610 from ..tools import Controller, BaseController, Proxy
1611
1612 @Controller('/foo/proxy')
1613 class FooServiceProxy(BaseController):
1614
1615 @Proxy()
1616 def proxy(self, path, **params):
1617 """
1618 if requested URL is "/foo/proxy/access/service?opt=1"
1619 then path is "access/service" and params is {'opt': '1'}
1620 """
1621
1622
1623 How does the RESTController work?
1624 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1625
1626 We also provide a simple mechanism to create REST based controllers using the
1627 ``RESTController`` class. Any class which inherits from ``RESTController`` will,
1628 by default, return JSON.
1629
1630 The ``RESTController`` is basically an additional abstraction layer which eases
1631 and unifies the work with collections. A collection is just an array of objects
1632 with a specific type. ``RESTController`` enables some default mappings of
1633 request types and given parameters to specific method names. This may sound
1634 complicated at first, but it's fairly easy. Lets have look at the following
1635 example:
1636
1637 .. code-block:: python
1638
1639 import cherrypy
1640 from ..tools import ApiController, RESTController
1641
1642 @ApiController('ping')
1643 class Ping(RESTController):
1644 def list(self):
1645 return {"msg": "Hello"}
1646
1647 def get(self, id):
1648 return self.objects[id]
1649
1650 In this case, the ``list`` method is automatically used for all requests to
1651 ``api/ping`` where no additional argument is given and where the request type
1652 is ``GET``. If the request is given an additional argument, the ID in our
1653 case, it won't map to ``list`` anymore but to ``get`` and return the element
1654 with the given ID (assuming that ``self.objects`` has been filled before). The
1655 same applies to other request types:
1656
1657 +--------------+------------+----------------+-------------+
1658 | Request type | Arguments | Method | Status Code |
1659 +==============+============+================+=============+
1660 | GET | No | list | 200 |
1661 +--------------+------------+----------------+-------------+
1662 | PUT | No | bulk_set | 200 |
1663 +--------------+------------+----------------+-------------+
1664 | POST | No | create | 201 |
1665 +--------------+------------+----------------+-------------+
1666 | DELETE | No | bulk_delete | 204 |
1667 +--------------+------------+----------------+-------------+
1668 | GET | Yes | get | 200 |
1669 +--------------+------------+----------------+-------------+
1670 | PUT | Yes | set | 200 |
1671 +--------------+------------+----------------+-------------+
1672 | DELETE | Yes | delete | 204 |
1673 +--------------+------------+----------------+-------------+
1674
1675 To use a custom endpoint for the above listed methods, you can
1676 use ``@RESTController.MethodMap``
1677
1678 .. code-block:: python
1679
1680 import cherrypy
1681 from ..tools import ApiController, RESTController
1682
1683 @RESTController.MethodMap(version='0.1')
1684 def create(self):
1685 return {"msg": "Hello"}
1686
1687 This decorator supports three parameters to customize the
1688 endpoint:
1689
1690 * ``resource"``: resource id.
1691 * ``status=200``: set the HTTP status response code
1692 * ``version``: version
1693
1694 How to use a custom API endpoint in a RESTController?
1695 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1696
1697 If you don't have any access restriction you can use ``@Endpoint``. If you
1698 have set a permission scope to restrict access to your endpoints,
1699 ``@Endpoint`` will fail, as it doesn't know which permission property should be
1700 used. To use a custom endpoint inside a restricted ``RESTController`` use
1701 ``@RESTController.Collection`` instead. You can also choose
1702 ``@RESTController.Resource`` if you have set a ``RESOURCE_ID`` in your
1703 ``RESTController`` class.
1704
1705 .. code-block:: python
1706
1707 import cherrypy
1708 from ..tools import ApiController, RESTController
1709
1710 @ApiController('ping', Scope.Ping)
1711 class Ping(RESTController):
1712 RESOURCE_ID = 'ping'
1713
1714 @RESTController.Resource('GET')
1715 def some_get_endpoint(self):
1716 return {"msg": "Hello"}
1717
1718 @RESTController.Collection('POST')
1719 def some_post_endpoint(self, **data):
1720 return {"msg": data}
1721
1722 Both decorators also support five parameters to customize the
1723 endpoint:
1724
1725 * ``method="GET"``: the HTTP method allowed to access this endpoint.
1726 * ``path="/<method_name>"``: the URL path of the endpoint, excluding the
1727 controller URL path prefix.
1728 * ``status=200``: set the HTTP status response code
1729 * ``query_params=[]``: list of method parameter names that correspond to URL
1730 query parameters.
1731 * ``version``: version
1732
1733 How to restrict access to a controller?
1734 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1735
1736 All controllers require authentication by default.
1737 If you require that the controller can be accessed without authentication,
1738 then you can add the parameter ``secure=False`` to the controller decorator.
1739
1740 Example:
1741
1742 .. code-block:: python
1743
1744 import cherrypy
1745 from . import ApiController, RESTController
1746
1747
1748 @ApiController('ping', secure=False)
1749 class Ping(RESTController):
1750 def list(self):
1751 return {"msg": "Hello"}
1752
1753 How to create a dedicated UI endpoint which uses the 'public' API?
1754 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1755
1756 Sometimes we want to combine multiple calls into one single call
1757 to save bandwidth or for other performance reasons.
1758 In order to achieve that, we first have to create an ``@UiApiController`` which
1759 is used for endpoints consumed by the UI but that are not part of the
1760 'public' API. Let the ui class inherit from the REST controller class.
1761 Now you can use all methods from the api controller.
1762
1763 Example:
1764
1765 .. code-block:: python
1766
1767 import cherrypy
1768 from . import UiApiController, ApiController, RESTController
1769
1770
1771 @ApiController('ping', secure=False) # /api/ping
1772 class Ping(RESTController):
1773 def list(self):
1774 return self._list()
1775
1776 def _list(self): # To not get in conflict with the JSON wrapper
1777 return [1,2,3]
1778
1779
1780 @UiApiController('ping', secure=False) # /ui-api/ping
1781 class PingUi(Ping):
1782 def list(self):
1783 return self._list() + [4, 5, 6]
1784
1785 How to access the manager module instance from a controller?
1786 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1787
1788 We provide the manager module instance as a global variable that can be
1789 imported in any module.
1790
1791 Example:
1792
1793 .. code-block:: python
1794
1795 import logging
1796 import cherrypy
1797 from .. import mgr
1798 from ..tools import ApiController, RESTController
1799
1800 logger = logging.getLogger(__name__)
1801
1802 @ApiController('servers')
1803 class Servers(RESTController):
1804 def list(self):
1805 logger.debug('Listing available servers')
1806 return {'servers': mgr.list_servers()}
1807
1808
1809 How to write a unit test for a controller?
1810 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1811
1812 We provide a test helper class called ``ControllerTestCase`` to easily create
1813 unit tests for your controller.
1814
1815 If we want to write a unit test for the above ``Ping`` controller, create a
1816 ``test_ping.py`` file under the ``tests`` directory with the following code:
1817
1818 .. code-block:: python
1819
1820 from .helper import ControllerTestCase
1821 from .controllers.ping import Ping
1822
1823
1824 class PingTest(ControllerTestCase):
1825 @classmethod
1826 def setup_test(cls):
1827 cp_config = {'tools.authenticate.on': True}
1828 cls.setup_controllers([Ping], cp_config=cp_config)
1829
1830 def test_ping(self):
1831 self._get("/api/ping")
1832 self.assertStatus(200)
1833 self.assertJsonBody({'msg': 'Hello'})
1834
1835 The ``ControllerTestCase`` class starts by initializing a CherryPy webserver.
1836 Then it will call the ``setup_test()`` class method where we can explicitly
1837 load the controllers that we want to test. In the above example we are only
1838 loading the ``Ping`` controller. We can also provide ``cp_config`` in order to
1839 update the controller's cherrypy config (e.g. enable authentication as shown in the example).
1840
1841 How to update or create new dashboards in grafana?
1842 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1843
1844 We are using ``jsonnet`` and ``grafonnet-lib`` to write code for the grafana dashboards.
1845 All the dashboards are written inside ``grafana_dashboards.jsonnet`` file in the
1846 monitoring/grafana/dashboards/jsonnet directory.
1847
1848 We generate the dashboard json files directly from this jsonnet file by running this
1849 command in the grafana/dashboards directory:
1850 ``jsonnet -m . jsonnet/grafana_dashboards.jsonnet``.
1851 (For the above command to succeed we need ``jsonnet`` package installed and ``grafonnet-lib``
1852 directory cloned in our machine. Please refer -
1853 ``https://grafana.github.io/grafonnet-lib/getting-started/`` in case you have some trouble.)
1854
1855 To update an existing grafana dashboard or to create a new one, we need to update
1856 the ``grafana_dashboards.jsonnet`` file and generate the new/updated json files using the
1857 above mentioned command. For people who are not familiar with grafonnet or jsonnet implementation
1858 can follow this doc - ``https://grafana.github.io/grafonnet-lib/``.
1859
1860 Example grafana dashboard in jsonnet format:
1861
1862 To specify the grafana dashboard properties such as title, uid etc we can create a local function -
1863
1864 ::
1865
1866 local dashboardSchema(title, uid, time_from, refresh, schemaVersion, tags,timezone, timepicker)
1867
1868 To add a graph panel we can specify the graph schema in a local function such as -
1869
1870 ::
1871
1872 local graphPanelSchema(title, nullPointMode, stack, formatY1, formatY2, labelY1, labelY2, min, fill, datasource)
1873
1874 and then use these functions inside the dashboard definition like -
1875
1876 ::
1877
1878 {
1879 radosgw-sync-overview.json: //json file name to be generated
1880
1881 dashboardSchema(
1882 'RGW Sync Overview', 'rgw-sync-overview', 'now-1h', '15s', .., .., ..
1883 )
1884
1885 .addPanels([
1886 graphPanelSchema(
1887 'Replication (throughput) from Source Zone', 'Bps', null, .., .., ..)
1888 ])
1889 }
1890
1891 The valid grafonnet-lib attributes can be found here - ``https://grafana.github.io/grafonnet-lib/api-docs/``.
1892
1893
1894 How to listen for manager notifications in a controller?
1895 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1896
1897 The manager notifies the modules of several types of cluster events, such
1898 as cluster logging event, etc...
1899
1900 Each module has a "global" handler function called ``notify`` that the manager
1901 calls to notify the module. But this handler function must not block or spend
1902 too much time processing the event notification.
1903 For this reason we provide a notification queue that controllers can register
1904 themselves with to receive cluster notifications.
1905
1906 The example below represents a controller that implements a very simple live
1907 log viewer page:
1908
1909 .. code-block:: python
1910
1911 import collections
1912
1913 import cherrypy
1914
1915 from ..tools import ApiController, BaseController, NotificationQueue
1916
1917
1918 @ApiController('livelog')
1919 class LiveLog(BaseController):
1920 log_buffer = collections.deque(maxlen=1000)
1921
1922 def __init__(self):
1923 super(LiveLog, self).__init__()
1924 NotificationQueue.register(self.log, 'clog')
1925
1926 def log(self, log_struct):
1927 self.log_buffer.appendleft(log_struct)
1928
1929 @cherrypy.expose
1930 def default(self):
1931 ret = '<html><meta http-equiv="refresh" content="2" /><body>'
1932 for l in self.log_buffer:
1933 ret += "{}<br>".format(l)
1934 ret += "</body></html>"
1935 return ret
1936
1937 As you can see above, the ``NotificationQueue`` class provides a register
1938 method that receives the function as its first argument, and receives the
1939 "notification type" as the second argument.
1940 You can omit the second argument of the ``register`` method, and in that case
1941 you are registering to listen all notifications of any type.
1942
1943 Here is an list of notification types (these might change in the future) that
1944 can be used:
1945
1946 * ``clog``: cluster log notifications
1947 * ``command``: notification when a command issued by ``MgrModule.send_command``
1948 completes
1949 * ``perf_schema_update``: perf counters schema update
1950 * ``mon_map``: monitor map update
1951 * ``fs_map``: cephfs map update
1952 * ``osd_map``: OSD map update
1953 * ``service_map``: services (RGW, RBD-Mirror, etc.) map update
1954 * ``mon_status``: monitor status regular update
1955 * ``health``: health status regular update
1956 * ``pg_summary``: regular update of PG status information
1957
1958
1959 How to write a unit test when a controller accesses a Ceph module?
1960 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1961
1962 Consider the following example that implements a controller that retrieves the
1963 list of RBD images of the ``rbd`` pool:
1964
1965 .. code-block:: python
1966
1967 import rbd
1968 from .. import mgr
1969 from ..tools import ApiController, RESTController
1970
1971
1972 @ApiController('rbdimages')
1973 class RbdImages(RESTController):
1974 def __init__(self):
1975 self.ioctx = mgr.rados.open_ioctx('rbd')
1976 self.rbd = rbd.RBD()
1977
1978 def list(self):
1979 return [{'name': n} for n in self.rbd.list(self.ioctx)]
1980
1981 In the example above, we want to mock the return value of the ``rbd.list``
1982 function, so that we can test the JSON response of the controller.
1983
1984 The unit test code will look like the following:
1985
1986 .. code-block:: python
1987
1988 import mock
1989 from .helper import ControllerTestCase
1990
1991
1992 class RbdImagesTest(ControllerTestCase):
1993 @mock.patch('rbd.RBD.list')
1994 def test_list(self, rbd_list_mock):
1995 rbd_list_mock.return_value = ['img1', 'img2']
1996 self._get('/api/rbdimages')
1997 self.assertJsonBody([{'name': 'img1'}, {'name': 'img2'}])
1998
1999
2000
2001 How to add a new configuration setting?
2002 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2003
2004 If you need to store some configuration setting for a new feature, we already
2005 provide an easy mechanism for you to specify/use the new config setting.
2006
2007 For instance, if you want to add a new configuration setting to hold the
2008 email address of the dashboard admin, just add a setting name as a class
2009 attribute to the ``Options`` class in the ``settings.py`` file::
2010
2011 # ...
2012 class Options(object):
2013 # ...
2014
2015 ADMIN_EMAIL_ADDRESS = ('admin@admin.com', str)
2016
2017 The value of the class attribute is a pair composed by the default value for that
2018 setting, and the python type of the value.
2019
2020 By declaring the ``ADMIN_EMAIL_ADDRESS`` class attribute, when you restart the
2021 dashboard module, you will automatically gain two additional CLI commands to
2022 get and set that setting::
2023
2024 $ ceph dashboard get-admin-email-address
2025 $ ceph dashboard set-admin-email-address <value>
2026
2027 To access, or modify the config setting value from your Python code, either
2028 inside a controller or anywhere else, you just need to import the ``Settings``
2029 class and access it like this:
2030
2031 .. code-block:: python
2032
2033 from settings import Settings
2034
2035 # ...
2036 tmp_var = Settings.ADMIN_EMAIL_ADDRESS
2037
2038 # ....
2039 Settings.ADMIN_EMAIL_ADDRESS = 'myemail@admin.com'
2040
2041 The settings management implementation will make sure that if you change a
2042 setting value from the Python code you will see that change when accessing
2043 that setting from the CLI and vice-versa.
2044
2045
2046 How to run a controller read-write operation asynchronously?
2047 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2048
2049 Some controllers might need to execute operations that alter the state of the
2050 Ceph cluster. These operations might take some time to execute and to maintain
2051 a good user experience in the Web UI, we need to run those operations
2052 asynchronously and return immediately to frontend some information that the
2053 operations are running in the background.
2054
2055 To help in the development of the above scenario we added the support for
2056 asynchronous tasks. To trigger the execution of an asynchronous task we must
2057 use the following class method of the ``TaskManager`` class::
2058
2059 from ..tools import TaskManager
2060 # ...
2061 TaskManager.run(name, metadata, func, args, kwargs)
2062
2063 * ``name`` is a string that can be used to group tasks. For instance
2064 for RBD image creation tasks we could specify ``"rbd/create"`` as the
2065 name, or similarly ``"rbd/remove"`` for RBD image removal tasks.
2066
2067 * ``metadata`` is a dictionary where we can store key-value pairs that
2068 characterize the task. For instance, when creating a task for creating
2069 RBD images we can specify the metadata argument as
2070 ``{'pool_name': "rbd", image_name': "test-img"}``.
2071
2072 * ``func`` is the python function that implements the operation code, which
2073 will be executed asynchronously.
2074
2075 * ``args`` and ``kwargs`` are the positional and named arguments that will be
2076 passed to ``func`` when the task manager starts its execution.
2077
2078 The ``TaskManager.run`` method triggers the asynchronous execution of function
2079 ``func`` and returns a ``Task`` object.
2080 The ``Task`` provides the public method ``Task.wait(timeout)``, which can be
2081 used to wait for the task to complete up to a timeout defined in seconds and
2082 provided as an argument. If no argument is provided the ``wait`` method
2083 blocks until the task is finished.
2084
2085 The ``Task.wait`` is very useful for tasks that usually are fast to execute but
2086 that sometimes may take a long time to run.
2087 The return value of the ``Task.wait`` method is a pair ``(state, value)``
2088 where ``state`` is a string with following possible values:
2089
2090 * ``VALUE_DONE = "done"``
2091 * ``VALUE_EXECUTING = "executing"``
2092
2093 The ``value`` will store the result of the execution of function ``func`` if
2094 ``state == VALUE_DONE``. If ``state == VALUE_EXECUTING`` then
2095 ``value == None``.
2096
2097 The pair ``(name, metadata)`` should unequivocally identify the task being
2098 run, which means that if you try to trigger a new task that matches the same
2099 ``(name, metadata)`` pair of the currently running task, then the new task
2100 is not created and you get the task object of the current running task.
2101
2102 For instance, consider the following example:
2103
2104 .. code-block:: python
2105
2106 task1 = TaskManager.run("dummy/task", {'attr': 2}, func)
2107 task2 = TaskManager.run("dummy/task", {'attr': 2}, func)
2108
2109 If the second call to ``TaskManager.run`` executes while the first task is
2110 still executing then it will return the same task object:
2111 ``assert task1 == task2``.
2112
2113
2114 How to get the list of executing and finished asynchronous tasks?
2115 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2116
2117 The list of executing and finished tasks is included in the ``Summary``
2118 controller, which is already polled every 5 seconds by the dashboard frontend.
2119 But we also provide a dedicated controller to get the same list of executing
2120 and finished tasks.
2121
2122 The ``Task`` controller exposes the ``/api/task`` endpoint that returns the
2123 list of executing and finished tasks. This endpoint accepts the ``name``
2124 parameter that accepts a glob expression as its value.
2125 For instance, an HTTP GET request of the URL ``/api/task?name=rbd/*``
2126 will return all executing and finished tasks which name starts with ``rbd/``.
2127
2128 To prevent the finished tasks list from growing unbounded, we will always
2129 maintain the 10 most recent finished tasks, and the remaining older finished
2130 tasks will be removed when reaching a TTL of 1 minute. The TTL is calculated
2131 using the timestamp when the task finished its execution. After a minute, when
2132 the finished task information is retrieved, either by the summary controller or
2133 by the task controller, it is automatically deleted from the list and it will
2134 not be included in further task queries.
2135
2136 Each executing task is represented by the following dictionary::
2137
2138 {
2139 'name': "name", # str
2140 'metadata': { }, # dict
2141 'begin_time': "2018-03-14T15:31:38.423605Z", # str (ISO 8601 format)
2142 'progress': 0 # int (percentage)
2143 }
2144
2145 Each finished task is represented by the following dictionary::
2146
2147 {
2148 'name': "name", # str
2149 'metadata': { }, # dict
2150 'begin_time': "2018-03-14T15:31:38.423605Z", # str (ISO 8601 format)
2151 'end_time': "2018-03-14T15:31:39.423605Z", # str (ISO 8601 format)
2152 'duration': 0.0, # float
2153 'progress': 0 # int (percentage)
2154 'success': True, # bool
2155 'ret_value': None, # object, populated only if 'success' == True
2156 'exception': None, # str, populated only if 'success' == False
2157 }
2158
2159
2160 How to use asynchronous APIs with asynchronous tasks?
2161 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2162
2163 The ``TaskManager.run`` method as described in a previous section, is well
2164 suited for calling blocking functions, as it runs the function inside a newly
2165 created thread. But sometimes we want to call some function of an API that is
2166 already asynchronous by nature.
2167
2168 For these cases we want to avoid creating a new thread for just running a
2169 non-blocking function, and want to leverage the asynchronous nature of the
2170 function. The ``TaskManager.run`` is already prepared to be used with
2171 non-blocking functions by passing an object of the type ``TaskExecutor`` as an
2172 additional parameter called ``executor``. The full method signature of
2173 ``TaskManager.run``::
2174
2175 TaskManager.run(name, metadata, func, args=None, kwargs=None, executor=None)
2176
2177
2178 The ``TaskExecutor`` class is responsible for code that executes a given task
2179 function, and defines three methods that can be overridden by
2180 subclasses::
2181
2182 def init(self, task)
2183 def start(self)
2184 def finish(self, ret_value, exception)
2185
2186 The ``init`` method is called before the running the task function, and
2187 receives the task object (of class ``Task``).
2188
2189 The ``start`` method runs the task function. The default implementation is to
2190 run the task function in the current thread context.
2191
2192 The ``finish`` method should be called when the task function finishes with
2193 either the ``ret_value`` populated with the result of the execution, or with
2194 an exception object in the case that execution raised an exception.
2195
2196 To leverage the asynchronous nature of a non-blocking function, the developer
2197 should implement a custom executor by creating a subclass of the
2198 ``TaskExecutor`` class, and provide an instance of the custom executor class
2199 as the ``executor`` parameter of the ``TaskManager.run``.
2200
2201 To better understand the expressive power of executors, we write a full example
2202 of use a custom executor to execute the ``MgrModule.send_command`` asynchronous
2203 function:
2204
2205 .. code-block:: python
2206
2207 import json
2208 from mgr_module import CommandResult
2209 from .. import mgr
2210 from ..tools import ApiController, RESTController, NotificationQueue, \
2211 TaskManager, TaskExecutor
2212
2213
2214 class SendCommandExecutor(TaskExecutor):
2215 def __init__(self):
2216 super(SendCommandExecutor, self).__init__()
2217 self.tag = None
2218 self.result = None
2219
2220 def init(self, task):
2221 super(SendCommandExecutor, self).init(task)
2222
2223 # we need to listen for 'command' events to know when the command
2224 # finishes
2225 NotificationQueue.register(self._handler, 'command')
2226
2227 # store the CommandResult object to retrieve the results
2228 self.result = self.task.fn_args[0]
2229 if len(self.task.fn_args) > 4:
2230 # the user specified a tag for the command, so let's use it
2231 self.tag = self.task.fn_args[4]
2232 else:
2233 # let's generate a unique tag for the command
2234 self.tag = 'send_command_{}'.format(id(self))
2235 self.task.fn_args.append(self.tag)
2236
2237 def _handler(self, data):
2238 if data == self.tag:
2239 # the command has finished, notifying the task with the result
2240 self.finish(self.result.wait(), None)
2241 # deregister listener to avoid memory leaks
2242 NotificationQueue.deregister(self._handler, 'command')
2243
2244
2245 @ApiController('test')
2246 class Test(RESTController):
2247
2248 def _run_task(self, osd_id):
2249 task = TaskManager.run("test/task", {}, mgr.send_command,
2250 [CommandResult(''), 'osd', osd_id,
2251 json.dumps({'prefix': 'perf histogram dump'})],
2252 executor=SendCommandExecutor())
2253 return task.wait(1.0)
2254
2255 def get(self, osd_id):
2256 status, value = self._run_task(osd_id)
2257 return {'status': status, 'value': value}
2258
2259
2260 The above ``SendCommandExecutor`` executor class can be used for any call to
2261 ``MgrModule.send_command``. This means that we should need just one custom
2262 executor class implementation for each non-blocking API that we use in our
2263 controllers.
2264
2265 The default executor, used when no executor object is passed to
2266 ``TaskManager.run``, is the ``ThreadedExecutor``. You can check its
2267 implementation in the ``tools.py`` file.
2268
2269
2270 How to update the execution progress of an asynchronous task?
2271 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2272
2273 The asynchronous tasks infrastructure provides support for updating the
2274 execution progress of an executing task.
2275 The progress can be updated from within the code the task is executing, which
2276 usually is the place where we have the progress information available.
2277
2278 To update the progress from within the task code, the ``TaskManager`` class
2279 provides a method to retrieve the current task object::
2280
2281 TaskManager.current_task()
2282
2283 The above method is only available when using the default executor
2284 ``ThreadedExecutor`` for executing the task.
2285 The ``current_task()`` method returns the current ``Task`` object. The
2286 ``Task`` object provides two public methods to update the execution progress
2287 value: the ``set_progress(percentage)``, and the ``inc_progress(delta)``
2288 methods.
2289
2290 The ``set_progress`` method receives as argument an integer value representing
2291 the absolute percentage that we want to set to the task.
2292
2293 The ``inc_progress`` method receives as argument an integer value representing
2294 the delta we want to increment to the current execution progress percentage.
2295
2296 Take the following example of a controller that triggers a new task and
2297 updates its progress:
2298
2299 .. code-block:: python
2300
2301 import random
2302 import time
2303 import cherrypy
2304 from ..tools import TaskManager, ApiController, BaseController
2305
2306
2307 @ApiController('dummy_task')
2308 class DummyTask(BaseController):
2309 def _dummy(self):
2310 top = random.randrange(100)
2311 for i in range(top):
2312 TaskManager.current_task().set_progress(i*100/top)
2313 # or TaskManager.current_task().inc_progress(100/top)
2314 time.sleep(1)
2315 return "finished"
2316
2317 @cherrypy.expose
2318 @cherrypy.tools.json_out()
2319 def default(self):
2320 task = TaskManager.run("dummy/task", {}, self._dummy)
2321 return task.wait(5) # wait for five seconds
2322
2323
2324 How to deal with asynchronous tasks in the front-end?
2325 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2326
2327 All executing and most recently finished asynchronous tasks are displayed on
2328 "Background-Tasks" and if finished on "Recent-Notifications" in the menu bar.
2329 For each task a operation name for three states (running, success and failure),
2330 a function that tells who is involved and error descriptions, if any, have to
2331 be provided. This can be achieved by appending
2332 ``TaskManagerMessageService.messages``. This has to be done to achieve
2333 consistency among all tasks and states.
2334
2335 Operation Object
2336 Ensures consistency among all tasks. It consists of three verbs for each
2337 different state f.e.
2338 ``{running: 'Creating', failure: 'create', success: 'Created'}``.
2339
2340 #. Put running operations in present participle f.e. ``'Updating'``.
2341 #. Failed messages always start with ``'Failed to '`` and should be continued
2342 with the operation in present tense f.e. ``'update'``.
2343 #. Put successful operations in past tense f.e. ``'Updated'``.
2344
2345 Involves Function
2346 Ensures consistency among all messages of a task, it resembles who's
2347 involved by the operation. It's a function that returns a string which
2348 takes the metadata from the task to return f.e.
2349 ``"RBD 'somePool/someImage'"``.
2350
2351 Both combined create the following messages:
2352
2353 * Failure => ``"Failed to create RBD 'somePool/someImage'"``
2354 * Running => ``"Creating RBD 'somePool/someImage'"``
2355 * Success => ``"Created RBD 'somePool/someImage'"``
2356
2357 For automatic task handling use ``TaskWrapperService.wrapTaskAroundCall``.
2358
2359 If for some reason ``wrapTaskAroundCall`` is not working for you,
2360 you have to subscribe to your asynchronous task manually through
2361 ``TaskManagerService.subscribe``, and provide it with a callback,
2362 in case of a success to notify the user. A notification can
2363 be triggered with ``NotificationService.notifyTask``. It will use
2364 ``TaskManagerMessageService.messages`` to display a message based on the state
2365 of a task.
2366
2367 Notifications of API errors are handled by ``ApiInterceptorService``.
2368
2369 Usage example:
2370
2371 .. code-block:: javascript
2372
2373 export class TaskManagerMessageService {
2374 // ...
2375 messages = {
2376 // Messages for task 'rbd/create'
2377 'rbd/create': new TaskManagerMessage(
2378 // Message prefixes
2379 ['create', 'Creating', 'Created'],
2380 // Message suffix
2381 (metadata) => `RBD '${metadata.pool_name}/${metadata.image_name}'`,
2382 (metadata) => ({
2383 // Error code and description
2384 '17': `Name is already used by RBD '${metadata.pool_name}/${
2385 metadata.image_name}'.`
2386 })
2387 ),
2388 // ...
2389 };
2390 // ...
2391 }
2392
2393 export class RBDFormComponent {
2394 // ...
2395 createAction() {
2396 const request = this.createRequest();
2397 // Subscribes to 'call' with submitted 'task' and handles notifications
2398 return this.taskWrapper.wrapTaskAroundCall({
2399 task: new FinishedTask('rbd/create', {
2400 pool_name: request.pool_name,
2401 image_name: request.name
2402 }),
2403 call: this.rbdService.create(request)
2404 });
2405 }
2406 // ...
2407 }
2408
2409
2410 REST API documentation
2411 ~~~~~~~~~~~~~~~~~~~~~~
2412 Ceph-Dashboard provides two types of documentation for the **Ceph RESTful API**:
2413
2414 * **Static documentation**: available at :ref:`mgr ceph api`. This comes from a versioned specification located at ``src/pybind/mgr/dashboard/openapi.yaml``.
2415 * **Interactive documentation**: available from a running Ceph-Dashboard instance (top-right ``?`` icon > API Docs).
2416
2417 If changes are made to the ``controllers/`` directory, it's very likely that
2418 they will result in changes to the generated OpenAPI specification. For that
2419 reason, a checker has been implemented to block unintended changes. This check
2420 is automatically triggered by the Pull Request CI (``make check``) and can be
2421 also manually invoked: ``tox -e openapi-check``.
2422
2423 If that checker failed, it means that the current Pull Request is modifying the
2424 Ceph API and therefore:
2425
2426 #. The versioned OpenAPI specification should be updated explicitly: ``tox -e openapi-fix``.
2427 #. The team @ceph/api will be requested for reviews (this is automated via GitHub CODEOWNERS), in order to asses the impact of changes.
2428
2429 Additionally, Sphinx documentation can be generated from the OpenAPI
2430 specification with ``tox -e openapi-doc``.
2431
2432 The Ceph RESTful OpenAPI specification is dynamically generated from the
2433 ``Controllers`` in ``controllers/`` directory. However, by default it is not
2434 very detailed, so there are two decorators that can and should be used to add
2435 more information:
2436
2437 * ``@EndpointDoc()`` for documentation of endpoints. It has four optional arguments
2438 (explained below): ``description``, ``group``, ``parameters`` and
2439 ``responses``.
2440 * ``@ControllerDoc()`` for documentation of controller or group associated with
2441 the endpoints. It only takes the two first arguments: ``description`` and
2442 ``group``.
2443
2444
2445 ``description``: A a string with a short (1-2 sentences) description of the object.
2446
2447
2448 ``group``: By default, an endpoint is grouped together with other endpoints
2449 within the same controller class. ``group`` is a string that can be used to
2450 assign an endpoint or all endpoints in a class to another controller or a
2451 conceived group name.
2452
2453
2454 ``parameters``: A dict used to describe path, query or request body parameters.
2455 By default, all parameters for an endpoint are listed on the Swagger UI page,
2456 including information of whether the parameter is optional/required and default
2457 values. However, there will be no description of the parameter and the parameter
2458 type will only be displayed in some cases.
2459 When adding information, each parameters should be described as in the example
2460 below. Note that the parameter type should be expressed as a built-in python
2461 type and not as a string. Allowed values are ``str``, ``int``, ``bool``, ``float``.
2462
2463 .. code-block:: python
2464
2465 @EndpointDoc(parameters={'my_string': (str, 'Description of my_string')})
2466 def method(my_string): pass
2467
2468 For body parameters, more complex cases are possible. If the parameter is a
2469 dictionary, the type should be replaced with a ``dict`` containing its nested
2470 parameters. When describing nested parameters, the same format as other
2471 parameters is used. However, all nested parameters are set as required by default.
2472 If the nested parameter is optional this must be specified as for ``item2`` in
2473 the example below. If a nested parameters is set to optional, it is also
2474 possible to specify the default value (this will not be provided automatically
2475 for nested parameters).
2476
2477 .. code-block:: python
2478
2479 @EndpointDoc(parameters={
2480 'my_dictionary': ({
2481 'item1': (str, 'Description of item1'),
2482 'item2': (str, 'Description of item2', True), # item2 is optional
2483 'item3': (str, 'Description of item3', True, 'foo'), # item3 is optional with 'foo' as default value
2484 }, 'Description of my_dictionary')})
2485 def method(my_dictionary): pass
2486
2487 If the parameter is a ``list`` of primitive types, the type should be
2488 surrounded with square brackets.
2489
2490 .. code-block:: python
2491
2492 @EndpointDoc(parameters={'my_list': ([int], 'Description of my_list')})
2493 def method(my_list): pass
2494
2495 If the parameter is a ``list`` with nested parameters, the nested parameters
2496 should be placed in a dictionary and surrounded with square brackets.
2497
2498 .. code-block:: python
2499
2500 @EndpointDoc(parameters={
2501 'my_list': ([{
2502 'list_item': (str, 'Description of list_item'),
2503 'list_item2': (str, 'Description of list_item2')
2504 }], 'Description of my_list')})
2505 def method(my_list): pass
2506
2507
2508 ``responses``: A dict used for describing responses. Rules for describing
2509 responses are the same as for request body parameters, with one difference:
2510 responses also needs to be assigned to the related response code as in the
2511 example below:
2512
2513 .. code-block:: python
2514
2515 @EndpointDoc(responses={
2516 '400':{'my_response': (str, 'Description of my_response')}})
2517 def method(): pass
2518
2519
2520 Error Handling in Python
2521 ~~~~~~~~~~~~~~~~~~~~~~~~
2522
2523 Good error handling is a key requirement in creating a good user experience
2524 and providing a good API.
2525
2526 Dashboard code should not duplicate C++ code. Thus, if error handling in C++
2527 is sufficient to provide good feedback, a new wrapper to catch these errors
2528 is not necessary. On the other hand, input validation is the best place to
2529 catch errors and generate the best error messages. If required, generate
2530 errors as soon as possible.
2531
2532 The backend provides few standard ways of returning errors.
2533
2534 First, there is a generic Internal Server Error::
2535
2536 Status Code: 500
2537 {
2538 "version": <cherrypy version, e.g. 13.1.0>,
2539 "detail": "The server encountered an unexpected condition which prevented it from fulfilling the request.",
2540 }
2541
2542
2543 For errors generated by the backend, we provide a standard error
2544 format::
2545
2546 Status Code: 400
2547 {
2548 "detail": str(e), # E.g. "[errno -42] <some error message>"
2549 "component": "rbd", # this can be null to represent a global error code
2550 "code": "3", # Or a error name, e.g. "code": "some_error_key"
2551 }
2552
2553
2554 In case, the API Endpoints uses @ViewCache to temporarily cache results,
2555 the error looks like so::
2556
2557 Status Code 400
2558 {
2559 "detail": str(e), # E.g. "[errno -42] <some error message>"
2560 "component": "rbd", # this can be null to represent a global error code
2561 "code": "3", # Or a error name, e.g. "code": "some_error_key"
2562 'status': 3, # Indicating the @ViewCache error status
2563 }
2564
2565 In case, the API Endpoints uses a task the error looks like so::
2566
2567 Status Code 400
2568 {
2569 "detail": str(e), # E.g. "[errno -42] <some error message>"
2570 "component": "rbd", # this can be null to represent a global error code
2571 "code": "3", # Or a error name, e.g. "code": "some_error_key"
2572 "task": { # Information about the task itself
2573 "name": "taskname",
2574 "metadata": {...}
2575 }
2576 }
2577
2578
2579 Our WebUI should show errors generated by the API to the user. Especially
2580 field-related errors in wizards and dialogs or show non-intrusive notifications.
2581
2582 Handling exceptions in Python should be an exception. In general, we
2583 should have few exception handlers in our project. Per default, propagate
2584 errors to the API, as it will take care of all exceptions anyway. In general,
2585 log the exception by adding ``logger.exception()`` with a description to the
2586 handler.
2587
2588 We need to distinguish between user errors from internal errors and
2589 programming errors. Using different exception types will ease the
2590 task for the API layer and for the user interface:
2591
2592 Standard Python errors, like ``SystemError``, ``ValueError`` or ``KeyError``
2593 will end up as internal server errors in the API.
2594
2595 In general, do not ``return`` error responses in the REST API. They will be
2596 returned by the error handler. Instead, raise the appropriate exception.
2597
2598 Plug-ins
2599 ~~~~~~~~
2600
2601 New functionality can be provided by means of a plug-in architecture. Among the
2602 benefits this approach brings in, loosely coupled development is one of the most
2603 notable. As the Ceph Dashboard grows in feature richness, its code-base becomes
2604 more and more complex. The hook-based nature of a plug-in architecture allows to
2605 extend functionality in a controlled manner, and isolate the scope of the
2606 changes.
2607
2608 Ceph Dashboard relies on `Pluggy <https://pluggy.readthedocs.io>`_ to provide
2609 for plug-ing support. On top of pluggy, an interface-based approach has been
2610 implemented, with some safety checks (method override and abstract method
2611 checks).
2612
2613 In order to create a new plugin, the following steps are required:
2614
2615 #. Add a new file under ``src/pybind/mgr/dashboard/plugins``.
2616 #. Import the ``PLUGIN_MANAGER`` instance and the ``Interfaces``.
2617 #. Create a class extending the desired interfaces. The plug-in library will
2618 check if all the methods of the interfaces have been properly overridden.
2619 #. Register the plugin in the ``PLUGIN_MANAGER`` instance.
2620 #. Import the plug-in from within the Ceph Dashboard ``module.py`` (currently no
2621 dynamic loading is implemented).
2622
2623 The available Mixins (helpers) are:
2624
2625 - ``CanMgr``: provides the plug-in with access to the ``mgr`` instance under ``self.mgr``.
2626
2627 The available Interfaces are:
2628
2629 - ``Initializable``: requires overriding ``init()`` hook. This method is run at
2630 the very beginning of the dashboard module, right after all imports have been
2631 performed.
2632 - ``Setupable``: requires overriding ``setup()`` hook. This method is run in the
2633 Ceph Dashboard ``serve()`` method, right after CherryPy has been configured,
2634 but before it is started. It's a placeholder for the plug-in initialization
2635 logic.
2636 - ``HasOptions``: requires overriding ``get_options()`` hook by returning a list
2637 of ``Options()``. The options returned here are added to the
2638 ``MODULE_OPTIONS``.
2639 - ``HasCommands``: requires overriding ``register_commands()`` hook by defining
2640 the commands the plug-in can handle and decorating them with ``@CLICommand``.
2641 The commands can be optionally returned, so that they can be invoked
2642 externally (which makes unit testing easier).
2643 - ``HasControllers``: requires overriding ``get_controllers()`` hook by defining
2644 and returning the controllers as usual.
2645 - ``FilterRequest.BeforeHandler``: requires overriding
2646 ``filter_request_before_handler()`` hook. This method receives a
2647 ``cherrypy.request`` object for processing. A usual implementation of this
2648 method will allow some requests to pass or will raise a ``cherrypy.HTTPError``
2649 based on the ``request`` metadata and other conditions.
2650
2651 New interfaces and hooks should be added as soon as they are required to
2652 implement new functionality. The above list only comprises the hooks needed for
2653 the existing plugins.
2654
2655 A sample plugin implementation would look like this:
2656
2657 .. code-block:: python
2658
2659 # src/pybind/mgr/dashboard/plugins/mute.py
2660
2661 from . import PLUGIN_MANAGER as PM
2662 from . import interfaces as I
2663
2664 from mgr_module import CLICommand, Option
2665 import cherrypy
2666
2667 @PM.add_plugin
2668 class Mute(I.CanMgr, I.Setupable, I.HasOptions, I.HasCommands,
2669 I.FilterRequest.BeforeHandler, I.HasControllers):
2670 @PM.add_hook
2671 def get_options(self):
2672 return [Option('mute', default=False, type='bool')]
2673
2674 @PM.add_hook
2675 def setup(self):
2676 self.mute = self.mgr.get_module_option('mute')
2677
2678 @PM.add_hook
2679 def register_commands(self):
2680 @CLICommand("dashboard mute")
2681 def _(mgr):
2682 self.mute = True
2683 self.mgr.set_module_option('mute', True)
2684 return 0
2685
2686 @PM.add_hook
2687 def filter_request_before_handler(self, request):
2688 if self.mute:
2689 raise cherrypy.HTTPError(500, "I'm muted :-x")
2690
2691 @PM.add_hook
2692 def get_controllers(self):
2693 from ..controllers import ApiController, RESTController
2694
2695 @ApiController('/mute')
2696 class MuteController(RESTController):
2697 def get(_):
2698 return self.mute
2699
2700 return [MuteController]
2701
2702
2703 Additionally, a helper for creating plugins ``SimplePlugin`` is provided. It
2704 facilitates the basic tasks (Options, Commands, and common Mixins). The previous
2705 plugin could be rewritten like this:
2706
2707 .. code-block:: python
2708
2709 from . import PLUGIN_MANAGER as PM
2710 from . import interfaces as I
2711 from .plugin import SimplePlugin as SP
2712
2713 import cherrypy
2714
2715 @PM.add_plugin
2716 class Mute(SP, I.Setupable, I.FilterRequest.BeforeHandler, I.HasControllers):
2717 OPTIONS = [
2718 SP.Option('mute', default=False, type='bool')
2719 ]
2720
2721 def shut_up(self):
2722 self.set_option('mute', True)
2723 self.mute = True
2724 return 0
2725
2726 COMMANDS = [
2727 SP.Command("dashboard mute", handler=shut_up)
2728 ]
2729
2730 @PM.add_hook
2731 def setup(self):
2732 self.mute = self.get_option('mute')
2733
2734 @PM.add_hook
2735 def filter_request_before_handler(self, request):
2736 if self.mute:
2737 raise cherrypy.HTTPError(500, "I'm muted :-x")
2738
2739 @PM.add_hook
2740 def get_controllers(self):
2741 from ..controllers import ApiController, RESTController
2742
2743 @ApiController('/mute')
2744 class MuteController(RESTController):
2745 def get(_):
2746 return self.mute
2747
2748 return [MuteController]