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