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