
Application Deployment at InterSystems Caché
- Tutorial

Introduction
So, you developed your application on InterSystems technologies. Now it needs to be deployed at the client and often more than once. During the development process, you got installation instructions - because it is not enough just to import the classes, you also need to
To solve these problems, there is a % Installer utility . This article is about her.
% Installer
This utility allows you to define an installation manifest that describes the target configuration of Caché, rather than steps to achieve it. You describe what should be, and Caché will already generate all the necessary code for this. You distribute, accordingly, only the manifest itself, code generation is already in place within the framework of a specific Caché server.
To write a manifest, you create an XData block with a description of the desired configuration, as well as a method that generates COS code based on the XData block (it is always the same). Once you have written the manifest, you can invoke it during the installation of Caché, from a terminal or COS code. The manifest must be executed in the% SYS area. The manifest is available both system parameters (super-port, OS, mgr directory, etc.), as well as arbitrary parameters passed by the user. Therefore, the installer class must meet the following requirements:
- Include a link to
%occInclude.inc
; - Contain a block
XData
with the configuration of the Caché server; - A block can be called any valid name.
- Add
[XMLNamespace = INSTALLER]
after the block name to enable prompts in the studio; - The root element (there can be only one) -
all other elements are located inside it; - You must define a method
setup()
that performs code generation from the XData block.
Using
Ready installation manifest can be launched in several ways :
- In the% SYS area from the terminal or COS code
do ##class(MyPackage.MyInstaller).setup()
- Automatically upon installation of Caché. To do this, export the installer class to the DefaultInstallerClass.xml file in the folder with the Caché distribution (where setup_cache.exe, or cinstall is located). When installing Caché, it will be imported into the% SYS area and launched (via the setup () method)
Example
Consider a simple example. Let's create a class
App.Installer
with an installer that creates an area with the name passed by the user:App.Installer
Include% occInclude
Class App.Installer
{
/// The generated code can be viewed in zsetup + 1 ^ App.Installer.1
XData Install [XMLNamespace = INSTALLER]
{
}
/// The method that is called to complete the installation.
/// During compilation of the class, COS code is generated
/// After that the installer starts with the parameters as follows:
/// Set pVars ("Namespace") = "TempNamespace"
/// Do ## class (App.Installer). setup (.pVars)
ClassMethod setup (ByRef pVars, pLogLevel As% Integer = 0, pInstaller As% Installer.Installer) As% Status [CodeMode = objectgenerator, Internal]
{
Quit ## class (% Installer.Manifest).% Generate ( % compiledclass,% code, "Install")
}
}
Class App.Installer
{
/// The generated code can be viewed in zsetup + 1 ^ App.Installer.1
XData Install [XMLNamespace = INSTALLER]
{
}
/// The method that is called to complete the installation.
/// During compilation of the class, COS code is generated
/// After that the installer starts with the parameters as follows:
/// Set pVars ("Namespace") = "TempNamespace"
/// Do ## class (App.Installer). setup (.pVars)
ClassMethod setup (ByRef pVars, pLogLevel As% Integer = 0, pInstaller As% Installer.Installer) As% Status [CodeMode = objectgenerator, Internal]
{
Quit ## class (% Installer.Manifest).% Generate ( % compiledclass,% code, "Install")
}
}
In this example, the following happens:
- Check if there is a region with a name equal to the value of the Namespace variable (for example, the value is NewNamespace);
- If not, the fact of starting the creation of the NewNamespace area is logged;
- Area Definition:
- C name NewNamespace;
- The area needs to be created;
- Code database NewNamespace;
- Ensemble is not included;
- NewNamespace data database.
- Database creation
- C name NewNamespace;
- In the mgr / NewNamespace folder (note that the MGRDIR variable is available to us by default).
- Logging to the completion area.
To start from the terminal, execute the following commands:
Set pVars ("Namespace") = "NewNamespace"
Do ## class (App.Installer) .setup (.pVars)
What will bring
2015-10-16 16:26:18 0 App.Installer: Installation starting at 2015-10-16 16:26:18, LogLevel = 0
2015-10-16 16:26:18 0: Creating namespace NewNamespace
2015-10 -16 16:26:19 0: End Creating namespace NewNamespace
2015-10-16 16:26:19 0 App.Installer: Installation succeeded at 2015-10-16 16:26:19
2015-10-16 16:26: 19 0% Installer: Elapsed time .605257s
2015-10-16 16:26:18 0: Creating namespace NewNamespace
2015-10 -16 16:26:19 0: End Creating namespace NewNamespace
2015-10-16 16:26:19 0 App.Installer: Installation succeeded at 2015-10-16 16:26:19
2015-10-16 16:26: 19 0% Installer: Elapsed time .605257s
List of items
The manifest is formed from the following elements:
Element | Parent element | Attributes (default value) | Description |
Arg | Invoke, Error | Value - argument value | Passes an argument to a method called through Invoke or Error |
Classmapping | Configuration | Package - a package to display From - the name of the database from which we display | Creates a mapping of classes from the database to the oblique, inside the Configuration element of which we are |
Compile | Namespace | Class - name of the class (s) to compile Flags - compilation flags (ck) IgnoreErrors - ignore errors (0) | Compiles classes. Calls $ System.OBJ.Compile (Class, Flags) |
Configuration | Namespace | Needed to create a scope and databases. The closing tag activates the mappings and updates the cpf file | |
Copyclass | Namespace | Src - source class Target - target class Replace - delete the source class (0) | Copy or move source class to target |
Copydir | Manifest | Src - source directory Targe - target directory IgnoreErrors - ignore errors (0) | Copy directory |
Copyfile | Manifest | Src - source file Targe - target file IgnoreErrors - ignore errors (0) | Copy file |
Credential | Production | Name - name of the access requisite Username - username Password - password Overwrite - override if exists | Creates or redefines access details |
Cspapplication | Namespace | AuthenticationMethods - available authentication methods AutoCompile - auto- compilation CSPZENEnabled - CSP / ZEN flag ChangePasswordPage - password change page CookiePath - path for cookie session CustomErrorPage - custom error page DefaultSuperclass - default super class DefaultTimeout - session timeout Description - Directory description - path to CSP- EventClass files - Grant event class - list of roles that are issued when GroupById logs in - group by ID InboundWebServicesEnabled - incoming web services IsNamespaceDefault - application for the default area LockCSPName - lock on the CSP name LoginClass - login page PackageName - package name PermittedClasses - allowed classes Recurse - subdirectories (0) Resource - required resource ServeFilesTimeout service files - timeout for service files TwoFactorEnabled - two-factor authentication Url - name of web application UseSessionCookie - use cookie for session | Creates or modifies a web application. A detailed description of the settings in the documentation and the Security.Applications class |
Database | Configuration | BlockSize - block size ClusterMountMode - mount the database as part of the Collation cluster - sort Create - create the database - yes, no, overwrite (yes) Dir - directory Encrypted - encrypt EncryptionKeyID - encryption key ID ExpansionSize - extension InitialSize - initial size MaximumSize - minimum size MountAtStartup - mount at startup MountRequired - mount required Name - name PublicPermissions - public rights Resource - StreamLocation resource - stream location | Creates or modifies a database. A detailed description of the settings in the documentation and the Config.Databases class |
Default | Manifest | Name - the name of the variable Value - the value of the variable Dir - the value of the variable, if this is the path to the folder / file | Defines the value of a variable if not defined |
Else | Manifest, Namespace | It is executed if the if-condition check ended negatively. | |
Error | Manifest | Status - error code Source - error source | Throws an exception. $ {} and # {} syntax not available |
Foreach | Manifest | Index - variable name Values - list of variable values | Joint Loop Operator |
Global mapping | Configuration | Global - global name From - database name from which we display Collation - sorting (Caché Standard) | Displays global |
If | Manifest, Namespace | Condition - condition | Conditional jump operator |
Ifdef | Manifest, Namespace | Var - variable name | Conditional jump operator, if the variable is defined |
IfNotDef | Manifest, Namespace | Var - variable name | Conditional jump operator if the variable is not defined |
Import | Namespace | File - file / folder for import Flags - compilation flags (ck) IgnoreErrors - ignore errors (0) Recurse - recursive import (0) | Imports files. Calls: $ System.OBJ.ImportDir (File ,, Flags ,, Recurse) and $ System.OBJ.Load (File, Flags) |
Invoke | Namespace | Class - class Method - method CheckStatus - check the return status Return - write the result to a variable | Calls a class method, you can pass arguments and get the result of execution |
Loadpage | Namespace | Name - path to the CSP page Dir - folder with CSP pages Flags - compilation flags (ck) IgnoreErrors - ignore errors (0) | Loads CSP files through $ System.CSP.LoadPage (Name, Flags) and $ System.CSP.LoadPageDir (Dir, Flags) |
Log | Manifest | Level - logging level from 0 (minimum) to 3 (in detail) Text - text, up to 32000 characters | Adds a message to the log if the logging level is greater than or equal to the level attribute |
Manifest | The root element. The only one in the manifest, all other elements are located inside it | ||
Namespace | Manifest | Name - area name Сreate - create area - yes, no, overwrite (yes) Code - DB with code Data - DB with Ensemble data - enable Ensemble in the area Other attributes associated with Ensemble web applications | Defines the scope of the installer |
Production | Namespace | Name - product name AutoStart - automatic launch of products | Configures Ensemble products |
Resource | Manifest | Name - resource name Description - description Permission - public rights | Creates or modifies a resource |
Role | Manifest | Name - role name Description - description Resources - resources in the form "MyResource: RW, MyResource1: RWU" RolesGranted - give related roles | Creates a role |
Routine mapping | Configuration | Routines - name of the routine (s) Type - one of the types "MAC, INT, INC, OBJ, ALL" From - from which database | Creates mapping routine |
Setting | Production | Item - custom element Target - setting type: Item, Host, Adapter Setting - setting name Value - setting value | Configures an Ensemble product item. Invokes the Ens.Production: ApplySettings method |
Systemsetting | Manifest | Name - class. Package property Config Value - property value | Sets the value of the properties of the Config package (via the Modify method) |
User | Manifest | Username - username PasswordVar - variable containing the password Roles - list of user roles Fullname - full name Namespace - start area Routine - start routine ExpirationDate - date after which the user will no longer be activated ChangePassword - change the password with the next login Enabled - if the user is activated | Create or Modify a User |
Var | Manifest | Name - variable name Value - variable value | Defines the value of a variable |
Variables
Variables can act as attribute values; they are defined in one of three ways:
- $ {<Variable_name>} - during the execution of the manifest, the value of the variable is calculated (passed by the user or one of the environment variables, see below);
- $ {# <ParameterName>} - at compile time they are replaced with the value of the specified parameter of the installer class;
- # {
} - during the execution of the manifest, the value of the specified COS expression is calculated. Do not forget about quotation marks.
Parameter values are determined at the compilation stage, so they can be part of a variable or COS expression. The interpretation of variables occurs before the interpretation of the COS code, so the variables can be included in the COS expression, for example:
#{$ZCVT("${NAMESPACE}","L")}.
Environment Variables
The following variables are always available:
Variable | Description | Value example |
Sourcedir | (Only when installing Cache) The directory where the installer is located (setup_cache.exe or cinstall) | / InterSystems / distr / |
ISCUpgrade | (Only when installing Cache) Determines whether to install or upgrade | 0 (installation) 1 (update) |
CFGDIR | See INSTALLDIR. | / InterSystems / Cache / |
CFGFILE | Path to cpf file | /InterSystems/Cache/cache.cpf |
CFGNAME | Instance Name | Cache |
CPUCOUNT | CPU Cores | 4 |
Cspdir | CSP Directory | / InterSystems / Cache / csp / |
Hostname | Web server name | SCHOOL15 |
HTTPPORT | Web server port | 80 |
INSTALLDIR | Directory where Caché is installed | / InterSystems / Cache / |
MGRDIR | Management Directory (mgr) | / InterSystems / Cache / mgr / |
PLATFORM | operating system | Unix |
Port | Caché Superserver Port | 1972 |
PROCESSOR | Platform name | x86-64 |
VERSION | Caché Version | 2015.1.1 |
Debugging
It is not clear what values attributes can take. For clarification, look at the generated int code for the setup method. As a rule, the main challenge is the method:
tInstaller.ElementName()
, ie a method of class % Installer.Installer which already calls directly system methods. Alternatively, you can look at the class code
%Installer., атрибуты элемента это свойства его класса. Кодогенерация осуществляется в методах %OnBeforeGenerateCode, %OnGenerateCode, %OnAfterGenerateCode.
Для целей отладки, рекомендую оборачивать вызов установщика в транзакцию. Так с помощью команд TSTART/TROLLBACK можно легко отменить все изменения, сделанные внутри Caché (внешние к Caché изменения, например создание файла БД отменены не будут).
Пример использования
Проект MDX2JSON содержит установщик. Для установки достаточно импортировать в любую область файл installer.xml с классом MDX2JSON.Installer. Импортировать можно или через панель управления или просто переносом класса в студию.
Далее выполните в терминале:
do ##class(MDX2JSON.Installer).setup()
В результате произойдёт загрузка файлов из GitHub-репозитория, установка «по умолчанию» в область MDX2JSON с созданием базы MDX2JSON, маппинга пакета MDX2SJON в %All, создание REST-приложения /MDX2JSON и многое другое, о чём будет написано в терминале.
Ещё примеры
Пример в документации.
Класс Sample.Installer в области Samples.
Проект CacheGitHubCI содержит установщик.
Проект SYSMON Dashboards содержит установщик.
Проект DeepSee Audit содержит установщик.
Выводы
Утилиту %Installer можно использовать для поставки решений на InterSystems Caché и Ensemble.
Ссылки
Документация