Application Deployment at InterSystems Caché

  • Tutorial
Kazuya Akimoto Ten Blue Eyes

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 modify the system with a file to fine-tune the environment for your needs.

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 XDatawith 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.Installerwith 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")
}
}

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

List of items


The manifest is formed from the following elements:
ElementParent elementAttributes (default value)Description
ArgInvoke, ErrorValue - argument valuePasses an argument to a method called through Invoke or Error
ClassmappingConfigurationPackage - 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
CompileNamespaceClass - name of the class (s) to compile
Flags - compilation flags (ck)
IgnoreErrors - ignore errors (0)
Compiles classes. Calls $ System.OBJ.Compile (Class, Flags)
ConfigurationNamespaceNeeded to create a scope and databases. The closing tag activates the mappings and updates the cpf file
CopyclassNamespaceSrc - source class
Target - target class
Replace - delete the source class (0)
Copy or move source class to target
CopydirManifestSrc - source directory
Targe - target directory
IgnoreErrors - ignore errors (0)
Copy directory
CopyfileManifestSrc - source file
Targe - target file
IgnoreErrors - ignore errors (0)
Copy file
CredentialProductionName - name of the access requisite
Username - username
Password - password
Overwrite - override if exists
Creates or redefines access details
CspapplicationNamespaceAuthenticationMethods - 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
DatabaseConfigurationBlockSize - 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
DefaultManifestName - 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
ElseManifest, NamespaceIt is executed if the if-condition check ended negatively.
ErrorManifestStatus - error code
Source - error source
Throws an exception. $ {} and # {} syntax not available
ForeachManifestIndex - variable name
Values ​​- list of variable values
Joint Loop Operator
Global mappingConfigurationGlobal - global name
From - database name from which we display Collation - sorting (Caché Standard)
Displays global
IfManifest, NamespaceCondition - conditionConditional jump operator
IfdefManifest, NamespaceVar - variable nameConditional jump operator, if the variable is defined
IfNotDefManifest, NamespaceVar - variable nameConditional jump operator if the variable is not defined
ImportNamespaceFile - 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)
InvokeNamespaceClass - 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
LoadpageNamespaceName - 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)
LogManifestLevel - 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
ManifestThe root element. The only one in the manifest, all other elements are located inside it
NamespaceManifestName - 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
ProductionNamespaceName - product name
AutoStart - automatic launch of products
Configures Ensemble products
ResourceManifestName - resource name
Description - description
Permission - public rights
Creates or modifies a resource
RoleManifestName - role name
Description - description
Resources - resources in the form "MyResource: RW, MyResource1: RWU" RolesGranted - give related roles
Creates a role
Routine mappingConfigurationRoutines - name of the routine (s)
Type - one of the types "MAC, INT, INC, OBJ, ALL"
From - from which database
Creates mapping routine
SettingProductionItem - 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
SystemsettingManifestName - class. Package property Config
Value - property value
Sets the value of the properties of the Config package (via the Modify method)
UserManifestUsername - 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
VarManifestName - 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:
VariableDescriptionValue 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 upgrade0 (installation)
1 (update)
CFGDIRSee INSTALLDIR./ InterSystems / Cache /
CFGFILEPath to cpf file/InterSystems/Cache/cache.cpf
CFGNAMEInstance NameCache
CPUCOUNTCPU Cores4
CspdirCSP Directory/ InterSystems / Cache / csp /
HostnameWeb server nameSCHOOL15
HTTPPORTWeb server port80
INSTALLDIRDirectory where Caché is installed/ InterSystems / Cache /
MGRDIRManagement Directory (mgr)/ InterSystems / Cache / mgr /
PLATFORMoperating systemUnix
PortCaché Superserver Port1972
PROCESSORPlatform namex86-64
VERSIONCaché Version2015.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.

Ссылки


Документация

Also popular now: