Parallels H-Sphere - 3.5 Developer Guide

Parallels® H-Sphere
Parallels H-Sphere 3.5 Developer Guide
Legal and Copyright Notice
ISBN: N/A
Parallels Holdings, Ltd.
c/o Parallels International GmbH
Vordergasse 59
CH-Schaffhausen
Switzerland
Phone: +41-526320-411
Fax: +41-52672-2010
© Copyright 2011,
Parallels, Inc.
All rights reserved
Distribution of this work or derivative of this work in any form is prohibited unless prior
written permission is obtained from the copyright holder.
Product and service names mentioned herein are the trademarks of their respective owners.
Contents
Preface 5
About This Guide ........................................................................................................................... 6
Typographical Conventions ........................................................................................................... 6
Feedback ....................................................................................................................................... 7
H-Sphere System Database 8
Getting User Information from the Parallels H-Sphere System Database .................................... 9
Database Connections ................................................................................................................ 13
Regular Shared Connections ............................................................................................ 13
Connections With Opened Transaction ............................................................................ 13
Unix Hosting Resources and Tools 15
Creating Unix-Hosted Resources ................................................................................................ 16
Example: ............................................................................................................................ 21
Global Resources And Resource Dependencies ........................................................................ 26
globals.xml ......................................................................................................................... 26
resource_dependences.xml .............................................................................................. 30
List of Resource Dependencies ........................................................................................ 30
Account Preferences ................................................................................................................... 33
TimeUtils Class ............................................................................................................................ 33
FreeMarker Access Control List (FMACL) Objects ..................................................................... 35
Purpose ............................................................................................................................. 35
Implementation .................................................................................................................. 35
External Credits ........................................................................................................................... 37
Running Parallels H-Sphere in Debug Mode .............................................................................. 38
Script Runner ............................................................................................................................... 39
Windows Hosting Resources 40
Creating Resources for Winbox ................................................................................................... 41
Introduction ........................................................................................................................ 41
Requirements .................................................................................................................... 41
Naming Conventions ......................................................................................................... 41
General Scheme of Resource Functioning ....................................................................... 42
Methods ............................................................................................................................. 43
Keys ................................................................................................................................... 44
Error Handling ................................................................................................................... 45
Resource Hierarchy ........................................................................................................... 46
Logging .............................................................................................................................. 46
Resource Types ................................................................................................................ 46
Schemas ............................................................................................................................ 47
Attributes ........................................................................................................................... 48
Crash Reporting on Winbox ........................................................................................................ 52
Crash Record File Structure .............................................................................................. 52
Detecting Crashes in Parallels H-Sphere and non Parallels H-Sphere Modules ............. 53
IIS 6.0 Native Mode ..................................................................................................................... 53
ISAPI Filters ....................................................................................................................... 54
IIS Log Plugin .................................................................................................................... 54
Preface 4
Parallels H-Sphere XML API 55
Enabling Parallels H-Sphere XML API ........................................................................................ 57
Testing Parallels H-Sphere XML API .......................................................................................... 57
Getting the List of Available XML API Services ........................................................................... 59
Generating WSDL Files for Parallels H-Sphere XML API Services ............................................ 60
Parallels H-Sphere XML API Security Settings and Authentication ............................................ 60
Adding Custom Payment Gateways and Domain Registrars 63
Web Payment SDK ...................................................................................................................... 64
Domain Registrar SDK ................................................................................................................ 64
Merchant Gateway SDK .............................................................................................................. 64
Appendix 66
Logging in as the cpanel User ..................................................................................................... 67
Restarting Parallels H-Sphere Control Panel .............................................................................. 67
In this chapter:
About This Guide ............................................................................................... 6
Typographical Conventions ............................................................................... 6
Feedback .......................................................................................................... 7
C H A P T E R 1

Preface

6 Preface
Formatting convention
Type of Information
Example
Special Bold
Items you must select, such as menu options, command buttons, or items in a list.
Go to the System tab. Titles of chapters, sections, and subsections.
Read the Basic Administration chapter.
Italics
Used to emphasize the importance of a point, to introduce a term or to designate a command line placeholder, which is to be replaced with a real name or value.
The system supports the so called wildcard character search.
Monospace
The names of commands, files, directories, and domain names.
The license file is located in the
http://docs/common/ licenses directory.

About This Guide

This guide explains how to perform certain development tasks, such as, creating custom Unix-hosted and Windows-hosted resources. It provides Parallels H-Sphere XML API reference to manage Parallels H-Sphere services from remote applications via SOAP.
It is helpful that you also refer to Parallels H-Sphere Customization Guide for the explanation of Parallels H-Sphere customization, localization, and Parallels H-Sphere addons (packages).

Typographical Conventions

Before you start using this guide, it is important to understand the documentation conventions used in it.
The following kinds of formatting in the text identify special information.
Preface 7
Preformatted
On-screen computer output in your command­line sessions; source code in XML, C++, or other programming languages.
# ls –al /files
total 14470
Preformatted Bold
What you type, contrasted with on-screen computer output.
# cd /root/rpms/php
CAPITALS
Names of keys on the keyboard.
SHIFT, CTRL, ALT
KEY+KEY
Key combinations for which the user must press and hold down one key and then press another.
CTRL+P, ALT+F4

Feedback

If you have found a mistake in this guide, or if you have suggestions or ideas on how to improve this guide, please send your feedback using the online form at
http://www.parallels.com/en/support/usersdoc/. Please include in your report the
guides title, chapter and section titles, and the fragment of text in which you have found an error.
This chapter explains how to write common queries to the H-Sphere system database
In this chapter:
Getting User Information from the Parallels H-Sphere System Database .......... 9
Database Connections ...................................................................................... 13
C H A P T E R 2

H-Sphere System Database

and how to operate with the database connections.
H-Sphere System Database 9

Getting User Information from the Parallels H-Sphere System Database

Selecting user info:
select users.* from users, user_account where users.id=user_account.user_id and user_account.account_id= USER_ACCOUNT_ID;
Selecting mail accounts info:
select m.* from mailboxes m, parent_child p where p.child_type=1002 and p.child_id=m.id and p.account_id= USER_ACCOUNT_ID;
Selecting resellers info:
select u.* from users u, resellers r, user_account a where u.id=r.admin_id and r.id=a.user_id and account_id= USER_ACCOUNT_ID;
Selecting credit card info:
select c.* from users u, user_billing_infos u_b, credit_card c, user_account a where u.id = u_b.user_id and c.id = u_b.billing_info_id and
u.id=a.user_id and a.account_id= USER_ACCOUNT_ID;
Selecting resellers users credit card info:
This is possible if you dont encrypt credit card numbers in Parallels H-Sphere database. In this case run the following query:
select cc.cc_number, cc.name, cc.exp_year, cc.exp_month, cc.type from accounts as acc join credit_card as cc on (cc.id=acc.bi_id) where acc.reseller_id= RESELLER_ACCOUNT_ID;
Selecting credit card types:
All supported credit cards:
select * from cc_brands;
Credit cards allowed in Merchant Gateway:
select * from active_merch_gateway;
Selecting virtual FTP info:
select f.* from ftp_vuser f, parent_child p where p.child_type=2003 and p.child_id=f.id and p.account_id= USER_ACCOUNT_ID;
Selecting users home directory:
To select users home directory from the system database and connect it to account:
select * from unix_user where unix_user.id = parent_child.child_id and parent_child.account_id = USER_ACCOUNT_ID;
Selecting users website directory:
Website directory always equals users home directory and domain name.
Selecting users hosting plan:
10 H-Sphere System Database
To select the name of the plan, run the following query:
select plans.description from plans, accounts where accounts.id = USER_ACCOUNT_ID and plans.id = accounts.plan_id;
Selecting domain name:
To obtain data on domain names, run the following query:
select domains.name from domains, parent_child where domains.id = parent_child.child_id and parent_child.account_id = USER_ACCOUNT_ID;
Selecting IP address:
To retrieve data on all IPs, run the following query:
select IP from l_server_ips, parent_child where child_id = l_server_ips.r_id and parent_child.child_type = 8 and
parent_child.account_id = USER_ACCOUNT_ID;.
There can be multiple IPs per domain.
Selecting IP of the domain:
To retrieve IP for the given domain name, run the following command:
select IP from l_server_ips, domains, parent_child where domains.id = parent_child.parent_id and parent_child.child_id = l_server_ips.r_id and domains.name =YOUR_DOMAIN_NAME’;
Selecting account ID for the domain:
To get the data about account ID of the given domain, execute the query:
select account_id from domains, parent_child where domains.id = parent_child.child_id and domains.name =DOMAIN_NAME’;
Selecting logical server of the domain:
To retrieve IP for the given domain name, run the following command:
select hostid from unix_user, parent_child where parent_child.account_id = YOUR_ACCOUNT_ID and child_id = unix_user.id;
Selecting shared IP of the domain:
To get the information about shared IPs for the domain, run:
select IP from l_server_ips where where l_server_id =HOSTIDand flag =SHARED_IP;
Selecting users e-mail address:
To receive data on clients contact emails, run the following query:
select * from contact_info, accounts where contact_info.id = accounts.ci_id and accounts.id = USER_ACCOUNT_ID;
Selecting emails of all users, excluding resellers end users:
To receive the list of all email addresses ignoring resellers end users, run the following query:
H-Sphere System Database 11
select c_i.email from contact_info c_i join accounts a on (c_i.id=a.ci_id and a.reseller_id=1);
Getting user emails by their MySQL database names:
select c.email from mysqldb m, parent_child pc, accounts a, contact_info c where m.db_name=DBNAMEand m.id=pc.child_id and pc.child_type=6001 and pc.account_id=a.id and a.ci_id=c.id;
Verify users:
To verify whether a user exists in Parallels H-Sphere:
select id from users where username=USER_NAMEand password=PASSWORD’;
Defining physical/logical servers:
Run the following commands to get info about physical/logical servers:
by IP address:
select l_server_id from l_server_ips where l_server_ips = IP_ADDRESS;
by logical server:
select p_server_id from l_server where id = LOGICAL_SERVER_ID’;
selecting info about physical server:
select * from p_server where id = PHYSICAL_SERVER_ID’;
Selecting users billing info:
To select billing info from accounts, run the following query:
select * from billing_info, accounts where billing_info.id = accounts.bi_id and accounts.id =USER_ACCOUNT_ID;
Billing periods for plans:
All information including discounts if present:
select * from plan_value where name like _PERIOD%and plan_id=plan_id;
Discounts:
select * from plan_value where name like %_DISC_%and plan_id=plan_id;
Payment modes:
select billing from plans where id=plan_id;
plans.billing takes the following values:
0 - without billing;
1 - billing mode;
2 - billing with trial period.
Getting plan pricing details:
select * from plan_value where plan_id=plan_id;
Getting domain registration pricing details:
select * from tld_prices;
12 H-Sphere System Database
 select * from plan_value where name like „_TLD_%‟;
H-Sphere System Database 13

Database Connections

There are two possible types of connections to the Parallels H-Sphere database:
Regular shared connections
Connections with opened transaction
Important: In any case, you should use only prepared statements when working with the Parallels H-Sphere database!

Regular Shared Connections

The part of the code which establishes and uses a regular database connection should look something similar to this:
PreparedStatement ps = null; Connection con = Session.getDb(); try {
ps = con.prepareStatement(...........);
......................................
} finally { Session.closeStatement(ps); con.close(); }

Connections With Opened Transaction

In general, the part of the code which establishes and uses a transaction connection should look as follows:
// checking if the transaction exists boolean wasTrans = Session.isTransConnection(); Connection con = wasTrans ? Session.getDb() : Session.getTransConnection(); try { // some operation with the database } catch (Exception ex){ if (!wasTrans) { // rollback transaction con.rollback(); // some data to release cache and to synchronize with old data in HS DB } throw ex; } finally { if (!wasTrans) { // commit transaction and release connection Session.commitTransConnection(con); } else { con.close();
14 H-Sphere System Database
} }
Important:
1 There is the pool of transaction connections (5 by default). Opening a
new transaction that exceeds this maximum would cause the system to hang up.
2 As the number of available transactions is resctricted, you must
release the transaction connection you have opened by using the following command:
Session.commitTransConnection(con);
3 To get an opened transaction connection:
con = Session.getTransConnection();
4 Later in the code, you may get the same connection:
con = Session.getDb();
Note: Never close a transaction connection you havent opened!
5 Please make sure you synchronize your objects with the
corresponding data in the database. You must release your cache if you make a rollback.
This chapter explains how to write custom Unix hosting resources and outlines some
In this chapter:
Creating Unix-Hosted Resources ...................................................................... 16
Global Resources And Resource Dependencies ............................................... 26
Account Preferences ......................................................................................... 33
TimeUtils Class ................................................................................................. 33
FreeMarker Access Control List (FMACL) Objects ............................................ 35
External Credits ................................................................................................. 37
Running Parallels H-Sphere in Debug Mode ..................................................... 38
Script Runner .................................................................................................... 39
C H A P T E R 3

Unix Hosting Resources and Tools

other developer tools related to Parallels H-Sphere Unix servers.
16 Unix Hosting Resources and Tools

Creating Unix-Hosted Resources

A Unix-hosted resource is created as follows:
1 Login as the cpanel user (on page 67) to CP server.
2 Create a class that implements this resource.
Create a new Parallels H-Sphere resource class in the
~cpanel/shiva/psoft/hsphere/resource directory. For example:
package psoft.hsphere.resource; import psoft.hsphere.*; import java.util.Collection;
public class MyResource extends Resource { public MyResource(int type, Collection init) throws Exception { super(type, init);
...........
} public MyResource(ResourceId rid) throws Exception { super(rid);
...........
} }
The class must have 2 constructors, as illustrated in the above example.
The first constructor, MyResource(int type, Collection init), is used
on the resource creation and its init argument contains the list of the String class objects. The MyResource methods arguments starting from the third are parameters passed from the HTML form. For example:
<assign result=parent.addChild(request.resource_name,””, db_id, user_id)>
Here, db_id and user_id are parameters taken from the HTML form.
In this case, the values of db_id and user_id are passed to constructor as Collection of Strings.
The second constructor, MyResource(ResourceId rid), is used when the
user (owner of the resource) is logged in and ClassLoader loads the resource.
Also, the resource may overwrite the initDone() method called upon the resource creation. initDone() is designed to save all additional parameters into the database and to execute additional scripts.
The resource may also overwrite the delete() method called upon the recource deletion. This method is used to delete all additional database records related to this resource.
If the resource creates system resources (directories, files, etc.) on a certain host, the resource should implement the HostDependentResource interface:
package psoft.hsphere.resource;
Unix Hosting Resources and Tools 17
public interface HostDependentResource { /**
Method checks if a resource can be moved to the target server
@param newHostId
@return
@throws Exception
*/ public boolean canBeMovedTo(long newHostId) throws Exception;
/** The method physically creates a physical implementation
of a resource on a logical serevr with the passed ID
@param targetHostId
@throws Exception
*/ public void physicalCreate(long targetHostId) throws Exception;
/**
The metod deletes a physical implementation of a resource on
a logical server with the passed ID
@param targetHostId
@throws Exception
*/ public void physicalDelete(long targetHostId) throws Exception; /**
The method sets an ID of the logical server to
which this resource is linked
@param newHostId
@throws Exception
*/ public void setHostId(long newHostId) throws Exception; /**
The method returns an ID of a logical server
to which this resource is being linked
@return
@throws Exception
*/ public long getHostId() throws Exception; }
In case of the HostDependentResource implementation, the method physicalCreate(long targetHostId) must be called from the method initDone(), and the method physicalDelete(long targetHostId) from
the method delete(). The methods physicalCreate(long targetHostId) and physicalDelete(long targetHostId) call scripts to create and delete system resources, respectfully. The method canBeMovedTo(long newHostId) should return true if physical components of the resource (files, directories, etc) can be moved to or created on the host. The methods setHostId(long newHostId) and getHostId() respectfully set and get id of the host where resource physical components are located.
18 Unix Hosting Resources and Tools
General order of calling methods during the first resource creation is as follows:
Column
Type
Modifier
Description
id
integer
not null
unique resource type id
name
character varying(40)
not null
unique resource name
price
character varying(5)
flags:
M (initial value must be set)
R (recurrent)
U (usage)
F (initial value is optional)
S (setup)
description
character varying(100)
resource brief description
MyResource(int type, Collection init) public void initDone() public void physicalCreate(long targetHostId)
The resource parameter values predefined in the <plan_name>.xml file can be retrieved by calling the getPlanValue(String key) method defined in Resource.class. For example, in unix.xml, the myresource resource is described with the res_myresource construction with the block of predefined values:
<res_myresource> ... <values> <value name=some_key>some value</value> ... </values> </res_myresource>
Then, to get the value for some_key, the getPlanValue method is used as follows:
<assign value=myresource.getPlanValue(some_key)>
In order to retrieve the resource values, FM_ methods should be implemented to be called from the HTML form. FM_ method, with its name having the FM_ prefix, is a method that returns a value of the TemplateModel class. If you call an FM_ method from a template, the Freemarker code will look like:
<assign multiply=myresource.multiply(a, b)>
Here, myresource is resource name in the plan, and multiply refers to the FM_multiply(a, b) method, where a and b are the methods arguments. In
this case, the TemplateModels FM_multiply(int x, int y) method of MyResource class will be called.
3 Insert resource information into the Par allels H-Sphere database.
Information must be added to the type_name table:
Unix Hosting Resources and Tools 19
rprice
character varying(5)
reseller flags:
R (recurrent)
U (usage)
F (initial value is optional)
S (setup)
required
smallint
flag indicating if this resource is required for all accounts
priority
smallint
must be 0
ttl
integer
resource deletion time (should not be set initially)
20 Unix Hosting Resources and Tools
Index: type_name_name
Primary key: type_name_pkey To add a resource, insert the resource data into the
type_name table, like this:
INSERT INTO type_name (id,name,description,required,priority) VALUES (119, my_resource, My Resource,0,0);
1 Include the resource to the plan XML configuration file.
The resource should be included into XML configuration files for each type of plans where this resource is to be enabled (for example, unix.xml for Unix plan). These files are located in the ~cpanel/shiva/psoft/hsphere/plan/wizard/xml/ directory.
You need to add the resource tags with the new resource wherever necessary according to the guide on creating XML plan wizards in Parallels H-Sphere Customization Guide.
For example:
<categories>
.......................
<category description=planeditor.myresource”>
.........................................
<resource name=my_resource class=psoft.hsphere.resource.MyResourceadminonly=”1”/>
.........................................
</category>
.......................
</categories>
To make the resource available automatically upon accounts creation, add the res_RESOURCE_NAME construction to the plan XML file, where RESOURCE_NAME is the value set in the name attribute of the resource tag for the given resource.
Make sure you also set the interface text label set as the description attribute of the category tag. This is done in the custom hsphere_lang.properties file. For the label in the above example, the label is set as follows:
planeditor.myresource = My Resource
2 Implement the resource in CP Web interface.
1. Create templates for this resource.
Create templates according to the template procedure. See the example below for the templates you may need to add.
2. Add a new menu item for this resource in CP menu.
Customize CP menu and add a new menu item to the custom menu.xml, for example:
<menudef id=unix”>
....................
<menuitem name=myresourcelabel=myresource.label URL=design/myresource.htmlresource=”” tip=myresource.tip/>
....................
</menudef>
Unix Hosting Resources and Tools 21
Then, add labels myresource.label and myresource.tip to the custom hsphere_lang.properties file and run language bundle compiler:
[]$ java psoft.hsphere.LangBundlesCompiler
3 Create scripts for the resources physical implementation.
You must be logged in as root to create these scripts in the /hsphere/shared/scripts/ directory. See the example below on how you may create these scripts.
Note: Make changes to custom templates, interface text bundles and XML files, not to the default ones! Otherwise, you will lose your settings with subsequent Parallels H­Sphere upgrades. Please refer to the Parallels H-Sphere Customization Guide for details.

Example:

Below is a detailed example of how to create and add a new resource to Parallels H­Sphere.
1 Login as cpanel user (on page 67) to the CP server.
2 Create a resource class:
package psoft.hsphere.resource; import java.util.*; import psoft.hsphere.*; public class MyResource extends Resource implements HostDependentResource { public MyResource(int type, Collection init) throws Exception { super(type, init); }
public MyResource(ResourceId rid) throws Exception { super(rid); }
/*In this case the resource can be moved to any host*/ public boolean canBeMovedTo(long newHostId) throws Exception { return true; }
/* This method is started when the resource is created */ public void initDone() throws Exception { physicalCreate(Long.parseLong(recursiveGet(host_id).toString ())); }
/*
Deletes persistant representation of the resource as well as its system/physical representation
@throws Exception */ public void delete() throws Exception {
22 Unix Hosting Resources and Tools
physicalDelete(Long.parseLong(recursiveGet(host_id).toString ())); }
/*This method implements method of HostDependentResource interface.
In this case method collects the information about resource
and runs the myresource-init script with collected
information as arguments.
*/ public void physicalCreate(long targetHostId) throws Exception { //Unix-based implementation: List l = new ArrayList(); l.add(recursiveGet(login).toString()); l.add(recursiveGet(“dir).toString()); HostEntry he = HostManager.getHost(targetHostId); he.exec(myresource-init, l); //Win-based implementation: // WinHostEntry he = (WinHostEntry) HostManager.getHost(targetHostId); // boolean isSOAP = WinService.isSOAPSupport(); // if (isSoap) { // SOAPEnvelope envelope = he.invokeMethod(create, new String[][] { // {resourcename, myresource}, // {username, recursiveGet(login).toString()}, // {directory, recursiveGet(dir).toString()}} // ); // if (envelope == null) { // throw new HSUserException(The error invoked during SOAP calling); // } // } else { // throw new HSUserException(SOAP is not supported); // }
}
/*This method implements method of HostDependentResource interface.
In this case method collects the information about resource
and executes the myresource-init script with collected
information as arguments in order to physically delete
resource. */ public void physicalDelete(long targetHostId) throws Exception { //Unix-based realisation: List l = new ArrayList(); l.add(recursiveGet(login).toString()); l.add(recursiveGet(dir).toString()); HostEntry he = HostManager.getHost(targetHostId); he.exec(myresource-delete, l); //Win-based realisation:
Unix Hosting Resources and Tools 23
// WinHostEntry he = (WinHostEntry) HostManager.getHost(targetHostId); // boolean isSOAP = WinService.isSOAPSupport(); // if (isSoap) { // SOAPEnvelope envelope = he.invokeMethod(delete, new String[][] { // {resourcename, myresource}, // {username, recursiveGet(login).toString()}, // {directory, recursiveGet(dir).toString()}} // ); // if (envelope == null) { // throw new HSUserException(The error invoked during SOAP calling); // } // } else { // throw new HSUserException(SOAP is not supported); // }
}
/*This method implements method of HostDependentResource interface.
id of this resource host cannot be set */ public void setHostId(long newHostId) throws Exception { return; }
/*This method implements method of HostDependentResource interface
and returns value of hos_id key in resource tree. */ public long getHostId() throws Exception { return Long.parseLong(recursiveGet(host_id).toString()); } }
3 Insert the resource info into the system database:
[]$ psql hsphere hsphere=# INSERT INTO type_name (id, name, description, required, priority) hsphere-# VALUES (777, my_resource, My Resource, 0, 0);
4 Add the new resource to plan XML config files.
For example, ~cpanel/shiva/psoft/hsphere/plan/wizard/xml/unix.xml for Unix plan type:
<categories>
.......................
<category description=planeditor.myresource”>
.........................................
<resource name=my_resourcerequired=”0” noprice=”1” class=psoft.hsphere.resource.MyResource/>
.........................................
24 Unix Hosting Resources and Tools
</category>
.......................
</categories>
Note: Resource will be created automatically with accounts if the
<res_my_resource> </res_my_resource> tag is defined in unix.xml
Set interface text label for the new resource:
Edit ~cpanel/shiva/custom/bundles/hsphere_lang.properties:
planeditor.myresource = My Resource
Then, run language bundle compiler:
[]$ java psoft.hsphere.LangBundlesCompiler
5 Implement the resource in CP Web interface:
1. create resource template files:
Create
~cpanel/shiva/custom/templates/common/design/myresource.htm l:
<assign template=design/myresource.html”> <include functions”> <call draw_menu(myresource)> <include control/unixuser/myresource.html”> <call bottom()>
Create
~cpanel/shiva/custom/templates/common/unixuser/myresource.h tml:
<call draw_tooltip()> <call draw_table_header(“2”, lang.domain.editincluded.ftp)> <tr> <td><call draw_label(My Resource)></td> <td><call onoff(account.getChild(unixuser), my_resource)></td> </tr> <call draw_table_footer()>
2. Add a link to this resource in CP menu
Add a new menu item in ~cpanel/shiva/custom/xml/menu.xml:
....................
<menudef id=unix”>
....................
<menuitem name=myresourcelabel=myresource.label URL=design/myresource.htmlresource=”” tip=myresource.tip/>
....................
</menudef>
....................
Then, add labels myresource.label and myresource.tip to ~cpanel/shiva/psoft/hsphere/lang/hsphere_lang.properties and run language bundle compiler:
[]$ java psoft.hsphere.LangBundlesCompiler
Unix Hosting Resources and Tools 25
6 Create scripts for physical implementation of the resource. You must
login as root.
Create the file hsphere/shared/scripts/myresource-init:
#!/bin/sh cd $2; mkdir myresource; exit 0
Create the file hsphere/shared/scripts/myresource-delete:
#!/bin/sh cd $2; rm -rf myresource; exit 0
26 Unix Hosting Resources and Tools

Global Resources And Resource Dependencies

To simplify describing and provide flexible access mechanism, it was logically split into two parts: globals and resource dependencies.
Globals is the mechanism to provide enabling/disabling some features (resources) both for the entire system and for separate reseller hosting systems. By now, we have the following Globals: Parallels H-Sphere resources, key - value like objects stored in db, Class managed key sets, Class maintained sophisticated objects (former pseudo resources).
Resource Dependencies is a description of how resources/objects depend on other resources/objects. Not only chains of dependencies up to Globals can be defined here, there is also a possibility to describe parent-child and ancestor-descendant resource dependencies. Such resource dependencies are used to make a decision which resources can be added to user accounts and which cannot.

globals.xml

This file lists global resources. Location: ~cpanel/shiva/psoft/hsphere/globals.xml
Example: http://hsphere.parallels.com/HSdocumentation/xmls/globals.xml
DTD scheme:
<!DOCTYPE globals [ <!ELEMENT globals (section+, special?)> <!ELEMENT section ((object | plan_dependent_resource | set)*)> <!ELEMENT object (check_config?)> <!ELEMENT plan_dependent_resource (check_config?, user_plan*)> <!ELEMENT set (check_config?)> <!ELEMENT maintained_object EMPTY> <!ELEMENT check_config (property+ | variant+)> <!ELEMENT variant (property+)> <!ELEMENT property EMPTY> <!ELEMENT special (maintained_object+)> <!ELEMENT user_plan EMPTY> <!ATTLIST section id CDATA #REQUIRED> <!ATTLIST section label CDATA #IMPLIED> <!ATTLIST section description CDATA #IMPLIED> <!ATTLIST section show (each | globals | plans | custom) each> <!ATTLIST section store (each | settings | plans | custom) each> <!ATTLIST section online_help CDATA #IMPLIED> <!ATTLIST object name CDATA #REQUIRED> <!ATTLIST object label CDATA #IMPLIED>
Unix Hosting Resources and Tools 27
<!ATTLIST object label_enabled CDATA #IMPLIED> <!ATTLIST object label_disabled CDATA #IMPLIED> <!ATTLIST object default (enabled | disabled | unavailable) enabled> <!ATTLIST plan_dependent_resource name CDATA #REQUIRED> <!ATTLIST set name CDATA #REQUIRED> <!ATTLIST set label CDATA #REQUIRED> <!ATTLIST set default (enabled | disabled | unavailable) enabled> <!ATTLIST set class CDATA #REQUIRED> <!ATTLIST set managed (globally | reseller) globally”> <!ATTLIST property key CDATA #REQUIRED> <!ATTLIST property value CDATA “*”> <!ATTLIST maintained_object name CDATA #REQUIRED> <!ATTLIST maintained_object class CDATA #REQUIRED> <!ATTLIST user_plan type CDATA #REQUIRED> <!ATTLIST user_plan label CDATA #IMPLIED> <!ATTLIST user_plan default (enabled | disabled | unavailable) enabled> ]
It can be seen that the root level consists of one or more section elements. Section is the way to combine several global objects or sets into a group and to show them in Parallels H-Sphere CP interface in a suitable form.
Beside this, there is also one more auxiliary section special which is used to define Class Maintained Global Objects.
Elements and attributes:
section:
id: mnemonic identifier; mandatory attribute, the rest are non-mandatory
label: a key having correspondences in the language bundle files
description: a key, like the above one, for the text describing some peculiarities of
the section
online_help: a key having correspondence in the online_help.xml file. You may
choose which one of description or online_help is more suitable in each particular case.
show: by default is set to show always. If necessary, you may restrict this rule by
specifying one of the following values:
globals: to show in master admins globals menu
plans: to show in reseller plan wizards only
invisible: to exclude the section from standard page flow and show it
somewhere else on the page calling it by hand (e.g.: admin.getGlobalSection)
28 Unix Hosting Resources and Tools
store: by default, it is set to each what means storing the status values of all
objects in the section both into the settings table of the hsphere database and in the table plan_value for reseller plans. Normally, the attributes show and store should match to each other (have the similar values). Be careful with changing these attributes as it may lead to undesired results. For instance, if the
attribute store is set to settings, whereas the section objects are shown in reseller plan wizards, these values wont be stored in the plan_value table, so they wont affect separate reseller hosting systems. And one more case, if the attribute store is set by default to each”, but the globals from this section are prohibited to be shown on the page Globals (e.g. attribute show is set to plans), the respective values will be set to DISABLED in the settings table. So, all the object in the section will become Disabled.
Global object: an Parallels H-Sphere resource or a simple property that has a
mandatory attribute name (treat this as a property key). An example of the global object is cp_ssl_ip_based. By default, all global objects are Enabled unless you decide to change this by specifying the value explicitly (the attribute default).
default: if necessary, you may change it to disabled
name: mandatory attribute, the rest attributes are non-mandatory
label: the same as for section
label_enabled, label_disabled: replace the label attribute and are used to show the
object as radio button instead of checkbox
plan_dependent_resource: added to provide solution for disabling resources for
different plan types separately, frontpage for Unix and Windows platforms in particular
set of keys: the way to describe a group of entities where each of them contains a
unique key, description and status. An example of a set is Logical Server Groups. Each server group has a key which is group id, description and status. Due to significant difficulties to describe each global set in XML, the behavior of this type of globals is implemented by a Java class specified with the attribute class. The other attributes label and default are described above.
managed: this attribute shows if this global resource, being managed by admin, is
also manageable by reseller: managed=reseller”. In particular, this is implemented in dedicated server template (see Admin Guide) where resellers can set prices for templates provided by main hosting provider (admin). If managed is not set, it is considered to be globally by default (i.e., not manageable by resellers).
maintained_object: the class Maintained Global Objects belong to a special type of global
objects. Each object is maintained by a Java class specified in the attribute class in the xml. To get Maintained Global Objects working, all you need is to write a
maintainer class maintainer. This class should extend the standard class psoft.hsphere.global.ClassMaintainedGlobalObject. In your class you
either:
a override the method boolean isEnabled(), or
b override all the 3 methods: boolean isEnabled(Reseller r), boolean
isEnabled(int resellerPlanId), boolean isEnabled(ServletRequest rq), or
Unix Hosting Resources and Tools 29
c override all the methods: Globals.State getObjectState(Reseller r),
Globals.State getObjectState(int resellerPlanId) and Globals.State getObjectState(ServletRequest rq).
Doing (a) and (b), you can have only 2 possible statuses for the objects: ENABLED or UNAVAILABLE. The method (c) allows you to have any status you need (at least those ones defined in the class Globals.State). Please note that the Maintained Global Objects are neither shown on the Globals page in the CP interface nor they are shown in Reseller plans. Their states cannot be stored in the database either. Besides, none of the true Parallels H-Sphere resources can be made Maintained Global Object.
check_config: each of the objects/sets described above may require additional
checks whether it is configured to work properly in the ~cpanel/shiva/psoft_config/hsphere.properties file. To provide this, the additional structure is added:
<check_config> <property key=.../> <property key=.../>
....
</check_config>
Here, an object will be considered as configured if all of the specified properties are defined in the hsphere.properties file, no matter what values they have. You may strengthening this by specifying the desired values in the property elements (the attribute value). If necessary, you may also implement the OR logic in conditions by including the following structure::
<check_config> <!-- Variant 1 --> <variant> <property key=.../> <property key=.../>
....
</variant> <!-- Variant 2 --> <variant> <property key=.../> <property key=.../>
....
</variant> ... </check_config>
This means that an object has either Variant 1 of each of the specified properties set, or Variant 2 with its list of properties set, etc.
Note: The same scheme works for describing resource dependencies in
resource_dependences.xml (see description below). For example:
<resource name=hosting”> <variant> <requires name=domainrelation=parent/> </variant> <variant> <requires name=parked_domainrelation=parent/>
30 Unix Hosting Resources and Tools
</variant>
Dependent Resource
Parent Resource(s)
miva
empresa
oscommerce
MySQL
miva_lic_manager
miva
<variant> <requires name=3ldomainrelation=parent/> </variant> </resource>
Here, the hosting resource can be a child resource for either domain (Transferred Domain), or 3ldomain (Third-Level Domain), or parked_domain (Parked Domain) resources.

resource_dependences.xml

This file describes relationships between parent and dependent resources. Location: ~cpanel/shiva/psoft/hsphere/resource_dependences.xml
Example: http://hsphere.parallels.com/HSdocumentation/xmls/resource_dependences.xml
DTD scheme:
<!DOCTYPE dependences [ <!ELEMENT dependences (resource+)> <!ELEMENT resource (requires+ | variant+)> <!ELEMENT variant (requires+)> <!ELEMENT requires EMPTY>
<!ATTLIST resource name CDATA #REQUIRED> <!ATTLIST requires name CDATA #REQUIRED> <!ATTLIST requires relation (parent) #IMPLIED> ]>
As you can see, this is quite a simple structure, so it is very easy to write resource dependence rules. For example, to make vps_ip resource the available, is it required to enable the resource vps:
<resource name=cf_dsn_record”> <requires name=odbc/> <requires name=cf/> </resource>
Using the attribute relation you may specify that the required resource is a direct parent or ancestor for the current resource.

List of Resource Dependencies

Unix Hosting Resources and Tools 31
urchin_lic_manager
urchin
MySQLDatabase
MySQL
MySQLUser
MySQL
mysqldb_quota
MySQL
MSSQLLogin
MSSQL
MSSQLDatabase
MSSQL
MSSQLUser
MSSQL
MSSQLQuota
MSSQL
pgsqldatabase
pgsql
pgsqluser
pgsql
pgsqldb_quota
pgsql
real_user
realserver_user
real_server_traffic
realserver_user
winquota
realserver_user
cfentry
cf
mnogosearch
MySQL
phpbb
php, MySQL
asp_secured
asp
sshresource
sshmanager
vps_ip
vps
vps_mem_limit
vps
vps_proc_limit
vps
vps_ip_traffic
vps
kanoodlemanager
kanoodle
ds_custom_build
ds_enable
ds_manager
ds_enable
ds_reboot_enable
ds_enable
32 Unix Hosting Resources and Tools
ds_backup_enable
ds_enable
allow_ds_resell
ds_enable
allow_own_ds
ds_enable
ds
ds_enable
ds_bandwidth
ds
cf_dsn_record
odbc, cf
Unix Hosting Resources and Tools 33

Account Preferences

You can set individual interface preferences: preferred design (skin), icon set, or language - for a particular account.
This can be implemented within an Parallels H-Sphere template by using the following Freemarker commands:
1 Set account preferences:
<assign res = account.preferences(KEY, VALUE)>
2 Retrieve account preferences:
<assign property1 = account.preferences(KEY)>
Here:
KEY is the key of an interface preference to be assigned to an account (up to 64
chars),
VALUE is its value (up to 256 chars).
The following keys are available in Parallels H-Sphere (refer to the Skin And Icon Set Customization document in Parallels H-Sphere Customization Guide for detailed description of the ~cpanel/shiva/psoft/hsphere/design_config.xml file):
design_id - preferred design id (in design_config.xml);
icon_image_set - preferred icons image set (in design_config.xml);
skill_icon_set - preferred icons skill set (in design_config.xml);
lang - preferred language.
For example, to assign the XPressia design for an account:
<assign res = account.preferences(design_id, xcp)>

TimeUtils Class

The TimeUtils class is designed to subsitute all other Parallels H-Sphere classes dealing with time. This class is needed for testing any Parallels H-Sphere features that use time (like accounts, domain registration renewals, and the like).
From now on, please ALWAYS use the following TimeUtils wrappers instead of any other Date/Time functions:
System.currentTimeMillis() = TimeUtils.currentTimeMillis() new java.util.Date = TimeUtils.getDate() Calendar.getInstance() = TimeUtils.getCalendar() Thread.sleep(s) + TimeUtils.sleep(s)
Other utilities HIGHLY recommendable for usage:
34 Unix Hosting Resources and Tools
java.sql.Date getSQLDate() java.sql.Timestamp getSQLTimestamp() java.sql.Time getSQLTime() java.util.Time getTime()
Unix Hosting Resources and Tools 35

FreeMarker Access Control List (FMACL) Objects

FreeMarker Access Control List (FMACL) Objects provide an easy and effective way to manage Parallels H-Sphere resources and grant different levels of access to their methods from FreeMarker templates. This technology is especially useful for making changes in third-party products implemented as Parallels H-Sphere .hsp packages (for example, custom plans and reports) See Parallels H-Sphere Customization Guide for details on packages.

Purpose

Formerly, when we needed to handle the same functionality related to different objects (take domain registration as an example), we would split the code among these resources. For example, some of the methods would be in BillViewer, some in BillManager, CreateUser, HsphereToolbox, etc... This led to problems with changing the code - it had to be changed across a wide variety of classes. Also, due to that, the same code was often repeated.
Especially, it was hard for third parties to integrate such functionality to Parallels H­Sphere. In particular, to add a custom resource manager, the resource should be added and should be represented in all admin plans, which, in turn, required changes in the system database.
The idea comes from the fact that some functionality is not really a resource, but a set of facilities of common purpose (for example, report generation), accessed differently on different levels. This solution is implemented in FMACL objects.

Implementation

To provide access to required methods, the new FreeMarker obj tag is introduced. Now the methods will be accessible in FreeMarker templates as obj.key.method. For example, to call the getTLDPrice method of the psoft.hsphere.admin.DomainRegistration class from a template, we simply write:
obj.domreg.getTLDPrice()
Here, domreg is a key associated with psoft.hsphere.admin.DomainRegistration in the acl_objects.xml file.
Each object is instantiated via default constructor (without params) and must implement the FreeMarkers TemplateHashModel:
http://freemarker.sourceforge.net/docs/api/freemarker/template/TemplateHashModel.ht ml.
36 Unix Hosting Resources and Tools
Access permissions to class methods must be set in the corresponding .acl files for each class, located in the same directory and bearing the same name as the class files. For example, access permissions for the
psoft.hsphere.admin.DomainRegistration class must be set in the psoft/hsphere/admin/DomainRegistration.acl file.
FMACL Objects XML File
The objects are defined in ~cpanel/shiva/psoft/hsphere/acl_objects.xml in the following format:
<objects> <object key=reports class=psoft.hsphere.reports.ReportManager”> <object key=domreg class=psoft.hsphere.admin.DomainRegistration”> ... </objects>
Here, each unique key corresponds to an Parallels H-Sphere class. Each class defined here must have its .acl file in the same directory and with the same name. For example, for psoft.hsphere.admin.DomainRegistration there must be the psoft/hsphere/admin/DomainRegistration.acl file with access permissions for used methods of this class.
To re-define or customize (merge) the default acl_objects.xml file, set the
ACL_OBJECTS property in a package properties file. See Customizing XMLs With Packages in Parallels H-Sphere Customization Guide for details.
Setting Levels of Access to Class Methods
Access permissions to class methods are set in hsphere_class.acl files in the following lines:
key access_mask
where:
key is template hash model key;
access_mask is a combination of the following characters defining the level of
access:
a - Parallels H-Sphere admin
r - reseller admin
u - user
e - everyone, including access from the outside of Parallels H-Sphere.
Access mask specifies on which level a key is accessible (the level will be determined by checking the plan of a user logged in). If the key is not accessible, the system will throw TemplateModelException.
Example for setting access permission for domain registration (domreg):
Unix Hosting Resources and Tools 37
getTLDPrice aru setTLDPrice ar lookup e enableTLD a
This means that the getTLDPrice method will be accessible by admin, reseller admin and user, setTLDPrice by admin and reseller admin, lookup by everyone (even if user is not logged in), enableTLD only by admin.
The access will be provided by calling obj.domreg.lookup,
obj.domreg.geTLDPrice, etc., in Parallels H-Sphere templates (see Parallels H- Sphere Customization Guide).

External Credits

Parallels H-Sphere supports external credits, or external charges: charges exported from external billing systems.
External charges are stored in the external_credits table. The ecCron internal CP cron adds charges from external billing software to the external_credits table as the accounts credits.
To set the time interval when ecCron is launched, you need to add the following line to
~cpanel/shiva/psoft_config/hsphere.properties:
EX_CHARGE_CRON=5
In the above example, ecCron would start every 5 minutes.
The external_credits table is created during Parallels H-Sphere upgrade and has the following structure:
CREATE TABLE external_credits ( id int NOT NULL, account_id int4, amount float, created timestamp with time zone, description varchar(128), PRIMARY KEY(id) );
38 Unix Hosting Resources and Tools

Running Parallels H-Sphere in Debug Mode

To run Parallels H-Sphere in debug mode:
1 Compile classes with debug information:
./configure -javacwith-params=”-g” make shiva
2 Set the following option on in jserv.conf to be able to launch
JServ manually:
ApJServManual on
3 Create debug.sh shell script to run JServ in debug mode:
#!/bin/sh properties=/home/shiva/apache/etc/jserv.properties log=/home/shiva/apache/logs/jserv_manual.log CLASSPATH=$CLASSPATH:/usr/local/java/JSDK2.0/lib/jsdk.jar CLASSPATH=$CLASSPATH:/usr/local/apache/libexec/ApacheJServ.jar java -Xdebug ­Xrunjdwp:transport=dt_socket,address=9999,server=y,suspend=n \ org.apache.jserv.JServ $properties $1 2 >> $log # address=9999 - port to which the debugger may be attached # choose any available port you like
4 In IDE, set the following debug configuration:
Transport: Socket Debuger Mode: Attach Host: localhost Port: 9999
5 Start Apache and run debug.sh after Apache start. Set IDE
breakpoints and launch debug from IDE.
Unix Hosting Resources and Tools 39

Script Runner

Script-runner is a utility that launches Parallels H-Sphere scripts on Unix servers.
Parallels H-Sphere control panel establishes an SSH connection with a Unix box and runs script-runner:
ssh -a -x root@xxx.xxx.xxx.xxx /hsphere/shared/scripts/script-runner.pl
Further, the control panel sends commands to the output stream of the SSH session and script-runner reads and performs the commands and then outputs.
The format of command passed to script-runner is:
COMMAND=command_name&PARAM1=param1&..&PARAMN=paramn&INPUT=input\n
It starts with the keyword COMMAND followed by actual command. Then, if necessary, it‟s followed by the parameters that are numbered from 1 and further. All parts of the command are separated with the ampersand (&). The = symbol is followed by the value. The command ends with the line feed character.
If the command requires standard input, you should set the INPUT parameter. Commands are passed in the 8-bit ASCII encoding. Command parameters and standard input are passed in the URL-encoding. Version 1.8 contains script-runner-b64 utility that has the same functionality as script-runner, but data should be passed in the Base64 encoding and it returns the result in the same encoding.
Script-runner returns output in the following format:
OUTPUT=some_output&ERROR=text_of_error_or_empty_string&EXIT_CODE=0
If there is an error during script execution, parameter ERROR will contain the error text and output code EXIT_CODE will be non-zero. OUTPUT is a standard script output.
To check if script-runner is ready to accept commands, use the PING command. You should get the PONG output.
Script-runner logs all executed scripts and their output. They can be found in the /var/log/scriptrunner directory on the box where script-runner is running.
This section outlines certain development tasks for H-Sphere Winbox-related
In this chapter:
Creating Resources for Winbox ......................................................................... 41
Crash Reporting on Winbox .............................................................................. 52
IIS 6.0 Native Mode ........................................................................................... 53
C H A P T E R 4

Windows Hosting Resources

resources.
Windows Hosting Resources 41

Creating Resources for Winbox

Introduction

In terms of Parallels H-Sphere, any resource on a Windows server can be considered as a module (or a group of modules), and has to support the following functionalities:
create and delete a physical resource;
read and change parameters of the physical resource.
By physical resource we mean any resource of the OS (IP address, account, etc), or additional software used as a part of the hosting service. Different physical resources can have the same functionality in terms of hosting (even if they are implemented in completely different ways), like MS FTP Server. Even for the same software, different versions of the physical resource implementation can exist with different functionality. As a result, each Parallels H-Sphere resource can have several implementations, i.e., modules working with a particular implementation of a physical resource. Yet, only one implementation of a particular Parallels H-Sphere resource can be active at a time. To put it simply, we will be using a resource to describe its physical implementation.

Requirements

To implement a new resource, the following software is required:
.NET Framework version 1.0.3705 and higher
Parallels H-Sphere Windows package installed or Psoft.HSphere.dll
assembly available
You can use any .NET compatible language. Yet, since the core part of Parallels H­Sphere winbox is written in C#, all examples will be presented in C#.

Naming Conventions

We recommend using the following naming conventions when developing new resources.
Namespaces
All resources should belong to Psoft.Hsphere.Resources or to namespaces inside it. If there are several implementations of the same resource, they should be placed in the same namespace.
Assemblies
The name of the assembly should have the following format:
42 Windows Hosting Resources
Resources.<Resource class name> if assembly contains class of only one resource
and the resource is located directly in the namespace
Psoft.HSphere.Resources (e.g.: Resources.Diskquota for resource Psoft.HSphere.Resources.DiskQuota)
Resources.<Namespace Name> if assembly contains several resources in this
namespace. (e.g.: Resource.IIS.ColdFusion for the implementation of different versions of the ColdFusion resource)
Attributes
All names in attributes (logical name of the resource, physical name, parameter names in schemas) should be typed in lower case.

General Scheme of Resource Functioning

Each resource has a logical name known to the CP. If there are several implementations of the same resource, only one can be active at a time.
The implementation is defined in the config file. The implementation of the resources should be in separate non-core assemblies that will be loaded dynamically. The class that implements resource and its assembly is defined in the config file. Also, in the config file, the attributes of the resource are defined, and each instance of the resource will get those attributes in addition to parameters. Attributes should represent constant parameters for a given implementation that are common for all instances.
A resource (group of resources) has to be implemented as a public class (classes) inherited from the abstract class Psoft.HSphere.Resources.Resource that can be found in Psoft.HSphere.dll and is implemented as class library. To do that, you need to add references to Psoft.HSphere.dll during the compilation using option/reference.
Class Psoft.HSphere.Resources.Resource defines the set of methods that have to be implemented by the inherited resource:
public abstract void Create(); public abstract void Get(); public abstract void Update(Parameters newParams); public abstract void Delete(); public abstract void Suspend(); public abstract void Resume();
Windows Hosting Resources 43
The names of the methods describe their functionality (more details are below). Besides that, each resource inherits a collection of parameters from the abstract parent of the Psoft.HSphere.Transport.Protocols.Parameters type. That collection is represented as a hash table, and the values of parameters can be retrieved via the parameter names. When a particular operation is executed on the resource (like create, delete, update parameters... etc), Parallels H-Sphere Windows engine creates an instance of a corresponding resource and sets values for the parameters as they are passed from the CP. Besides that, the resource can have a collection of configurable attributes, which are defined in the Parallels H-Sphere config file. Parallels H-Sphere Windows engine adds attributes into the collection of parameters as well. After that, a corresponding method is called on the resource. Due to that, during a call of any of those methods, the instance of the resource has all the required information to perform the operation.
While developing a resource, you have to consider that the resource does not support statuses, and you should not save any type of info in the instance of the resource, as it can be destroyed as soon as a method is executed.

Methods

void Create()
This code should implement physical creation of the resource. Parameters required to create the resource will be passed as parameters collection. The number and names of parameters are defined by specifics of physical resource and set in special attributes­schemas (defined later in this document).
void Get()
This method should implement the code to retrieve parameters of a physical resource. Retrieved values should be written into a collection of parameters. If such functionality is not required for the resource, it can be implemented as an empty method:
void Get() {}
void Update(Parameters newParams)
This method should implement a way to change all or some parameters of a physical resource. The method accepts a collection of parameters that need to be changed. During the implementation of this method, you dont have to update the collection resource parameters (this will be done by Parallels H-Sphere Windows engine if the code is completed successfully). It is enough to update parameters of the physical resource.
If the given functionality is not required for the resource, it can be implemented as an empty method:
void Update(Parameters newParams) {}
void Delete()
This method should implement the deletion of the physical resource. If the given functionality is not required for the resource, it can be implemented as an empty method:
44 Windows Hosting Resources
void Delete() {}
void Suspend()
This method should implement the suspension of the physical resource. If the given functionality is not required for the resource, it can be implemented as an empty method:
void Suspend() {}
void Resume()
This method should resume the physical resource. If the given functionality is not required for the resource, it can be implemented as an empty method:
void Resume() {}

Keys

Parallels H-Sphere Windows engine and resource classes deal with resource keys.
There are two types of keys, logical and physical. Logical key can be defined as a parameter which differentiates instance of the resource from the set of other instances for the resource user (i.e. CP). To operate with particular instance of the resource, in addition to all other parameters added to its methods, you need to pass the parameter that will uniquely identify the resource. Physical key is very much like a logical key, with the only difference that resource user (i.e. CP) knows nothing about it (there is no unique identifier). Sometimes physical resources require keys to operate with them, which makes sense only in the context of the given physical key. It can be exemplified by numeric IDs of virtual Web or FTP hosts (unique numerical identifiers) in the IIS metabase, that are required to operate with a given host on the level of metabase.
On the other hand, for virtual Web host uniqueness can be implemented by means of domain name, and for virtual FTP host by means of IP. In that case domain name is a logical key for the resource that implements virtual web host. A number in the metabase - its resources physical key. At the same moment Parallels H-Sphere Windows engine provides mechanisms for the translation of virtual key into physical key. In most cases, logical key can coincide with physical key.
As mentioned above, a resource has two types of parameters that eventually are stored in common collection of parameters - configuration (common to all instances) and instance (different for each particular instance of the resource). Instance parameters are passed during the method call and should contain logical key for the given resource.
Each key is implemented via subclass of abstract class Psoft.HSphere.Resources.Key. This class defines the following set of methods to be overloaded:
public abstract object Val { get; set; } public abstract int Compare(object objVal); public abstract Key Add(object objVal); public abstract Key Sub(object objVal); public abstract Key Inc();
Windows Hosting Resources 45
public abstract Key Dec();
Those methods define basic operations for manipulating and comparing keys. In most cases, you dont need to create a new key class, as you can use two already existing classes: Psoft.HSphere.Resources.NumKey and Psoft.HSphere.Resources.StrKey, that correspondingly implement numeric and string keys.
Class Resource has two attributes, Pkey and Lkey, to represent physical and logical keys for the instance of the resource:
public Key PKey { get; set; } public Key LKey { get; }
LKey is read-only, as the value of the logical key is automatically retrieved from the
parameter collection.

Error Handling

All the classes implementing exceptions that are connected with resources have to be inherited from the class Psoft.HSphere.Resources.ResourceException. There are several types of error conditions that should be indicated when manipulating with resources:
an attempt to create resource that already exists
This error type can appear only in the method Create(). For that type, there is the class Psoft.HSphere.Resources.ResourceAlreadyExistsException inherited from ResourceException. During the implementation of the Create() method, you have to make sure that given exception is thrown in the situation when
the physical resource exists and from the point of view of the resources logic it is considered as an error. (For some resources, given condition may not be an error, for example, an error that appears while adding an IP that has been already set up before can be safely ignored).
an attempt to do an operation on the resource that doesnt exist
The second type of error conditions can appear in any method, but Create(). That type of errors is described by the class Psoft.HSphere.Resources.ResourceNotFoundException. During the implementation of such methods, you have to make sure that those conditions are taken care of, and that the exception is thrown.
an error in the data passed as parameters.
The third type of conditions is described by the class Psoft.HSphere.Resources.ResourceInvalidParameterException. That type is used to describe situations when the problem is created by incorrect data entered by end user - to allow end user to fix them.
Class Resource has got a set of methods to generate exceptions of these types:
protected void ErrorNotFound() protected void ErrorNotFound(string message) protected void ErrorAlreadyExists() protected void ErrorAlreadyExists(string message) protected void ErrorInvalidParameter(string pName)
46 Windows Hosting Resources

Resource Hierarchy

According to the Parallels H-Sphere logic, each resource belongs to a hierarchy of resources. This hierarchy shows dependence of one resource on another. For example, to create the virtual Web host resource, it is required to specify an account name that will be the owner of that virtual host. It means that virtual host resource depends on resource account, and stands below it in the hierarchy of resources.
During the development of resource class, you can specify the place of the resource in the hierarchy using a special attribute. Even though the configuration of resource attributes is located in the config file, each resource has access to only its own set of attributes. Yet, it also inherits configuration parameters of its parent resource (in the hierarchy). Therefore, resource gets configuration parameters of all its parents in parameters collection.
This resources quality does not depend on the instance of the resource, such as configuration parameters are common for all instances of the resource.
There is another aspect of using resource hierarchy. The child resource can access parent resource to retrieve parent resources instance parameters. Each resource has instance parameter which is its logical key. That parameter uniquely identifies the instance of this resource. We can connect child resource with parent resource by means of parameter from the instance parameters set, that has the same name as key parameter. In such child resource we have access to instance of parent resource, using the Parent attribute inherited from Resource:
public Resource Parent { get; }
Accordingly, by means of the Pkey attribute, physical key of the parent resource instance can access the collection of parameters via the Params property:
public Parameters Params {get; set;}

Logging

Each resource inherits the method Log that can be used for logging. The log output will be placed in the common log file resource.log. The method has the following signature:
protected void Log(string format, params object[] args)

Resource Types

Windows Hosting Resources 47
Resources can be of two types: those that support listing and those that dont support listing. In the case of listable resource, Parallels H-Sphere Windows engine will load all instances of the resource into cache. Cache will be used to consequently retrieve instances of the given resource. Listable resources do two important things: the information is cached that allows to optimize the method Get(), and such resources support automatic generation of new physical keys during creation of resource. If resource has to support physical keys and it requires their automatic management, resource has to be listable. To notify that resource is listable, you have to overload a static method:
ArrayList Enum(Key parPKey, Parameters configParams, ResourceLogger log)
This method has to return list of physical keys for existing instances of resource. As parameters, the value of physical key of corresponding parent resource is passed (if there is no parent resource, or if parent resource doesnt support physical keys, the parameter can be ignored), configuration resource parameters and log object.
Resources that dont support physical keys can be listable as well.
The method Enum has to return list of logical keys, as they are also physical keys for those resources.
Listable resources support automatic access synchronization to their instances. They also provide additional level of checking the existing resource during creation, and missing resource check during other operations using cache. They will automatically generate ResourceAlreadyExistsException or ResourceNotFoundException exceptions.

Schemas

Schemas are used not only in resources, but we will discuss them only in the context of Resource. Schemas are descriptions of attributes of a particular object. Schemas are implemented by class Psoft.HSPhere.Configuraiton.Schema. Constructor of the given class accepts XML string as a parameter. That XML string describes the given schema. XML schemas consist of the following elements: schema tag, properties tag (prop), attributes of properties. Schema tag contains a prop tag which can have attribute tags. The prop tag has the following attributes:
name: required attribute, it defines name of the property
description: contains short description of the property
type: contains identifier of the property type. The following identifiers are supported:
str: string (default)
num: numeric
unum: non-signed numeric
bool: boolean
select: list (will be described bellow)
path: file system path
password: password
48 Windows Hosting Resources
ip: IP address
domain: domain name
url: URL
mail: mailbox name
mask: IP mask
mac: MAC address
value: default value of the property
key: false by default. If false, it is not the key property. If true, property is a key
property.
Optional: false by default. If false the property is optional, otherwise it is required.
readonly: false by default. If false, the property can be changed (can be passed as
the parameter), if true, the property is read-only.
If parameter has the type select, this tag has to contain list of tags that describe values of the list. Values by default are set to be equal to the name of the value.
There are two types of schemas for resources:
schemas that describe configuration parameters,
schemas that describe instance parameters.
A resource doesnt have to have a configuration parameters schema (for example, if it doesnt have config parameters), but schema of instantace parameters must always be defined.
Based on that schema, the input is validated on the presence of key and required parameters. The default values are also set at that stage for missing parameters. If the parameter is described in both config and instance schemas, then if parameter wasnt passed (it is possible, if it was described as optional), the value for it will be taken from the config file, otherwise, the input value has higher priority and is used as the parameter. Examples of schemas are represented below in the chapter Attributes.

Attributes

Resource has a list of attributes, some of them are required. Attributes define properties of the resource and define its behavior.
ResourceName
Required attribute that specifies logical name of the resource. It will be passed as the name to invoke that resource by the CP.
Example: [ResourceName(hosting)]
PhysicalName
Required attribute that contains implementation name of the given logical resource. Example: [PhysicalName(iis5_website)]
LKey
Windows Hosting Resources 49
Required attribute that defines logical key for the resource, or, more specifically, the name of the key parameter of the implementing class. Example: [LKey(hostname, typeof(StrKey))]
ResourceDescription
Optional attribute that contains short description of the resource. Example: [ResourceDescription(IIS 5.0 virtual web host)] Even though this attribute is not required, we highly recommend using it.
ParentName
Optional attribute that contains logical name of the parent resource. Example: [ParentName(account)]
This attribute defines the place of the resource in the resource hierarchy. If it is not defined, the resource is considered to be root in the hierarchy.
ManagedPKey
Optional attribute. Shows if physical keys will be automatically managed. Example: [ManagedPKey]
If the attribute is not defined, the resource has to generate unique physical keys. If the resource doesnt support physical keys, this attribute is meaningless.
ResourceSchema
Optional attribute. Describes the configuration schema and input parameters of the resource.
Example:
[ResourceSchema( @<schema> <prop name=hostnametype=domaindescription=Virtual web host name/> <prop name=iptype=ipdescription=Virtual web host IP/> <prop name=porttype=unumvalue=80description=Virtual web host port/> <prop name=usernamedescription=Owner account of virtual web host/> <prop name=docrootoptional=truedescription=Document root of virtual web host/> <prop name=docrootpathreadonly=truedescription=Document root directory full path/> <prop name=statustype=selectvalue=starting description=Status of virtual web host‟> <prop name=startingvalue=‟1‟ description=Starting virtual web host/> <prop name=stoppingvalue=‟3‟ description=Stopping virtual web host/> <prop name=pausingvalue=‟5‟ description=Pausing virtual web host/> <prop name=continuingvalue=‟7‟ description=Continuing virtual web host/> </prop>
50 Windows Hosting Resources
<prop name=indextype=boolvalue=false description=Indexing flag/> <prop name=idomianoptional=truetype=domain description=Instant alias of virtual web host/> <prop name=dedicatediptype=boolvalue=false description=true if IP property is dedicated IP/> <prop name=ss_lidoptional=‟truedescription=Site Studio lid/> <prop name=appleveltype=selectoptional=true description=Web applications isolating level‟> <prop name=inprocvalue=‟0‟ description=Inproc application/> <prop name=outprocvalue=‟1‟ description=Outproc application/> <prop name=pooledvalue=‟2‟ description=Pooled application/> </prop> </schema>”, @<schema> <prop name=logsdirtype=pathdescription=Log files directory/> <prop name=suspendskeletontype=path value=‟\skeleton\suspenddescription=Suspned skeleton location/> <prop name=inheritdefaultdocstype=boolvalue=false description=Direct to inherit default documents from default web properties/> <prop name=removecontentvalue=falsetype=bool description=Force to remove all content from deleted website/> <prop name=enableparentpathvalue=truetype=bool description=If true using of absolute pathes (such as \somedir\somescript.asp) in the ASP scripts will be enabled/> <prop name=defaultdocsvalue=default.htm, default.asp, default.html, index.html, index.htm, default.stm, index.stm, default.shtml, index.shtml, default.shtm, index.shtm, default.aspx, index.aspx description=List of default documents/> <prop name=appleveltype=selectvalue=pooled description=Web applications isolating level‟> <prop name=inprocvalue=‟0‟ description=Inproc application/> <prop name=outprocvalue=‟1‟ description=Outproc application/> <prop name=pooledvalue=‟2‟ description=Pooled application/> </prop> </schema> )]
This attribute has two constructors. The first constructor accepts both schemas as shown in the example. The second constructor is used for resources that dont have configuration parameters and have only one schema.
Windows Hosting Resources 51
Exclusive
Optional attribute. Specifies if synchronization should be used to access different instances of the resource.
Example: [Exclusive]
If the attribute is not defined, synchronization will not be performed. If the resource is listable, the attribute is ignored, because listable resources automatically support synchronization.
Offline
Optional attribute. Shows that all the operation on the resource has to be performed offline.
Example: [Offline]
Currently not implemented.
IgnoreExists
Optional Attribute. Affects the behaviour when theres an attempt to create an already existing resource.
Example: [IgnoreExists] If the attribute is set, the already existing condition is not considered to be an error.
Cacheable
Optional attribute. Affects the cache behaviour during data access from cache for listable resources.
Example: [Cacheable(false)]
The default is true. If set to false, the data will not be caught. This can be useful for resources with read-only parameters, such as usage for disk quota. For non-listable parameters, this attribute is ignored.
CaseSensitive
Optional. Defines if logical keys are case sensitive.
Example: [CaseSensitive]
False by default.
52 Windows Hosting Resources

Crash Reporting on Winbox

Parallels H-Sphere Winbox writes unhandled exceptions to files iis.log and hssvc.log that are located in the <Parallels H-Sphere dir>\logs\crash
directory. The messages written to these logs arent very informative and are barely helpful in debugging unless you install the pdb package that complements error logs with detailed debug information. To install the pdb package, see how to update Winbox to the latest stable version. The pdb package can send crash reports to Positive Software support - the installer will prompt you for the SMTP server.

Crash Record File Structure

Each crash record file is of the following structure:
the first line contains a crash date and crash description;
the rest of the lines contain a crash stack.
Example:
[26.07.2004 / 16:36:33] Thread: 27904; Access violation occurred in module inetinfo (image ) at RtlAllocateHeap() in :line 0 (in module ntdll) at () in :line 0 (in module htaccess) at () in :line 0 (in module htaccess) at () in :line 0 (in module htaccess) at ?BuildURLMovedResponse@HTTP_REQ_BASE@@QAEHPAVBUFFER@@PAVSTR@@KH@Z() in :line 0 (in module w3svc) at ?BuildURLMovedResponse@HTTP_REQ_BASE@@QAEHPAVBUFFER@@PAVSTR@@KH@Z() in :line 0 (in module w3svc) at ?ResetSSLInfo@W3_SERVER_INSTANCE@@SGXPAX@Z() in :line 0 (in module w3svc) at ?Disconnect@CLIENT_CONN@@QAEXPAVHTTP_REQ_BASE@@KKHPAH@Z() in :line 0 (in module w3svc) at ?ScanForTerminator@@YGPAEPBD@Z() in :line 0 (in module w3svc) at ?Copy@STR@@QAEHPBDK@Z() in :line 0 (in module w3svc) at ?RemoveEntry@CDirMonitor@@QAE?AW4LK_RETCODE@@PAVCDirMonitorEntry@@@Z() in :line 0 (in module ISATQ) at () in :line 0 (in module )
Each crash stack line may contain:
information about the function being executed when the crash occurred;
source information, such as a source files name and lines number
Note: to record Parallels H-Sphere modules source information the pdb package is required (see the Parallels H-Sphere Winbox update instructions for details).
module name containing crashed function
Windows Hosting Resources 53

Detecting Crashes in Parallels H-Sphere and non Parallels H-Sphere Modules

The name of the module in the crash stack line indicates which module the crash occurred in. The example above (in module htaccess) indicates that the crash occurred in Parallels H- Sphere module. An empty module files name, for example (in module) indicates that the crash occurred in the main module.
When a crash occurs in any module, the crash report framework generates an exception containing information about the crash. A crash in Parallels H-Sphere module will trigger the exception and a record with Parallels H- Sphere module name will be written to the report file, for example (in module htaccess). As non Parallels H-Sphere modules cant catch the exception generated by the crash report framework, it will return back to crash report as C++ exception and will be registered in the crash report file immediately after the initial crash record. In this case two records will be written into the report file: the initial crash record and the C++ exception record as shown in the following example:
[26.07.2004 / 16:36:33] Thread: 3432; Access violation occured in module w3wp (image ) at () in :line 0 (in module )
[26.07.2004 / 16:36:33] Thread: 3432; C++ exception occured in module w3wp (image ) at RaiseException() in :line 0 (in module kernel32) at () in :line 0 (in module htaccess) at () in :line 0 (in module htaccess) at UnhandledExceptionFilter() in :line 0 (in module kernel32) at FlsSetValue() in :line 0 (in module kernel32)
Two records with the same crash date, time and crash description indicate that the crash occurred in a non Parallels H-Sphere module.
Note: the time for the second record can differ by several seconds.

IIS 6.0 Native Mode

Parallels H-Sphere is compatible with IIS 6.0 native mode. Parallels H-Sphere automatically switches IIS 6.0 to native mode during the installation or update procedure. After this, you need to restart IIS to apply changes.
In addition, Parallels H-Sphere switches the identity of all existing application pools to a Local System account instead of the default Network service account. It doesnt manage application pools at this time, so if a new application pool is created, its identity should be manually set to Local System account.
There are several ISAPI filters and IIS log plugins that are part of Parallels H-Sphere which are implemented in the modules described below.
54 Windows Hosting Resources

ISAPI Filters

Since IIS 6.0 in native mode has quite different architecture regarding the ISAPI filters and log plugins, these modules were rewritten to accomplish compatibility with IIS 6.0 native mode simultaneously with IIS 5.0 support.
HsAuth.dll - ISAPI filter intended to realize several of web authentication schemes
such as web authentication for virtual accounts (for Serv-U users), web authentication for FrontPage and cookie authentication.
Parallels H-Sphere uses a user account as an anonymous account for the user domain instead of the standard built-in IUSR account to avoid unapproved content changes. For SERV-U FTP, FrontPage reads the anonymous account settings for the virtual host and treats this account as an account which has the anonymous access to FrontPage. Therefore Parallels H-Sphere sets the Basic authentication to the FrontPage virtual directories and installs the HSauth filter to authenticate the user when he connects via FrontPage client.
HtAccess.dll - ISAPI filter intended to realize folder protect feature for WebShell 4.0.
Parallels H-Sphere does not support ISAPI_Rewrite filter because it processes the URL and then changes it. But in the current security model of HTProtect work such operation is not allowed . So ISAPI_Rewrite and HTAccess filters conflict with each other when both are running in IIS.
SharedSSL.dll - ISAPI filter intended to realize Shared SSL functionality.
To process https requests, we created service virtual hosts for each IP where shared SSL service is used, including dedicated IPs. A service virtual host home dir contains virtual directories for websites that have shared SSL enabled. Such a virtual directory bears the name of the third level domain alias and points to the document root of the corresponding website. ISAPI shared SSL filter, which is installed on every service virtual host, redirects https requests to the appropriate virtual directory.

IIS Log Plugin

Now due to changes in Parallels H-Sphere log plugins, even currently modified HTTP log files can be opened for writing or removed.
HsLogPlugin.dll - module which contains several IIS log plugin intended to realize stats collecting on the fly, different schemes of web and ftp logging such as simple web logging, transfer log, etc.
Parallels H-Sphere XML API, written in Java, is designed to manage Parallels H-
C H A P T E R 5

Parallels H-Sphere XML API

Sphere services from remote applications via SOAP. It uses the Apache Axis implementation of SOAP and runs under the Apache Tomcat engine.
Remote applications interact with CP services by means of XML-formatted requests transferred via HTTP (direct TCP connection can also be set up). Error messages are also processed in XML.
XML schema is based on the SOAP RPC convention: http://www.w3.org/TR/soap12/.

Mechanism of Interaction

XML API provides the following mechanism of communication between remote applications and the Control Panel:
A remote Java application calls CP methods to perform particular actions (for
example, to create an account or to return the list of domains). For this, it invokes its SOAP client to form the corresponding XML request and to http it to the Control Panel;
the CP SOAP server receives this XML request, parses the request> and calls a
target Parallels H-Sphere service;
the target Parallels H-Sphere service performs actions according to the received
request (for example, creates an account or returns the list of domains), and responds via the SOAP server to the remote application. If the request is incorrect, the SOAP server returns XML with SOAP fault.
Therefore, though HTTP is used for data transfer, Parallels H-Sphere XML API services are not called from a Web browser!
Where To Get Parallels H-Sphere XML API
For Java, you may download Parallels H-Sphere XML API from the following location:
Axis libraries: http://hsphere.parallels.com/shiv/HS/xml-api/Libraries.tgz
Parallels H-Sphere Java XML API library: http://hsphere.parallels.com/shiv/HS/xml-
api/hsphereXMLApi.jar
Sample Java classes for testing Parallels H-Sphere XML API functionality:
http://hsphere.parallels.com/shiv/HS/xml-api/AxisExamples.tgz
For other programming languages (for Java as well), you can use WSDL file to implement Parallels H-Sphere XML API services in this language. See how to generate WSDL via Axis (on page 57).
56 Parallels H-Sphere XML API
Here you may find a sample Parallels H-Sphere signup form written in PHP 5 (which
In this chapter:
Enabling Parallels H-Sphere XML API ............................................................... 57
Testing Parallels H-Sphere XML API ................................................................. 57
Getting the List of Available XML API Services ................................................. 59
Generating WSDL Files for Parallels H-Sphere XML API Services .................... 60
Parallels H-Sphere XML API Security Settings and Authentication .................... 60
has an embedded SOAP client) using Parallels H-Sphere XML API:
http://hsphere.parallels.com/HSdocumentation/xmls/xml­api/hs_xml_api_signup_example.tgz.
Services
Actions supported by XML API are grouped by services:
Admin Services - basic admin services: adding new accounts, etc.
User Services - basic user services: getting account information
Domain Services - creating/deleting domains and subdomains
Web Services - managing Web options
FTP Services - managing FTP options
User FTP Services - managing user FTP resources: subusers, passwors, etc.
DNS Services - managing DNS
Mail Services - creating/deleting mailboxes, mailing lists, autoresponders, mail
forwards, etc.
MySQL Services - managing MySQL databases and users
PostgreSQL Services - managing PostgreSQL databases and users
MSSQL Services - managing MSSQL databases and users
Support Services - managing trouble tickets (Parallels H-Sphere support center)
Migration Services - migrating users and resellers by means of corresponding XML
forms
PGP Services - PGP encryption/decryption in Parallels H-Sphere trouble tickets
See the XML API services documentation generated by the Javadoc tool:
http://hsphere.parallels.com/HSdocumentation/xmls/xml-api/.
Note: When generating AuthToken for reseller, in addition to defining resellers accountID, login and password, set also login in the Role to “” (empty) and account id in the Role to 0.
Parallels H-Sphere XML API 57

Enabling Parallels H-Sphere XML API

Parallels H-Sphere XML API is designed to manage Parallels H-Sphere services via SOAP protocol. It is based on Apache Axis implementation of SOAP (http://ws.apache.org/axis/index.html) and runs under Apache Tomcat engine.
You can download (on page 55) Axis libraries and the latest version of XML API libraries.
Warning: Parallels H-Sphere XML API is an experimental feature. Please be careful in using it for critical tasks!
To enable XML API in Parallels H-Sphere:
1 Log into the CP server as the cpanel user (on page 67).
2 Edit the
~cpanel/shiva/psoft_config/allow_access.properties file to grant access to CP server via SOAP port from external IPs (on page 60).
3 Copy the wsdd config file:
cp ~cpanel/shiva/psoft/hsphere/axis/server-config.wsdd ~cpanel/hsphere/WEB-INF/
Skip this step if the file is already in the target location.
4 Edit the Tomcat XML configuration file:
vi ~cpanel/jakarta/conf/server.xml
Find the following commented fragment:
<!--Connector port=8080maxThreads=150 minSpareThreads=25maxSpareThreads=75 enableLookups=falseredirectPort=8443acceptCount=100 debug=”0” connectionTimeout=20000 disableUploadTimeout=true” /-->
and replace it with the following code:
<Connector port=8180maxThreads=150minSpareThreads=25 maxSpareThreads=75enableLookups=falseacceptCount=100 debug=”0” connectionTimeout=20000 disableUploadTimeout=true/>
Optionally, leave the port at 8080.
5 Restart Parallels H-Sphere (on page 67).
After that, XML API will be available. You may wish to test if it works correctly by means of our test Java classes that use Parallels H-Sphere XML API:
http://hsphere.parallels.com/shiv/HS/xml-api/AxisExamples.tgz.

Testing Parallels H-Sphere XML API

58 Parallels H-Sphere XML API
1 Make sure you are logged into the CP server as the cpanel user.
2 Download (on page 55) the latest version of test Java classes to the
~cpanel/shiva/psoft/hsphere/axis/test directory (create it first if it does not exist):
cd ~cpanel/shiva/psoft/hsphere/axis/test/ wget http://hsphere.parallels.com/shiv/HS/xml­api/AxisExamples.tgz
3 Extract the archive with the command:
tar zxf AxisExamples.tgz
Java source .java files will be added into the current ~cpanel/shiva/psoft/hsphere/axis/test/ directory.
4 Edit the necessary test classes (at least
AdminServicesTest.java) replacing URL in the folowing line:
String endpoint = http://localhost:8080/psoft/servlet/AdminServices.jws;
with your URL:
String endpoint = http://your_cp_host:8180/your_cp_url_path/AdminServices.jws;
where your_cp_url_path is by default psoft/servlet but you may change it in your Tomcat configuration on the CP server.
If you have enabled XML API (on page 57) with port 8180, make sure it is specified in the URL.
Note: Dont forget to include XML API libraries into your Java classpath:
http://hsphere.parallels.com/shiv/HS/xml-api/hsphereXMLApi.jar
5 Compile Java classes:
cd ~cpanel/shiva/psoft/hsphere/axis/test/ javac *.java
6 Upon the successful compilation, run the following command:
java psoft.hsphere.axis.test.AdminServicesTest admin <hs_admin_password>
You will see the > prompt. Here, enter the line:
searchbydomainname domain-name
where domain-name is a customers domain name.
7 On the next > invitation, press ENTER to force the service to run.
8 Repeat the previous two steps while testing other services, for
instance, getAccounts, getDomains, searchbydomainname, etc:
[cpanel@exampleuser test]$ java psoft.hsphere.axis.test.AdminServicesTest admin admin >getAccounts example.com >Params:1:example.com 1 >getDomains example.com >Params:1:example.com
Parallels H-Sphere XML API 59
Please refer to Parallels H-Sphere XML API Reference (on page 55) to learn how to invoke other Web services via XML interface.
9 Press CTRL-D to stop.

Getting the List of Available XML API Services

You can get the list of available XML services by typing in your browser:
http://your_cp_host:8180/your_cp_url_path/AxisServlet
where:
your_cp_host is your CP host domain (CP_HOST in hsphere.properties)
your_cp_url_path is usually psoft/servlet if not configured otherwise in your CP
servers Tomcat configuration.
If this doesnt work, check servlet mapping in your Tomcat configuration:
1 Log into the CP server as the cpanel user (on page 67).
2 Open the ~cpanel/hsphere/WEB-INF/web.xml file for edition.
3 Make sure the following lines are present in the file:
<servlet> <servlet-name>AxisServlet</servlet-name> <display-name>Apache-Axis Servlet</display-name> <servlet-class> org.apache.axis.transport.http.AxisServlet </servlet-class> </servlet>
4 Find the following mapping block:
<servlet-mapping> <servlet-name>AxisServlet</servlet-name> <url-pattern>*.jws</url-pattern> </servlet-mapping>
and add the following lines right underneath:
<servlet-mapping> <servlet-name>AxisServlet</servlet-name> <url-pattern>/AxisServlet</url-pattern> </servlet-mapping>
5 Restart Parallels H-Sphere (on page 67).
6 Try again this URL in your browser:
http://your_cp_host:8180/your_cp_url_path/AxisServlet
7 You may also wish to test AxisTestServlet from the package of test
Java classes: http://your_cp_host:8180/your_cp_url_path/AxisTestServlet
60 Parallels H-Sphere XML API
Generating WSDL Files for Parallels H­Sphere XML API Services
You can generate WSDL files for Parallels H-Sphere XML API services by means of the Axis org.apache.axis.wsdl.Java2WSDL utility.
For example, to generate a WSDL file for SupportServices, log into CP server as cpanel (on page 67) and run:
java org.apache.axis.wsdl.Java2WSDL -o SupportService.wsdl ­lhttp://localhost:8080/psoft/servlet/AxisServlet psoft.hsphere.axis.SupportServices
Example: Parallels H-Sphere XML API signup form implementation in PHP 5 (SOAP client embedded) via WSDL: http://hsphere.parallels.com/HSdocumentation/xmls/xml-
api/hs_xml_api_signup_example.tgz.

Parallels H-Sphere XML API Security Settings and Authentication

In order to tighten Parallels H-Sphere XML API security, the
psoft.hsphere.axis.AxisAccessFilter class is created, implementing the javax.servlet.Filter interface. This filter allows to check incoming request to a
certain servlet to match some condition BEFORE passing it to the servlet, and allows to wrap/change request/response.
When the filter is turned on, the following lines are added into the <web-app> tag in the ~cpanel/hsphere/WEB-INF/web.xml file:
<filter> <filter-name>axis_access_filter</filter-name> <filter-class>psoft.hsphere.axis.AxisAccessFilter</filter­class> </filter> <filter-mapping> <filter-name>axis_access_filter</filter-name> <servlet-name>AxisServletName</servlet-name> </filter-mapping>
where AxisServletName is Axis servlet name (usually, AxisServlet) and axis_access_filter is the filters name.

Granting SOAP Access from Remote IPs

Parallels H-Sphere XML API 61
AxisAccessFilter checks if remote IP address of incoming request is specified in the ~cpanel/shiva/psoft_config/allow_access.properties file. If this IP is in the file, the request will be passed to Axis servlet. Otherwise the response will return the 403 error.
If the file does not exist, SOAP access is blocked for all IPs.
allow_access.properties has the following format:
To set the list of IPs (semicolon-separated):
ACCESS_ALLOW = ip1;ip2;ip3;...
To grant SOAP access from all IPs:
ACCESS_ALLOW = ALL

Making XML API calls, which request data from other user’s account.

If you are an H-Sphere admin, you may wish to request data from other user's account. To do that, you should specify your own auth token to be authenticated by XML API, and specify a login of the user in at/role/login node.
For example, here is a proper way of making a getTraffic call for user unixuser:
<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema­instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:axis="http://axis.hsphere.psoft"> <soapenv:Header/> <soapenv:Body> <axis:getTraffic soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encodin g/"> <at xsi:type="urn:AuthToken" xmlns:urn="urn:AdminServices"> <accountId xsi:nil="true" /> <login xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">admi n</login> <password xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">xxxx xxx</password> <role xsi:type="urn:Role"> <login xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">unix user</login> </role> </at> <accountId xsi:type="xsd:long">1028</accountId> </axis:getTraffic> </soapenv:Body> </soapenv:Envelope>
62 Parallels H-Sphere XML API
Response:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soapenv:Body> <ns1:getTrafficResponse soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encodin g/" xmlns:ns1="http://axis.hsphere.psoft"> <getTrafficReturn href="#id0"/> </ns1:getTrafficResponse> <multiRef id="id0" soapenc:root="0" soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encodin g/" xsi:type="xsd:double" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">500. 0</multiRef> </soapenv:Body> </soapenv:Envelope>
This chapter dwells on developer tools for adding new payment gateways and domain
In this chapter:
Web Payment SDK ........................................................................................... 64
Domain Registrar SDK ...................................................................................... 64
Merchant Gateway SDK .................................................................................... 64
C H A P T E R 6

Adding Custom Payment Gateways and Domain Registrars

registration services into H-Sphere.
64 Adding Custom Payment Gateways and Domain Registrars

Web Payment SDK

Parallels H-Sphere Web Payment SDK is a development tool to integrate Web payment systems as installable Parallels H-Sphere packages (.hsp). The SDK allows developing and testing Web payment packages outside Parallels H-Sphere.
To use Web payment SDK, make sure you have the following software installed:
Java 1.3 or higher: http://java.sun.com/
Apache Ant 1.5 or higher - a Java-based build tool: http://ant.apache.org/
JUnit - a framework to write repeatable tests: http://junit.sourceforge.net/
Download Latest Web Payment SDK:
http://hsphere.parallels.com/HSdocumentation/sdk/webpayment-sdk/webpayment-sdk-
1.0-29.zip
Online Documentation:
http://hsphere.parallels.com/HSdocumentation/sdk/webpayment-sdk/docs/
Read about .hsp package installation in Parallels H-Sphere Customization Guide.

Domain Registrar SDK

Parallels H-Sphere Registrar SDK is a toolkit to integrate domain registration services (domain registrars) as installable Parallels H-Sphere packages (.hsp). The SDK allows developing and testing gateway packages outside Parallels H-Sphere.
To use Registrar SDK, make sure you have the following software installed:
Java 1.3 or higher: http://java.sun.com/
Apache Ant 1.6 or higher - a Java-based build tool: http://ant.apache.org/
JUnit - a framework to write repeatable tests: http://junit.sourceforge.net/
Download Latest Registrar SDK:
http://hsphere.parallels.com/HSdocumentation/sdk/registrar-sdk/registrar-sdk-1.2-40.zip
Online Documentation: http://hsphere.parallels.com/HSdocumentation/sdk/registrar-
sdk/docs/
Read about .hsp packages in Parallels H-Sphere Customization Guide.

Merchant Gateway SDK

Adding Custom Payment Gateways and Domain Registrars 65
Parallels H-Sphere Merchant Gateway SDK is a development tool to integrate merchant gateways as installable Parallels H-Sphere packages (.hsp). The SDK allows developing and testing gateway packages outside Parallels H-Sphere.
To use Merchant Gateway SDK, make sure you have the following software installed:
Java 1.3 or higher: http://java.sun.com/
Apache Ant 1.6.1 or higher - a Java-based build tool: http://ant.apache.org/
JUnit - a framework to write repeatable tests: http://junit.sourceforge.net/
Download Latest Merchant Gateway SDK:
http://hsphere.parallels.com/HSdocumentation/sdk/merchgateway-sdk/merchgateway­sdk-1.0-104.zip
Online Documentation:
http://hsphere.parallels.com/HSdocumentation/sdk/merchgateway-sdk/docs/
Read about .hsp packages in Parallels H-Sphere Customization Guide.
In this chapter:
Logging in as the cpanel User ........................................................................... 67
Restarting Parallels H-Sphere Control Panel ..................................................... 67
C H A P T E R 7

Appendix

Appendix 67

Logging in as the cpanel User

Parallels H-Sphere control panel runs under the cpanel user on the CP server. You need to log in as cpanel to perform many administrative tasks, such as CP configuration, customization, access the system databse, running console Parallels H­Sphere java tools, and many others.
Under cpanel, Parallels H-Sphere control panel communicates with other Parallels H­Sphere boxes via SSH.
To log in as the cpanel user:
1 Log in as root first:
$ su -l
2 Log in as the cpanel user:
# su -l cpanel

Restarting Parallels H-Sphere Control Panel

To restart Parallels H-Sphere Control Panel:
1 Log into the CP server as root.
2 Run:
Linux:
/etc/rc.d/init.d/httpdcp stop killall -9 java sleep 10 /etc/rc.d/init.d/httpdcp start
FreeBSD:
/usr/local/etc/rc.d/apachecp.sh stop killall -9 java sleep 10 /usr/local/etc/rc.d/apachecp.sh start
Loading...