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