# MDC - MPS Database compare

The MDC Python library allows the user to compare 2 versions of MPS and generate a difference report and a patch that 
is able to transform the initial database into the modified one.

## 1. Description
The library uses the MPSCD library to read the database, compare the two data sets, and generate a HTML report.

It provides 2 different reports, short and full, aimed to quickly see the changes or debug in details all the changes 
that occurred in the database. It is meant to be generic, meaning that any database that is supported by the MPSCD 
is also supported by MDC. 

The library is divided in folders:

- **docs/** (documentation)
- **scripts/** (executables)
- **src/** (library code)
- **tests/** (unit tests and testing databases)

The **scripts/** folder creates Python executable scripts, to be deployed in the user PATH. In this way the user 
can invoke the comparison of databases directly from terminal, without having to actually use the library.

The **src/** folder has all the library code inside. It is also divided into sub folders (configuration, logic) based 
on the databases the library currently supports.

## 2. Setup
In order to start using the library you need to install it on the target machine.

### 2.1. Requirements
The library requires the **MPSCD** library in order to work. Please follow the installation instruction of the 
MPSCD library for additional information. The versions of the library must match - in general the interface of the 
MPSCD library is not suppose to change, but there might be changes needed in the future. If this is the case (the 
interface of the MPSCD library is changed) this library needs to be updated as well (or use the old version of the MPSCD 
library - we discourage this approach).

### 2.2. Installation
To install the library run the following command in the **root** folder of the project:

<pre><code>
sudo python setup.py install
</code></pre>

To test if the installation was successful you can execute
this command:

<pre><code>
mps_comapre_config_db --help
</code></pre>

The expected output is the help string for the mps_comapre_config_db executable. If this is not the case, 
there was an error with the library installation. If the help is displayed you successfully installed the library 
in your default Python **site-packages** folder and the executables in your default executables path. 
You can start using the library (see chapter **Usage**).

### 2.3. Installation location
The installation location is site dependent. There are 2 folders that need to be specified in order to place the 
library in the desired location:

- install-lib: location where the library files are deployed.
- install-scripts: location where executable scripts are deployed.

"install-lib" should be part of your PYTHONPATH (environment variable). This will allow the modules to be imported 
in your python scripts. It is also a requirement to run the scripts that depend on the library.

"install-scripts" should be part of your PATH (environment variable). This is not required to run the scripts, 
but is advisable if you want to be able to execute them from the terminal in any location.

Example:

<pre><code>
python setup.py install 
--install-lib=/afs/slac/g/lcls/tools/python/python2.6.4/slac-packages 
--install-scripts=/afs/slac/g/lcls/tools/python/python2.6.4/bin
</code></pre>

In the example above, the user is suppose to have:

- **PATH**: /afs/slac/g/lcls/tools/python/python2.6.4/bin
- **PYTHONPATH**: /afs/slac/g/lcls/tools/python/python2.6.4/slac-packages

## 3. Documentation
All the available documentation is located in the **docs/** folder of the project. Some documentation is static but 
most of it is auto-generated from the source code.

### 3.1 README file
The HTML version of this README file is generated automatically from the markdown file **README.md** in the **root** 
folder of the project. To generate this file, you need to install markdown2 on the target machine:
[https://github.com/trentm/python-markdown2](https://github.com/trentm/python-markdown2)

In the root folder of the project run the command:

<pre><code>
markdown2 README.md > docs/README.html
</code></pre>

The README will be generated and written in HTML form to the **docs/README.html** file.

### 3.2. API reference
<b>(Available <a href="api_reference/help.html" target="_blank">here</a>)</b>

The API reference is built using **Epydoc**. If you want to generate the API reference you will have to install 
Epydoc on the target machine:
[http://epydoc.sourceforge.net/](http://epydoc.sourceforge.net/)

In the root folder of the project there is already a configuration( **epydoc.cfg** ) file for generating the reference 
in the correct format. To generate the reference, execute the following command in the **root** folder of the project:

<pre><code>
epydoc --config=epydoc.cfg
</code></pre>

The API reference will be generated and written in HTML form to the **docs/api\_reference** folder. 
Start browsing the reference at **docs/api\_reference/index.html**.

### 3.3. Library execution profiling
A profiling session has been performed on the library to determine where the length of the comparison arises from. 
It has been found that most of the time (89%) is used up for reading the entities from tha databases and mapping them 
to Python objects.

The profiles of the most common operations are available in the **ConfigComparator_profile\.txt** report.

Profiling has been done using the **line_profiler** module:
[https://github.com/rkern/line_profiler](https://github.com/rkern/line_profiler)

If additional profiling and reports are needed follow the instructions on the provided site to install and use the 
profiler.

## 4. How data is compared
**Module**: src.GenericComparator

All the data is first read from both databases. This is the most time consuming process and it takes approximately 90% 
of all the comparison time. The data is organized in a dictionary by model type for easier retrieve during the 
comparison process.

We proceed by calculating the differences for each class. This is done by simply going threw all the IDs of a specific 
class (from 1 to the maximum value of the ids for that specific class) and comparing objects in the initial and 
modified database. When comparing objects we compare all their relations as well as attributes (in contrast with 
the equality operation from the MPSCD library which compares only ID and relation ID because of lazy loading). The 
result of the comparison is a dictionary of the differences grouped by class type.

Additionally, depending on the configuration, changes in related objects can trigger base objects to be marked as 
modified. This relations are specified in the **modification_dependencies** parameter. We check if any of the dependent 
attributes on objects that are not yet marked as modified have changed. If this is the case, the base object they relate 
to is added to the dictionary of changed objects.

## 5. How the report is generated
**Module**: src.dal.HtmlGenerator

The HTML generator takes as input the output of the data comparison operation from the **src\.GenericComparator** 
module. There is a module called **Templates** that contains all the HTML templates for various portions of the report. 
The templates also include the CSS needed to style the report in the desired manner.

The generator first checks if any objects that are marked as modified are of **CachedCodeListBaseObject** type. If any 
are found, they are placed in the **Modified code list** chapter of the report (see **Report format** chapter for 
more details). The **Modified code list** chapter is displayed only if there are modifications to the code lists.

For each modification group that is requested in the **model_grouping** parameter, a separated sub-chapter is generated. 
The procedure processes the provided differences one at the time, taking into account only the modifications of the 
base object of a particular modification group. All needed additional attributes to be displayed in the report are 
read from the **visualization_grouping** parameter and are retrieved from the provided databases cache.

In parallel, while generating modification groups tables, the index (to be placed at the beginning of the report) is 
constructed.

In case the **display_names** parameter is specified, attribute names will not be displayed but instead 
their aliases will be displayed. This allows to display more descriptive and user friendly names for convoluted and 
complicated attribute names.

## 6. Report format
The report is formatted as a series of chapters that describe the changes in the 2 provided databases. There are 3 
chapter:

- Index (list of entity groups that have changes, and how many changes are there)
- Code list changes (list of IDs of code list objects that changed, excluding the created one)
- Model changes (list of changes in the model groups)

The first 2 chapter (Index and Code list changes) are to offer the reviewer an overview of the changes 
performed on the database before diving into the detailed descriptions that are present in the Model changes chapter.

### 6.1. Code list changes
Since code list changes should be relatively uncommon and can affect a large number of objects in the database 
the reviewer should be warned that such changes occurred, and should be given additional information on the modified 
objects.

This is achieved by displaying a table where the first column represents the name of the model class, and the second 
column specifies which objects were changed, by simply listing the IDs of the changed objects. The reviewer can then 
manually access the database to verify the changes are correct. The exact changes on the code list objects are visible 
in the **Model changes** chapter.

This code list changes does not include newly created objects, since they cannot adversely affect existing database 
objects. The newly created objects are still displayed in the **Model changes** chapter.

### 6.2. Model changes
The chapter is formatted as a series of sub-chapters that describe the changes for each entity group.

An entity group is made up by:

- The attributes of the base entity of that group.
- The additional attributes of the base entity relations.

Attributes of the base entity as well as additional attributes are displayed only if they are different in the 
before and after database. In order to be able to identify the entities themselves, the unique values for each base 
entity are always displayed, even if they are equal. The parameter **show_class_id** can be passed to the 
GenericComparator to display or hide IDs of objects (unique values are always displayed). 
A red background signals that the value of the attribute changed, while a green one signals that the value is the 
same (only unique fields are eligible to be green, since only unique fields are displayed even if they are equal).

Entities in a entity group are divided by thick black lines - after every line a new object is displayed. There is 
also a separator (an empty white row), at the top of each entity, and in the right corner the separator 
contains the modification type of the entity below (Modified object, Created object, or Deleted object). In the sort 
version of the report, there is also a link to the long version, specifically to the entity that the link was 
clicked on.

There are 3 column. The first column contains the attribute name, the second one the attribute value in the initial 
database, the third one the attribute value in the modified database.

## 7. Usage
Before continuing with this chapter it is mandatory that the library was successful installed on the target 
machine and that you have two test MPS configuration databases. Two sample databases are provided in the **tests/** 
folder, but this one **must not** be modified, because test cases relate directly to data in this database. 
You can, however, make a copy of it and use it to test the scripts in this chapter.

### 7.1. Library
In order to add support for additional databases, one must first add support for this databases in the MPSCD library. 
Consult the MPSCD library documentation for information how to do that.

Additionally, you need to specify the following parameters:

- **modification_dependencies**: Defines which changes in sub entities mark the root entity as changed.
- **visualization_grouping**: Defines which parameters will be displayed in the report.
- **display_names** (optional): Defines the attribute aliases displayed in the report.

For additional information on this attributes format and meaning, please consult the API reference.

To further customize the report output, there are **parameters** that can be passed to the **GenericComparator\.py** 
module. This parameters are in the form of a dictionary. The currently implemented values for keys are:

- **before_filename**: Filename of the initial database. To be displayed in the report.
- **after_filename**: Filename of the modified database. To be displayed in the report.
- **patch_filename**: Filename of the patch. If specified, a patch to convert the initial to the modified database 
is created.
- **display_names**: Attribute aliases, to be displayed instead of attribute names.
- **show_base_class_attributes**: Automatically display all base class attributes in report.
- **show_class_id**: Show object IDs.
- **links_root_url**: If specified, links to another report are included in this report.

Consult the existing implementations (**ConfigComparatorShort\.py**) for more details.

### 7.2. Scripts
When installing the library the scripts get installed in the executable path of the current environment and are 
therefore available in the terminal.

The execution of scripts can be terminated using the CTRL+C keyboard combination. Scripts with long running operations 
have a loader that can be turned off with the -s (silent) flag.

#### 7.2.1. mps_compare_config_db
The script compares the provided databases and outputs the HTML report directly to the console or to the provided 
output file.

Help for the script:

<pre><code>
usage: mps_compare_config_db [-h] [-o OUTPUT] [-s] [-f]
                             before_database after_database

Compare 2 versions of the MPS configuration database.

positional arguments:
  before_database       Path to the initial database.
  after_database        Path to the modified database.

optional arguments:
  -h, --help            show this help message and exit
  -o OUTPUT, --output OUTPUT
                        Destination path for the reports.
  -s, --silent          Silent execution. Leave console clean.
  -f, --full            Produce full report only.
</code></pre>

The following example is supposed to be executed in the root folder of the library:

<pre><code>
compare_config_db tests/before_MpsConfigDatabase.mps tests/after_MpsConfigDatabase.mps -o output.html
</code></pre>

You can open the report by opening the **short_output\.html** or full_output\.html** in any web browser.

A similar result (only the full report is generated) can be obtained also by piping the output of the 
script directly to a file:

<pre><code>
compare_config_db tests/before_MpsConfigDatabase.mps tests/after_MpsConfigDatabase.mps>full_output.html
</code></pre>

When you want to run the script as part of a build or any other automated procedure you might want to run it in silent 
mode: 

<pre><code>
compare_config_db tests/before_MpsConfigDatabase.mps tests/after_MpsConfigDatabase.mps -o output.html -s
</code></pre>

This will prevent the loader to be displayed. An output will be posted to the standard output only in case of an 
error in the procedure. This feature might be used to detect problems during the automated processes.


## 8. Licence
<pre><code>
/*
**
**                                Copyright 2004
**                                      by
**                         The Board of Trustees of the
**                       Leland Stanford Junior University.
**                              All rights reserved.
**
**         Work supported by the U.S. Department of Energy under contract
**       DE-AC03-76SF00515.
**
**                               Disclaimer Notice
**
**        The items furnished herewith were developed under the sponsorship
**   of the U.S. Government.  Neither the U.S., nor the U.S. D.O.E., nor the
**   Leland Stanford Junior University, nor their employees, makes any war-
**   ranty, express or implied, or assumes any liability or responsibility
**   for accuracy, completeness or usefulness of any information, apparatus,
**   product or process disclosed, or represents that its use will not in-
**   fringe privately-owned rights.  Mention of any product, its manufactur-
**   er, or suppliers shall not, nor is it intended to, imply approval, dis-
**   approval, or fitness for any particular use.  The U.S. and the Univer-
**   sity at all times retain the right to use and disseminate the furnished
**   items for any purpose whatsoever.                       Notice 91 02 01
**
*/
</code></pre>