Update CII oldb logging example authored by Marcus Schilling's avatar Marcus Schilling
[[_TOC_]] [[_TOC_]]
--- ---
--- ---
--- ---
### How-to post-install CII services ### How-to post-install CII services
Most CII services (not: telemetry and alarms) come as part of the DevEnv installation, however some post-installation set-up is needed before they can be used. Most CII services (not: telemetry and alarms) come as part of the DevEnv installation, however some post-installation set-up is needed before they can be used.
Post-installation is always necessary when you start working on a newly installed DevEnv host. After an upgrade of the DevEnv on an existing host, post-install may be necessary, too. In these cases, the Release Notes of the DevEnv version will inform you so. Post-installation is always necessary when you start working on a newly installed DevEnv host. After an upgrade of the DevEnv on an existing host, post-install may be necessary, too. In these cases, the Release Notes of the DevEnv version will inform you so.
_Note on DevEnv versions before 3.6_: On older DevEnv versions, you need to download the post-install first. On DevEnv 3.4, first execute this command (as root): `yum -y install elt-ciisrv-postinstall`. On DevEnv 3.5, execute this command (as root): `yum -y update elt-ciisrv-postinstall` _Note on DevEnv versions before 3.6_: On older DevEnv versions, you need to download the post-install first. On DevEnv 3.4, first execute this command (as root): `yum -y install elt-ciisrv-postinstall`. On DevEnv 3.5, execute this command (as root): `yum -y update elt-ciisrv-postinstall`
To run post-install, execute this command (as root): To run post-install, execute this command (as root):
```plaintext ```plaintext
# /elt/ciisrv/postinstall/cii-postinstall <choose a role> # /elt/ciisrv/postinstall/cii-postinstall <choose a role>
``` ```
To learn about the options, run the command without arguments. To learn about the options, run the command without arguments.
For more details and examples, see the [cii-postinstall user manual](http://www.eso.org/\~eltmgr/CII/latest/manuals/html/docs/services.html) For more details and examples, see the [cii-postinstall user manual](http://www.eso.org/\~eltmgr/CII/latest/manuals/html/docs/services.html)
After postinstall, you will want to start the CII services on your host (unless you have assigned the "groupclient" role to the host, which means you will use the CII Services running on another host). After postinstall, you will want to start the CII services on your host (unless you have assigned the "groupclient" role to the host, which means you will use the CII Services running on another host).
--- ---
--- ---
--- ---
### How-to start/stop CII services ### How-to start/stop CII services
The cii-services utility lets you start/stop/monitor the CII services. For some operations, it requires root-privileges, and can be run with `sudo`. If you don't use sudo, it will show a root password prompt when needed. The cii-services utility lets you start/stop/monitor the CII services. For some operations, it requires root-privileges, and can be run with `sudo`. If you don't use sudo, it will show a root password prompt when needed.
Note: Before using CII services, you or an administrator have to run the CII-post-installation, see [How-to post-install CII services](#how-to-post-install-cii-services) Note: Before using CII services, you or an administrator have to run the CII-post-installation, see [How-to post-install CII services](#how-to-post-install-cii-services)
_status_ This is a feature-centric view, that basically tells you which features you have available. For example, "Blob Values" means that the Distributed File System MinIO (in previous versions: Hadoop) is available for storage of large values and binaries. _status_ This is a feature-centric view, that basically tells you which features you have available. For example, "Blob Values" means that the Distributed File System MinIO (in previous versions: Hadoop) is available for storage of large values and binaries.
```plaintext ```plaintext
$ cii-services status $ cii-services status
``` ```
_info_ This is a deployment-centric view that tells you whether the services are running and where they are. _info_ This is a deployment-centric view that tells you whether the services are running and where they are.
```plaintext ```plaintext
$ cii-services info $ cii-services info
``` ```
_start / stop_ _start / stop_
```plaintext ```plaintext
$ sudo cii-services start <services> $ sudo cii-services start <services>
``` ```
To learn about the options, run the command without arguments. To learn about the options, run the command without arguments.
For more details and examples, see the [cii-services user manual](http://www.eso.org/\~eltmgr/CII/latest/manuals/html/docs/services.html) For more details and examples, see the [cii-services user manual](http://www.eso.org/\~eltmgr/CII/latest/manuals/html/docs/services.html)
--- ---
--- ---
--- ---
### How-to get CII Demo apps ### How-to get CII Demo apps
CII has demo apps that you can download as source, modify, and build yourself. They demonstrate the use of the CII services. CII has demo apps that you can download as source, modify, and build yourself. They demonstrate the use of the CII services.
```plaintext ```plaintext
$ git clone https://oauth2:ujak_jA2BjkL2UDW6v5h@gitlab.eso.org/cii/info/cii-demo.git $ git clone https://oauth2:ujak_jA2BjkL2UDW6v5h@gitlab.eso.org/cii/info/cii-demo.git
Cloning into 'cii-demo'... Cloning into 'cii-demo'...
[...] [...]
$ cd cii-demo $ cd cii-demo
$ ./cii-demo.sh $ ./cii-demo.sh
Building (this may take some minutes) ... Building (this may take some minutes) ...
Installing into INTROOT: /home/eltdev/INTROOT Installing into INTROOT: /home/eltdev/INTROOT
PREFIX is set to: /home/eltdev/INTROOT PREFIX is set to: /home/eltdev/INTROOT
Find the build output in ./cii-demo.sh.build.log Find the build output in ./cii-demo.sh.build.log
[...] [...]
``` ```
After this, you find the list of available demo apps in the (generated) README file. You can at any time modify the sources and rebuild them with "waf build install". Look inside "cii-demo.sh" if unsure. After this, you find the list of available demo apps in the (generated) README file. You can at any time modify the sources and rebuild them with "waf build install". Look inside "cii-demo.sh" if unsure.
Most demo apps require CII Services be running on your host or on another host => Check that the related CII Services (e.g. config service for a a config demo app) are accessible: see [How-to start/stop CII Services](#how-to-start-stop-cii-services) Most demo apps require CII Services be running on your host or on another host => Check that the related CII Services (e.g. config service for a a config demo app) are accessible: see [How-to start/stop CII Services](#how-to-start-stop-cii-services)
--- ---
--- ---
--- ---
### Insufficent Manuals, Contributions ### Insufficent Manuals, Contributions
**Problem** **Problem**
I found some information in the user manuals is incomplete, unclear, outdated, or misleading. I found some information in the user manuals is incomplete, unclear, outdated, or misleading.
**Solution 1** **Solution 1**
If you're not even really sure what you're looking for, go and [create a CII ticket](https://jira.eso.org/secure/CreateIssue!default.jspa), and we can help with the problem at hand, and discuss how to improve the documentation for others. If you're not even really sure what you're looking for, go and [create a CII ticket](https://jira.eso.org/secure/CreateIssue!default.jspa), and we can help with the problem at hand, and discuss how to improve the documentation for others.
**Solution 2** **Solution 2**
If you have a fairly clear idea what should be added to the manuals, you can propose and make changes to the documentation source files directly. Contributions are welcome! If you have a fairly clear idea what should be added to the manuals, you can propose and make changes to the documentation source files directly. Contributions are welcome!
The CII all-in-one User Manual is composed of a dozen sub-documents in reStructured text format (.rst). The only (minor) challenge is therefore to identify which sub-document you want to edit. The CII all-in-one User Manual is composed of a dozen sub-documents in reStructured text format (.rst). The only (minor) challenge is therefore to identify which sub-document you want to edit.
The documentation resides in `https://gitlab.eso.org/cii/info/cii-docs.git` that you can clone as usual to local workspace, then modify and create a merge request. The documentation resides in `https://gitlab.eso.org/cii/info/cii-docs.git` that you can clone as usual to local workspace, then modify and create a merge request.
Alternatively, and recommended, you can edit the files directly in the browser by using the File Editor built into gitlab: Alternatively, and recommended, you can edit the files directly in the browser by using the File Editor built into gitlab:
_Note: If any of the buttons mentioned below is greyed out, you're lacking permissions. If so, please contact us first to request permission._ _Note: If any of the buttons mentioned below is greyed out, you're lacking permissions. If so, please contact us first to request permission._
1. Browse to <https://gitlab.eso.org/cii/info/cii-docs>, 1. Browse to <https://gitlab.eso.org/cii/info/cii-docs>,
and navigate to folder `userManual/ciiman/src/docs` and navigate to folder `userManual/ciiman/src/docs`
2. Find the correct .rst file, select it, and press "Edit", 2. Find the correct .rst file, select it, and press "Edit",
and from the pop-up list of choices, prefer the "Edit single file" and from the pop-up list of choices, prefer the "Edit single file"
3. Make your changes in the content editing page. 3. Make your changes in the content editing page.
Note you can toggle between Write and Preview mode. Note you can toggle between Write and Preview mode.
When done with editing, see the lower part of the screen: When done with editing, see the lower part of the screen:
4. Describe your change: 4. Describe your change:
* Commit message: please write some rationale for your contribution * Commit message: please write some rationale for your contribution
Info: this text will re-appear later as the Title of your Merge Request. Info: this text will re-appear later as the Title of your Merge Request.
* Target branch: * Target branch:
* DO NOT use the default (master), instead: * DO NOT use the default (master), instead:
* empty the field and write e.g. * empty the field and write e.g.
"hints-on-creating-document", or "hints-on-creating-document", or
"more-details-on-network-interface" "more-details-on-network-interface"
Note there cannot be whitespace in this name Note there cannot be whitespace in this name
* Checkbox "Start a new merge request": leave default (YES) * Checkbox "Start a new merge request": leave default (YES)
5. Commit changes (blue button on lower left), 5. Commit changes (blue button on lower left),
The Merge Request window appears: The Merge Request window appears:
6. It is all prefilled. If you want you can make changes: 6. It is all prefilled. If you want you can make changes:
* The Title. It is prefilled from your commit message, but you can change it * The Title. It is prefilled from your commit message, but you can change it
* Leave all the defaults (Mark as draft: NO, Delete source branch: YES, Squash: NO) * Leave all the defaults (Mark as draft: NO, Delete source branch: YES, Squash: NO)
7. Create Merge Request (blue button) 7. Create Merge Request (blue button)
Inspect the result: Inspect the result:
8. wait for pipeline to finish 8. wait for pipeline to finish
* After the pipeline finishes, Jenkins will add its comment to your merge request page. * After the pipeline finishes, Jenkins will add its comment to your merge request page.
* and in that comment follow the link under "Artifacts List" to see your change applied. * and in that comment follow the link under "Artifacts List" to see your change applied.
8. To refine the applied change, go back to step 1. 8. To refine the applied change, go back to step 1.
Use the same branch name in step 4, so that you do not create a 2nd Merge Request Use the same branch name in step 4, so that you do not create a 2nd Merge Request
(what you want is to update your Merge Request, not create another one). (what you want is to update your Merge Request, not create another one).
We'll check the merge request, and your change can make it to the next release. Thanks in advance! We'll check the merge request, and your change can make it to the next release. Thanks in advance!
### ------------------------------------------------------ ### ------------------------------------------------------
### \[ICD\] ### \[ICD\]
### Failure to build ZPB from ICD \[ICD waf build\] ### Failure to build ZPB from ICD \[ICD waf build\]
**Problem** **Problem**
Building an ICD, I get the following error: Building an ICD, I get the following error:
```plaintext ```plaintext
error: return type specification for constructor invalid error: return type specification for constructor invalid
``` ```
**Solution** **Solution**
You have defined a struct containing a member of the same name ("feedback" in the example below). Rename one of the two. You have defined a struct containing a member of the same name ("feedback" in the example below). Rename one of the two.
```plaintext ```plaintext
<struct name="feedback"> <struct name="feedback">
<member name="feedback" type="float" arrayDimensions="(10)"/> <member name="feedback" type="float" arrayDimensions="(10)"/>
<member name="counter" type="uint32_t"/> <member name="counter" type="uint32_t"/>
</struct> </struct>
``` ```
or you have used a struct name that is a reserved word in Protobuf. Rename it. or you have used a struct name that is a reserved word in Protobuf. Rename it.
```plaintext ```plaintext
<struct name="Swap"> <struct name="Swap">
<member name="counter" type="uint32_t"/> <member name="counter" type="uint32_t"/>
</struct> </struct>
``` ```
**Background** **Background**
In the first case, the code that gets generated for the member looks to the compiler like a mal-formed constructor. In the second case, you have used a struct name that is already taken by a method name that protobuf secretly generates into the code to be compiled, which then leads to the same problem. In the first case, the code that gets generated for the member looks to the compiler like a mal-formed constructor. In the second case, you have used a struct name that is already taken by a method name that protobuf secretly generates into the code to be compiled, which then leads to the same problem.
--- ---
--- ---
--- ---
### No cpp/python from ICD \[ICD waf build\] ### No cpp/python from ICD \[ICD waf build\]
**Problem** **Problem**
When I build my ICD, the build completes without errors or warnings, but I find it has not generated any cpp and python classes for my ICD. I do see protoc file, though When I build my ICD, the build completes without errors or warnings, but I find it has not generated any cpp and python classes for my ICD. I do see protoc file, though
**Solution** **Solution**
Check that you have specified all needed dependencies in your waf script. The "requires" list needs to contain the following entries: requires='cxx python protoc fastdds boost cii gtest nosetests pytest' Check that you have specified all needed dependencies in your waf script. The "requires" list needs to contain the following entries: requires='cxx python protoc fastdds boost cii gtest nosetests pytest'
The full waf script for your project would look something like this: The full waf script for your project would look something like this:
```plaintext ```plaintext
declare_project(name='mytests', declare_project(name='mytests',
version='1.0.0', version='1.0.0',
requires='cxx python protoc fastdds boost cii gtest nosetests pytest', requires='cxx python protoc fastdds boost cii gtest nosetests pytest',
boost_libs='program_options', boost_libs='program_options',
cstd='gnu11', cstd='gnu11',
cxx_std='gnu++14', cxx_std='gnu++14',
recurse='myconfig mylsvsim icd tests') recurse='myconfig mylsvsim icd tests')
``` ```
Also, note that in DevEnv 3.x the order of dependencies matters: Also, note that in DevEnv 3.x the order of dependencies matters:
```plaintext ```plaintext
# Will not work, see the warnings during the 'waf configure' step. # Will not work, see the warnings during the 'waf configure' step.
requires='cxx python protoc fastdds cii boost gtest nosetests pytest pyqt5 sphinx' requires='cxx python protoc fastdds cii boost gtest nosetests pytest pyqt5 sphinx'
# This order works # This order works
requires='cxx python protoc fastdds boost cii gtest nosetests pytest pyqt5 sphinx' requires='cxx python protoc fastdds boost cii gtest nosetests pytest pyqt5 sphinx'
``` ```
--- ---
--- ---
--- ---
### PYBIND errors \[ICD waf build\] ### PYBIND errors \[ICD waf build\]
**Problem** **Problem**
Trying to build your MAL Application, you get errors like below related to the PYBIND module. Trying to build your MAL Application, you get errors like below related to the PYBIND module.
```plaintext ```plaintext
icd/python/bindings/src/ModProto-benchmark.cpp:18:25: error: expected initializer before ‘-’ token icd/python/bindings/src/ModProto-benchmark.cpp:18:25: error: expected initializer before ‘-’ token
PYBIND11_MODULE(ModProto-benchmark, modproto-benchmark) { PYBIND11_MODULE(ModProto-benchmark, modproto-benchmark) {
``` ```
**Solution** **Solution**
Check the name of your ICD file: Check the name of your ICD file:
```plaintext ```plaintext
> find icd > find icd
icd icd
icd/wscript icd/wscript
icd/src icd/src
icd/src/proto-benchmark.xml icd/src/proto-benchmark.xml
``` ```
The icd file name contains a minus, which is actually reflected in the above error message. The icd file name contains a minus, which is actually reflected in the above error message.
Rename the file to something like this: Rename the file to something like this:
```plaintext ```plaintext
> find icd > find icd
icd icd
icd/wscript icd/wscript
icd/src icd/src
icd/src/protobenchmark.xml icd/src/protobenchmark.xml
``` ```
In general, due to the many code generation steps taking place, your freedom in ICD file naming is limited. In general, due to the many code generation steps taking place, your freedom in ICD file naming is limited.
--- ---
--- ---
--- ---
### multiple XMLs found \[ICD waf build\] ### multiple XMLs found \[ICD waf build\]
**Problem** **Problem**
Trying to build your ICD module, you see this error: Trying to build your ICD module, you see this error:
```plaintext ```plaintext
Waf: Entering directory \`/home/eltdev/repos/hlcc/build' Waf: Entering directory \`/home/eltdev/repos/hlcc/build'
Error: multiple XMLs found, just one supported. Error: multiple XMLs found, just one supported.
``` ```
while in fact you have only one XML file in your ICD directory. while in fact you have only one XML file in your ICD directory.
**Solution** **Solution**
Check the file name of your ICD file: Check the file name of your ICD file:
make sure it starts with an uppercase letter. make sure it starts with an uppercase letter.
**Background** **Background**
The error message is misleading (will be improved, [ECII-426](https://jira.eso.org/browse/ECII-426)). The error message is misleading (will be improved, [ECII-426](https://jira.eso.org/browse/ECII-426)).
The code generator for malicd_topics fails when the ICD file name starts with lowercase. The code generator for malicd_topics fails when the ICD file name starts with lowercase.
For more information, see also: [KB: PYBIND errors \[ICD waf build\]](onenote:#KB%20PYBIND%20errors%20%5BICD%20waf%20build%5D&section-id=%7BF524F9BE-F51D-4A01-9976-93359FCC4966%7D&page-id=%7B0FEE4FB9-C58B-4E8A-A276-2EC4367CFB30%7D&end&base-path=https://europeansouthernobservatory.sharepoint.com/sites/ELT_Control/SiteAssets/ELT_Control%20Notebook/Documentation/ELT%20Control%20KnowledgeBase.one) For more information, see also: [KB: PYBIND errors \[ICD waf build\]](onenote:#KB%20PYBIND%20errors%20%5BICD%20waf%20build%5D&section-id=%7BF524F9BE-F51D-4A01-9976-93359FCC4966%7D&page-id=%7B0FEE4FB9-C58B-4E8A-A276-2EC4367CFB30%7D&end&base-path=https://europeansouthernobservatory.sharepoint.com/sites/ELT_Control/SiteAssets/ELT_Control%20Notebook/Documentation/ELT%20Control%20KnowledgeBase.one)
--- ---
--- ---
--- ---
### g++: internal compiler error, g++ fatal error \[ICD waf build\] ### g++: internal compiler error, g++ fatal error \[ICD waf build\]
**Problem** **Problem**
Trying to build an ICD-module or MAL-application, the build takes a long time, and/or fails with an error message like this: Trying to build an ICD-module or MAL-application, the build takes a long time, and/or fails with an error message like this:
```plaintext ```plaintext
g++: fatal error: Killed signal terminated program cc1plus g++: fatal error: Killed signal terminated program cc1plus
compilation terminated. compilation terminated.
``` ```
```plaintext ```plaintext
Software/CcsLibs/CcsTestData/python/bindings/src/ModCcstestdata.cpp:18:1: note: Software/CcsLibs/CcsTestData/python/bindings/src/ModCcstestdata.cpp:18:1: note:
in expansion of macro ‘PYBIND11_MODULE’ in expansion of macro ‘PYBIND11_MODULE’
PYBIND11_MODULE(ModCcstestdata, modccstestdata) { PYBIND11_MODULE(ModCcstestdata, modccstestdata) {
^ ^
g++: internal compiler error: Killed (program cc1plus) g++: internal compiler error: Killed (program cc1plus)
``` ```
**Background** **Background**
The cpp compiler runs out of memory and crashes. You can see the effect by running htop in a separate terminal, all memory (including swap space) is consumed by the g++ compiler, which consequently crashes. The cpp compiler runs out of memory and crashes. You can see the effect by running htop in a separate terminal, all memory (including swap space) is consumed by the g++ compiler, which consequently crashes.
_Memory needed for building a given ICD module_ _Memory needed for building a given ICD module_
There is a base load that is the same for all ICD modules. On top of that, the ICD file contents determine how much memory is needed to build the module. There is a base load that is the same for all ICD modules. On top of that, the ICD file contents determine how much memory is needed to build the module.
_Rule of Thumb_ _Rule of Thumb_
| MAL version | Base Load | Mem per ICD-Struct | | MAL version | Base Load | Mem per ICD-Struct |
|-------------|-----------|--------------------| |-------------|-----------|--------------------|
| MAL 1.x | 650 MB (2/3 GB) | 320 MB (1/3 GB) | | MAL 1.x | 650 MB (2/3 GB) | 320 MB (1/3 GB) |
| MAL 2.0 | 650 MB (2/3 GB) | 110 MB (1/8 GB) | | MAL 2.0 | 650 MB (2/3 GB) | 110 MB (1/8 GB) |
Thus, if your biggest ICD contains 20 structs, building under MAL 1.x will require around 7 GB of available free memory. Thus, if your biggest ICD contains 20 structs, building under MAL 1.x will require around 7 GB of available free memory.
_Measuring_ _Measuring_
Record metrics of the ICD build with this time-command: Record metrics of the ICD build with this time-command:
```plaintext ```plaintext
$ alias time='TIME="real\t%E\nmem\t%Mk\ncpu\t%P\npf\t%F" time' $ alias time='TIME="real\t%E\nmem\t%Mk\ncpu\t%P\npf\t%F" time'
$ time waf build $ time waf build
[...] [...]
real 10:28.19 real 10:28.19
mem 7206676k mem 7206676k
cpu 765% cpu 765%
pf 166 pf 166
``` ```
- If the build crashes, the time-command's output will not be fully reliable (the real memory need is higher than what the output shows). - If the build crashes, the time-command's output will not be fully reliable (the real memory need is higher than what the output shows).
- High page fault counts (`pf 1168635`) generally indicate you should reduce the module's footprint, see Solutions below. - High page fault counts (`pf 1168635`) generally indicate you should reduce the module's footprint, see Solutions below.
More info is available at [ECII-109](https://jira.eso.org/browse/ECII-109) More info is available at [ECII-109](https://jira.eso.org/browse/ECII-109)
**Solution 1: Decrease the module's footprint** **Solution 1: Decrease the module's footprint**
1. Remove unnecessary middlewares 1. Remove unnecessary middlewares
Use the `xyz_disabled` options: Use the `xyz_disabled` options:
```python ```python
from wtools import module from wtools import module
# Disable OPCUA and DDS, since not part of this interface. # Disable OPCUA and DDS, since not part of this interface.
module.declare_malicd(mal_opts={'opcua_disabled': True, 'dds_disabled': True}) module.declare_malicd(mal_opts={'opcua_disabled': True, 'dds_disabled': True})
``` ```
2. Reduce build parallelism 2. Reduce build parallelism
By default the build system uses all cores on the host. Less parallelism means less memory consumers during the build. This is controlled by the waf `-j` option. By default the build system uses all cores on the host. Less parallelism means less memory consumers during the build. This is controlled by the waf `-j` option.
To build with only 4 cores: `$ time waf -j4 build` To build with only 4 cores: `$ time waf -j4 build`
As a rough estimate, each waf build task will consume around 2 GB RAM, so on a 12 core host with 16 GB RAM, a parallelism of 8 may be a good choice. Try different numbers of cores and use the output from the time-command (see above) to find an optimum between real, page faults, and cpu. As a rough estimate, each waf build task will consume around 2 GB RAM, so on a 12 core host with 16 GB RAM, a parallelism of 8 may be a good choice. Try different numbers of cores and use the output from the time-command (see above) to find an optimum between real, page faults, and cpu.
3. Adjust the compiler flags 3. Adjust the compiler flags
The default set of compiler flags applied by the build system consume significant memory. We recommend using "-O2 -flto -pipe" (_to be confirmed_) instead. This is how you pass custom compiler flags for your ICD-module: The default set of compiler flags applied by the build system consume significant memory. We recommend using "-O2 -flto -pipe" (_to be confirmed_) instead. This is how you pass custom compiler flags for your ICD-module:
In your project wscript: In your project wscript:
```python ```python
from wtools import project from wtools import project
[...] [...]
def configure(cnf): def configure(cnf):
cnf.env.CXXFLAGS_MALPYTHON = '-O2 -flto -pipe' cnf.env.CXXFLAGS_MALPYTHON = '-O2 -flto -pipe'
[...] [...]
``` ```
4. Refactor your ICD 4. Refactor your ICD
Reduce the memory need by splitting the big ICDs up into 2 or more smaller ICD modules. Reduce the memory need by splitting the big ICDs up into 2 or more smaller ICD modules.
**Solution 2: Increase the available memory** **Solution 2: Increase the available memory**
1. Find RAM consumers and stop them, at least temporarily. For example, ElasticSearch uses a significant amount of RAM: `sudo cii-services stop elasticsearch` 1. Find RAM consumers and stop them, at least temporarily. For example, ElasticSearch uses a significant amount of RAM: `sudo cii-services stop elasticsearch`
2. Add temporary swap space to your host 2. Add temporary swap space to your host
```shell ```shell
# As root: # As root:
fallocate -l 8G /swapfile fallocate -l 8G /swapfile
dd if=/dev/zero of=/swapfile bs=1024 count=8388608 dd if=/dev/zero of=/swapfile bs=1024 count=8388608
chmod 600 /swapfile chmod 600 /swapfile
mkswap /swapfile mkswap /swapfile
swapon /swapfile swapon /swapfile
# and to remove it: # and to remove it:
swapoff -v /swapfile swapoff -v /swapfile
rm -f /swapfile rm -f /swapfile
``` ```
3. Add permanent memory to your VM 3. Add permanent memory to your VM
Increase your RAM, respectively ask your system administrator to do it. Assess the necessary amount by using the "Rule Of Thumb" above. Increase your RAM, respectively ask your system administrator to do it. Assess the necessary amount by using the "Rule Of Thumb" above.
--- ---
--- ---
--- ---
### Choose middlewares to build \[MAL ICD\] ### Choose middlewares to build \[MAL ICD\]
**Problem** **Problem**
I am certain that my ICD will never be used over OPC UA. Nonetheless, the ICD-compilation builds OPC UA mappings for my ICD. This is unnecessarily extending the compilation time for my application. I am certain that my ICD will never be used over OPC UA. Nonetheless, the ICD-compilation builds OPC UA mappings for my ICD. This is unnecessarily extending the compilation time for my application.
**Solution** **Solution**
By default the ICD-compilation builds mappings for all middlewares. But it is possible to exclude certain middleware mappings from compilation, which will reduce compilation time. You do this by passing mal options to the icd-generator. By default the ICD-compilation builds mappings for all middlewares. But it is possible to exclude certain middleware mappings from compilation, which will reduce compilation time. You do this by passing mal options to the icd-generator.
**Example** **Example**
wscript wscript
```plaintext ```plaintext
declare_malicd(use='icds.base', mal_opts = { 'opcua_disabled': True } ) declare_malicd(use='icds.base', mal_opts = { 'opcua_disabled': True } )
``` ```
The available options are: The available options are:
- opcua_disabled = if True, disable OPCUA middleware generation - opcua_disabled = if True, disable OPCUA middleware generation
- dds_disabled = if True, disable DDS middleware generation - dds_disabled = if True, disable DDS middleware generation
- zpb_disabled = if True, disable ZEROMQ middleware generation - zpb_disabled = if True, disable ZEROMQ middleware generation
--- ---
--- ---
--- ---
### Variable Tracking exceeded \[ICD\] ### Variable Tracking exceeded \[ICD\]
**Problem** **Problem**
When building an ICD using CII-MAL, you see this warning message: When building an ICD using CII-MAL, you see this warning message:
```plaintext ```plaintext
variable tracking size limit exceeded variable tracking size limit exceeded
``` ```
**Background** **Background**
The -fvar-tracking-assignments is automatically enabled by GCC when optimizations are enabled. The -fvar-tracking-assignments is automatically enabled by GCC when optimizations are enabled.
There is a limit on how many variables can be tracked by the compiler. The warning tells you that more vars would need to be tracked than what's supported. There is a limit on how many variables can be tracked by the compiler. The warning tells you that more vars would need to be tracked than what's supported.
You can disable the tracking manually with -fno-var-tracking-assignments. You can disable the tracking manually with -fno-var-tracking-assignments.
There are two easy ways to do it on the overall project. There are two easy ways to do it on the overall project.
**Solution A** **Solution A**
```plaintext ```plaintext
Export CXXFLAGS=-fno-var-tracking-assignments Export CXXFLAGS=-fno-var-tracking-assignments
``` ```
And then rerun “waf configure” and continue with the build. And then rerun “waf configure” and continue with the build.
Note: you have to have the exported variable each time you do a “waf configure” as that is the point at which such flags are saved Note: you have to have the exported variable each time you do a “waf configure” as that is the point at which such flags are saved
**Solution B** **Solution B**
If you want it to be inside the project then put the flags fixed inside your project, so in the top level wscript (where you define the project) add this configure section before the project declaration: If you want it to be inside the project then put the flags fixed inside your project, so in the top level wscript (where you define the project) add this configure section before the project declaration:
```plaintext ```plaintext
def configure(cnf): def configure(cnf):
cnf.env.append_value('CXXFLAGS', \['-fno-var-tracking-assignments'\]) cnf.env.append_value('CXXFLAGS', \['-fno-var-tracking-assignments'\])
``` ```
### ------------------------------------------------------ ### ------------------------------------------------------
### \[MAL\] ### \[MAL\]
--- ---
--- ---
--- ---
### Avoid ephemeral ports \[MAL\] ### Avoid ephemeral ports \[MAL\]
**Problem** **Problem**
When you leave a client running for a while (say 20 minutes) without server available, you start getting errors: When you leave a client running for a while (say 20 minutes) without server available, you start getting errors:
```plaintext ```plaintext
Message=Malformed message received, missing frames. Message=Malformed message received, missing frames.
``` ```
Starting the server does not fix the situation, and gives this error: Starting the server does not fix the situation, and gives this error:
```plaintext ```plaintext
Errno 48 : Address already in use Errno 48 : Address already in use
``` ```
**Solution** **Solution**
The solution is to not use ports from the ephemeral range (aka local port range). The port numbers in the ephemeral range can be found with `cat /proc/sys/net/ipv4/ip_local_port_range`. For DevEnv 3.x with CentOS 8 they are: The solution is to not use ports from the ephemeral range (aka local port range). The port numbers in the ephemeral range can be found with `cat /proc/sys/net/ipv4/ip_local_port_range`. For DevEnv 3.x with CentOS 8 they are:
| Port Range | Usable for MAL | | Port Range | Usable for MAL |
|------------|----------------| |------------|----------------|
| 1 -1023 | 🟠 No | | 1 -1023 | 🟠 No |
| 1024 - 32767 | 🟢 Yes | | 1024 - 32767 | 🟢 Yes |
| 32768 - 60999 | 🟠 No | | 32768 - 60999 | 🟠 No |
| 61000 - 65535 | 🟢 Yes | | 61000 - 65535 | 🟢 Yes |
With the implementation of ECII-402, the MAL library will write a warning log (and can also be configured to throw an exception) if an application runs a MAL instance on one of the ephemeral ports. With the implementation of ECII-402, the MAL library will write a warning log (and can also be configured to throw an exception) if an application runs a MAL instance on one of the ephemeral ports.
**Background** **Background**
(Explanation provided by M. Sekoranja) (Explanation provided by M. Sekoranja)
After a while of (re-)connection attempts, the client will manage to connect... to itself! Because a client will never expect client's messages, errors of malformed messages are emitted. After a while of (re-)connection attempts, the client will manage to connect... to itself! Because a client will never expect client's messages, errors of malformed messages are emitted.
This happens because TCP design allows for a 'simultaneous connect feature': if a client is trying to connect to local port and if the port is from the ephemeral range, it can occasionally connect to itself. The client thinks it is connected to a server, however it is actually connected to itself. Moreover, the server can not bind to its server port anymore. This happens because TCP design allows for a 'simultaneous connect feature': if a client is trying to connect to local port and if the port is from the ephemeral range, it can occasionally connect to itself. The client thinks it is connected to a server, however it is actually connected to itself. Moreover, the server can not bind to its server port anymore.
--- ---
--- ---
--- ---
### Req/Rep Connection Listeners \[MAL Python\] ### Req/Rep Connection Listeners \[MAL Python\]
**Problem** **Problem**
MAL includes a callback registration method to allow monitoring of the MAL service connection status. MAL includes a callback registration method to allow monitoring of the MAL service connection status.
This is done with the method `registerConnectionListener()`. This is done with the method `registerConnectionListener()`.
Given the example below, this does not work, and the `listenerMethod()` is never called. Given the example below, this does not work, and the `listenerMethod()` is never called.
```plaintext ```plaintext
import sys import sys
import datetime import datetime
import signal import signal
import traceback import traceback
import logging import logging
import elt.pymal as mal import elt.pymal as mal
from pymalcpp import TimeoutException from pymalcpp import TimeoutException
from ModTrk.Trk.StdCmds import StdCmdsSync from ModTrk.Trk.StdCmds import StdCmdsSync
from ModTrk.Trk.StdCmds import StdCmdsAsync from ModTrk.Trk.StdCmds import StdCmdsAsync
from ModTrk.Trk import TelPosition from ModTrk.Trk import TelPosition
from ModTrk.Trk import AxesPosition from ModTrk.Trk import AxesPosition
THREE_SECONDS = datetime.timedelta(seconds=3) THREE_SECONDS = datetime.timedelta(seconds=3)
MINUTE = datetime.timedelta(seconds=60) MINUTE = datetime.timedelta(seconds=60)
MY_SERVER_URL='localhost' MY_SERVER_URL='localhost'
MY_SERVER_PORT='44444' MY_SERVER_PORT='44444'
def listenerMethod(state): def listenerMethod(state):
print("listenerMethod: registerConnectionListener() response :" + str(state)) print("listenerMethod: registerConnectionListener() response :" + str(state))
uri = 'zpb.rr://' + MY_SERVER_URL + ':' + str(MY_SERVER_PORT) + '/m1/' + 'TrkLsvServer' uri = 'zpb.rr://' + MY_SERVER_URL + ':' + str(MY_SERVER_PORT) + '/m1/' + 'TrkLsvServer'
print('MAL URI: ' + uri) print('MAL URI: ' + uri)
zpbMal = mal.loadMal('zpb', {}) zpbMal = mal.loadMal('zpb', {})
factory = mal.CiiFactory.getInstance() factory = mal.CiiFactory.getInstance()
factory.registerMal('zpb', zpbMal ) factory.registerMal('zpb', zpbMal )
stdcmds = factory.getClient(uri, StdCmdsAsync, qos=mal.rr.qos.ReplyTime(THREE_SECONDS)) stdcmds = factory.getClient(uri, StdCmdsAsync, qos=mal.rr.qos.ReplyTime(THREE_SECONDS))
stdcmds.registerConnectionListener(listenerMethod) stdcmds.registerConnectionListener(listenerMethod)
connectionFuture = stdcmds.asyncConnect() connectionFuture = stdcmds.asyncConnect()
connectionFuture.wait_for(THREE_SECONDS) connectionFuture.wait_for(THREE_SECONDS)
rtn = stdcmds.Status() rtn = stdcmds.Status()
rtn.wait() rtn.wait()
print( str(rtn.get() )) print( str(rtn.get() ))
``` ```
_From <_[_https://jira.eso.org/browse/ECII-212_](https://jira.eso.org/browse/ECII-212)_>_ _From <_[_https://jira.eso.org/browse/ECII-212_](https://jira.eso.org/browse/ECII-212)_>_
**Solution** **Solution**
The developer must keep a reference to the returned Object from the `registerConnectionListener()` invocation. The developer must keep a reference to the returned Object from the `registerConnectionListener()` invocation.
```plaintext ```plaintext
stdcmds = factory.getClient(uri, StdCmdsAsync, qos=mal.rr.qos.ReplyTime(THREE_SECONDS)) stdcmds = factory.getClient(uri, StdCmdsAsync, qos=mal.rr.qos.ReplyTime(THREE_SECONDS))
listenerRegistration = stdcmds.registerConnectionListener(listenerMethod) listenerRegistration = stdcmds.registerConnectionListener(listenerMethod)
``` ```
**Background** **Background**
The documentation states a Return value, but is the responsibility of the developer to keep the reference. Otherwise, the object will be deleted when exiting the block of code. The documentation states a Return value, but is the responsibility of the developer to keep the reference. Otherwise, the object will be deleted when exiting the block of code.
Remember to delete (assign None), to this object when closing the connection to the MAL service. Remember to delete (assign None), to this object when closing the connection to the MAL service.
_From <_[_https://jira.eso.org/browse/ECII-212_](https://jira.eso.org/browse/ECII-212)_>_ _From <_[_https://jira.eso.org/browse/ECII-212_](https://jira.eso.org/browse/ECII-212)_>_
--- ---
--- ---
--- ---
### Latency on Pub/Sub \[MAL ZMQ\] ### Latency on Pub/Sub \[MAL ZMQ\]
**Problem** **Problem**
We see latencies of 400-1000ms in MAL ZMQ pub/sub communication, for sending a 12k x 12k image blob. We see latencies of 400-1000ms in MAL ZMQ pub/sub communication, for sending a 12k x 12k image blob.
For the 2 first transmissions, there is somewhere between 400 and 500ms latency on the publisher side between just before calling the "publish" method and when we see the first packets on the wire. For the 2 first transmissions, there is somewhere between 400 and 500ms latency on the publisher side between just before calling the "publish" method and when we see the first packets on the wire.
This is for all messages, not only for the first messages. When we let the program run several minutes, during that period, all messages have a consistent delay when arriving on subscriber side. This is for all messages, not only for the first messages. When we let the program run several minutes, during that period, all messages have a consistent delay when arriving on subscriber side.
**Solution** **Solution**
From MAL 1.0.4 on, From MAL 1.0.4 on,
MAL supports the below MAL specific property to limit queue size for large message publishers. MAL supports the below MAL specific property to limit queue size for large message publishers.
```plaintext ```plaintext
mal::Mal::Properties m_malProperties1; mal::Mal::Properties m_malProperties1;
m_malProperties1["zpb.ps.zmq.sndhwm"] = "1"; m_malProperties1["zpb.ps.zmq.sndhwm"] = "1";
auto publisher = factory.getPublisher<mal::example::Sample>(uri, auto publisher = factory.getPublisher<mal::example::Sample>(uri,
{ std::make_shared<mal::ps::qos::Latency>( { std::make_shared<mal::ps::qos::Latency>(
std::chrono::milliseconds(100)), std::chrono::milliseconds(100)),
std::make_shared<mal::ps::qos::Deadline>( std::make_shared<mal::ps::qos::Deadline>(
std::chrono::seconds(1)) }, m_malProperties1); std::chrono::seconds(1)) }, m_malProperties1);
``` ```
For more information how to use MAL specific properties, see MAL Binding Manual. For more information how to use MAL specific properties, see MAL Binding Manual.
**Background** **Background**
The issue has been first reported in [ECII-159](https://jira.eso.org/browse/ECII-159). The issue has been first reported in [ECII-159](https://jira.eso.org/browse/ECII-159).
The problem lies in the ZMQ send queues. Default size is 1000 and with 144MB per message (in this case) this means 144GB. Limiting this to 1 (for a test) a publisher can handle 20 subscribers (tested) without any problems. The solution is to reconfigure the send-queue size appropriately. The problem lies in the ZMQ send queues. Default size is 1000 and with 144MB per message (in this case) this means 144GB. Limiting this to 1 (for a test) a publisher can handle 20 subscribers (tested) without any problems. The solution is to reconfigure the send-queue size appropriately.
--- ---
--- ---
--- ---
### Sending an array of unions \[MAL CPP\] ### Sending an array of unions \[MAL CPP\]
**Problem** **Problem**
Trying to send a msg, I get the following error message from CII: Trying to send a msg, I get the following error message from CII:
```plaintext ```plaintext
[libprotobuf ERROR google/protobuf/message_lite.cc:121] Can't parse message of type "generated.zpb.fcfif.StdCmds_Request" because it is missing required fields: data.Setup.payload[0].piezoData.input [libprotobuf ERROR google/protobuf/message_lite.cc:121] Can't parse message of type "generated.zpb.fcfif.StdCmds_Request" because it is missing required fields: data.Setup.payload[0].piezoData.input
``` ```
My ICD definition looks like this My ICD definition looks like this
```xml ```xml
<enum name="PiezoInput"> <enum name="PiezoInput">
<enumerator name="PIEZO_INPUT_SETMODE" /> <enumerator name="PIEZO_INPUT_SETMODE" />
<enumerator name="PIEZO_INPUT_MOVE" /> <enumerator name="PIEZO_INPUT_MOVE" />
</enum> </enum>
<enum name="PiezoMode"> <enum name="PiezoMode">
<enumerator name="PIEZO_MODE_1" /> <enumerator name="PIEZO_MODE_1" />
<enumerator name="PIEZO_MODE_2" /> <enumerator name="PIEZO_MODE_2" />
</enum> </enum>
<struct name="PiezoModeStruct"> <struct name="PiezoModeStruct">
<member name="mode" type="nonBasic" nonBasicTypeName="PiezoMode" /> <member name="mode" type="nonBasic" nonBasicTypeName="PiezoMode" />
</struct> </struct>
<enum name="PiezoMove"> <enum name="PiezoMove">
<enumerator name="PIEZO_MOVE_1" /> <enumerator name="PIEZO_MOVE_1" />
<enumerator name="PIEZO_MOVE_2" /> <enumerator name="PIEZO_MOVE_2" />
</enum> </enum>
<union name="PiezoUnion"> <union name="PiezoUnion">
<discriminator type="nonBasic" nonBasicTypeName="PiezoInput" /> <discriminator type="nonBasic" nonBasicTypeName="PiezoInput" />
<case> <case>
<caseDiscriminator value ="PIEZO_INPUT_SETMODE"/> <caseDiscriminator value ="PIEZO_INPUT_SETMODE"/>
<member name="piezoModeData" type="nonBasic" nonBasicTypeName="PiezoModeStruct" /> <member name="piezoModeData" type="nonBasic" nonBasicTypeName="PiezoModeStruct" />
</case> </case>
<case> <case>
<caseDiscriminator value ="PIEZO_INPUT_MOVE"/> <caseDiscriminator value ="PIEZO_INPUT_MOVE"/>
<member name="piezoMoveData" type="nonBasic" nonBasicTypeName="PiezoMove" /> <member name="piezoMoveData" type="nonBasic" nonBasicTypeName="PiezoMove" />
</case> </case>
</union> </union>
<struct name="Piezo"> <struct name="Piezo">
<member name="id" type="string" /> <member name="id" type="string" />
<member name="input" type="nonBasic" nonBasicTypeName="PiezoUnion" /> <member name="input" type="nonBasic" nonBasicTypeName="PiezoUnion" />
</struct> </struct>
<interface name="PiezoTest"> <interface name="PiezoTest">
<method name="test" returnType="void"> <method name="test" returnType="void">
<argument name="arr" type="nonBasic" nonBasicTypeName="Piezo" arrayDimensions="(10)" /> <argument name="arr" type="nonBasic" nonBasicTypeName="Piezo" arrayDimensions="(10)" />
</method> </method>
</interface> </interface>
``` ```
My code looks like this My code looks like this
```plaintext ```plaintext
[...] [...]
auto piezo = mal->createDataEntity<::fcfif::Piezo>(); auto piezo = mal->createDataEntity<::fcfif::Piezo>();
piezo->setId("foo"); piezo->setId("foo");
auto input = piezo->getInput(); auto input = piezo->getInput();
auto mode = input->getPiezoModeData(); auto mode = input->getPiezoModeData();
mode->setAction(::fcfif::ActionPiezoMode::SET_AUTO); mode->setAction(::fcfif::ActionPiezoMode::SET_AUTO);
auto union = mal->createDataEntity<::fcfif::FcsUnion>(); auto union = mal->createDataEntity<::fcfif::FcsUnion>();
union->setPiezoData(piezo); union->setPiezoData(piezo);
[...] [...]
``` ```
**Solution** **Solution**
```plaintext ```plaintext
auto p = factory.getClient<::fcfif::PiezoTestSync>(uri, auto p = factory.getClient<::fcfif::PiezoTestSync>(uri,
{std::make_shared<mal::rr::qos::ReplyTime> {std::make_shared<mal::rr::qos::ReplyTime>
(std::chrono::seconds(3))}, (std::chrono::seconds(3))},
{}); {});
auto mal = p->getMal(); auto mal = p->getMal();
auto piezo = mal->createDataEntity<::fcfif::Piezo>(); auto piezo = mal->createDataEntity<::fcfif::Piezo>();
piezo->setId("foo"); piezo->setId("foo");
auto input = piezo->getInput(); auto input = piezo->getInput();
auto piezoModeStruct = mal->createDataEntity<::fcfif::PiezoModeStruct>(); auto piezoModeStruct = mal->createDataEntity<::fcfif::PiezoModeStruct>();
piezoModeStruct->setMode(::fcfif::PiezoMode::PIEZO_MODE_1); piezoModeStruct->setMode(::fcfif::PiezoMode::PIEZO_MODE_1);
input->setPiezoModeData(piezoModeStruct); input->setPiezoModeData(piezoModeStruct);
auto piezo2 = mal->createDataEntity<::fcfif::Piezo>(); auto piezo2 = mal->createDataEntity<::fcfif::Piezo>();
piezo2->setId("foo2"); piezo2->setId("foo2");
auto input2 = piezo2->getInput(); auto input2 = piezo2->getInput();
input2->setPiezoMoveData(::fcfif::PiezoMove::PIEZO_MOVE_1); input2->setPiezoMoveData(::fcfif::PiezoMove::PIEZO_MOVE_1);
std::vector<std::shared_ptr<::fcfif::Piezo>> sa; std::vector<std::shared_ptr<::fcfif::Piezo>> sa;
sa.push_back(piezo); sa.push_back(piezo);
sa.push_back(piezo2); sa.push_back(piezo2);
p->test(sa); p->test(sa);
``` ```
**Background** **Background**
Your code does not work since you do not use union instance provided by the parent structure. You need to obtain nested structure/union via accessors and do not try to created your own (detached) instance. Your code does not work since you do not use union instance provided by the parent structure. You need to obtain nested structure/union via accessors and do not try to created your own (detached) instance.
This issue was first described in [ECII-154](https://jira.eso.org/browse/ECII-154) This issue was first described in [ECII-154](https://jira.eso.org/browse/ECII-154)
--- ---
--- ---
--- ---
### Failed to send request, send queue full \[MAL\] ### Failed to send request, send queue full \[MAL\]
**Problem** **Problem**
You are intending to update a config, but you get an IllegalStateException where the last line is You are intending to update a config, but you get an IllegalStateException where the last line is
```plaintext ```plaintext
elt.mal.zpb.rr.ClientAsyncImpl:183 elt.mal.zpb.rr.ClientAsyncImpl:183
``` ```
throw `new MalException("Failed to send request, send queue full");` throw `new MalException("Failed to send request, send queue full");`
**Solution** **Solution**
Probably you have called close() on the CiiConfigClient instance somewhere, maybe also implicitly during a try-with-resource block. Probably you have called close() on the CiiConfigClient instance somewhere, maybe also implicitly during a try-with-resource block.
--- ---
--- ---
--- ---
### Getting More Logs \[MAL Log\] ### Getting More Logs \[MAL Log\]
**Problem** **Problem**
The MAL seems to misbehave. How can I get more log messages from the MAL used in my application? The MAL seems to misbehave. How can I get more log messages from the MAL used in my application?
**Solution A** **Solution A**
**Java** **Java**
From MAL 1.1.0, edit the MAL log4j config xml and specify the MAL log levels: From MAL 1.1.0, edit the MAL log4j config xml and specify the MAL log levels:
```plaintext ```plaintext
<Logger name="elt.mal" level="TRACE" /> <Logger name="elt.mal" level="TRACE" />
``` ```
**Cpp** **Cpp**
Example for **Zpb.** For other middlewares, see below Example for **Zpb.** For other middlewares, see below
1. Put a log-config file into your file system: 1. Put a log-config file into your file system:
```plaintext ```plaintext
log4cplus.rootLogger=TRACE, stdout log4cplus.rootLogger=TRACE, stdout
log4cplus.logger.malDds=TRACE, MyFileAppender log4cplus.logger.malDds=TRACE, MyFileAppender
log4cplus.logger.malDdsBasePubSub=TRACE, MyFileAppender log4cplus.logger.malDdsBasePubSub=TRACE, MyFileAppender
log4cplus.logger.malDdsPublisher=TRACE, MyFileAppender log4cplus.logger.malDdsPublisher=TRACE, MyFileAppender
log4cplus.logger.malDdsInstancePublisher=TRACE, MyFileAppender log4cplus.logger.malDdsInstancePublisher=TRACE, MyFileAppender
log4cplus.logger.malDdsSubscriptionManager=TRACE, MyFileAppender log4cplus.logger.malDdsSubscriptionManager=TRACE, MyFileAppender
log4cplus.logger.malDdsSubscriptionReaderListener=TRACE, MyFileAppender log4cplus.logger.malDdsSubscriptionReaderListener=TRACE, MyFileAppender
log4cplus.logger.malDdsSubscriber=TRACE, MyFileAppender log4cplus.logger.malDdsSubscriber=TRACE, MyFileAppender
log4cplus.logger.malDdsMrvSubscriber=TRACE, MyFileAppender log4cplus.logger.malDdsMrvSubscriber=TRACE, MyFileAppender
log4cplus.logger.malDdsRequesterImpl=TRACE, MyFileAppender log4cplus.logger.malDdsRequesterImpl=TRACE, MyFileAppender
log4cplus.additivity.malDds=True log4cplus.additivity.malDds=True
log4cplus.additivity.malDdsBasePubSub=True log4cplus.additivity.malDdsBasePubSub=True
log4cplus.additivity.malDdsPublisher=True log4cplus.additivity.malDdsPublisher=True
log4cplus.additivity.malDdsInstancePublisher=True log4cplus.additivity.malDdsInstancePublisher=True
log4cplus.additivity.malDdsSubscriptionManager=True log4cplus.additivity.malDdsSubscriptionManager=True
log4cplus.additivity.malDdsSubscriptionReaderListener=True log4cplus.additivity.malDdsSubscriptionReaderListener=True
log4cplus.additivity.malDdsSubscriber=True log4cplus.additivity.malDdsSubscriber=True
log4cplus.additivity.malDdsMrvSubscriber=True log4cplus.additivity.malDdsMrvSubscriber=True
log4cplus.additivity.malDdsRequesterImpl=True log4cplus.additivity.malDdsRequesterImpl=True
log4cplus.logger.malZpb=TRACE, MyFileAppender log4cplus.logger.malZpb=TRACE, MyFileAppender
log4cplus.logger.malZpbBasePubSub=TRACE, MyFileAppender log4cplus.logger.malZpbBasePubSub=TRACE, MyFileAppender
log4cplus.logger.malZpbPublisher=TRACE, MyFileAppender log4cplus.logger.malZpbPublisher=TRACE, MyFileAppender
log4cplus.logger.malZpbInstancePublisher=TRACE, MyFileAppender log4cplus.logger.malZpbInstancePublisher=TRACE, MyFileAppender
log4cplus.logger.malZpbSubscriber=TRACE, MyFileAppender log4cplus.logger.malZpbSubscriber=TRACE, MyFileAppender
log4cplus.logger.malZpbMrvSubscriber=TRACE, MyFileAppender log4cplus.logger.malZpbMrvSubscriber=TRACE, MyFileAppender
log4cplus.logger.malZpbServer=TRACE, MyFileAppender log4cplus.logger.malZpbServer=TRACE, MyFileAppender
log4cplus.logger.malZpbClientAsyncImpl=TRACE, MyFileAppender log4cplus.logger.malZpbClientAsyncImpl=TRACE, MyFileAppender
log4cplus.additivity.malZpb=True log4cplus.additivity.malZpb=True
log4cplus.additivity.malZpbBasePubSub=True log4cplus.additivity.malZpbBasePubSub=True
log4cplus.additivity.malZpbPublisher=True log4cplus.additivity.malZpbPublisher=True
log4cplus.additivity.malZpbInstancePublisher=True log4cplus.additivity.malZpbInstancePublisher=True
log4cplus.additivity.malZpbSubscriber=True log4cplus.additivity.malZpbSubscriber=True
log4cplus.additivity.malZpbMrvSubscriber=True log4cplus.additivity.malZpbMrvSubscriber=True
log4cplus.additivity.malZpbServer=True log4cplus.additivity.malZpbServer=True
log4cplus.additivity.malZpbClientAsyncImpl=True log4cplus.additivity.malZpbClientAsyncImpl=True
log4cplus.logger.malOpcua=TRACE, MyFileAppender log4cplus.logger.malOpcua=TRACE, MyFileAppender
log4cplus.logger.malOpcuaBasePubSub=TRACE, MyFileAppender log4cplus.logger.malOpcuaBasePubSub=TRACE, MyFileAppender
log4cplus.logger.malOpcuaPublisher=TRACE, MyFileAppender log4cplus.logger.malOpcuaPublisher=TRACE, MyFileAppender
log4cplus.logger.malOpcuaInstancePublisher=TRACE, MyFileAppender log4cplus.logger.malOpcuaInstancePublisher=TRACE, MyFileAppender
log4cplus.logger.malOpcuaSubscriber=TRACE, MyFileAppender log4cplus.logger.malOpcuaSubscriber=TRACE, MyFileAppender
log4cplus.logger.malOpcuaMrvSubscriber=TRACE, MyFileAppender log4cplus.logger.malOpcuaMrvSubscriber=TRACE, MyFileAppender
log4cplus.logger.malOpcuaMrvDataMonitor=TRACE, MyFileAppender log4cplus.logger.malOpcuaMrvDataMonitor=TRACE, MyFileAppender
log4cplus.logger.malOpcuaDataPoller=TRACE, MyFileAppender log4cplus.logger.malOpcuaDataPoller=TRACE, MyFileAppender
log4cplus.logger.malOpcuaDataMonitor=TRACE, MyFileAppender log4cplus.logger.malOpcuaDataMonitor=TRACE, MyFileAppender
log4cplus.logger.malOpcuaClient=TRACE, MyFileAppender log4cplus.logger.malOpcuaClient=TRACE, MyFileAppender
log4cplus.logger.malOpcuaClientEventLoop=TRACE, MyFileAppender log4cplus.logger.malOpcuaClientEventLoop=TRACE, MyFileAppender
log4cplus.additivity.malOpcua=True log4cplus.additivity.malOpcua=True
log4cplus.additivity.malOpcuaBasePubSub=True log4cplus.additivity.malOpcuaBasePubSub=True
log4cplus.additivity.malOpcuaPublisher=True log4cplus.additivity.malOpcuaPublisher=True
log4cplus.additivity.malOpcuaInstancePublisher=True log4cplus.additivity.malOpcuaInstancePublisher=True
log4cplus.additivity.malOpcuaSubscriber=True log4cplus.additivity.malOpcuaSubscriber=True
log4cplus.additivity.malOpcuaMrvSubscriber=True log4cplus.additivity.malOpcuaMrvSubscriber=True
log4cplus.additivity.malOpcuaMrvDataMonitor=True log4cplus.additivity.malOpcuaMrvDataMonitor=True
log4cplus.additivity.malOpcuaDataPoller=True log4cplus.additivity.malOpcuaDataPoller=True
log4cplus.additivity.malOpcuaDataMonitor=True log4cplus.additivity.malOpcuaDataMonitor=True
log4cplus.additivity.malOpcuaClient=True log4cplus.additivity.malOpcuaClient=True
log4cplus.additivity.malOpcuaClientEventLoop=True log4cplus.additivity.malOpcuaClientEventLoop=True
log4cplus.appender.stdout=log4cplus::ConsoleAppender log4cplus.appender.stdout=log4cplus::ConsoleAppender
log4cplus.appender.stdout.layout=log4cplus::PatternLayout log4cplus.appender.stdout.layout=log4cplus::PatternLayout
log4cplus.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n log4cplus.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
log4cplus.appender.MyFileAppender=log4cplus::RollingFileAppender log4cplus.appender.MyFileAppender=log4cplus::RollingFileAppender
log4cplus.appender.MyFileAppender.File=/tmp/elt-mal-cpp-trace.log log4cplus.appender.MyFileAppender.File=/tmp/elt-mal-cpp-trace.log
log4cplus.appender.MyFileAppender.layout=log4cplus::PatternLayout log4cplus.appender.MyFileAppender.layout=log4cplus::PatternLayout
log4cplus.appender.MyFileAppender.layout.ConversionPattern=[%-5p][%D{%Y/%m/%d %H:%M:%S:%q}][%-l][%t] %m%n log4cplus.appender.MyFileAppender.layout.ConversionPattern=[%-5p][%D{%Y/%m/%d %H:%M:%S:%q}][%-l][%t] %m%n
``` ```
2. Configure log4cplus prior to using CII MAL: 2. Configure log4cplus prior to using CII MAL:
```plaintext ```plaintext
#include <log4cplus/configurator.h> #include <log4cplus/configurator.h>
std::string pathToLogPropFile = "..."; std::string pathToLogPropFile = "...";
if (pathToLogPropFile .size() > 0) { if (pathToLogPropFile .size() > 0) {
log4cplus::PropertyConfigurator::doConfigure(pathToLogPropFile ); log4cplus::PropertyConfigurator::doConfigure(pathToLogPropFile );
} }
``` ```
3. Pass the path to the log-config to the specific MAL being loaded: 3. Pass the path to the log-config to the specific MAL being loaded:
MAL logging is initialized from a configuration file, the path of which is read from mal properties with key mal::PROP_LOG_CONFIG_FILENAME. When loading mal, use set mal::PROP_LOG_CONFIG_FILENAME in mal properties. MAL logging is initialized from a configuration file, the path of which is read from mal properties with key mal::PROP_LOG_CONFIG_FILENAME. When loading mal, use set mal::PROP_LOG_CONFIG_FILENAME in mal properties.
For example: For example:
```plaintext ```plaintext
auto zpbMal = mal::loadMal("zpb", auto zpbMal = mal::loadMal("zpb",
mal::Mal::Properties{{mal::PROP_LOG_CONFIG_FILENAME,"/path/to/mal-log4cplus.conf"}} mal::Mal::Properties{{mal::PROP_LOG_CONFIG_FILENAME,"/path/to/mal-log4cplus.conf"}}
); );
``` ```
or in **python:** or in **python:**
```plaintext ```plaintext
import elt.pymal as mal import elt.pymal as mal
zpbMal = mal.loadMal ("zpb", {"zpb.log4cplus.filename":"/path/to/mal-log4cplus.conf"}) zpbMal = mal.loadMal ("zpb", {"zpb.log4cplus.filename":"/path/to/mal-log4cplus.conf"})
``` ```
python example with inline config python example with inline config
```plaintext ```plaintext
import elt.pymal import elt.pymal
with open ("/tmp/mal.log.conf", 'w') as f: with open ("/tmp/mal.log.conf", 'w') as f:
f.write(''' f.write('''
log4cplus.appender.stdout=log4cplus::ConsoleAppender log4cplus.appender.stdout=log4cplus::ConsoleAppender
log4cplus.logger.malDds=TRACE, stdout log4cplus.logger.malDds=TRACE, stdout
log4cplus.logger.malDdsBasePubSub=TRACE, stdout log4cplus.logger.malDdsBasePubSub=TRACE, stdout
log4cplus.logger.malDdsSubscriber=TRACE, stdout log4cplus.logger.malDdsSubscriber=TRACE, stdout
''') ''')
ddsMalProps = {"dds.log4cplus.filename" : "/tmp/mal.log.conf"} ddsMalProps = {"dds.log4cplus.filename" : "/tmp/mal.log.conf"}
ddsMal = elt.pymal.loadMalForUri("dds.ps://", ddsMalProps) ddsMal = elt.pymal.loadMalForUri("dds.ps://", ddsMalProps)
``` ```
**Solution B** **Solution B**
With [ECII-246](https://jira.eso.org/browse/ECII-246), it is possible to change the log levels of the MAL loggers at run-time via a method call: With [ECII-246](https://jira.eso.org/browse/ECII-246), it is possible to change the log levels of the MAL loggers at run-time via a method call:
```plaintext ```plaintext
#include <mal/util/MalLoggingUtil.hpp> #include <mal/util/MalLoggingUtil.hpp>
::elt::mal::util::logging::setLogLevelForLoggers( ... ) ::elt::mal::util::logging::setLogLevelForLoggers( ... )
// set all mal loggers to INFO... // set all mal loggers to INFO...
std::vector<elt::mal::util::logging::LoggerInfo> loggers = elt::mal::util::logging::getLoggers(); std::vector<elt::mal::util::logging::LoggerInfo> loggers = elt::mal::util::logging::getLoggers();
std::vector<elt::mal::util::logging::LoggerInfo> info; std::vector<elt::mal::util::logging::LoggerInfo> info;
for (auto const& logger : loggers) { for (auto const& logger : loggers) {
info.push_back(elt::mal::util::logging::LoggerInfo(logger.loggerName, ::log4cplus::INFO_LOG_LEVEL)); info.push_back(elt::mal::util::logging::LoggerInfo(logger.loggerName, ::log4cplus::INFO_LOG_LEVEL));
} }
elt::mal::util::logging::setLogLevelForLoggers(info); elt::mal::util::logging::setLogLevelForLoggers(info);
// print all mal loggers and log level // print all mal loggers and log level
loggers = elt::mal::util::logging::getLoggers(); loggers = elt::mal::util::logging::getLoggers();
std::cout << "Loggers:\n"; std::cout << "Loggers:\n";
for (auto const& logger : loggers) { for (auto const& logger : loggers) {
std::cout << "\t" << logger.loggerName << ": " << logger.logLevel << std::endl; std::cout << "\t" << logger.loggerName << ": " << logger.logLevel << std::endl;
} }
``` ```
The allowed logger names are listed below. The allowed logger names are listed below.
**Background** **Background**
MAL does not use the Cii Logging System (CiiLogManager etc.) directly. Instead, MAL expects logging to be initialized from a configuration file. Note that the format of the log-config differs per programming language. MAL does not use the Cii Logging System (CiiLogManager etc.) directly. Instead, MAL expects logging to be initialized from a configuration file. Note that the format of the log-config differs per programming language.
List of logger names available in the **Cpp MAL / Python MAL:** List of logger names available in the **Cpp MAL / Python MAL:**
Loggers for **mal-zpb** Loggers for **mal-zpb**
- malZpbInstancePublisher - malZpbInstancePublisher
- malZpbPublisher - malZpbPublisher
- malZpbClientAsyncImpl - malZpbClientAsyncImpl
- malZpbServer - malZpbServer
- malZpb - malZpb
- malZpbSubscriber - malZpbSubscriber
- malZpbMrvSubscriber - malZpbMrvSubscriber
- malZpbBasePubSub - malZpbBasePubSub
Loggers for **mal-dds** Loggers for **mal-dds**
- malDds - malDds
- malDdsSubscriptionManager - malDdsSubscriptionManager
- malDdsSubscriptionReaderListener - malDdsSubscriptionReaderListener
- malDdsSubscriber - malDdsSubscriber
- malDdsPublisher - malDdsPublisher
- malDdsBasePubSub - malDdsBasePubSub
- malDdsMrvSubscriber - malDdsMrvSubscriber
- malDdsRequesterImpl - malDdsRequesterImpl
- malDdsInstancePublisher - malDdsInstancePublisher
Loggers for **mal-opcua** Loggers for **mal-opcua**
- malOpcua - malOpcua
- malOpcuaBasePubSub - malOpcuaBasePubSub
- malOpcuaMrvSubscriber - malOpcuaMrvSubscriber
- malOpcuaMrvDataMonitor - malOpcuaMrvDataMonitor
- malOpcuaInstancePublisher - malOpcuaInstancePublisher
- malOpcuaPublisher - malOpcuaPublisher
- malOpcuaSubscriber - malOpcuaSubscriber
- malOpcuaDataPoller - malOpcuaDataPoller
- malOpcuaDataMonitor - malOpcuaDataMonitor
- malOpcuaClient - malOpcuaClient
- malOpcuaClientEventLoop - malOpcuaClientEventLoop
--- ---
--- ---
--- ---
### More Frames expected \[MAL ZMQ\] ### More Frames expected \[MAL ZMQ\]
**Problem** **Problem**
In your application you get errors like this: In your application you get errors like this:
```plaintext ```plaintext
Oct 16, 2019 11:26:21 AM elt.mal.zpb.ps.ZpbSubscriber events Oct 16, 2019 11:26:21 AM elt.mal.zpb.ps.ZpbSubscriber events
WARNING: Remote data entity type hash does not match (1040672065 != 1708154137). WARNING: Remote data entity type hash does not match (1040672065 != 1708154137).
Oct 16, 2019 11:26:21 AM elt.mal.zpb.ps.ZpbSubscriber events Oct 16, 2019 11:26:21 AM elt.mal.zpb.ps.ZpbSubscriber events
WARNING: Failed to process message. WARNING: Failed to process message.
java.lang.RuntimeException: more frames expected java.lang.RuntimeException: more frames expected
at elt.mal.zpb.ps.ZpbSubscriber.requireMoreFrames(ZpbSubscriber.java:82) at elt.mal.zpb.ps.ZpbSubscriber.requireMoreFrames(ZpbSubscriber.java:82)
at elt.mal.zpb.ps.ZpbSubscriber.events(ZpbSubscriber.java:114) at elt.mal.zpb.ps.ZpbSubscriber.events(ZpbSubscriber.java:114)
``` ```
**Background** **Background**
The first warning message indicates that your client has received a piece of data (= MAL entity type) on a channel that should not carry such data. This means you are running two publishers, publishing different types of data, on the same channel. The first warning message indicates that your client has received a piece of data (= MAL entity type) on a channel that should not carry such data. This means you are running two publishers, publishing different types of data, on the same channel.
**Example of topic definition with port-clash** **Example of topic definition with port-clash**
```xml ```xml
<pubsub_topic> <pubsub_topic>
<topic_name>sm:current_pos</topic_name> <topic_name>sm:current_pos</topic_name>
<topic_type>sm_current_pos</topic_type> <topic_type>sm_current_pos</topic_type>
<address_uri>zpb.ps://134.171.2.220:57110/test</address_uri> <address_uri>zpb.ps://134.171.2.220:57110/test</address_uri>
<qos latency_ms="1" deadline_ms="100"/> <qos latency_ms="1" deadline_ms="100"/>
<performance rate_hz="10" latency_ms="1" synchronous="false" /> <performance rate_hz="10" latency_ms="1" synchronous="false" />
<mal> <mal>
<zpb /> <zpb />
</mal> </mal>
</pubsub_topic> </pubsub_topic>
<pubsub_topic> <pubsub_topic>
<topic_name>hp:global_status</topic_name> <topic_name>hp:global_status</topic_name>
<topic_type>hp_global_status</topic_type> <topic_type>hp_global_status</topic_type>
<address_uri>zpb.ps://134.171.2.220:57110/test</address_uri> <address_uri>zpb.ps://134.171.2.220:57110/test</address_uri>
<qos latency_ms="10" deadline_ms="100"/> <qos latency_ms="10" deadline_ms="100"/>
<performance rate_hz="1" latency_ms="10" synchronous="false" /> <performance rate_hz="1" latency_ms="10" synchronous="false" />
<mal> <mal>
<zpb /> <zpb />
</mal> </mal>
</pubsub_topic> </pubsub_topic>
``` ```
The second warning and the error trace are just a consequence of the first warning. The second warning and the error trace are just a consequence of the first warning.
**Solution** **Solution**
Check your topics.xml file, and make sure each channel has its own exclusive topic name. Check your topics.xml file, and make sure each channel has its own exclusive topic name.
In the above example, e.g.: In the above example, e.g.:
```plaintext ```plaintext
zpb.ps://134.171.2.220:57110/test1 zpb.ps://134.171.2.220:57110/test1
``` ```
and and
```plaintext ```plaintext
zpb.ps://134.171.2.220:57110/test2 zpb.ps://134.171.2.220:57110/test2
``` ```
--- ---
--- ---
--- ---
### Address in use \[MAL ZMQ\] ### Address in use \[MAL ZMQ\]
**Problem** **Problem**
Running your application, you see this error message: Running your application, you see this error message:
```plaintext ```plaintext
ZMQException: Errno 48 : Address already in use ZMQException: Errno 48 : Address already in use
``` ```
**Solution A** **Solution A**
Another instance of your application is still running. Another instance of your application is still running.
**Solution B** **Solution B**
Another instance of your application has non-gracefully terminated without freeing the network port. Another instance of your application has non-gracefully terminated without freeing the network port.
Ensure your application always performs a call to "mal.close()" on shutdown. Ensure your application always performs a call to "mal.close()" on shutdown.
**Solution C** **Solution C**
This could be really a Usage Error due to wrong configuration. This could be really a Usage Error due to wrong configuration.
The error message is in fact misleading. The error message is in fact misleading.
**Example** **Example**
```plaintext ```plaintext
eltcii33 [09:38:27] eeltdev:~/mschilli > mal-esotests-testclient1 pub sAddr=zpb://eltcii28:12333/Sample tSlow=100 nSamp=100 eltcii33 [09:38:27] eeltdev:~/mschilli > mal-esotests-testclient1 pub sAddr=zpb://eltcii28:12333/Sample tSlow=100 nSamp=100
pub:sys: Available MAL Flavours loaded: [dds, opc, zpb] pub:sys: Available MAL Flavours loaded: [dds, opc, zpb]
pub:config: sAddr=zpb://eltcii28:12333/Sample pub:config: sAddr=zpb://eltcii28:12333/Sample
pub:config: nSamp=100 pub:config: nSamp=100
pub:config: tSlow=100 pub:config: tSlow=100
Internal Error: org.eso.elt.mal.MalException: org.zeromq.ZMQException: Errno 48 : Address already in use Internal Error: org.eso.elt.mal.MalException: org.zeromq.ZMQException: Errno 48 : Address already in use
``` ```
**Reason** **Reason**
The above code is trying, on host eltcii33, to publish with an endpoint eltcii28. The above code is trying, on host eltcii33, to publish with an endpoint eltcii28.
**Fix** **Fix**
On eltcii33, the endpoint must be eltcii33. On eltcii33, the endpoint must be eltcii33.
--- ---
--- ---
--- ---
### Scheme not supported \[MAL\] ### Scheme not supported \[MAL\]
**Problem** **Problem**
Running your application, you get this error message: Running your application, you get this error message:
```plaintext ```plaintext
elt.mal.SchemeNotSupportedException: middleware not supported elt.mal.SchemeNotSupportedException: middleware not supported
``` ```
**Solution A** **Solution A**
In your code, you've misspelled the middleware name, e.g. "opc" instead of "opcua" In your code, you've misspelled the middleware name, e.g. "opc" instead of "opcua"
**Solution B** **Solution B**
The middleware is supported in fact, but failed to load. The middleware is supported in fact, but failed to load.
- E.g. in DDS, you are using a Qos profile xml file which has some illegal syntax inside. - E.g. in DDS, you are using a Qos profile xml file which has some illegal syntax inside.
--- ---
--- ---
--- ---
### Choosing a NIC \[MAL DDS\] ### Choosing a NIC \[MAL DDS\]
**Problem** **Problem**
I'm using MAL-DDS (or MAL-MUDPI), and I have two network cards (NICs) installed. MAL uses the wrong one, i.e. my network traffic goes into the "office" network, but should go into the "control" network. I'm using MAL-DDS (or MAL-MUDPI), and I have two network cards (NICs) installed. MAL uses the wrong one, i.e. my network traffic goes into the "office" network, but should go into the "control" network.
**Background** **Background**
As multicast addresses are by definition not associated with hardware (ie they map to MAC addresses which have no corresponding Ethernet card), there is no means for the OS to resolve which NIC the IGMP subscription should be sent down. Thus the NIC must be specified, or the default is used (which is the office network). As multicast addresses are by definition not associated with hardware (ie they map to MAC addresses which have no corresponding Ethernet card), there is no means for the OS to resolve which NIC the IGMP subscription should be sent down. Thus the NIC must be specified, or the default is used (which is the office network).
The multicast middlewares (DDS and MUDPI) supported by the MAL allow you to specify which NIC you want to use for outgoing traffic. Thus, this boils down to configuring the middleware. The multicast middlewares (DDS and MUDPI) supported by the MAL allow you to specify which NIC you want to use for outgoing traffic. Thus, this boils down to configuring the middleware.
**Solution (DDS)** **Solution (DDS)**
Get the XML file shown in Solution #1 on this page: <https://community.rti.com/howto/control-or-restrict-network-interfaces-nics-used-discovery-and-data-distribution>, and continue with this article: [KB: Configuring DDS](https://gitlab.eso.org/ecs/eltsw-docs/-/wikis/KnowledgeBase/CII#configuring-dds-mal-dds) Get the XML file shown in Solution #1 on this page: <https://community.rti.com/howto/control-or-restrict-network-interfaces-nics-used-discovery-and-data-distribution>, and continue with this article: [KB: Configuring DDS](https://gitlab.eso.org/ecs/eltsw-docs/-/wikis/KnowledgeBase/CII#configuring-dds-mal-dds)
**Solution (MUDPI)** **Solution (MUDPI)**
Set the "mudpi.ps.interfaceName" mal property when creating the MAL: Set the "mudpi.ps.interfaceName" mal property when creating the MAL:
```plaintext ```plaintext
auto &factory = ::elt::mal::loadMalForUri("mudpi.ps://", auto &factory = ::elt::mal::loadMalForUri("mudpi.ps://",
{ {"mudpi.ps.interfaceName","192.168.100.165"} } ); { {"mudpi.ps.interfaceName","192.168.100.165"} } );
``` ```
--- ---
--- ---
--- ---
### Configuring DDS \[MAL DDS\] ### Configuring DDS \[MAL DDS\]
**Problem** **Problem**
Some of the middlewares usable through MAL offer a variety of configuration options. Some of the middlewares usable through MAL offer a variety of configuration options.
This article explains how to define and use configuration for the DDS middleware. This article explains how to define and use configuration for the DDS middleware.
**Solution** **Solution**
To configure DDS, 3 things are necessary: To configure DDS, 3 things are necessary:
- put the desired config into an external XML file (see Fast DDS documentation/examples) - put the desired config into an external XML file (see Fast DDS documentation/examples)
- set the FASTRTPS_DEFAULT_PROFILES_FILE (Connext: NDDS_QOS_PROFILES) environment variable, so DDS finds the XML file (This environment variable need NOT be set, the path can be passed directly in the MAL properties, malprops in the example below). - set the FASTRTPS_DEFAULT_PROFILES_FILE (Connext: NDDS_QOS_PROFILES) environment variable, so DDS finds the XML file (This environment variable need NOT be set, the path can be passed directly in the MAL properties, malprops in the example below).
- pass 2 properties to the MAL factory, so DDS finds the right profile in the XML file - pass 2 properties to the MAL factory, so DDS finds the right profile in the XML file
**Example: How to restrict DDS traffic to your own host** **Example: How to restrict DDS traffic to your own host**
XML file (see <https://fast-dds.docs.eprosima.com/en/latest/fastdds/discovery/general_disc_settings.html>) XML file (see <https://fast-dds.docs.eprosima.com/en/latest/fastdds/discovery/general_disc_settings.html>)
```xml ```xml
<?xml version="1.0" encoding="UTF-8" ?> <?xml version="1.0" encoding="UTF-8" ?>
<dds> <dds>
<profiles xmlns="http://www.eprosima.com/XMLSchemas/fastRTPS_Profiles"> <profiles xmlns="http://www.eprosima.com/XMLSchemas/fastRTPS_Profiles">
<participant profile_name="MyApp_Default"> <participant profile_name="MyApp_Default">
<rtps> <rtps>
<builtin> <builtin>
<discovery_config> <discovery_config>
<ignoreParticipantFlags>FILTER_DIFFERENT_HOST</ignoreParticipantFlags> <ignoreParticipantFlags>FILTER_DIFFERENT_HOST</ignoreParticipantFlags>
</discovery_config> </discovery_config>
</builtin> </builtin>
</rtps> </rtps>
</participant> </participant>
</profiles> </profiles>
</dds> </dds>
``` ```
Code (C++) Code (C++)
```cpp ```cpp
// Create DDS-MAL with custom mal properties // Create DDS-MAL with custom mal properties
// With Fast DDS, profile.library prop and env var *must* have same value! // With Fast DDS, profile.library prop and env var *must* have same value!
// Here the env var precedes, but you could do the inverse (using setenv). // Here the env var precedes, but you could do the inverse (using setenv).
char* env_var = std::getenv("FASTRTPS_DEFAULT_PROFILES_FILE"); char* env_var = std::getenv("FASTRTPS_DEFAULT_PROFILES_FILE");
const ::elt::mal::Mal::Properties malprops { {"dds.qos.profile.library", env_var}, const ::elt::mal::Mal::Properties malprops { {"dds.qos.profile.library", env_var},
{"dds.qos.profile.name", "MyApp_Default"} }; {"dds.qos.profile.name", "MyApp_Default"} };
auto &factory = ::elt::mal::loadMalForUri ("dds.ps://", malprops); auto &factory = ::elt::mal::loadMalForUri ("dds.ps://", malprops);
// Publishers created from here on will have the setting applied // Publishers created from here on will have the setting applied
auto malpub = factory.getPublisher<AltAz> (pubsuburi, qos, {}); auto malpub = factory.getPublisher<AltAz> (pubsuburi, qos, {});
``` ```
Before running your code: Before running your code:
```plaintext ```plaintext
export FASTRTPS_DEFAULT_PROFILES_FILE=<path of XML file> export FASTRTPS_DEFAULT_PROFILES_FILE=<path of XML file>
``` ```
--- ---
--- ---
--- ---
### Using DDS Monitor \[MAL DDS\] ### Using DDS Monitor \[MAL DDS\]
**Problem** **Problem**
The DDS monitor _fastdds_monitor_ can show all DDS Participants (peers) for the selected domain. The DDS monitor _fastdds_monitor_ can show all DDS Participants (peers) for the selected domain.
**Solution** **Solution**
Important is that in order to enable publishing of this meta data, it must be enabled either via an environment variable in the shell that the DDS application is run in (i.e. in publishers and subscribers, not in the shell where the fastdds_monitor is running, OR (preferably) set in the XML QoS file. Important is that in order to enable publishing of this meta data, it must be enabled either via an environment variable in the shell that the DDS application is run in (i.e. in publishers and subscribers, not in the shell where the fastdds_monitor is running, OR (preferably) set in the XML QoS file.
Using the environment variable: Using the environment variable:
```plaintext ```plaintext
export FASTDDS_STATISTICS="HISTORY_LATENCY_TOPIC;NETWORK_LATENCY_TOPIC;PUBLICATION_THROUGHPUT_TOPIC;\ export FASTDDS_STATISTICS="HISTORY_LATENCY_TOPIC;NETWORK_LATENCY_TOPIC;PUBLICATION_THROUGHPUT_TOPIC;\
RTPS_SENT_TOPIC;RTPS_LOST_TOPIC;HEARTBEAT_COUNT_TOPIC;ACKNACK_COUNT_TOPIC;NACKFRAG_COUNT_TOPIC;\ RTPS_SENT_TOPIC;RTPS_LOST_TOPIC;HEARTBEAT_COUNT_TOPIC;ACKNACK_COUNT_TOPIC;NACKFRAG_COUNT_TOPIC;\
GAP_COUNT_TOPIC;DATA_COUNT_TOPIC;RESENT_DATAS_TOPIC;SAMPLE_DATAS_TOPIC;PDP_PACKETS_TOPIC;EDP_PACKETS_TOPIC;\ GAP_COUNT_TOPIC;DATA_COUNT_TOPIC;RESENT_DATAS_TOPIC;SAMPLE_DATAS_TOPIC;PDP_PACKETS_TOPIC;EDP_PACKETS_TOPIC;\
DISCOVERY_TOPIC;PHYSICAL_DATA_TOPIC" DISCOVERY_TOPIC;PHYSICAL_DATA_TOPIC"
``` ```
Setting in the QoS XML file: Setting in the QoS XML file:
```plaintext ```plaintext
<participant profile_name="MyApp_Default_Participant"> <participant profile_name="MyApp_Default_Participant">
<rtps> <rtps>
<propertiesPolicy> <propertiesPolicy>
<properties> <properties>
<!-- Activate Fast DDS Statistics Module --> <!-- Activate Fast DDS Statistics Module -->
<property> <property>
<name>fastdds.statistics</name> <name>fastdds.statistics</name>
<value>HISTORY_LATENCY_TOPIC;NETWORK_LATENCY_TOPIC;PUBLICATION_THROUGHPUT_TOPIC;RTPS_SENT_TOPIC;RTPS_LOST_TOPIC;HEARTBEAT_COUNT_TOPIC;ACKNACK_COUNT_TOPIC;NACKFRAG_COUNT_TOPIC;GAP_COUNT_TOPIC;DATA_COUNT_TOPIC;RESENT_DATAS_TOPIC;SAMPLE_DATAS_TOPIC;PDP_PACKETS_TOPIC;EDP_PACKETS_TOPIC;DISCOVERY_TOPIC;PHYSICAL_DATA_TOPIC</value> <value>HISTORY_LATENCY_TOPIC;NETWORK_LATENCY_TOPIC;PUBLICATION_THROUGHPUT_TOPIC;RTPS_SENT_TOPIC;RTPS_LOST_TOPIC;HEARTBEAT_COUNT_TOPIC;ACKNACK_COUNT_TOPIC;NACKFRAG_COUNT_TOPIC;GAP_COUNT_TOPIC;DATA_COUNT_TOPIC;RESENT_DATAS_TOPIC;SAMPLE_DATAS_TOPIC;PDP_PACKETS_TOPIC;EDP_PACKETS_TOPIC;DISCOVERY_TOPIC;PHYSICAL_DATA_TOPIC</value>
</property> </property>
</properties> </properties>
</propertiesPolicy> </propertiesPolicy>
``` ```
Once this is done, the statistics are visible. Note that not all statistics (e.g. the QoS of a participant) are correctly displayed by the DDS Monitor, this is slowly being improved with each release. Once this is done, the statistics are visible. Note that not all statistics (e.g. the QoS of a participant) are correctly displayed by the DDS Monitor, this is slowly being improved with each release.
I already have some comments/feedback to eProsima. I welcome any feedback from your tests as well. I already have some comments/feedback to eProsima. I welcome any feedback from your tests as well.
By default all MAL DDS peers have the name “RTPSParticipant”. By default all MAL DDS peers have the name “RTPSParticipant”.
There are two ways to set a custom name: There are two ways to set a custom name:
A participant name can be assigned in the XML QoS file as follows: A participant name can be assigned in the XML QoS file as follows:
```plaintext ```plaintext
<participant profile_name="MyApp_Default_Participant"> <participant profile_name="MyApp_Default_Participant">
<rtps> <rtps>
<name>MyApp_Participant</name> <name>MyApp_Participant</name>
</rtps> </rtps>
``` ```
However this means all participants sharing this profile have the same name. However this means all participants sharing this profile have the same name.
Using the MAL Property to allow setting the participant name, which will set and/or override any participant name read from the QoS file. Using the MAL Property to allow setting the participant name, which will set and/or override any participant name read from the QoS file.
The property is: dds.qos.participant.name The property is: dds.qos.participant.name
For example it may be used as follows: For example it may be used as follows:
```plaintext ```plaintext
const ::elt::mal::Mal::Properties pubprops { const ::elt::mal::Mal::Properties pubprops {
{"dds.qos.profile.library", env_var}, {"dds.qos.profile.library", env_var},
{"dds.qos.profile.name.publisher", "MyApp_Default_Publisher"}, {"dds.qos.profile.name.publisher", "MyApp_Default_Publisher"},
{"dds.qos.profile.name.writer", "MyApp_Default_Writer"}, {"dds.qos.profile.name.writer", "MyApp_Default_Writer"},
{"dds.qos.profile.name.topic", "MyApp_Default_Topic"}, {"dds.qos.profile.name.topic", "MyApp_Default_Topic"},
{"dds.qos.participant.name", "icd-demo-publisher"}, {"dds.qos.participant.name", "icd-demo-publisher"},
{"dds.qos.profile.name.participant", "MyApp_Default_Participant"} {"dds.qos.profile.name.participant", "MyApp_Default_Participant"}
}; };
``` ```
***Example*** ***Example***
build and install icd-demo: build and install icd-demo:
- git clone https://gitlab.eso.org/cii/mal/icd-demo.git - git clone https://gitlab.eso.org/cii/mal/icd-demo.git
- cd icd-demo/ - cd icd-demo/
- waf configure build install - waf configure build install
- set the environment variable above and run the deme publisher and subscriber - set the environment variable above and run the deme publisher and subscriber
- mal-api-demo-publisher --uri "dds.ps:///m1" - mal-api-demo-publisher --uri "dds.ps:///m1"
- mal-api-demo-subscriber --uri "dds.ps:///m1" - mal-api-demo-subscriber --uri "dds.ps:///m1"
- finally, run fastdds_monitor to observe the statistics. - finally, run fastdds_monitor to observe the statistics.
--- ---
--- ---
--- ---
### Topic History a.k.a. late joiners \[MAL DDS\] ### Topic History a.k.a. late joiners \[MAL DDS\]
Many PubSub topics need to cater for late joining subscribers. That is, subscribers typically need to receive that last value published, and then all values published from the time of joining, on. Many PubSub topics need to cater for late joining subscribers. That is, subscribers typically need to receive that last value published, and then all values published from the time of joining, on.
There are a few key aspects of DDS that must be configured to enable this: There are a few key aspects of DDS that must be configured to enable this:
1. The topic must publish a type that has a key. History is stored in the publisher on an instance (i.e. key value) basis (i.e. one sample per instance). In ICD XML, the type struct must contain a member with key="true" set, e.g.: 1. The topic must publish a type that has a key. History is stored in the publisher on an instance (i.e. key value) basis (i.e. one sample per instance). In ICD XML, the type struct must contain a member with key="true" set, e.g.:
```plaintext ```plaintext
<struct name="Sample" trace="true"> <struct name="Sample" trace="true">
<member name="daqId" type="int64_t" key="true" /> <member name="daqId" type="int64_t" key="true" />
<member name="value" type="double" /> <member name="value" type="double" />
</struct> </struct>
``` ```
2. The topic QoS must be set to have historyQos set to KEEP_LAST, with depth 1. For example: 2. The topic QoS must be set to have historyQos set to KEEP_LAST, with depth 1. For example:
```plaintext ```plaintext
<topic profile_name="MyApp_Default_Topic"> <topic profile_name="MyApp_Default_Topic">
<historyQos> <historyQos>
<kind>KEEP_LAST</kind> <kind>KEEP_LAST</kind>
<depth>1</depth> <depth>1</depth>
</historyQos> </historyQos>
</topic> </topic>
``` ```
3. Both data_writer and data_reader QoS must be set to reliability RELIABLE. Reliable communications is required to receive historical data. 3. Both data_writer and data_reader QoS must be set to reliability RELIABLE. Reliable communications is required to receive historical data.
```plaintext ```plaintext
<reliability> <reliability>
<kind>RELIABLE</kind> <kind>RELIABLE</kind>
<max_blocking_time> <max_blocking_time>
<sec>1</sec> <sec>1</sec>
</max_blocking_time> </max_blocking_time>
</reliability> </reliability>
``` ```
4. The data_reader QoS must be set durability to TRANSIENT_LOCAL. This means it will request missed data samples, but not beyond the life of the system (i.e. no persistence to disk). Without this setting the subscriber will not inquire about missed data. 4. The data_reader QoS must be set durability to TRANSIENT_LOCAL. This means it will request missed data samples, but not beyond the life of the system (i.e. no persistence to disk). Without this setting the subscriber will not inquire about missed data.
```plaintext ```plaintext
<durability> <durability>
<kind>TRANSIENT_LOCAL</kind> <kind>TRANSIENT_LOCAL</kind>
</durability> </durability>
``` ```
With the above settings in place, late joining subscribers should receive the last data published for each instance, for each topic, from connected publishers. With the above settings in place, late joining subscribers should receive the last data published for each instance, for each topic, from connected publishers.
More details on Fast DDS Qos: https://fast-dds.docs.eprosima.com/en/latest/fastdds/api_reference/dds_pim/core/policy/historyqospolicykind.html More details on Fast DDS Qos: https://fast-dds.docs.eprosima.com/en/latest/fastdds/api_reference/dds_pim/core/policy/historyqospolicykind.html
--- ---
--- ---
--- ---
### DDS SHM Shared Memory Startup Errors \[MAL DDS\] ### DDS SHM Shared Memory Startup Errors \[MAL DDS\]
**Problem** **Problem**
On startup of DDS application an error about Shared Memory (SHM) is displayed, for example: On startup of DDS application an error about Shared Memory (SHM) is displayed, for example:
RTPS SHM: "port marked as not ok" RTPS SHM: "port marked as not ok"
**Solution** **Solution**
The SHM transport is one of the default transports of a DDS application and is used to communicate to peers on the same host. The relevant files created by DDS are visible in /dev/shm/\*fast\*. The SHM transport is one of the default transports of a DDS application and is used to communicate to peers on the same host. The relevant files created by DDS are visible in /dev/shm/\*fast\*.
If a DDS application does not exit cleanly, it may leave SHM files present, possibly leading to errors when the application restarts, and in any case polluting the /dev/shm/ folder. If a DDS application does not exit cleanly, it may leave SHM files present, possibly leading to errors when the application restarts, and in any case polluting the /dev/shm/ folder.
To clean up the SHM files used by DDS the following command is provided: To clean up the SHM files used by DDS the following command is provided:
```plaintext ```plaintext
fastdds shm clean fastdds shm clean
``` ```
--- ---
--- ---
--- ---
### Discovery over multiple NICs \[MAL DDS\] ### Discovery over multiple NICs \[MAL DDS\]
**Problem** **Problem**
How do DataReaders connect over multiple NICs How do DataReaders connect over multiple NICs
**Explanantion** **Explanantion**
Let's say we have 3 hosts: Let's say we have 3 hosts:
- A: one NIC on 192.168.1.10 and another NIC on 10.10.10.10 - A: one NIC on 192.168.1.10 and another NIC on 10.10.10.10
- B: one NIC on 192.168.1.11 - B: one NIC on 192.168.1.11
- C: one NIC on 10.10.10.12 - C: one NIC on 10.10.10.12
On host A we have a participant with FASTDDS_STATISTICS="PUBLICATION_THROUGHPUT_TOPIC" and a DataWriter on topic _important_high_frequency_data_. On host A we have a participant with FASTDDS_STATISTICS="PUBLICATION_THROUGHPUT_TOPIC" and a DataWriter on topic _important_high_frequency_data_.
On host B we have a participant with FASTDDS_STATISTICS="SUBSCRIPTION_THROUGHPUT_TOPIC" and a DataReader on topic _important_high_frequency_data_ On host B we have a participant with FASTDDS_STATISTICS="SUBSCRIPTION_THROUGHPUT_TOPIC" and a DataReader on topic _important_high_frequency_data_
On host C we have the Fast DDS monitor. On host C we have the Fast DDS monitor.
Participants B and C will **not** discover each other, since they are on different LANs. Participants B and C will **not** discover each other, since they are on different LANs.
Participant A discovery will announce: Participant A discovery will announce:
"I have a DataWriter for topic _important_high_frequency_data_ communicating through any of 192.168.1.10, 10.10.10.10. "I have a DataWriter for topic _important_high_frequency_data_ communicating through any of 192.168.1.10, 10.10.10.10.
I also have a DataWriter for topic _fastdds_statistics_publication_throughput_ communicating through any of 192.168.1.10, 10.10.10.10." I also have a DataWriter for topic _fastdds_statistics_publication_throughput_ communicating through any of 192.168.1.10, 10.10.10.10."
Participant B discovery will announce: Participant B discovery will announce:
"I have a DataReader for topic _important_high_frequency_data_ listening on 192.168.1.11. "I have a DataReader for topic _important_high_frequency_data_ listening on 192.168.1.11.
I also have a DataWriter for topic _fastdds_statistics_subscription_throughput_ communicating through any of 192.168.1.11." I also have a DataWriter for topic _fastdds_statistics_subscription_throughput_ communicating through any of 192.168.1.11."
The DataWriter on participant A will then send data for topic _important_high_frequency_data_ listening to 192.168.1.11 (through NIC 192.168.1.10) The DataWriter on participant A will then send data for topic _important_high_frequency_data_ listening to 192.168.1.11 (through NIC 192.168.1.10)
Participant C discovery will announce: Participant C discovery will announce:
"I have a DataReader for topic _fastdds_statistics_publication_throughput_ listening on 10.10.10.12. "I have a DataReader for topic _fastdds_statistics_publication_throughput_ listening on 10.10.10.12.
I also have a DataReader for topic _fastdds_statistics_subscription_throughput_ listening on 10.10.10.12." I also have a DataReader for topic _fastdds_statistics_subscription_throughput_ listening on 10.10.10.12."
The statistics DataWriter on participant A will then send data for topic _fastdds_statistics_publication_throughput_ to 10.10.10.12 (through NIC 10.10.10.10) and be visible on DDS Monitor. The statistics DataWriter on participant A will then send data for topic _fastdds_statistics_publication_throughput_ to 10.10.10.12 (through NIC 10.10.10.10) and be visible on DDS Monitor.
--- ---
--- ---
\-------------------------------------------------------------------------- \--------------------------------------------------------------------------
### Summary of OPC/UA MAL in C++ ### Summary of OPC/UA MAL in C++
This article covers integration of OPC/UA in CII MAL specifically for OPC/UA Data Access and Subscription profiles. OPC/UA method invocation is also supported in CII MAL but is not described in this article, likewise details of the Python (and Java) support are not provided. Only C++ is considered here. This article covers integration of OPC/UA in CII MAL specifically for OPC/UA Data Access and Subscription profiles. OPC/UA method invocation is also supported in CII MAL but is not described in this article, likewise details of the Python (and Java) support are not provided. Only C++ is considered here.
OPC/UA communication middleware is exposed in CII MAL as either Publish/Subscribe or Request/Reply APIs. OPC/UA communication middleware is exposed in CII MAL as either Publish/Subscribe or Request/Reply APIs.
The XML ICD definition of types in CII is used to map sets of data points together that are read/written as a group. The XML ICD definition of types in CII is used to map sets of data points together that are read/written as a group.
Each attribute in the defined type is connected to a corresponding data point in the OPC/UA data space via a URI. Thus the CII URI for a complex type will contain specific addresses of multiple nodes in the OPC/UA data space. Each attribute in the defined type is connected to a corresponding data point in the OPC/UA data space via a URI. Thus the CII URI for a complex type will contain specific addresses of multiple nodes in the OPC/UA data space.
--- ---
--- ---
--- ---
#### Pub/Sub API for OPC/UA Clients: #### Pub/Sub API for OPC/UA Clients:
The CII MAL Pub/Sub API utilizes OPC/UA Data Access Reads and Writes, as well OPC/UA subscription. A Publisher will directly trigger an OPC DA write, while a Subscriber will work in one of two ways, depending on the type associated with the subscriber: The CII MAL Pub/Sub API utilizes OPC/UA Data Access Reads and Writes, as well OPC/UA subscription. A Publisher will directly trigger an OPC DA write, while a Subscriber will work in one of two ways, depending on the type associated with the subscriber:
- If the subscribers CII URI contains only a single node (i.e. the XML ICD type contained only a single attribute) then the Subscriber will create an OPC/UA subscription on that data point. The subscription will trigger notification of updates to the data point node, which will then be queued for notification via the CII Subscriber API. - If the subscribers CII URI contains only a single node (i.e. the XML ICD type contained only a single attribute) then the Subscriber will create an OPC/UA subscription on that data point. The subscription will trigger notification of updates to the data point node, which will then be queued for notification via the CII Subscriber API.
- If the Subscriber is using subscription, the opc.ps.outstandingPublishRequests property should not be zero (e.g. set it to 5), see the example code below. The reason is that the publish queue is used to store and send subscription notification events, and if the queue is small the even notifications may simply be dropped. - If the Subscriber is using subscription, the opc.ps.outstandingPublishRequests property should not be zero (e.g. set it to 5), see the example code below. The reason is that the publish queue is used to store and send subscription notification events, and if the queue is small the even notifications may simply be dropped.
- If the subscriber CII URI contains multiple nodes (i.e. the XML ICD type contains multiple attributes) then the Subscriber launches a thread to perform periodic polling of data from the OPC/UA server. The rate is based on the properties passed in creating the subscriber. e.g. - If the subscriber CII URI contains multiple nodes (i.e. the XML ICD type contains multiple attributes) then the Subscriber launches a thread to perform periodic polling of data from the OPC/UA server. The rate is based on the properties passed in creating the subscriber. e.g.
```cpp ```cpp
try{ try{
subscriber = factory.getSubscriber<T>(opcua_uri, ::elt::mal::ps::qos::QoS::DEFAULT, subscriber = factory.getSubscriber<T>(opcua_uri, ::elt::mal::ps::qos::QoS::DEFAULT,
{ {"opc.ps.outstandingPublishRequests","5"}, { {"opc.ps.outstandingPublishRequests","5"},
{"opc.asyncLoopExecutionPeriodMs","50"}, {"opc.asyncLoopExecutionPeriodMs","50"},
{"opc.asyncCallSubmitTimeoutMs","1000"}, {"opc.asyncCallSubmitTimeoutMs","1000"},
{"opc.ps.pollingPeriodMs","20000"}, {"opc.ps.pollingPeriodMs","20000"},
{"opc.asyncCallRetryPeriodMs","250"} } ); {"opc.asyncCallRetryPeriodMs","250"} } );
} catch(...) { } catch(...) {
throw; throw;
} }
``` ```
--- ---
--- ---
--- ---
#### Request/Reply API for OPC/UA Clients: #### Request/Reply API for OPC/UA Clients:
As OPC/UA Data Access read and write essentially follow a synchronous request/reply pattern, CII MAL also provides this interface for OPC/UA clients. As OPC/UA Data Access read and write essentially follow a synchronous request/reply pattern, CII MAL also provides this interface for OPC/UA clients.
The ICD is termed "virtual" in CII nomenclature as it does not require definition as an XML ICD using the service syntax, rather the same types defined for the Pub/Sub API may be used with a CII MAL OPC/UA Request/Reply. The ICD is termed "virtual" in CII nomenclature as it does not require definition as an XML ICD using the service syntax, rather the same types defined for the Pub/Sub API may be used with a CII MAL OPC/UA Request/Reply.
This approach means OPC/UA Data Access read (and write) are synchronous, and may be called as needed by the application. This approach means OPC/UA Data Access read (and write) are synchronous, and may be called as needed by the application.
```cpp ```cpp
namespace mal { namespace mal {
namespace rr { namespace rr {
namespace da { namespace da {
class DataAccess : public ::elt::mal::rr::RrEntity { class DataAccess : public ::elt::mal::rr::RrEntity {
public: public:
[...] [...]
template <typename T> template <typename T>
void read(::elt::mal::ps::DataEntity<T>& value) { void read(::elt::mal::ps::DataEntity<T>& value) {
readUnsafe(&value); readUnsafe(&value);
} }
template <typename T> template <typename T>
void write(const ::elt::mal::ps::DataEntity<T>& value) { void write(const ::elt::mal::ps::DataEntity<T>& value) {
writeUnsafe(&value); writeUnsafe(&value);
} }
``` ```
A test application showing its use is here: A test application showing its use is here:
<https://gitlab.eso.org/cosylab/elt-cii/mal/mal-test/-/blob/develop/cpp/mal-test-performance/opcua/mal-opcua-da-speed/src/common.cpp> <https://gitlab.eso.org/cosylab/elt-cii/mal/mal-test/-/blob/develop/cpp/mal-test-performance/opcua/mal-opcua-da-speed/src/common.cpp>
--- ---
--- ---
--- ---
### Request-Reply Python Snippets \[MAL Python\] ### Request-Reply Python Snippets \[MAL Python\]
To interact with any MAL based remote service, you can use the python shell to connect to the remote object and invoke its methods and process the return values. To interact with any MAL based remote service, you can use the python shell to connect to the remote object and invoke its methods and process the return values.
The whole lifecycle (including clean-up) looks like this: The whole lifecycle (including clean-up) looks like this:
```python ```python
# connect # connect
import elt.pymal import elt.pymal
malfact = elt.pymal.loadMalForUri("zpb.rr://", {}) malfact = elt.pymal.loadMalForUri("zpb.rr://", {})
import ModStdif.Stdif.StdCmds import ModStdif.Stdif.StdCmds
client = malfact.getClient("zpb.rr://127.0.0.1:12081/StdCmds", client = malfact.getClient("zpb.rr://127.0.0.1:12081/StdCmds",
ModStdif.Stdif.StdCmds.StdCmdsSync, ModStdif.Stdif.StdCmds.StdCmdsSync,
elt.pymal.rr.qos.DEFAULT, {}) elt.pymal.rr.qos.DEFAULT, {})
# interact # interact
print (client.GetState()) print (client.GetState())
# disconnect # disconnect
malfact.unregisterMal ("zpb") malfact.unregisterMal ("zpb")
``` ```
**Side-note**: For what it's worth, this can be done as a one-liner: **Side-note**: For what it's worth, this can be done as a one-liner:
```plaintext ```plaintext
python <<< 'import elt.pymal ; malfact = elt.pymal.loadMalForUri("zpb.rr://", {}) ; import ModStdif.Stdif.StdCmds ; client = malfact.getClient("zpb.rr://127.0.0.1:12081/StdCmds", ModStdif.Stdif.StdCmds.StdCmdsSync, elt.pymal.rr.qos.DEFAULT, {}) ; print (client.GetState()) ; malfact.unregisterMal ("zpb") ' python <<< 'import elt.pymal ; malfact = elt.pymal.loadMalForUri("zpb.rr://", {}) ; import ModStdif.Stdif.StdCmds ; client = malfact.getClient("zpb.rr://127.0.0.1:12081/StdCmds", ModStdif.Stdif.StdCmds.StdCmdsSync, elt.pymal.rr.qos.DEFAULT, {}) ; print (client.GetState()) ; malfact.unregisterMal ("zpb") '
``` ```
... which would be equivalent to this msgsend call: ... which would be equivalent to this msgsend call:
``` ```
msgsend -t 60 -u zpb.rr://127.0.0.1:12081/StdCmds ::stdif::StdCmds::GetState msgsend -t 60 -u zpb.rr://127.0.0.1:12081/StdCmds ::stdif::StdCmds::GetState
``` ```
### ------------------------------------------------------ ### ------------------------------------------------------
### \[OLDB\] ### \[OLDB\]
--- ---
--- ---
--- ---
### Less or More Logs \[OLDB Log\] ### Less or More Logs \[OLDB Log\]
**Problem** **Problem**
You are using the OLDB API, and you are getting more logs than you asked for. For example, simply testing for the existence of a datapoint: `[ERROR] Path not found config exception occurred: Path oldb/datapoints/myroot/somedp, version 1 not found` You are using the OLDB API, and you are getting more logs than you asked for. For example, simply testing for the existence of a datapoint: `[ERROR] Path not found config exception occurred: Path oldb/datapoints/myroot/somedp, version 1 not found`
or, the OLDB API seems to be misbehaving, and you want more logs. or, the OLDB API seems to be misbehaving, and you want more logs.
**Solution** **Solution**
Please read the article "[Adjust CII Log Levels \[Log\]](#user-content-adjust-cii-log-levels-log)" in the Log section of this Knowledge Base. The relevant logger names for the OLDB API are: Please read the article "[Adjust CII Log Levels \[Log\]](#user-content-adjust-cii-log-levels-log)" in the Log section of this Knowledge Base. The relevant logger names for the OLDB API are:
```plaintext ```plaintext
CiiOldb CiiOldb
CiiOldbDataPoint CiiOldbDataPoint
CiiOldbDirectoryTreeProvider CiiOldbDirectoryTreeProvider
CiiOldbFactory CiiOldbFactory
CiiOldbRedisDataPointProvider CiiOldbRedisDataPointProvider
CiiOldbRemoteDataPointProvider CiiOldbRemoteDataPointProvider
CiiOldbRemoteFileProvider CiiOldbRemoteFileProvider
``` CiiRedisClient
ThreadSubscriberConsumer
Example: to turn off ERROR logs for testing the existence of non-existing datapoints, use: config.CiiConfigClient
```
```plaintext
log4cplus.logger.CiiOldbRemoteDataPointProvider=FATAL Example: to turn off ERROR logs for testing the existence of non-existing datapoints, use:
```
```plaintext
--- log4cplus.logger.CiiOldbRemoteDataPointProvider=FATAL
```
---
---
---
---
### Cannot create Datapoints \[OLDB\]
---
**Problem**
### Cannot create Datapoints \[OLDB\]
Trying to create a datapoint, you get errors such as:
**Problem**
```plaintext
Cannot save to zpb.rr://ciiconfservicehost:9116/configuration/service/clientApi Trying to create a datapoint, you get errors such as:
[ERROR][CiiOldb] Unknown error occurred ::elt::error::icd::CiiSerializableException ```plaintext
``` Cannot save to zpb.rr://ciiconfservicehost:9116/configuration/service/clientApi
This is often caused by low disk space (95% used) available for the oldb permanent store: [ERROR][CiiOldb] Unknown error occurred ::elt::error::icd::CiiSerializableException
```
```plaintext
df -h /var/lib/elasticsearch This is often caused by low disk space (95% used) available for the oldb permanent store:
```
```plaintext
The disk space taken by the permanent store database itself is in the vast majority of cases dominated by the log records stored in it. The solutions aim at decreasing this space. df -h /var/lib/elasticsearch
```
**Solution 1**
The disk space taken by the permanent store database itself is in the vast majority of cases dominated by the log records stored in it. The solutions aim at decreasing this space.
```plaintext
# Remove old log files: **Solution 1**
find /var/log/elasticsearch -type f -mtime +30 -delete
```plaintext
# Put database back into read-write mode: # Remove old log files:
curl -X PUT -H "Content-Type: application/json" localhost:9200/_all/_settings -d ' find /var/log/elasticsearch -type f -mtime +30 -delete
{ "index.blocks.read_only_allow_delete": null }'
# Put database back into read-write mode:
# Remove old log records: curl -X PUT -H "Content-Type: application/json" localhost:9200/_all/_settings -d '
curl -X POST "localhost:9200/cii_log_default_index/_delete_by_query?pretty" -H 'Content-Type: application/json' -d ' { "index.blocks.read_only_allow_delete": null }'
{ "query": { "range" : { "@timestamp" : { "lte": "now-30d/d" } } } }'
# Remove old log records:
# Note: Removal is a background operation, and can take several minutes until it shows an effect. curl -X POST "localhost:9200/cii_log_default_index/_delete_by_query?pretty" -H 'Content-Type: application/json' -d '
# Run the below command repeatedly to monitor the removal, the docs.count should be decreasing. { "query": { "range" : { "@timestamp" : { "lte": "now-30d/d" } } } }'
# See number of logs stored in permanent store ("docs.count"): # Note: Removal is a background operation, and can take several minutes until it shows an effect.
curl http://localhost:9200/_cat/indices/cii_log_default_index?v\&s=store.size # Run the below command repeatedly to monitor the removal, the docs.count should be decreasing.
```
# See number of logs stored in permanent store ("docs.count"):
**Solution 2 (brute-force)** curl http://localhost:9200/_cat/indices/cii_log_default_index?v\&s=store.size
```
If you could not bring your disk usage below 95%, you can also remove all logs from the permanent store. In this case, you may also want to prevent permanent log storage in the future.
**Solution 2 (brute-force)**
```plaintext
# Prevent storing logs in the permanent store: If you could not bring your disk usage below 95%, you can also remove all logs from the permanent store. In this case, you may also want to prevent permanent log storage in the future.
sudo cii-services stop log
```plaintext
# Remove all log records: # Prevent storing logs in the permanent store:
curl -X DELETE "localhost:9200/cii_log_default_index?pretty" sudo cii-services stop log
# Put database back into read-write mode: # Remove all log records:
curl -X PUT -H "Content-Type: application/json" localhost:9200/_all/_settings -d ' curl -X DELETE "localhost:9200/cii_log_default_index?pretty"
{ "index.blocks.read_only_allow_delete": null }'
# Put database back into read-write mode:
# Recreate empty log index curl -X PUT -H "Content-Type: application/json" localhost:9200/_all/_settings -d '
curl -X PUT "localhost:9200/cii_log_default_index?pretty" { "index.blocks.read_only_allow_delete": null }'
```
# Recreate empty log index
After that you can restart logging: curl -X PUT "localhost:9200/cii_log_default_index?pretty"
```
```plaintext
sudo cii-services start log After that you can restart logging:
```
```plaintext
**Background** sudo cii-services start log
```
If disk usage is 95% or more, elasticsearch goes into read-only mode, and creating new datapoints is not possible any more. To remove old content from the database, it is first necessary to create some free space on the disk (since the database needs space to perform deletetion-operations), then unlock the database, and then remove unnecessary old content from it.
**Background**
To check the read-only status:
```plaintext If disk usage is 95% or more, elasticsearch goes into read-only mode, and creating new datapoints is not possible any more. To remove old content from the database, it is first necessary to create some free space on the disk (since the database needs space to perform deletetion-operations), then unlock the database, and then remove unnecessary old content from it.
# Check read-only status:
# If the output contains any "true" values, you are facing the problem. To check the read-only status:
curl -XGET -H "Content-Type: application/json" localhost:9200/_all/_settings/ | jq -r '.[][][]["blocks"]' ```plaintext
``` # Check read-only status:
# If the output contains any "true" values, you are facing the problem.
curl -XGET -H "Content-Type: application/json" localhost:9200/_all/_settings/ | jq -r '.[][][]["blocks"]'
```
---
---
---
---
---
### Exception while connecting to OLDB service
---
When starting an application using the OLDB API, the following exception is received:
### Exception while connecting to OLDB service
```plaintext
<date/time>, ERROR, CiiOldbFactory/140635105143296, Unexpected config exception occurred while retrieving configuration for cii.config://remote/oldb/configurations/oldbClientConfig What:Path oldb/configurations/oldbClientConfig, version -1 not found When starting an application using the OLDB API, the following exception is received:
terminate called after throwing an instance of 'elt::oldb::CiiOldbException'
what(): Unexpected config exception occurred while retrieving configuration for cii.config://remote/oldb/configurations/oldbClientConfig What:Path oldb/configurations/oldbClientConfig, version -1 not found ```plaintext
``` <date/time>, ERROR, CiiOldbFactory/140635105143296, Unexpected config exception occurred while retrieving configuration for cii.config://remote/oldb/configurations/oldbClientConfig What:Path oldb/configurations/oldbClientConfig, version -1 not found
terminate called after throwing an instance of 'elt::oldb::CiiOldbException'
**Solution** This can indicate that elasticSearch on the config/oldb server is not running, or has crashed. Use cii-services command to check the status on the server where the (cii-internal) config is running. what(): Unexpected config exception occurred while retrieving configuration for cii.config://remote/oldb/configurations/oldbClientConfig What:Path oldb/configurations/oldbClientConfig, version -1 not found
```
---
**Solution** This can indicate that elasticSearch on the config/oldb server is not running, or has crashed. Use cii-services command to check the status on the server where the (cii-internal) config is running.
---
---
---
---
### Connecting to OLDB takes long, then fails \[cpp OLDB\]
---
**Question** My application blocks a long time on first OLDB access, and eventually fails with a timeout.
### Connecting to OLDB takes long, then fails \[cpp OLDB\]
**Answer**
**Question** My application blocks a long time on first OLDB access, and eventually fails with a timeout.
Reconfigure the communication timeout (default: 60 seconds)
**Answer**
a) through an environment variable and a properties file
Reconfigure the communication timeout (default: 60 seconds)
```plaintext
$ cat <<EOF >/tmp/cii_client.ini a) through an environment variable and a properties file
connection_timeout = 5
EOF ```plaintext
$ export CONFIG_CLIENT_INI = /tmp/cii_client.ini $ cat <<EOF >/tmp/cii_client.ini
``` connection_timeout = 5
EOF
b) programmatically (available since CII 2.0/DevEnv 3.9) $ export CONFIG_CLIENT_INI = /tmp/cii_client.ini
```
C++
```plaintext b) programmatically (available since CII 2.0/DevEnv 3.9)
CiiClientConfiguration config_client_ini = { .connection_timeout = 5, };
elt::config::CiiConfigClient::SetDevClientConfig (config_client_ini); C++
``` ```plaintext
CiiClientConfiguration config_client_ini = { .connection_timeout = 5, };
Python elt::config::CiiConfigClient::SetDevClientConfig (config_client_ini);
```plaintext ```
import elt.config
config_client_ini = elt.config.CiiClientConfiguration() Python
config_client_ini.connection_timeout=5 ```plaintext
elt.config.CiiConfigClient.set_dev_client_config(config_client_ini) import elt.config
``` config_client_ini = elt.config.CiiClientConfiguration()
config_client_ini.connection_timeout=5
elt.config.CiiConfigClient.set_dev_client_config(config_client_ini)
**Background** ```
The actual stalling comes from a failed MAL-communication with the CII Internal Configuration System, which likely is not running. Setting the timeout for the CiiConfigClient is therefore the thing to do. Note that the properties file (aka. "deployment config") takes precedence and will, if they overlap, overrule the programmatic (aka. "developer config") settings.
**Background**
---
The actual stalling comes from a failed MAL-communication with the CII Internal Configuration System, which likely is not running. Setting the timeout for the CiiConfigClient is therefore the thing to do. Note that the properties file (aka. "deployment config") takes precedence and will, if they overlap, overrule the programmatic (aka. "developer config") settings.
---
---
---
---
### Mock OLDB for unit tests \[OLDB cpp python\]
---
**Question**
### Mock OLDB for unit tests \[OLDB cpp python\]
Is there already a faked OLDB that I can use in my unit tests in cpp?
**Question**
**Answer**
Is there already a faked OLDB that I can use in my unit tests in cpp?
(by D. Kumar)
**Answer**
You can create an in-memory OLDB providing a cached config oldb implementation and using the local file system for blob data.
(by D. Kumar)
The oldb-client cpp module is providing a
You can create an in-memory OLDB providing a cached config oldb implementation and using the local file system for blob data.
- pure (virtual = 0) interface elt::oldb::CiiOldbDataPointProvider<sup>\[1\]</sup>, and two implementations:
- in-memory data point provider storing data points to the memory The oldb-client cpp module is providing a
(this is an empty implementation which provides a minimal operational fake oldb) - pure (virtual = 0) interface elt::oldb::CiiOldbDataPointProvider<sup>\[1\]</sup>, and two implementations:
- in-memory data point provider storing data points to the memory
- a redis data point provider storing data points to redis.
- a remote filesystem interface elt::oldb:impl::ciiOldbRemoteFileProvider.hpp<sup>\[2\]</sup>, and two implementations: (this is an empty implementation which provides a minimal operational fake oldb)
- S3 implementation
- local file system implementation: ciiOldbLocalFileProvider<sup>\[3\]</sup> _\[Note: not before DevEnv 3.4\]_ - a redis data point provider storing data points to redis.
- a remote filesystem interface elt::oldb:impl::ciiOldbRemoteFileProvider.hpp<sup>\[2\]</sup>, and two implementations:
Here are complete examples of unit tests showing the main use cases how to use oldb (with subscriptions) and metadata creation: - S3 implementation
- local file system implementation: ciiOldbLocalFileProvider<sup>\[3\]</sup> _\[Note: not before DevEnv 3.4\]_
<https://gitlab.eso.org/cii/srv/cii-srv/-/blob/master/oldb-client/cpp/oldb/test/oldbInMemoryTest.cpp>
Here are complete examples of unit tests showing the main use cases how to use oldb (with subscriptions) and metadata creation:
The same exists in python:
<https://gitlab.eso.org/cii/srv/cii-srv/-/blob/master/oldb-client/cpp/oldb/test/oldbInMemoryTest.cpp>
Example in <https://gitlab.eso.org/ahoffsta/cii-srv/-/blob/oldb-in-memory-missing-python-binding/oldb-client/python/oldb/test/oldbInMemoryTest.py>
The same exists in python:
References
Example in <https://gitlab.eso.org/ahoffsta/cii-srv/-/blob/oldb-in-memory-missing-python-binding/oldb-client/python/oldb/test/oldbInMemoryTest.py>
\[1\] <https://gitlab.eso.org/cii/srv/cii-srv/-/blob/master/oldb-client/cpp/oldb/src/include/ciiOldbDataPointProvider.hpp>
References
\[2\] <https://gitlab.eso.org/cii/srv/cii-srv/-/blob/master/oldb-client/cpp/oldb/src/include/provider/ciiOldbRemoteFileProvider.hpp>
\[1\] <https://gitlab.eso.org/cii/srv/cii-srv/-/blob/master/oldb-client/cpp/oldb/src/include/ciiOldbDataPointProvider.hpp>
\[3\] <https://gitlab.eso.org/cii/srv/cii-srv/-/blob/master/oldb-client/cpp/oldb/src/provider/ciiOldbLocalFileProvider.hpp> _\[Note: not before DevEnv 3.4\]_
\[2\] <https://gitlab.eso.org/cii/srv/cii-srv/-/blob/master/oldb-client/cpp/oldb/src/include/provider/ciiOldbRemoteFileProvider.hpp>
---
\[3\] <https://gitlab.eso.org/cii/srv/cii-srv/-/blob/master/oldb-client/cpp/oldb/src/provider/ciiOldbLocalFileProvider.hpp> _\[Note: not before DevEnv 3.4\]_
---
---
---
---
### access_key empty (DevEnv 3.2.0) \[OLDB\]
---
**Problem**
### access_key empty (DevEnv 3.2.0) \[OLDB\]
Trying to use the OLDB on DevEnv 3.2.0, I'm getting this error:
**Problem**
Unexpected exception occurred. What:Configuration invalid: access_key empty
Trying to use the OLDB on DevEnv 3.2.0, I'm getting this error:
**Solution**
Unexpected exception occurred. What:Configuration invalid: access_key empty
Run the following commands (you will be asked for the root pw):
**Solution**
```plaintext
wget -q www.eso.org/~mschilli/download/cii/postinstall/cii-postinstall-20210610 Run the following commands (you will be asked for the root pw):
cii-services stop config ```plaintext
wget -q www.eso.org/~mschilli/download/cii/postinstall/cii-postinstall-20210610
su -c "bash cii-postinstall-20210610 schemas"
cii-services stop config
# If the script
su -c "bash cii-postinstall-20210610 schemas"
#You should see the following output:
# If the script
Password:
CII PostInstall (20210610) #You should see the following output:
schemas: applying fix ECII397
/home/eltdev/ Password:
schemas: populating elasticsearch CII PostInstall (20210610)
schemas: skipping telemetry schemas: applying fix ECII397
schemas: skipping alarms /home/eltdev/
schemas: populating elasticsearch
cii-services start config schemas: skipping telemetry
schemas: skipping alarms
```
cii-services start config
**Background**
```
The OLDB settings coming with 3.2.0 are buggy.
**Background**
The CII post-install procedure is able to hotfix the settings (ECII397).
The OLDB settings coming with 3.2.0 are buggy.
The problem will be fixed in DevEnv 3.4.
The CII post-install procedure is able to hotfix the settings (ECII397).
---
The problem will be fixed in DevEnv 3.4.
---
---
---
---
### Datapoint already exists \[OLDB\]
---
**Problem**
### Datapoint already exists \[OLDB\]
My application tries to create an OLDB datapoint.
**Problem**
This fails because the datapoint "already exists":
My application tries to create an OLDB datapoint.
```plaintext
ERROR, CiiOldbRedisDataPointProvider/140709706681216, Data point uri: cii.oldb:/tcs/hb/tempser3 in Redis already exists. This fails because the datapoint "already exists":
```
```plaintext
In response, my application skips the creation step, and wants to use the reportedly existing datapoint. ERROR, CiiOldbRedisDataPointProvider/140709706681216, Data point uri: cii.oldb:/tcs/hb/tempser3 in Redis already exists.
```
However, when doing this, I get the error "datapoint doesn't exist":
In response, my application skips the creation step, and wants to use the reportedly existing datapoint.
```plaintext
Dynamic exception type: elt::oldb::CiiOldbDpUndefinedException However, when doing this, I get the error "datapoint doesn't exist":
std::exception::what: The data point cii.oldb:///tcs/hb/tempser3 with this name does not exist.
``` ```plaintext
Dynamic exception type: elt::oldb::CiiOldbDpUndefinedException
Likewise, when I run the oldb-gui database browser, it does not show this data point in the OLDB. std::exception::what: The data point cii.oldb:///tcs/hb/tempser3 with this name does not exist.
```
**Variant 2 of the Problem**
Likewise, when I run the oldb-gui database browser, it does not show this data point in the OLDB.
I try to access an OLDB datapoint, and I see two errors like this:
**Variant 2 of the Problem**
```plaintext
Target configuration does not exist: Failed to retrieve configuration from elastic search: Configuration I try to access an OLDB datapoint, and I see two errors like this:
[…]
elt.oldb.exceptions.CiiOldbDpExistsException: Data point cii.oldb:/alarm/alarm/device/motor/input_int_dp_alarm already exisits. ```plaintext
``` Target configuration does not exist: Failed to retrieve configuration from elastic search: Configuration
[…]
Go directly to Solution 2 below. elt.oldb.exceptions.CiiOldbDpExistsException: Data point cii.oldb:/alarm/alarm/device/motor/input_int_dp_alarm already exisits.
```
**Variant 3 of the Problem**
Go directly to Solution 2 below.
I try to delete an OLDB datapoint and I see an error like this:
**Variant 3 of the Problem**
```plaintext
CiiOldbPyB.CiiOldbException: De-serialization error:sizeof(T)\*count is greater then remaining I try to delete an OLDB datapoint and I see an error like this:
```
```plaintext
Go directly to Solution 2 below. CiiOldbPyB.CiiOldbException: De-serialization error:sizeof(T)\*count is greater then remaining
```
**Background**
Go directly to Solution 2 below.
The two errors are contradicting.
**Background**
Datapoints are stored in two databases: a document-database (permanent store) for its metadata, and a key-value-database (volatile store) for its current value. The above symptoms indicate that the two databases are out-of-sync, meaning the datapoint exists only "half".
The two errors are contradicting.
**Solution 1**
Datapoints are stored in two databases: a document-database (permanent store) for its metadata, and a key-value-database (volatile store) for its current value. The above symptoms indicate that the two databases are out-of-sync, meaning the datapoint exists only "half".
With DevEnv 4, which contains [ECII-500](https://jira.eso.org/browse/ECII-500), you can probably delete the datapoint to clean up the situation:
**Solution 1**
```plaintext
#!/usr/bin/env python With DevEnv 4, which contains [ECII-500](https://jira.eso.org/browse/ECII-500), you can probably delete the datapoint to clean up the situation:
import elt.config
import elt.oldb ```plaintext
#!/usr/bin/env python
oldb_client = elt.oldb.CiiOldbFactory.get_instance() import elt.config
elt.oldb.CiiOldbGlobal.set_write_enabled(True) import elt.oldb
uri = elt.config.Uri("cii.oldb:/tcs/hb/tempser3") oldb_client = elt.oldb.CiiOldbFactory.get_instance()
oldb_client.delete_data_point(uri) elt.oldb.CiiOldbGlobal.set_write_enabled(True)
``` uri = elt.config.Uri("cii.oldb:/tcs/hb/tempser3")
oldb_client.delete_data_point(uri)
**Solution 2**
```
If the above didn't help, find out which "half" of the datapoint exists.
**Solution 2**
1. The current value exists, and the metadata is missing. This is the case when upgrading DevEnv/CII without deleting the Redis cache.
2. The metadata exists, and the current value is missing If the above didn't help, find out which "half" of the datapoint exists.
Define the following shell functions (note: not applicable to redis-clusters): 1. The current value exists, and the metadata is missing. This is the case when upgrading DevEnv/CII without deleting the Redis cache.
2. The metadata exists, and the current value is missing
```plaintext
function oldb_ela_list { curl -s -X GET localhost:9200/configuration_instance/_search?size=2000\&q=data.uri.value:\"$1\" | jq -r '.hits.hits[]._id' | sort ; } Define the following shell functions (note: not applicable to redis-clusters):
function oldb_ela_del { curl -s -X POST localhost:9200/configuration_instance/_delete_by_query?q=data.uri.value:\"$1\" | jq -r '.deleted' ; } ```plaintext
function oldb_ela_list { curl -s -X GET localhost:9200/configuration_instance/_search?size=2000\&q=data.uri.value:\"$1\" | jq -r '.hits.hits[]._id' | sort ; }
function oldb_red_list { redis-cli --scan --pattern "*$1*" ; }
function oldb_ela_del { curl -s -X POST localhost:9200/configuration_instance/_delete_by_query?q=data.uri.value:\"$1\" | jq -r '.deleted' ; }
function oldb_red_del { redis-cli --scan --pattern "*$1*" | xargs redis-cli del ; }
``` function oldb_red_list { redis-cli --scan --pattern "*$1*" ; }
Then check if the problematic key is in the volatile store: function oldb_red_del { redis-cli --scan --pattern "*$1*" | xargs redis-cli del ; }
```
```plaintext
# Search for path component of dp-uri (here: "device") Then check if the problematic key is in the volatile store:
$ oldb_red_list device
... output will be e.g.: ```plaintext
/sampleroot/child/device/doubledp444 # Search for path component of dp-uri (here: "device")
/sampleroot/child/device/doubledp445 $ oldb_red_list device
/sampleroot/child/device/doubledp111 ... output will be e.g.:
/sampleroot/child/device/doubledp2222 /sampleroot/child/device/doubledp444
/sampleroot/child/device/doubledp445
# If the problematic key is in the list, delete it: /sampleroot/child/device/doubledp111
$ oldb_red_del device/doubledp444 /sampleroot/child/device/doubledp2222
```
# If the problematic key is in the list, delete it:
Otherwise, check if the problematic key is in the permanent store: $ oldb_red_del device/doubledp444
```
```plaintext
# Search for path component of dp-uri (whole-word search, e.g. "dev" would not match) Otherwise, check if the problematic key is in the permanent store:
$ oldb_ela_list device
... output e.g.: ```plaintext
oldb___datapoints___sampleroot___child___device___doubledp446___1 # Search for path component of dp-uri (whole-word search, e.g. "dev" would not match)
$ oldb_ela_list device
# Delete the offending metadata ... output e.g.:
$ oldb_ela_del doubbledp446 oldb___datapoints___sampleroot___child___device___doubledp446___1
# After deletion, restart the internal config server # Delete the offending metadata
$ sudo cii-services stop config ; sudo cii-services start config $ oldb_ela_del doubbledp446
```
# After deletion, restart the internal config server
**Solution 3** $ sudo cii-services stop config ; sudo cii-services start config
```
If none of the above helped, another possibility is to clean up the metadata.
**Solution 3**
WARNING: This is an invasive operation. It deletes all datapoints in the OLDB.
If none of the above helped, another possibility is to clean up the metadata.
```plaintext
# Clean up the OLDB databases WARNING: This is an invasive operation. It deletes all datapoints in the OLDB.
config-initEs.sh
oldb-initEs ```plaintext
redis-cli flushall # Clean up the OLDB databases
sudo cii-services stop config config-initEs.sh
sudo cii-services start config oldb-initEs
``` redis-cli flushall
sudo cii-services stop config
If you are dealing with a multi-user oldb ("role_groupserver", meaning it serves an OLDB to a team of developers), after executing the above commands you need to additionally execute (with privileges): sudo cii-services start config
```
```plaintext
/elt/ciisrv/postinstall/cii-postinstall role_groupserver If you are dealing with a multi-user oldb ("role_groupserver", meaning it serves an OLDB to a team of developers), after executing the above commands you need to additionally execute (with privileges):
```
```plaintext
If you have doubts, please contact us. /elt/ciisrv/postinstall/cii-postinstall role_groupserver
```
---
If you have doubts, please contact us.
---
---
---
---
### Command Line Tools and Python snippets \[OLDB\]
---
**Problem**
### Command Line Tools and Python snippets \[OLDB\]
I need to inspect or modify the content of the OLDB from the command line or a shell script.
**Problem**
**Solution**
I need to inspect or modify the content of the OLDB from the command line or a shell script.
**cii-oldb-traversal-tool** for searching through the OLDB
**Solution**
```plaintext
$ cii-oldb-traversal-tool --file output --quality OK **cii-oldb-traversal-tool** for searching through the OLDB
$ cat output
cii.oldb:///root/trklsv/cfg/log/level|OK|WARNING|2020-09-11T15:25:08Z ```plaintext
cii.oldb:///root/trklsv/cfg/req/endpoint|OK|zpb.rr://localhost:44444/m1/TrkLsvServer|2020-09-11T15:25:08Z $ cii-oldb-traversal-tool --file output --quality OK
cii.oldb:///root/trklsv/ctr/current/altaz/alt|OK|0.000000|2020-09-11T15:24:25Z $ cat output
cii.oldb:///root/trklsv/ctr/current/altaz/az|OK|0.000000|2020-09-11T15:24:25Z cii.oldb:///root/trklsv/cfg/log/level|OK|WARNING|2020-09-11T15:25:08Z
cii.oldb:///root/trklsv/ctr/current/radec/dec|OK|0.000000|2020-09-11T15:24:27Z cii.oldb:///root/trklsv/cfg/req/endpoint|OK|zpb.rr://localhost:44444/m1/TrkLsvServer|2020-09-11T15:25:08Z
cii.oldb:///root/trklsv/ctr/current/radec/ra|OK|0.000000|2020-09-11T15:24:27Z cii.oldb:///root/trklsv/ctr/current/altaz/alt|OK|0.000000|2020-09-11T15:24:25Z
cii.oldb:///root/trklsv/ctr/poserr|OK|0.000000|2020-09-11T15:24:27Z cii.oldb:///root/trklsv/ctr/current/altaz/az|OK|0.000000|2020-09-11T15:24:25Z
cii.oldb:///root/trklsv/ctr/status|OK|UNKNOWN|2020-09-11T15:23:55Z cii.oldb:///root/trklsv/ctr/current/radec/dec|OK|0.000000|2020-09-11T15:24:27Z
cii.oldb:///root/trklsv/ctr/substate|OK|UNKNOWN|2020-09-11T15:23:49Z cii.oldb:///root/trklsv/ctr/current/radec/ra|OK|0.000000|2020-09-11T15:24:27Z
cii.oldb:///root/trklsv/ctr/target/altaz/alt|OK|0.000000|2020-09-11T15:24:24Z cii.oldb:///root/trklsv/ctr/poserr|OK|0.000000|2020-09-11T15:24:27Z
cii.oldb:///root/trklsv/ctr/target/altaz/az|OK|0.000000|2020-09-11T15:24:25Z cii.oldb:///root/trklsv/ctr/status|OK|UNKNOWN|2020-09-11T15:23:55Z
cii.oldb:///root/trklsv/ctr/target/radec/dec|OK|0.000000|2020-09-11T15:24:26Z cii.oldb:///root/trklsv/ctr/substate|OK|UNKNOWN|2020-09-11T15:23:49Z
cii.oldb:///root/trklsv/ctr/target/radec/ra|OK|0.000000|2020-09-11T15:24:26Z cii.oldb:///root/trklsv/ctr/target/altaz/alt|OK|0.000000|2020-09-11T15:24:24Z
``` cii.oldb:///root/trklsv/ctr/target/altaz/az|OK|0.000000|2020-09-11T15:24:25Z
cii.oldb:///root/trklsv/ctr/target/radec/dec|OK|0.000000|2020-09-11T15:24:26Z
**oldb-cli** for reading, writing, subscribing to, creating, deleting an OLDB-datapoint cii.oldb:///root/trklsv/ctr/target/radec/ra|OK|0.000000|2020-09-11T15:24:26Z
```
```plaintext
$ oldb-cli read cii.oldb:///root/trklsv/cfg/req/endpoint **oldb-cli** for reading, writing, subscribing to, creating, deleting an OLDB-datapoint
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/eelt/ciisrv/1.0-RC3-20201030/lib/srv-support-libs/slf4j-nop-1.7.25.jar!/org/slf4j/impl/StaticLoggerBinder.class] ```plaintext
SLF4J: Found binding in [jar:file:/eelt/mal/1.1.0-2.2.3-20201027/lib/mal-opcua/slf4j-nop-1.7.25.jar!/org/slf4j/impl/StaticLoggerBinder.class] $ oldb-cli read cii.oldb:///root/trklsv/cfg/req/endpoint
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation. SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Actual binding is of type [org.slf4j.helpers.NOPLoggerFactory] SLF4J: Found binding in [jar:file:/eelt/ciisrv/1.0-RC3-20201030/lib/srv-support-libs/slf4j-nop-1.7.25.jar!/org/slf4j/impl/StaticLoggerBinder.class]
log4j:WARN No appenders could be found for logger (io.netty.util.internal.logging.InternalLoggerFactory). SLF4J: Found binding in [jar:file:/eelt/mal/1.1.0-2.2.3-20201027/lib/mal-opcua/slf4j-nop-1.7.25.jar!/org/slf4j/impl/StaticLoggerBinder.class]
log4j:WARN Please initialize the log4j system properly. SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
Timestamp: 2020-09-11T15:25:08.648Z SLF4J: Actual binding is of type [org.slf4j.helpers.NOPLoggerFactory]
Quality: OK log4j:WARN No appenders could be found for logger (io.netty.util.internal.logging.InternalLoggerFactory).
Value: zpb.rr://localhost:44444/m1/TrkLsvServer log4j:WARN Please initialize the log4j system properly.
``` Timestamp: 2020-09-11T15:25:08.648Z
Quality: OK
Value: zpb.rr://localhost:44444/m1/TrkLsvServer
**oldbReset** for putting an OLDB back to its initial state by removing all custom metadata and removing all datapoints. The tool can only be run on the server that hosts the OLDB. ```
```plaintext
$ oldbReset **oldbReset** for putting an OLDB back to its initial state by removing all custom metadata and removing all datapoints. The tool can only be run on the server that hosts the OLDB.
```
```plaintext
See "-h" for options. Note there is no command line option to bypass the mandatory interactive security question. $ oldbReset
```
See "-h" for options. Note there is no command line option to bypass the mandatory interactive security question.
**oldb Python API** for creating, deleting an OLDB-datapoint
```plaintext
$ python **oldb Python API** for creating, deleting an OLDB-datapoint
Python 3.7.6 (default, Jan 8 2020, 19:59:22)
[GCC 7.3.0] :: Anaconda, Inc. on linux ```plaintext
Type "help", "copyright", "credits" or "license" for more information. $ python
>>> Python 3.7.6 (default, Jan 8 2020, 19:59:22)
>>> import elt.oldb [GCC 7.3.0] :: Anaconda, Inc. on linux
>>> from elt.config import Uri Type "help", "copyright", "credits" or "license" for more information.
>>> oldb = elt.oldb.CiiOldbFactory.get_instance() >>>
``` >>> import elt.oldb
>>> from elt.config import Uri
… and, to create a datapoint: >>> oldb = elt.oldb.CiiOldbFactory.get_instance()
```
```plaintext
>>> elt.oldb.CiiOldbGlobal.set_write_enabled(True) … and, to create a datapoint:
>>> if not oldb.data_point_exists(Uri("cii.oldb:/ccs/tst/tmp1")):
>>> oldb.create_data_point_by_value (Uri("cii.oldb:/ccs/tst/tmp1"), "my text") ```plaintext
``` >>> elt.oldb.CiiOldbGlobal.set_write_enabled(True)
>>> if not oldb.data_point_exists(Uri("cii.oldb:/ccs/tst/tmp1")):
… and, to write a datapoint: >>> oldb.create_data_point_by_value (Uri("cii.oldb:/ccs/tst/tmp1"), "my text")
```
```plaintext
>>> elt.oldb.CiiOldbGlobal.set_write_enabled(True) … and, to write a datapoint:
>>> oldb.get_data_point (Uri("cii.oldb:/ccs/tst/tmp1")).write_value("my text")
``` ```plaintext
>>> elt.oldb.CiiOldbGlobal.set_write_enabled(True)
… and, to read a datapoint: >>> oldb.get_data_point (Uri("cii.oldb:/ccs/tst/tmp1")).write_value("my text")
```
```plaintext
>>> oldb.get_data_point(Uri("cii.oldb:/ccs/tst/tmp1")).read_value().get_value() … and, to read a datapoint:
'my text'
``` ```plaintext
>>> oldb.get_data_point(Uri("cii.oldb:/ccs/tst/tmp1")).read_value().get_value()
… and, to subscribe to a datapoint: 'my text'
```
```plaintext
>>> class CB: … and, to subscribe to a datapoint:
>>> def new_value(self,value,uri):
>>> print ("value:", value.get_value()) ```plaintext
>>> sub = elt.oldb.typesupport.STRING.get_new_subscription_instance(CB()) >>> class CB:
>>> oldb.get_data_point(Uri("cii.oldb:/ccs/tst/tmp1")).subscribe(sub) >>> def new_value(self,value,uri):
``` >>> print ("value:", value.get_value())
>>> sub = elt.oldb.typesupport.STRING.get_new_subscription_instance(CB())
… and, to delete a datapoint: >>> oldb.get_data_point(Uri("cii.oldb:/ccs/tst/tmp1")).subscribe(sub)
```
```plaintext
>>> elt.oldb.CiiOldbGlobal.set_write_enabled(True) … and, to delete a datapoint:
>>> oldb.delete_data_point (Uri("cii.oldb:/ccs/tst/tmp1"))
``` ```plaintext
>>> elt.oldb.CiiOldbGlobal.set_write_enabled(True)
### ------------------------------------------------------ >>> oldb.delete_data_point (Uri("cii.oldb:/ccs/tst/tmp1"))
```
### \[Log\]
### ------------------------------------------------------
---
### \[Log\]
---
---
---
---
### Change Log Levels at Run-time \[Log\]
---
**Problem**
### Change Log Levels at Run-time \[Log\]
I want to modify the log levels of my application programmatically, without having to reload the full log configuration.
**Problem**
**Solution**
I want to modify the log levels of my application programmatically, without having to reload the full log configuration.
With [ECII-282](https://jira.eso.org/browse/ECII-282), the CiiLogManager was extended in all three languages to allow dynamically change log levels.
**Solution**
**C++** added methods:
With [ECII-282](https://jira.eso.org/browse/ECII-282), the CiiLogManager was extended in all three languages to allow dynamically change log levels.
```plaintext
void elt::log::CiiLogManager::SetLogLevel(const std::string logger_name, log4cplus::LogLevel level) **C++** added methods:
void elt::log::CiiLogManager::SetLogLevel(log4cplus::Logger logger, log4cplus::LogLevel level)
``` ```plaintext
void elt::log::CiiLogManager::SetLogLevel(const std::string logger_name, log4cplus::LogLevel level)
**Java** added methods: void elt::log::CiiLogManager::SetLogLevel(log4cplus::Logger logger, log4cplus::LogLevel level)
```
```plaintext
void elt.log.CiiLogManager.setLogLevel( **Java** added methods:
final String loggerName, final org.apache.logging.log4j.Level level);
void elt.log.CiiLogManager.setLogLevel( ```plaintext
org.apache.logging.log4j.Logger logger, final org.apache.logging.log4j.Level level) void elt.log.CiiLogManager.setLogLevel(
``` final String loggerName, final org.apache.logging.log4j.Level level);
void elt.log.CiiLogManager.setLogLevel(
**Python** added methods: org.apache.logging.log4j.Logger logger, final org.apache.logging.log4j.Level level)
```
```plaintext
elt.log.CiiLogManager.set_log_level(name_or_logger: Union\[str, logging.Logger\], level: logging.Level) **Python** added methods:
```
```plaintext
--- elt.log.CiiLogManager.set_log_level(name_or_logger: Union\[str, logging.Logger\], level: logging.Level)
```
---
---
---
---
### Adjust CII Log Levels \[Log\]
---
With plain CII (no application frameworks on top), you define a log config file (myapp.logconfig):
### Adjust CII Log Levels \[Log\]
```plaintext
log4cplus.rootLogger=INFO, STDOUT With plain CII (no application frameworks on top), you define a log config file (myapp.logconfig):
log4cplus.appender.STDOUT=log4cplus::ConsoleAppender
log4cplus.appender.STDOUT.layout=elt::log::layout::CiiSimpleLayout ```plaintext
log4cplus.rootLogger=INFO, STDOUT
# other loggers, e.g. OLDB or MAL log4cplus.appender.STDOUT=log4cplus::ConsoleAppender
log4cplus.logger.CiiOldb=FATAL log4cplus.appender.STDOUT.layout=elt::log::layout::CiiSimpleLayout
```
# other loggers, e.g. OLDB or MAL
The name of the log config is your choice, but to comply with the rules of "waf install", best use such a project structure: log4cplus.logger.CiiOldb=FATAL
```
```plaintext
myapp/ The name of the log config is your choice, but to comply with the rules of "waf install", best use such a project structure:
├── resource
│ └── config ```plaintext
│ └── myapp.logconfig myapp/
├── src ├── resource
│ ├── myapp.cpp │ └── config
└── wscript │ └── myapp.logconfig
``` ├── src
│ ├── myapp.cpp
Then apply the log config from your application (myapp.cpp): └── wscript
```
```plaintext
#include <ciiLogManager.hpp> Then apply the log config from your application (myapp.cpp):
int main(int ac, char *av[]) {
::elt::log::CiiLogManager::Configure("resource/config/myapp.logconfig"); ```plaintext
log4cplus::Logger root_logger = ::elt::log::CiiLogManager::GetLogger(); #include <ciiLogManager.hpp>
root_logger.log(log4cplus::INFO_LOG_LEVEL, "Message via root logger"); int main(int ac, char *av[]) {
return 0; ::elt::log::CiiLogManager::Configure("resource/config/myapp.logconfig");
} log4cplus::Logger root_logger = ::elt::log::CiiLogManager::GetLogger();
``` root_logger.log(log4cplus::INFO_LOG_LEVEL, "Message via root logger");
return 0;
Side-note: To configure the logging fully programmatically, without a file, you would do: }
```plaintext ```
::elt::log::CiiLogManager::Configure({
{"log4cplus.appender.ConsoleAppender", "log4cplus::ConsoleAppender"}, Side-note: To configure the logging fully programmatically, without a file, you would do:
{"log4cplus.appender.ConsoleAppender.layout", "elt::log::layout::CiiSimpleLayout"}, ```plaintext
{"log4cplus.rootLogger", "FATAL, ConsoleAppender"}, ::elt::log::CiiLogManager::Configure({
}); {"log4cplus.appender.ConsoleAppender", "log4cplus::ConsoleAppender"},
``` {"log4cplus.appender.ConsoleAppender.layout", "elt::log::layout::CiiSimpleLayout"},
{"log4cplus.rootLogger", "FATAL, ConsoleAppender"},
**List of Loggers** Generally, to learn about all loggers that are active in your application, add this (temporarily) to your application: });
```
```plaintext
#include <ciiLogManager.hpp> Side-note 2: To configure the oldb logging from python, you would do:
[...] ```plaintext
std::cout << "Current loggers (in addition to root logger):" << std::endl; from elt.log import CiiLogManager
std::vector<log4cplus::Logger> list = log4cplus::Logger::getCurrentLoggers();
for (int i=0,n=list.size(); i<n; i++) { logconf={
log4cplus::Logger elem = list[i]; 'log4cplus.appender.STDOUT': 'log4cplus::ConsoleAppender',
std::cout << elem.getName() << std::endl; 'log4cplus.appender.STDOUT.layout': 'elt::log::layout::CiiSimpleLayout',
} 'log4cplus.logger.CiiOldb': 'DEBUG, STDOUT',
``` 'log4cplus.logger.CiiOldbDataPoint': 'DEBUG, STDOUT',
'log4cplus.logger.CiiOldbDirectoryTreeProvider': 'DEBUG, STDOUT',
Note: With the next version of CII, the logger name will be included in log messages by default. 'log4cplus.logger.CiiOldbFactory': 'TRACE, STDOUT',
'log4cplus.logger.CiiOldbRedisDataPointProvider': 'DEBUG, STDOUT',
**Log Format** To use a different log format (which CII allows, but the Control System guidelines do not), you can modify the above config like this: 'log4cplus.logger.CiiOldbRemoteDataPointProvider': 'DEBUG, STDOUT',
'log4cplus.logger.CiiOldbRemoteFileProvider': 'DEBUG, STDOUT',
```plaintext 'log4cplus.logger.CiiRedisClient': 'DEBUG, STDOUT',
#log4cplus.appender.STDOUT.layout=elt::log::layout::CiiSimpleLayout 'log4cplus.logger.ThreadSubscriberConsumer': 'DEBUG, STDOUT',
log4cplus.appender.STDOUT.layout=log4cplus::PatternLayout 'log4cplus.logger.config.CiiConfigClient': 'TRACE, STDOUT',
log4cplus.appender.STDOUT.layout.ConversionPattern=[%-5p][%D{%Y/%m/%d %H:%M:%S:%q}][%-l][%t] %m%n }
``` CiiLogManager.configure(logconf, cpp_logging=True)
--- ```
--- **List of Loggers** Generally, to learn about all loggers that are active in your application, add this (temporarily) to your application:
--- ```plaintext
#include <ciiLogManager.hpp>
### wscript packages for CII Log \[Log\] [...]
std::cout << "Current loggers (in addition to root logger):" << std::endl;
**Problem** std::vector<log4cplus::Logger> list = log4cplus::Logger::getCurrentLoggers();
for (int i=0,n=list.size(); i<n; i++) {
I want to write an cxx application using CII Log and no other CII services, nor CII MAL. Which packages do I need in my wscript? log4cplus::Logger elem = list[i];
std::cout << elem.getName() << std::endl;
**Solution** }
```
1) included this in the uses clause in the cxx program folder:
```plaintext **Log Format** To use a different log format (which CII allows, but the Control System guidelines do not), you can modify the above config like this:
client-api.elt-common.cpp.log
``` ```plaintext
#log4cplus.appender.STDOUT.layout=elt::log::layout::CiiSimpleLayout
2) and put this into the higher-level project or package wscript: log4cplus.appender.STDOUT.layout=log4cplus::PatternLayout
```plaintext log4cplus.appender.STDOUT.layout.ConversionPattern=[%-5p][%D{%Y/%m/%d %H:%M:%S:%q}][%-l][%t] %m%n
def configure(cnf): ```
cnf.check_wdep(wdep_name="client-api.elt-common.cpp.log", uselib_store="client-api.elt-common.cpp.log") ---
```
--- ---
--- ---
--- ### wscript packages for CII Log \[Log\]
**Problem**
### Too many files errors \[Log\]
I want to write an cxx application using CII Log and no other CII services, nor CII MAL. Which packages do I need in my wscript?
If an application (for example a UI) fails with "too many files" or "too many open files" errors, check the /var/log/elt and $CII_LOGS folder. There might be too many files there, typically produced by the logging system.
**Solution**
In particular there could be a number of 0-bytes files.
1) included this in the uses clause in the cxx program folder:
Cleanup the folder to solve the problem, as root. ```plaintext
client-api.elt-common.cpp.log
--- ```
--- 2) and put this into the higher-level project or package wscript:
```plaintext
--- def configure(cnf):
cnf.check_wdep(wdep_name="client-api.elt-common.cpp.log", uselib_store="client-api.elt-common.cpp.log")
```
---
### ------------------------------------------------------
---
### \[Lang\]
---
---
--- ### Too many files errors \[Log\]
--- If an application (for example a UI) fails with "too many files" or "too many open files" errors, check the /var/log/elt and $CII_LOGS folder. There might be too many files there, typically produced by the logging system.
### Catching API Exceptions \[Lang Python\] In particular there could be a number of 0-bytes files.
**Problem** Cleanup the folder to solve the problem, as root.
My application contains a call to the CII Python API. ---
When I ran it, it threw an exception with the following backtrace: ---
```plaintext ---
Top Level Unexpected exception:
Traceback (most recent call last):
File "/home/eltdev/MODULES/test/app.py", line 91, in instantiateDP
double_dp = self.oldb_client.create_data_point(uri, metadataInstName) ### ------------------------------------------------------
CiiOldbPyB.CiiOldbDpExistsException: The Data point cii.oldb:/root/test/xxxdp already exists.
``` ### \[Lang\]
Therefore, I added a corresponding try-catch around my call: ---
```plaintext ---
try:
... ---
except CiiOldbPyB.CiiOldbDpExistsException as e:
``` ### Catching API Exceptions \[Lang Python\]
When I run it, the try-catch doesn't work. **Problem**
Moreover, I now get two backtraces: My application contains a call to the CII Python API.
```plaintext When I ran it, it threw an exception with the following backtrace:
Top Level Unexpected exception:
Traceback (most recent call last): ```plaintext
File "/home/eltdev/MODULES/test/app.py", line 91, in instantiateDP Top Level Unexpected exception:
double_dp = self.oldb_client.create_data_point(uri, metadataInstName) Traceback (most recent call last):
CiiOldbPyB.CiiOldbDpExistsException: The Data point cii.oldb:/root/test/xxxdp already exists. File "/home/eltdev/MODULES/test/app.py", line 91, in instantiateDP
double_dp = self.oldb_client.create_data_point(uri, metadataInstName)
During handling of the above exception, another exception occurred: CiiOldbPyB.CiiOldbDpExistsException: The Data point cii.oldb:/root/test/xxxdp already exists.
Traceback (most recent call last): ```
File "/home/eltdev/MODULES/test/app.py", line 108, in main
oldbCreator.instantiateOLDB_exception() Therefore, I added a corresponding try-catch around my call:
File "/home/eltdev/MODULES/test/app.py", line 81, in instantiateOLDB_exception
self.instantiateDP(double_dp_uri, double_dp_meta.get_instance_name()) ```plaintext
File "/home/eltdev/MODULES/test/app.py", line 94, in instantiateDP try:
except CiiOldbPyB.CiiOldbDpExistsException: ...
NameError: name 'CiiOldbPyB' is not defined except CiiOldbPyB.CiiOldbDpExistsException as e:
``` ```
**Solution** When I run it, the try-catch doesn't work.
You were mislead by the first backtrace: the exception name in the backtrace is not what you should catch. Moreover, I now get two backtraces:
In your code, replace "**CiiOldbPyB**" with "**elt.oldb**": ```plaintext
Top Level Unexpected exception:
```plaintext Traceback (most recent call last):
try: File "/home/eltdev/MODULES/test/app.py", line 91, in instantiateDP
.... double_dp = self.oldb_client.create_data_point(uri, metadataInstName)
except elt.oldb.CiiOldbDpExistsException as e: CiiOldbPyB.CiiOldbDpExistsException: The Data point cii.oldb:/root/test/xxxdp already exists.
```
During handling of the above exception, another exception occurred:
For completeness - do no forget this statement: Traceback (most recent call last):
File "/home/eltdev/MODULES/test/app.py", line 108, in main
```plaintext oldbCreator.instantiateOLDB_exception()
import elt.oldb File "/home/eltdev/MODULES/test/app.py", line 81, in instantiateOLDB_exception
``` self.instantiateDP(double_dp_uri, double_dp_meta.get_instance_name())
File "/home/eltdev/MODULES/test/app.py", line 94, in instantiateDP
**Background** except CiiOldbPyB.CiiOldbDpExistsException:
NameError: name 'CiiOldbPyB' is not defined
The CII Python API is mostly a binding to the CII C++ API. ```
The CiiOldbPyB.CiiOldbDpExistsException is the original binding class. **Solution**
This binding class is re-exported under the name elt.oldb.CiiOldbDpExistsException. You were mislead by the first backtrace: the exception name in the backtrace is not what you should catch.
The elt.oldb module internally loads the C++ binding module CiiOldbPyB. So both are the same exception. In your code, replace "**CiiOldbPyB**" with "**elt.oldb**":
Nonetheless, you should use the re-exported name, not the original name in your application. We discourage the use of the original name because the structure of the CiiOldbPyB module is more "chaotic" and not equivalent to elt.oldb. ```plaintext
try:
Unfortunately, in the backtraces you will always see the original name instead of the re-exported name. ....
except elt.oldb.CiiOldbDpExistsException as e:
This question was originally asked in [ECII-422](https://jira.eso.org/browse/ECII-422). ```
### ------------------------------------------------------ For completeness - do no forget this statement:
### \[IntCfg\] ```plaintext
import elt.oldb
--- ```
--- **Background**
--- The CII Python API is mostly a binding to the CII C++ API.
### Elasticsearch disk usage and house-keeping \[IntCfg\] The CiiOldbPyB.CiiOldbDpExistsException is the original binding class.
The Elasticsearch database is used by many CII services, e.g. to store CII log messages, tracing data, and Oldb metadata. If you run a local elasticsearch database on your host (i.e. you have set up a "role_ownserver" during post-install), it is advisable to do some house-keeping on this database from time to time. This binding class is re-exported under the name elt.oldb.CiiOldbDpExistsException.
Some house-keeping is automated (e.g. ".monitoring-es" indices are automatically rolled over every few days), others may be automated in the future, but currently are not. Instead you should perform the tasks below at your own discretion. The elt.oldb module internally loads the C++ binding module CiiOldbPyB. So both are the same exception.
**SOS - Disk Full** When disk usage (`df -h /var/lib/elastic`) goes above 95%, elasticsearch goes into read-only mode. You will see this reported in /var/log/messages and the elastic logs, and by getting exceptions from CII operations like *oldb.CreateDataPoint()*. This will prevent you from doing any clean-up operations on elasticsearch. First, bring disk usage below 95% (e.g. by removing elastic logs with `find /var/log/elasticsearch -type f -mtime +10 -delete`, or by temporarily moving some files from the full partition to another partition), then put elasticsearch back into read-write mode with this command: Nonetheless, you should use the re-exported name, not the original name in your application. We discourage the use of the original name because the structure of the CiiOldbPyB module is more "chaotic" and not equivalent to elt.oldb.
`curl -XPUT -H "Content-Type: application/json" localhost:9200/_all/_settings -d '{ "index.blocks.read_only_allow_delete": null }'`. After this, you can proceed normally with the house-keeping operations described next.
Unfortunately, in the backtraces you will always see the original name instead of the re-exported name.
This question was originally asked in [ECII-422](https://jira.eso.org/browse/ECII-422).
1. Check which indices you have and how much memory they consume:
### ------------------------------------------------------
```plaintext
curl localhost:9200/_cat/indices/_all?v\&s=store.size ### \[IntCfg\]
```
---
2. To delete diagnostic indices that are older than X days:
---
```plaintext
function ela_purge_idx { name=$1; age=$2; limit=$(date -d "$age days ago" +"%Y%m%d") ; for a in `curl -s localhost:9200/_aliases | jq -r 'keys | .[]'` ; do [[ $a == *$name* ]] && [[ "${a//[!0-9]/}" -lt $limit ]] && curl -X DELETE localhost:9200/$a ; done } ---
ela_purge_idx jaeger 10 # delete *jaeger* indices older than 10 days ### Elasticsearch disk usage and house-keeping \[IntCfg\]
```
The Elasticsearch database is used by many CII services, e.g. to store CII log messages, tracing data, and Oldb metadata. If you run a local elasticsearch database on your host (i.e. you have set up a "role_ownserver" during post-install), it is advisable to do some house-keeping on this database from time to time.
3. To delete CII log messages that are older than 30 days:
Some house-keeping is automated (e.g. ".monitoring-es" indices are automatically rolled over every few days), others may be automated in the future, but currently are not. Instead you should perform the tasks below at your own discretion.
```plaintext
curl -X POST "localhost:9200/cii_log_default_index/_delete_by_query?pretty" -H 'Content-Type: application/json' -d' {"query": {"range" : {"@timestamp" : {"lte": "now-30d/d" } } } } ' **SOS - Disk Full** When disk usage (`df -h /var/lib/elastic`) goes above 95%, elasticsearch goes into read-only mode. You will see this reported in /var/log/messages and the elastic logs, and by getting exceptions from CII operations like *oldb.CreateDataPoint()*. This will prevent you from doing any clean-up operations on elasticsearch. First, bring disk usage below 95% (e.g. by removing elastic logs with `find /var/log/elasticsearch -type f -mtime +10 -delete`, or by temporarily moving some files from the full partition to another partition), then put elasticsearch back into read-write mode with this command:
``` `curl -XPUT -H "Content-Type: application/json" localhost:9200/_all/_settings -d '{ "index.blocks.read_only_allow_delete": null }'`. After this, you can proceed normally with the house-keeping operations described next.
4. Or brute-force, delete all CII log messages:
```plaintext
curl -X DELETE "localhost:9200/cii_log_default_index?pretty" 1. Check which indices you have and how much memory they consume:
curl -X PUT "localhost:9200/cii_log_default_index?pretty"
``` ```plaintext
curl localhost:9200/_cat/indices/_all?v\&s=store.size
5. To free your disk from elastic logs older than 10 days, do (as root): ```
```plaintext 2. To delete diagnostic indices that are older than X days:
find /var/log/elasticsearch -type f -mtime +10 -delete
``` ```plaintext
function ela_purge_idx { name=$1; age=$2; limit=$(date -d "$age days ago" +"%Y%m%d") ; for a in `curl -s localhost:9200/_aliases | jq -r 'keys | .[]'` ; do [[ $a == *$name* ]] && [[ "${a//[!0-9]/}" -lt $limit ]] && curl -X DELETE localhost:9200/$a ; done }
Finally, if you do not need CII logs stored in elasticsearch (= you don't use kibana), note that you can stop the log transport and log analysis engine. This way, elasticsearch will grow much slower.
``` ela_purge_idx jaeger 10 # delete *jaeger* indices older than 10 days
sudo cii-services stop log ```
```
3. To delete CII log messages that are older than 30 days:
```plaintext
--- curl -X POST "localhost:9200/cii_log_default_index/_delete_by_query?pretty" -H 'Content-Type: application/json' -d' {"query": {"range" : {"@timestamp" : {"lte": "now-30d/d" } } } } '
```
---
4. Or brute-force, delete all CII log messages:
--- ```plaintext
curl -X DELETE "localhost:9200/cii_log_default_index?pretty"
### config not found on remote db \[IntCfg\] curl -X PUT "localhost:9200/cii_log_default_index?pretty"
```
**Problem**
5. To free your disk from elastic logs older than 10 days, do (as root):
You are intending to read a config from the local config database ("localdb"), but you see an error message like this.
```plaintext
```plaintext find /var/log/elasticsearch -type f -mtime +10 -delete
elt.config.exceptions.CiiConfigNoTcException: Target configuration does not exist: Failed to retrieve configuration from elastic search: Configuration cii.config://*/supervisoryapp/TrkLsvDeploy on the remote db was not found ```
at elt.config.client.ConfigRemoteDatabase.retrieveConfig(ConfigRemoteDatabase.java:191)
at elt.config.client.CiiConfigClient.retrieveConfig(CiiConfigClient.java:354) Finally, if you do not need CII logs stored in elasticsearch (= you don't use kibana), note that you can stop the log transport and log analysis engine. This way, elasticsearch will grow much slower.
at elt.config.client.CiiConfigClient.retrieveConfig(CiiConfigClient.java:310) ```
at trkLsv.DataContext.loadConfig(DataContext.java:324) sudo cii-services stop log
at trkLsv.DataContext.<init>(DataContext.java:190) ```
at trkLsv.TrkLsv.go(TrkLsv.java:72)
at trkLsv.TrkLsv.main(TrkLsv.java:41)
Caused by: elt.error.icd.CiiSerializableException
at elt.config.service.client.icd.zpb.ServiceClientApiInterfaceAsyncImpl.processRequest(ServiceClientApiInterfaceAsyncImpl.java:73) ---
at elt.mal.zpb.rr.ClientAsyncImpl.events(ClientAsyncImpl.java:261)
at org.zeromq.ZPoller.dispatch(ZPoller.java:537) ---
at org.zeromq.ZPoller.poll(ZPoller.java:488)
at org.zeromq.ZPoller.poll(ZPoller.java:461) ---
at elt.mal.zpb.ZpbMal.processThread(ZpbMal.java:459)
at elt.mal.zpb.ZpbMal.lambda$new$0(ZpbMal.java:119) ### config not found on remote db \[IntCfg\]
at java.lang.Thread.run(Thread.java:748)
``` **Problem**
**Solution A** You are intending to read a config from the local config database ("localdb"), but you see an error message like this.
Your local file may be invalid (e.g. illegal format, or doesn't match the config class definition). ```plaintext
elt.config.exceptions.CiiConfigNoTcException: Target configuration does not exist: Failed to retrieve configuration from elastic search: Configuration cii.config://*/supervisoryapp/TrkLsvDeploy on the remote db was not found
Look at the content of your local config database, e.g. with at elt.config.client.ConfigRemoteDatabase.retrieveConfig(ConfigRemoteDatabase.java:191)
at elt.config.client.CiiConfigClient.retrieveConfig(CiiConfigClient.java:354)
```plaintext at elt.config.client.CiiConfigClient.retrieveConfig(CiiConfigClient.java:310)
$ find $INTROOT/localdb at trkLsv.DataContext.loadConfig(DataContext.java:324)
``` at trkLsv.DataContext.<init>(DataContext.java:190)
at trkLsv.TrkLsv.go(TrkLsv.java:72)
and correct the file in place, or fix the source yaml and then redeploy it from source to the localdb. at trkLsv.TrkLsv.main(TrkLsv.java:41)
Caused by: elt.error.icd.CiiSerializableException
**Background** at elt.config.service.client.icd.zpb.ServiceClientApiInterfaceAsyncImpl.processRequest(ServiceClientApiInterfaceAsyncImpl.java:73)
at elt.mal.zpb.rr.ClientAsyncImpl.events(ClientAsyncImpl.java:261)
You may have a malformed json file in your local db, which the config service failed to read. at org.zeromq.ZPoller.dispatch(ZPoller.java:537)
at org.zeromq.ZPoller.poll(ZPoller.java:488)
Because of the use the location wildcard "\*" in your code (in "[cii.config://\*/supervisoryapp/TrkLsvDeploy"](cii.config://\*/supervisoryapp/TrkLsvDeploy%22)), at org.zeromq.ZPoller.poll(ZPoller.java:461)
at elt.mal.zpb.ZpbMal.processThread(ZpbMal.java:459)
the config service has consequently tried to load the config from the remote config database, where no such config exists. at elt.mal.zpb.ZpbMal.lambda$new$0(ZpbMal.java:119)
at java.lang.Thread.run(Thread.java:748)
```
**Solution A**
Your local file may be invalid (e.g. illegal format, or doesn't match the config class definition).
Look at the content of your local config database, e.g. with
```plaintext
$ find $INTROOT/localdb
```
and correct the file in place, or fix the source yaml and then redeploy it from source to the localdb.
**Background**
You may have a malformed json file in your local db, which the config service failed to read.
Because of the use the location wildcard "\*" in your code (in "[cii.config://\*/supervisoryapp/TrkLsvDeploy"](cii.config://\*/supervisoryapp/TrkLsvDeploy%22)),
the config service has consequently tried to load the config from the remote config database, where no such config exists.
To that end, the error message is misleading, and should be improved (ticket [ECII-208](https://jira.eso.org/browse/ECII-208)). To that end, the error message is misleading, and should be improved (ticket [ECII-208](https://jira.eso.org/browse/ECII-208)).
\ No newline at end of file