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