KnowNow Event Router Programmer’s Guide


 This document covers the following topics:


Installing the Event Router

This section describes installing and configuring the KnowNow Event Router on Windows 2000 and Solaris. The following topics are covered:

·         Installation on Windows

·         Installation on Solaris

·         Setting the Port Number

·         Verifying the Event Router Installation

Installation on Windows

1.      Run the knrouter installer executable and follow the prompts on the screen to install the event router. The Event Router is installed as a service by default. For more information, refer to the KnowNow Event Router Getting Started Guide.
2.      Your knrouter.lic license key file will be sent to you via email. Place it in the \Program Files\KnowNow\Event_Router\conf subdirectory.
3.      To start the Event Router, click the Start Event Router icon created by the installer.

Installation on Solaris

To install the KnowNow Event Router on Solaris:

1.      Uncompress and extract the tar file within a directory of your choice. This creates a /usr/local/kn subdirectory in the directory where the tar file was extracted. Optionally, you can login as root and copy the files into /usr/local/kn.
2.      Place the knrouter.lic license key file in the /usr/local/kn/conf subdirectory. The knrouter.lic file is sent to you via email when you purchase or request an evaluation copy of the product. If you have not received a license file, please contact support@knownow.com
3.      Start the Router:

a        Change to the /usr/local/kn directory. This is the installation directory on solaris. When you change to it, you are making it your current local directory.

b        Start the Router in the foreground or the background. See commands below:

starting in foreground: bin/nsd -f -t conf/knrouter.conf

starting in background: bin/nsd -t conf/knrouter.con

 

By default, the Router listens for requests on port 8000. To change the port number, edit the httpport variable at the top of the config file. You must restart the Router for the changes in the port number to take effect.

c        To start the Router automatically when the machine reboots, the Solaris administrator needs to create a script in /etc/init.d for the Router and then symlink into that script form /etc/rc2.d or /etc/rc3.d.

Setting the Port Number

By default, the Event Router listens for requests on port 8000. To change the port number, edit the httpport variable, found near the top of the knrouter.conf file. The config file is located in the conf subdirectory where you installed the Event Router. You must restart the Router for changes in the port number to take effect.

Verifying the Event Router Installation

1.      Open a web browser and connect to http://hostname:8000/, where hostname: is the name or IP address of the computer running the Event Router.This will display a page containing links to several KnowNow sample applications as well as documentation. See Event Router Utilities for information on utilities you can use to manage the Event Router.
For example: If your Router is running on a machine named
router10 port 9500, you would connect to http://router10:9500/.
2.      If you are unable to connect to the Router, check the log file written in the log subdirectory which may contain messages that indicate the nature of any configuration problems. You should also verify that any firewalls between the client and server are set up to allow connections on the port you have configured for the Event Router.

Configuring the Event Router

This section describes how to configure the KnowNow Event Router on Windows 2000 and Solaris. The following topics are covered:

·         Event Router Utilities

·         Managing the Event Router

·         Clustering

·         Persistence

·         SSL Configuration

·         Tuning Parameters

Event Router Utilities

The following HTML-based utilities are installed with the Event Router.

·         KN Test - Performs automated tests to ensure that the web browser, Event Router and the JavaScript Microserver are functioning properly.

·         KN Ping - Measures event routing round-trip latency and throughput over a connection between the Event Router and a web browser.

·         KN Explorer - Displays the contents of topics and events managed by the Event Router in a web browser window.

·         KN Config Utility - Allows you to manage and configure your Event Router.

Using the Utilities

When you start your Event Router, the Router IP address and the port number it is using are displayed either in the console window or in the log file. For example:

0.0.0.0:8000

When running one of the utilities, be sure to specify the host name and port number of the Event Router you wish to test.

1.      Connect to the router start page using a web browser and the appropriate host name and port number.
2.      Select the Router Utilities link to display a page providing links to the three Event Router utilities.
3.      Click on a link for the desired utility and the utility displays in a new browser window.

·         To use KN Ping, enter a number in the first text field (or leave it set to 100) and click Run.

·         To use KN Explorer, select the hyperlinks to navigate through the topic hierarchy.

·         To use KN Test, follow the instructions provided with the utility.

·         To use KN Config, follow the instructions provided with the utility.

For more information about the utilities or to download sample applications and components, visit:

http://developer.knownow.com/

Managing the Event Router

The following sections discuss access control in the Event Router and clustering.

·         Access Control in the KnowNow Event Router

·         Clustering

·         Persistence

Access Control in the KnowNow Event Router

The KnowNow Event Router allows administrators to control:

·         which users can publish events to a particular topic

·         which users can subscribe to a particular topic

·         which users can create subtopics for a given topic

Configuration of the access control mechanisms takes place in three files:

·         passwd - defines valid users and their passwords

·         group - defines groups of users

·         perms - defines the permissions given to specified users and groups

These three files can be found in the conf subdirectory of the KnowNow Event Router's install directory. See the Event Router Configuration File  for parameters that must be edited to ensure authentication and authorization to work properly.

The three access control files are discussed in more detail below.

passwd

Entries in the passwd file are similar to UNIX/etc/passwd entries. The first field contains a username and the second filed contains the crypt() encrypted password for that user. The fields are separated by colons. Note that five (5) colons can optionally follow the encrypted password for compatibility with UNIX password editing tools. For example:

steve:ubphBI51DzSYc:::::

You need to use the passgen utility to create encrypted passwords. The passgen.exe is located in the /bin subdirectory. You give it a username and password on the command line and it spits out the encrypted entry for the passwd file. For example,

$ passgen steve foobar

will give

steve:aa9TsAg8bf3eo

which can be copied in to the passwd file by the administrator.

group

Entries in the group file are similar to UNIX/etc/group entries. The first field specifies a group name and the second field lists the users that are part of the group. The list of users in the second field must all be defined in the passwd file. Three colons separate the group name from the list of users in that group to maintain compatibility with UNIX group editing tools; comma delimiters are used to separate users. See the example below:

eng:::nsadmin,nobody

perms

This file defines the permissions given to users and groups on the KnowNow Event Router. There are four commands valid in this file:

allowuser

defines permissions associated with a single user

allowgroup

applies permissions to a group of users

denyuser

denies access to a specific user

denygroup

denies access to a specific group of users

The parameters of the perms file have the following format:

·         ACTION--dengroup, allowgroup, denyuser, or allowuser

·         INHERITANCE--inherit, or noinherit, default is inherit

·         METHOD--GET, POST, topic, notify, route

·         URL--the path on the KnowNow Event Router

·         ENTITY--either the name of a user or group, as specified in the passwd and group files

For Example:

To allow user "jenkins" to GET or POST to the Router:

allowuser inherit GET /kn jenkins

allowuser inherit POST /kn jenkins

To deny user "steve" to GET or POST to the Router:

denyuser inherit GET /kn steve

denyuser inherit POST /kn steve

To restrict the topic/foobar such that only one user can publish to the topic, modify the code as follows. In this example, sophie is the only user who will be able to publish to the specified topic:

allowuser noinherit notify /kn/foobar sophie

To restrict the topic /foobar such that only one user can delete or modify the properties of the topic, modify your code as follows. In this example, steve is the only user who will be able to delete or modify the specified topic.

allowuser noinherit topic /kn/foobar/kn_routes steve

To restrict the topic /foobar such that only one user can add or edit routes out of a specific topic, modify your code as follows. In this example, olivia is the only user who will be able to add/edit routes out of a specified topic.

allowuser noinherit route /kn/foobar/ olivia

The URLs in the allowuser lines are the topic names prepended with the path on the server the Router is connected to. So in the default case, where nomad is listening on /kn, you prepend that to the topic names as above.

In addition to the allowuser parameter, you can also use allowgroup to restrict access to only specified groups. The denyuser and denygroup parameters can also be used to subtract permissions that have been allowed by the allowgroup parameter setting.

passwd file entries are htaccess-style passwds; only the first two fields are used by the server. You can specify that a user not have a password by leaving the second field blank. In this case, the user still has to give a username to access the topic, but can leave the password field of the http challenge blank.

Restricting Access to Various Event Router Operations

This section describes how you restrict access to various operations in the Router: deleting a topic, attaching filters to a topic, attaching filters to a Router, fetching and uploading a config file, setting default event expiration times, and setting max queue lengths.

Deleting a topic

Any user that has the permission to add or edit a topic's properties also has the permission to delete the topic. You can restrict deletion of a topic by using the permissions file settings. For more information on the permissions file, refer to perms. Some topics may not be deleted. The Event Router specifically protects against anyone deleting:

·         /

·         /kn_config,

·         /kn_statistics

·         /kn_filters

Attaching filters

Filters can be added to any topics, except the subtopic topics. The following apply:

·         A filter cannot be added to any topic containing /kn_subtopics

·         Filters can be attached to special topics, such as /kn_config and /kn_statistics during the runtime of a Router; however, the filters will not be persisted.

Fetching and replacing the contents of the config file

·         You can fetch a copy of the config file by retrieving the config_file event in the /kn_config topic. The payload of the config_file event contains the contents of the Router configuration file.

·         You can replace the contents of an existing config file by posting a new config_file event to the /kn_config topic. The event must contain the new configuration file within the payload of the event. When the Router receives the event, it will:

·         make a copy of the existing config file and write it to disk

·         write the new config file (from the payload of the new config_file event to disk

·         restart itself with the new configuration file.

 

The Router must be running without the -f option (on Solaris/Linux), or as a service on Windows to restart itself automatically. For more information on Router installation, refer to the Event Router Getting Started Guide.

Setting default expiration time

You can use the kn_default_kn_expires header to set a default expiration time for events within a topic. Events expire based on the following rules:

·         /kn_subtopics topics always have an event expiration time set to infinity

·         /kn_routes topics default to having an event expiration time of infinity

·         /kn_journals topics default to having an event expiration time of JournalReconnectTimeout (which defaults to 60 seconds). The JournalReconnectTimeout parameter can be specified in the configuration file.

·         All other topics default to having an expiration time of default_kn_expires (which defaults to 3600 seconds). The default_kn_expires parameter can be specified in the configuration file.

·         The event expiration time of any topic (except /kn_subtopics topics) can be changed by using the kn_default_kn_expires header. You can set this parameter using the set_topic_property Router command.

The following example will set the topic called "mytopic" to have a default event expiration time of 600 seconds:

do_method=set_topic_property;kn_to=/mytopic;kn_default_kn_expires=600

Setting maximum queue length

You can limit the maximum number of events that are contained within a topic at any given time by setting the kn_max_queue_size property on the topic. By default, topics can have an unlimited number of events. If the kn_max_queue_size parameter is used, the topic acts as a FIFO (first in, first out) queue where only the last n events will be stored. For instance, the following example will set a max event queue length of 50 in the topic "mytopic." If the topic has 50 unexpired events, and a new event arrives, the oldest event in the queue will immediately expire in order to make room for the new event:

do_method=set_topic_property;kn_to=/mytopic;kn_max_queue_lenght=50

Event Router Configuration File

Editing of the topics/config is restricted only to the root user.

Authentication/Authorization modules

Before you can use the authentication and authorization modules, make sure you use a text editor to uncomment the following lines in .conf and verify the setup of the authentication and authorization files:

#

# Load Authentication module?

# ns_param authentication_module "${bindir}/knauthenticate${ext}"

 

#

# Load Authorization module?

#ns_param authorization_module "${bindir}/knauthorize${ext}"

After you have uncommented the above lines, ensure that the following settings are uncommented and point to the correct files:

# Authentication module settings

ns_section ns/server/${servername}/module/knauthenticate"

ns_param passwordFilePath "${homedir}/conf/passwd"

 

#Authorization module settings

ns_section "ns/server/${servername}/module/knauthorize"

ns_param permsFilePath "${homedir}/conf/perms"

tunnel_header

The tunnel_header option allows you to send additional http headers down a tunnel connection when it is opened. You can set as many tunnel_header statements as you like. The tunnel_header parameter(s) must be set in the nskn section of the config file. For example:

"proxy-hint: unbuffered"

Clustering

What is Clustering?

A cluster is when two or more Routers are configured into a cluster to provide:

·         machine fail-over mechanism

·         Scalability of connections

All Routers in a cluster mirror each other to look and act like one Router.

 

Clustering Routers does not help improve performance or throughput. In fact, there is a slight amount of overhead associated with clustering which can cause a slight decrease in performance.

Failover Mechanism

The Failover mechanism allows for uninterrupted Router requests to happen even if one of the Routers in the cluster goes down. For example, if a cluster contains Router A, Router B, and Router C, and Router A in the cluster goes down, the other Router(s) continues to serve Router requests without interrupting service. However, you need to be careful when clustering machines to ensure data integrity.

Since there is no guaranteed ordering within an asynchronous distributed system such as a Router, it is important to understand how the cluster works to ensure that data remains in sync across all nodes in a cluster.

If you have multiple clients or an asynchronous client publishing update events to topics, you should feed all requests for those clients to a single node in the cluster. Otherwise, events crossing paths between cluster nodes will lead to inconsistency across the cluster.

For instance, if publishers P1 and P2 are both sending updates to a cluster with stock ticker and price information on IBM, the following situation could occur. Assume that P1 sends an event to node N1 with kn_id="IBM" and kn_payload="100". At the same time, P2 sends an event to node N2 with kn_id="IBM" and kn_payload="102". Each node will accept the request and pass it along to its peers. But due to latency issues, and the fact that the events are being duplicate-squashed and updated, it is possible that node N1 could end up with the opposite event as node N2. The current solution for this problem is to feed all incoming cluster requests to the same node. This can be accomplished using a load balancer. If one node goes down, the load balancer can switch to using the other node, and thus prevent the loss of routing service.

 

If a machine in the cluster goes down, and you restart the machine, it does not make any attempt to re-sync with the other machines. There is no transaction mechanism built into clustering; therefore, events (at any given time) may appear to be in a slightly different order. Ordering of events is not preserved across the nodes in a cluster. Therefore, topics may contain the same events, but they may be stored in a different order on each clustered Router.

Scalability of Connections

Clustering can also be used to increase the total number of connections to the Router. The number of connections on a Router is limited to the operating system's limits for open file descriptors. Solaris allows 64K file descriptors; whereas, Microsoft Windows and Linux allow 1K file descriptors each. You can exceed the operating system's limits by running several Routers in a cluster and distributing the connection load over multiple machines.

Router requests can be directed to any node in the cluster. The cluster module automatically takes each request and mirrors it across all of the other machines in the cluster. Therefore, every node in a cluster has the same topic hierarchy and receives all of the same events. However, the nodes in the cluster are not guaranteed to be exactly alike. The cluster configuration and route topology must be carefully planned to ensure that cluster nodes have the required level of similarity. For more information, refer to How to Cluster?

How to Cluster?

To run a cluster, you must first configure the cluster parameter, which is located in the nsknc section of the KNRouter configuration file. Before you can configure the cluster, you may need to uncomment the nsknc parameter in the modules section of the conf file. The cluster parameter takes a list of <host>:<port> combinations, separated by white space. There is no limit to the number of peers in the cluster, although practically 64 should be the limit. The default value is a dummy value that will not create any clusters.

The following example presents a scenario for setting up a cluster of two machines. See figure below:

1.      Set the hostname to be the URL of your local site. This section will be the same in the config files for both the machines in the cluster. Do NOT include the hostname in the cluster parameter of the config file.

set hostname http://www.mysite.com

2.      Set the local_host in the cluster parameter of the config file.

For machine 1:

ns_section "ns/server/${servername}/module/nskn"

local_host foobar.com:8888:443

For machine 2:

ns_section "ns/server/${servername}/module/nskn"

local_host 1.2.3.4:8080:443

If you copy the config file from one machine in the cluster to another, make sure that the local_host statement is set up for that specific machine and not copied over for a different machine.

3.      Set the cluster statement as follows:

ns_section "ns/server/${servername}/module/nsknc"

ns_param cluster "\

1.2.3.4:8080 \

foo.bar.com:8888 \

"

Notice that the example defines a cluster made of two peers: one listens on IP address 1.2.3.4 at port 8080; the other, which resolves to the IP address the DNS returns for foo.bar.com, listens on port 8888. Notice also that quotes are necessary; however back slashes (\) are used to break lines for a cleaner code.

 

The config file for each machine in the cluster should be exactly the same except for the local host statement.

 

Important Clustering Considerations:

·         On each client cluster box, remember to set the hostname to the externally visible DNS name of the cluster.

·         You must keep the <host>:<port> combinations in sync with the top-level "httpport" and "address" variables in the configuration file. Each peer must be able to recognize itself as one of the values in the cluster list. Also, the client must ensure that the nsknc module is loaded at KNRouter run-time. The existing entry for nsknc in the "modules" section is commented out by default.

·         Each value in the cluster list must contain the exact same cluster value in their local copy of the configuration file.

·         When clustered, the cluster can receive SSL requests but the intercommunication between clustered machines is only http. To ensure security, make sure that all machines within the cluster are behind the same firewall. Clustering requires HTTP communications to be enabled so that cluster members can communicate. If you need HTTPS-only Routers to work in a cluster, use a firewall or load balancer to block connections to port 80 on the cluster boxes (and only allow HTTPS connections on port 443).

·         The KnowNow Config Utility cannot be used through a load balance interface in a cluster configuration. The recommended approach is that you get one version of the .conf, perm, passwd, and group files just the way you want it, copy these files to each of the cluster machines, and then restart the cluster machines.

Persistence

The KnowNow Event Router uses Berkeley's SleepyCat database (see http://www.sleepycat.com/) to maintain a persistent state on disk. This allows the Router to be stopped and then restarted in the same state (that is, all of the topics and events that exist when a Router exits are available when the new Router starts).

 

Since there is no guaranteed ordering within an asynchronous distributed system such as a Router, events (at any given time) may appear to be in a slightly different order.

Previous versions of the KnowNow Event Router (v1.2 and earlier) used a custom implementation to achieve this functionality. The v1.3 Router had an embedded implementation of the SleepyCat database to maintain persistent data. The v1.5 Router has a new dynamic SleepyCat module to maintain persistent information. The v1.5 Router is almost identical to the v1.3 module except for a few minor differences to the configuration file.

Important:

·         Version 1.7 persistent files are different than the earlier versions. The Router will automatically upgrade to v1.7 when it's run. You cannot use the 1.7 database on a 1.6 Router after it has been upgraded.

·         Old persistent files (v1.2 and earlier) are not backwards compatible with the v1.3 or v1.5 Router formats. Starting a v1.3 or v1.5 Router will automatically delete old persistence files (v1.2 or earlier).

·         v1.3 versions of the persistence files will automatically be upgraded to use the v1.5 Router format the first time you use the v1.5 Router. However, you will NOT be able to roll back to the v1.3 format once the Router has upgraded the database.

The v1.5 Router supports the following configuration parameters for persistence. In the configuration file conf/knrouter.conf:

Under the KnowNow Persistence section (nsknp):

ns_section "ns/server/${servername}/module/nsknp";

ns_param persistence_file ${serverroot}/knrouter.prs;

ns_param persistence_interval 600;

Under the KnowNow section (nskn):

ns_section "ns/server/${servername}/module/nskn";

ns_param persistence_module "${bindir}/nsknp${ext}"

ns_param atomic_router false;

ns_param atomic_topic /topic;

persistence_file

The persistence_file parameter specifies the location of the database file. If the file does not exist when the Router starts, it is created automatically. A temporary database directory is also created automatically, if it does not exist. The database directory is only needed while the Router is running and may be deleted by the Router or manually after the Router is shut down. The temporary database directory has the same name as the persistence file with the string _db appended. For example, when the Router is running you may see something like this:

/usr/local/knrouter/runtime/knrouter.prs        //Database file

/usr/local/knrouter/runtime/knrouter.prs_db     //Database directory

persistence_interval

The persistence_interval parameter specifies how often non-atomic persistence information will be flushed out to disk. The interval is specified in seconds. In the example above, the Router flushes a snapshot of its state to disk every 600 seconds. This means that if the Router is abnormally terminated or crashes, it will only lose 600 seconds (at most) of information that cannot be recovered. The Router will always try to persist its state when it exits, so it is possible that even if the Router crashes, 100% may be recoverable.

persistence module

The persistence_module parameter specifies the name of the persistence module. The persistence functionality of the v1.5 Router has been moved out of the Router core and into a module. This allows you to develop your own modules for handling persistence using the Router's persistence API functions. The default configuration includes a module for using the SleepyCat database for persistence. You may configure the Router to not persist any information about the Router by removing this statement from the configuration file.

atomic_router

The atomic_router parameter instructs the Router to flush all topic and event information to disk continuously (as events occur). This allows the Router to have the best chance to recover 100% of its state following a shut down or crash, but may have a slight performance penalty.

atomic_topic

The atomic_topic parameter instructs the Router to continuously save a single topic's events to disk as they occur. This works in the same way as the atomic_router parameter, but only for one topic (per atomic_topic statement). Multiple topics can be run in atomic mode (without the whole Router being atomic) by specifying each atomic topic name with an atomic_topic statement in the configuration file.

Moving Persistence Information

The new persistence information should not be moved using regular file move/copy/rename commands. Using these commands could result in two potential problems:

·         if the Router is running, it is likely that the copy of the database will be inconsistent from the original or could even be corrupted (because the Router could be in the middle of writing while you are copying).

·         the database actually stores file-specific information within the database that will become inconsistent if you copy, move, or rename the database using standard file system commands, even if the Router is not running.

To get around this problem, use the db_kncopy utility to copy Router persistence information. This utility must be used every time you copy, move, or rename the persistence information. In addition, it can be used while the Router is actually running. The utility actually connects to the database, sets the necessary locks, and allows you to backup your persistence database without stopping the Router.

db_kncopy [-V] source_db destination_db

-V prints version information

source_db is the source database persistence file

destination_db is the destination database persistence file

The following example copies the knrouter.prs file to the backup.prs file .

db_kncopy knrouter.prs backup.prs

 

SSL Configuration

You can turn on SSL support for the Event Router by setting options in the config file.

1.      The following config file line loads the nsopenssl module, but it is commented out by default. You can un-comment it by removing the leading # character.

# ns_param nsopenssl ${bindir}/nsopenssl${ext}

2.      The nsopenssl section in the config file holds the configuration parameters:

ns_param port $httpsport

ns_param hostname $hostname

ns_param CertFile cert.pem

ns_param KeyFile rsa.pem

port

This setting is configured from the httpsport setting, common to the entire Event Router. The httpsport setting is located near the top of the configuration file; it sets the port on which to listen for SSL-encrypted connections. The default is 8443.

hostname

This setting is configured from the hostname setting, common to the entire Event Router

CertFile

The CertFile parameter should point to the signed certificate file from the Certification Authority (CA). The KnowNow Event Router certificates need to be in PEM format, which can be generated by several public CAs, as well as by all the major CA infrastructure products. This file resides in the conf/ subdirectory, along with the configuration file.

KeyFile

The KeyFile parameter should point to the RSA private key for the router. This file resides in the conf/ subdirectory, along with the configuration file.

Generating and Installing Certificates

To enable SSL on a router, you must generate and install a certificate:

1.      Generate the RSA key for the router by running the genrsa utility, located in the bin/ directory. After running the command, an RSA key in PEM format will be placed in your /usr/local/kn/conf directory. Run the command as follows:

$ /usr/local/kn/bin/genrsa -out /usr/local/kn/conf/rsa.pem

2.      Generate a Certificate Signing Request (CSR) by running the req utility, located in the bin/ directory. This creates your CA, generates a certificate for your router, then signs it with its private key. This allows clients to verify your router's identity and then encrypt transmitted data.

$ /usr/local/kn/bin/req -new -key /usr/local/kn/conf/rsa.pem

3.      Type the appropriate information into the data fields:

·         Country Name (2 letter code) [AU]:

·         State or Province Name (full name) [Some-State]:

·         Locality Name (e.g., city) []:

·         Organization Name (e.g., company) [Internet Widgits Pty Ltd]:

·         Organizational Unit Name (e.g., section) []:

·         Common Name (e.g., YOUR name) []:

·         Email Address []:

 

In the Common Name field, type the full hostname of the machine on which the router is running, for example, www.mycompany.com.

 

4.      When finished, the req utility prints a certificate request. Send this request to the appropriate CA and complete their approval process to receive a signed, valid certificate.
5.      Place the valid certificate in the /usr/local/kn/conf/cert.pem file and start up the KnowNow Event Router.

 

All of the major certificate authorities generate free "developer" certificates. These certificates, which are signed by invalid CA roots, are still useful for testing purposes. Refer to their respective web sites for more information.

Tuning Parameters

 

Parameter

Description

address

IP address to which the Event Router should bind. Useful if a machine has more than one network connection. Default value: [ns_info address], which tells the Router to bind to all interface

atomic_router

If true, every event transmitted to the router will force the router to persist state to disk. This may incur a performance penalty. Default value: false

atomic_topic

Allows a single topic to be configured as atomic, in which case event transmissions to that topic force the router to persist state to disk immediately. Can be used multiple times to make multiple topics atomic.

cluster

Enables a set of machines to participate in a cluster. Default value: dummy - no clusters are created.

default_kn_expires

The number of seconds an event lives if an expiration time is not set. This value can be set to infinity, which means the event will live forever. Default value: +3600 seconds

help_url

URL to redirect users to when they perform a do_method=help on the router.

hostname

The name of the host on which the Event Router is running. Default value: [ns_info hostname], which tells the router to figure out the hostname.

httpport

Specifies the port that the router listens on for requests. Default value: 8000

javascript_domain

Domain to set on all returned JavaScript. Used in cross-domain router setups. See the cross-domain router documentation for details.

javascript_kn_server

kn_server setting for use in cross-domain router setups. If cross-domain scripting is turned on, the URL specified for this parameter MUST be the one used by the browser to connect to the router. See the cross-domain router docs for details.

journalReconnectTimeout

The length of time that journals live after connections close. If clients reconnect in the time period specified in this parameter, they can recover connections atomically.

js_microserver

Filename inside static_files directory of the JavaScript Microserver.

license_dir

The directory that contains the license file for the router. Default value: conf subdirectory of router

maxconnections

Controls the maximum number of simultaneous connections the router will handle. Default value: 100

maxkeepalive

Controls the maximum number of requests that can use the HTTP Keep_Alive. If a value is not set, this parameter will use the values specified in maxconnection.

maxline

Maximum HTTP GET request size in bytes. Default value: 8K

maxport

Maximum size of event to accept in bytes. Default value: 2MB

maxthreads

Controls the number of inbound simultaneous requests the router can process. This does not affect persistent connections; it only affects the pool of threads used to process incoming HTTP GET and POST events. Default value: 50

persistence_file

The filename to persist the router state to. Default value: knrouter.prs

persistence_interval

How often does the router saves its state. Default value: 600 seconds

reaper_interval

How often, in seconds, that the router looks for and deletes expired events. Set this value to be lower than the default value for large numbers of expiring events. Default value: 600 seconds

static_files

Location on disk that contains the JavaScript Microserver and supporting files.

url

URL prefix to which the router responds to requests. Default value: /kn

tunnel_threads

The number of threads servicing connected clients. Set this number higher than the defaults for larger numbers of connected clients. Default value: 3

 

Using the Event Router

 

This section describes how your applications can use HTTP and HTTPS to send information to and receive information from an Event Router. This chapter contains the following sections:

·         Understanding the Event Router

·         Events

·         Using the HTTP Interface

·         HTTP Interface Control

·         Status Events

Understanding the Event Router

The KnowNow Event Router enables application-to-application communication across the Internet by providing real-time event subscription and publication services. Each Event Router routes events from publishers to subscribers. The router can send and receive events from any application to many applications, including Web browsers, in real-time, anywhere on the Internet. The Event Router is reliable, secure, easily managed, and highly scalable. The Event Router can coexist with your existing application servers, databases, and enterprise application integration (EAI) solutions.

Topic-based Event Routing

Any client application that is connected to an Event Router can act as an event publisher, a topic subscriber, or both. Topics themselves can also subscribe to other topics, allowing you to construct a hierarchy of topics and distribute one event into many topics or combine events from multiple topics into one new stream.

Sample Topic Hierarchy

Referencing Topics

A topic is identified by a Uniform Resource Identifier (URI), for example:

/chat/technology/xml

To avoid naming conflicts, the topic name should start with a domain name, for example:

/knownow.com/chat/technology/xml

A topic name can contain roman letters, digits, slashes, underscores, dashes, periods, and non-ASCII characters.

Creating Topics

Your application can create a topic by simply referencing the topic in a request to the Event Router.

Event Routing

When your application publishes an event, it always specifies a topic. The topic defines how the event is to be routed to all the subscribers of that topic. A route can point to another topic or to a generic listener.

Topics fall into three basic categories: topics, meta-topics, and journals. Topics are the primary nodes in a route topology where data is posted to. Topics may have meta-topics that are used to store information relevant to the topic such as hierarchy and routing data. Current meta-topics include
/kn_subtopics, and /kn_routes. kn_subtopics store events that correlate to a topic's children and /kn_routes store events that correlate to the routes out of a topic. Meta-topics are created only as needed.

Meta-topics provide a unique feature of introspection to the Router. It is possible to subscribe to meta-topics in exactly the same manner in which you subscribe to any other topic. For instance, if you subscribe to a topic's
/kn_routes meta-topic, you will receive events every time a route is added or removed from the topic. The same principle applies to
/kn_subtopics.

Journals are topics that have a persistent connection to a client over special routes called tunnels. Events for tunnels are created in the /kn_routes topic of the journal, but may be used for introspection purposes only. For instance, you may subscribe to a journal's /kn_routes topic to monitor the events that are generated when a client connects to or disconnects from the Router over a persistent connection. But you would not be able to modify those events and impact the behavior of the tunnels in any way.

Events

Each event processed by the Event Router contains a set of headers, consisting of a name and a value. Each name and value is a string of Unicode or UCS characters.

Event Headers

Headers may appear in any order within an event, but each header must have a unique name. The order of headers is not preserved. Headers and values may include any UCS or Unicode character (including reserved characters and characters not yet allocated) and may be of any length.

In the examples that follow, these tags are used to represent special characters:

·         NUL - A null character (character 0 , U+0000 ).

·         LF - The line feed character (character 10 , U+000A ).

A sample event might include the following headers:

·         A header named "header1" with the value "value1".

·         A header named "headerLFthree isNULlong" with the value "1".

·         A header named "kn_id" with the value "979273892_861_2249".

Required Headers

Header Name

Value Description

kn_payload

Contains the event's payload, analogous to a message body. If kn_payload is not present, the Event Router will insert this header with the empty string as the value.

kn_id

Contains the Event ID. By default, the ID is a pseudo-random string, such as 979273892_861_2249.

kn_time_t

Event timestamp expressed as seconds since Thursday, January 1, 00:00:00, 1970, UTC. By default, this is set to the event's creation time. An event created on Friday, January 12, 04:31:32 2001 UTC would have a kn_time_t value of 979273892.

kn_expires

The date and time when the event or route will expire. This may be expressed in the same format as kn_time_t or as a positive offset in seconds from the event's arrival time.

Specifying a value of "infinity" means this event will never expire. Specifying a value of "now" means this event is already expired.

If this header is not specified, the event may be subject to default expiration time configured by the router administrator.

When a route with no kn_to expires, the persistent connection is closed and the journal topic becomes stale.

kn_route_location

URI of the route along which this event was most recently forwarded, such as:

http://foo/kn/what/chat/kn_routes/964832125_29689_47

For routed events, this URI may be overridden by the kn_uri route parameter.

For status events, the URI may be provided by the kn_status_from parameter.

kn_route_id

The kn_id of the route along which this event was most recently forwarded.

kn_routed_from

The absolute URI of the topic from which this event was most recently forwarded.

Using the HTTP Interface

You use either the HTTP GET or POST methods to send a request to an Event Router. For most requests, the Event Router will return a status event that indicates the success or failure of a previous request.

The HTTP POST method is preferred for some requests (route and notify) as it avoids lengthy URLs.

The GET method is preferred for request types whose results are intended to be cached for long periods of time, such as lib, blank, and whoami.

Parameter Rules

·         For HTTP POST requests, parameters are sent as POST data in application/x-www-form-urlencoded format.

·         For HTTP GET requests, parameters are sent as URL query strings in application/x-www-form-urlencoded format.

·         Parameters and values use the UTF-8 character set encoding.

·         Path information, the part of the URL path following the server URL, can be used to specify a default topic for route and notify requests, but is not considered to be a parameter.

·         Your application can use the parameters described in HTTP Interface Control to select the desired Event Router operation or option.

·         Parameters described in Headers required for all events are available as event headers and, except where otherwise noted, are propagated along routes.

·         With the exception of parameter names starting with kn , parameters not listed here are generally available for use by your application as application-specific event headers.

·         All parameter names starting with kn_ are reserved for use by the Event Router.

·         Parameters described in Status event parameters are used in status events generated by the Event Router to indicate the success or failure of a request.

HTTP Interface Control

Your application can use the HTTP Interface (Control) parameters to select operations and set Event Router options. Your application specifies one of the following do_method values and any of the required parameters for the desired operation.

Default GET Behavior

If an HTTP GET request does not specify the do_method parameter and other parameters are provided, the Event Router will treat it as a route request. If an HTTP GET request specifies no parameters, the Event Router will treat it as a help request.

Default POST Behavior

If an HTTP POST request does not specify the do_method parameter and other parameters are provided, the Event Router will treat the request as a notify request.

Available do_method settings

do_method

supports status event

Preferred HTTP Method

Description

add_journal

Yes

POST

Adds a journal. This is the same as the using the route command with a null kn_to or a kn_to that starts with javascript:

kn_from - name of the journal (required).

add_notify

Yes

POST

Adds or replaces a notify event to a topic (same as the current notify command).

do_since_checkpoint

add_route

Yes

POST

Adds or replaces a route. This is the same as the route command, but this command will not create journals or delete routes, depending on the kn_to values.

kn_from - topic to route from (required).

kn_to - the URI to route to (required).

add_topic

Yes

POST

Adds a new topic to the Event Router. kn_to - specifies the name of topic to create and is required.

batch

Yes

POST

Sends multiple route requests, notify requests, or some of each type. Each request is contained in its own per kn_batch parameter.

Generates a status event for the batch request itself as well as a status event for each request contained in the batch.

blank

No

POST

Returns an empty HTML document with a JavaScript callback. Essential for enforcing the JavaScript same-domain security policy. This is useful because JavaScript access to about:blank is sometimes restricted.

clear_topic

Yes

POST

Deletes all events from a topic on the Event Router.

kn_to - specifies the name of the topic to delete and is required.

delete_notify

Yes

GET

Deletes an event from a topic. If the event does not exist, a 404 is returned.

kn_to - the name of the topic where the event exists (required).

kn_id - id of the event to delete (required).

delete_route

Yes

POST

Deletes a route. If the route does not exist, a 404 is returned.

kn_from - the name of the topic where the route begins (required).

kn_id - id of the route to delete (required).

help

No

GET

Returns a help document.

lib

No

GET

Returns the JavaScript Microserver library and includes the results of whoami.

This service is typically referenced near the beginning of an HTML page to make the page into an interactive web application.

noop

No

GET

Returns HTTP response 200 OK, with no content. This can be used to verify that the router is running on a given host/port/path-prefix while consuming minimal resources.

notify

Yes

POST

Posts an event to the destination specified by kn_to.

route

Yes

POST

Establishes a route from kn_from to kn_to. An empty kn_to is used to indicate a route is to be deleted.

set_topic_property

Yes

POST

Modifies a topic's properties on the Event Router. This is the same as calling update_notify on the topic's corresponding subtopic event.

kn_to - the name of the topic (required).

kn_default_kn_expires - default expiration time for events on this topic (optional). If this topic is a journal, then it is limited by the maxJournalReconnectTimeout parameter in the config file. This parameter limits the maximum amount of time that a journal can be set to maintain events. The default value of maxJournalReconnectTimeout is set to 3600 seconds (1 hour).

kn_max_queue_size - the maximum number of events to be stored in this topic (optional).

kn_filtername - the name of a filter (optional).

kn_filterparams - the parameters for the named filter (optional).

shutdown

 

 

Used to shutdown the Router. You can only use this command if you have permission to modify the /kn_config topic.

do_method=shutdown

update_notify

Y

POST

Updates an existing event. If the event does not exist, a 404 is returned. If the event does exist, only the headers that are set in this request will be changed in the event. All other headers will remain the same.

kn_to - the name of the topic where the event exists (required).

kn_id - id of the event to update (required).

update_route

Y

POST

Updates an existing route. If the route does not exist, a 404 is returned. If the route does exist, only the headers that are set in the request will be changed. All other headers will remain the same.

kn_from - the name of the topic where the route begins (required).

kn_id - id of the route to update (required).

whoami

N

GET

Returns JavaScript to set router- and session-specific window string properties. All returned string properties are optional and UTF-8 encoded.

Also returns a document.domain setting when the javascript_domain configuration file parameter is set.

 

 

All topic and notify commands look at the kn_to parameter to see if the destination of the request is on the current Router. If the request is not on the current Router, the request is forwarded to the proper Router. All route commands look at the kn_from parameter to see if the source of the route is on the current Router. If it is not, the request is forwarded to the proper Router. The Router will proxy the request and then return the response information from the destination Router.

Parameters

Parameter

Used With

Description

kn_batch

batch

Contains a single request in application/x-www-form-urlencoded format. Several kn_batch parameters may occur in a single batch request.

Example:

do_method=notify;kn_to=/what/chat;kn_payload=hi%20there

kn_deletions

route

add-route

update-route

Topics that have routes with the kn_deletion header set, will send a deletion event along the route any time an event is deleted from the topic. This event contains the same kn_id as the event that is being deleted, an empty payload, and a header set inside it as kn_deleted=true.

kn_deleted

 

This header is set to true, and sent along with deletion events.

kn_filtername

 

A filter name.

kn_filterparm

 

A filter parameter.

kn_from

route

add-route

update-route

The route's source, such as:

/postit or http://foo/kn/postit

The Router looks at kn_from for Router commands.

kn_response_format

any command that allows status events

Selects a format, simple or js, for events returned in the HTTP response. See also kn_response_flush.

kn_to

add-route

update-route

route

add-notify

update-notify

set-topic-property

add-topic

The route's destination, such as

/what/chat, http://foo/kn/what/chat

If the kn_to parameter is not specified, kn_to defaults to the path information. The Router looks at kn_to for any topic or notification commands.

 

kn_to

kn_status_to

notify

The topic to publish the event to.

The topic to which status events are redirected, for example:

/who/anonymous/s/22690909/kn_journal)

If this is not specified, status events will be returned in the HTTP response.

kn_status_from

 

A value to place in the kn_route_location header of status events, as described in Status Events.

Initial Route Population

The following parameters are used in route requests to control the immediate transmission of previously-transmitted events along a new route. If multiple parameters are specified, the route will be populated with the events which meet all the criteria specified by the parameters.

Status event parameters.

Parameter

Description

do_max_age

Defines a maximum age in seconds, or infinity for no maximum age, of previously posted events that are to be forwarded. All events in the source topic with an age less than or equal to the specified age will be forwarded along the route.

On tunnel connections, the status event indicating the route success is always sent before other events have been forwarded along the route.

On other routes, the status event indicating the route success is always sent after the events from the initial route population have been forwarded along the route.

do_max_n

A number n representing the maximum number of recently posted events in the source topic which have not expired that will be forwarded along the route. If fewer than n events remain, then all unexpired events will be forwarded.

On tunnel connections, the status event indicating the route success is always sent before other events have been forwarded along the route.

On other routes, the status event indicating the route success is always sent after the events from the initial route population have been forwarded along the route.

do_since_checkpoint

A previously delivered kn_route_checkpoint value indicating that all events after that checkpoint should be re-sent.

On tunnel connections, the status event indicating the route success is always sent before other events have been forwarded along the route.

On other routes, the status event indicating the route success is always sent after the events from the initial route population have been forwarded along the route.

 

 

do_max_n and do_max_age subscriptions cannot be used together.

 

Status Events

The Event Router generates status events to indicate the success or failure of most requests. Status events will also be generated for requests with unknown do_method values.

Separate status events are generated for each request contained within a batch request as well as a status event for the batch request itself.

If kn_status_to is not specified, the status events are returned in the body of the HTTP response and the status code and the reason phrase of the HTTP response are taken from the status field of the first status event. The kn_response_format parameter determines how the events are represented.

If kn_status_to has been specified, the HTTP response uses 204 No Content as the HTTP status code and reason phrase. In accordance with RFC 2616, there will be no response body. Instead, the events are forwarded to the topic whose URL is specified as the value of kn_status_to.

Status Event Headers

Parameter

Description

status

A three-digit HTTP reason code followed by a space and an HTTP reason phrase.

Codes 1xx, 2xx and 3xx codes generally indicate success.

Codes 4xx and 5xx generally indicate errors.

If this is the first event being returned over the requesting connection (when kn_status_to was not set and the request is not part of a batch request), the status will also be sent as the HTTP status code and reason phrase.

kn_payload

A detailed and human-readable description of the results of the request in plain text format. (Optional)

kn_route_location

URI of the route along which this status event was most recently forwarded, such as:

http://foo/kn/what/chat/kn_routes/964832125_29689_47

For routed events, this URI can be overridden by the kn_route_uri parameter.

Contains the value of the kn_status_from parameter from the original request that generated this status, if the original request included the kn_status_from header.

Event Filtering

 

This section describes how you can define and use your own filters for performing custom data transformation on event contents or blocking event entirely. This section covers the following topics:

·         Understanding Filters

·         Understanding the Filter API

·         Configuring Filter Modules

·         Attaching and Detaching Filters

Understanding Filters

As the Event Router processes events it receives, it can pass control to your filter plug-ins that you have created and configured. Filters can perform simple tasks, such as logging the contents of each event, or complex tasks, such as event data transformation or translation.

Filters you create can be attached to topics or to individual routes. When a filter is attached to a topic, control is passed to the filter each time an event is published to that topic. When a filter is attached to a route, control is passed to the filter each time an event is traversing the route. In either case, you can design your filter to examine and modify the contents of each event using criteria you specify.

Filters you create must be packaged as shared objects or DLLs, using the C++ API described in this section and in Event Router Module API.

Prior to starting the Event Router, the Router's configuration file must be modified to define the filters you wish to use. The configuration file entries also specify parameters that you may wish to pass to your filters, described later in this chapter.

Understanding the Filter API

The Event Router communicates with your filter plug-in using well-defined callback functions during three basic phases of operation; start-up, event filtering, and shutdown. Your filter plug-in must implement callback functions for each of these phases. For more information on the filter API, see Event Router Module API

Start-up Processing

When your filter plug-in is initialized at startup time, the Event Router will invoke your filter's KnModuleStart function. This function is called only once, so it's not required to be a threadsafe implementation.

Your filter plug-in's implementation of this function can provide any required initialization, such as connecting to an external system or initializing an internal XSLT engine.

Your filter plug-in can read configuration settings from the Event Router's knrouter.conf file, which can be configured to contain host names and login information for external systems the filter will use.

Upon completion, your plug-in's KnModuleStart implementation should return an indication of the overall success or failure of the initialization processing. If a failure indication is returned, the Event Router ignores the filter from that point on.

Sample Implementation of KnModuleStart

 

KN_EXPORT KnError KnModuleStart(const KnString &path, const KnSet &info)

{

KnLog(KnLogNotice, "SAMPLE_FILTER: KnModuleStart()");

KnLog(KnLogNotice, "SAMPLE_FILTER: Path = %s", path.c_str());

 

for (size_t i = 0; i < info.size(); ++i)

{

KnLog(KnLogNotice, "SAMPLE_FILTER: Info [%u] = %s : %s",

i, info[i].m_key.c_str(), info[i].m_value.c_str());

}

 

return KnErrorSuccess;

}

Shutdown Processing

When the Event Router is shutting down, your filter plug-in's KnModuleStop function will be called. Your plug-in's implementation of this function should provide any necessary clean-up processing, such as disconnecting from any external system and freeing any resources that may have been allocated. This function is called only once, so it's not required to be a threadsafe implementation.

Sample Implementation of KnModuleStop

 

KN_EXPORT KnError KnModuleStop()

{

KnLog(KnLogNotice, "SAMPLE_FILTER: KnModuleStop()");

 

return KnErrorSuccess;

}

Attaching Filters

Once the Event Router has loaded your filter plug-in and called the KnModuleStart function, client applications can attach the filter to topics or routes within the Event Router. If a filter is attached to a topic, control is passed to the filter each time an event is published to that topic. When a filter is attached to a route, control is passed to the filter each time an event is traversing the route.

The KnFilterTopicAttach function is called each time your filter plug-in is attached to a topic. The KnFilterRouteAttach function is called each time your filter is attached to a route.

An individual filter may be attached multiple times within the Event Router's topic and route hierarchy. KnFilterTopicAttach/ KnFilterRouteAttach is like a constructor called with parameters for a particular instantiation of the filter.

 

Your KnFilterTopicAttach or the KnFilterRouteAttach implementation must be threadsafe.

KnFilterTopicAttach always provides the URL of the topic that events are going into. KnFilterRouteAttach always contains destination URI of the route on which the plug-in has been attached. The client application attaching your filter may optionally specify a set of parameters to be passed as part of the attachment. This allows filters to be parameterized for each individual attachment just as a class can be instantiated as several different objects.

For example, you might create a generic XSLT transformer filter plug-in that is attached in five different locations. Each attachment of the same filter can be given its own XSLT sheet to govern the transform it will provide on an individual topic or route.

This sample implementation of KnFilterTopicAttach simply logs the passed parameters and the URI before returning.

Sample Implementation of KnFilterTopicAttach

 

KN_EXPORT KnError KnFilterTopicAttach(const KnString &filterParams, const KnString &uri, bool &transform)

{

KnLog(KnLogNotice, "SAMPLE_FILTER: KnFilterTopicAttach()");

KnLog(KnLogNotice, "SAMPLE_FILTER: Parameters = %s", filterParams.c_str());

KnLog(KnLogNotice, "SAMPLE_FILTER: Uri = %s", uri.c_str());

 

// Do not allow the filter to modify events as they pass through

transform = false;

 

return KnErrorSuccess;

}

 

 

Sample Implementation of KnFilterRouteAttach

 

KN_EXPORT KnError KnFilterRouteAttach(const KnString &filterParams, const KnString &source, const KnString &dest, bool &transform)

{

KnLog(KnLogNotice, "SAMPLE_FILTER: KnFilterRouteAttach()");

KnLog(KnLogNotice, "SAMPLE_FILTER: Parameters = %s", filterParams.c_str());

KnLog(KnLogNotice, "SAMPLE_FILTER: Source Uri = %s", source.c_str());

KnLog(KnLogNotice, "SAMPLE_FILTER: Destination Uri = %s", dest.c_str());

 

// Allow the filter to modify events as they pass through

transform = true;

 

return KnErrorSuccess;

}

Detaching Filters

The KnFilterTopicDetach function is called whenever a filter is removed from a topic. KnFilterRouteDetach is called when a filter is detached from a route. Your implementation should clean up any per-attachment resources that may have been allocated.

 

Your KnFilterTopicDetach or the KnFilterRouteDetach implementation must be threadsafe.

This sample implementation of KnFilterTopicDetach simply logs the passed parameters and the URI before returning.

Sample Implementation of KnFilterTopicDetach

 

KN_EXPORT KnError KnFilterTopicDetach(const KnString &filterParams, const KnString &uri)

{

KnLog(KnLogNotice, "SAMPLE_FILTER: KnFilterTopicDetach()");

KnLog(KnLogNotice, "SAMPLE_FILTER: Parameters = %s", filterParams.c_str());

KnLog(KnLogNotice, "SAMPLE_FILTER: Uri = %s", uri.c_str());

 

return KnErrorSuccess;

}

 

 

 

Sample Implementation of KnFilterRouteDetach

 

KN_EXPORT KnError KnFilterRouteDetach(const KnString &filterParams, const KnString &source, const KnString &dest)

{

KnLog(KnLogNotice, "SAMPLE_FILTER: KnFilterRouteDetach()");

KnLog(KnLogNotice, "SAMPLE_FILTER: Parameters = %s", filterParams.c_str());

KnLog(KnLogNotice, "SAMPLE_FILTER: Source Uri = %s", source.c_str());

KnLog(KnLogNotice, "SAMPLE_FILTER: Destination Uri = %s", dest.c_str());

 

return KnErrorSuccess;

}

Event Filtering

Your filter plug-in's KnFilterTopicEvent function is invoked by the Event Router whenever an event is being published to a topic. KnFilterRouteEvent is called when traversing a route to which the filter is attached. The KnFilterTopicEvent or the KnFilterRouteEvent callback is passed using the following arguments:

·         URL of the topic for topic filters; for route filters, there is a source and destination URL.

·         Event as a KnApiEvent object.

·         Any parameters associated with this attachment.

·         A discard flag you can set to true (1) if you want the Event Router the throw the event away.

 

Your See KnFilterTopicEvent/See KnFilterRouteEvent implementation must be threadsafe. Since See KnFilterTopicEvent/See KnFilterRouteEvent can be called simultaneously from multiple threads, make sure locks are used to serialize access to any shared data.

Your implementation of the See KnFilterTopicEvent/See KnFilterRouteEvent function can:

·         Examine the headers and values in the event and even modify the contents (if the filter was attached as a transform filter).

·         Use the KnEventPost function to send the event to another topic on the Event Router or to URI anywhere on the internet.

·         Completely block the event by setting the discard flag to true.

This sample implementation of KnFilterTopicEvent simply logs the passed parameters, the URI, and the event contents. It then sets the discard flag to true and returns.

Sample Implementation of KnFilterTopicEvent

 

KN_EXPORT KnError KnFilterTopicEvent(const KnString &filterParams, const KnString &uri, KnApiEvent &event, bool &discard)

{

KnLog(KnLogNotice, "SAMPLE_FILTER: KnFilterTopicEvent()");

KnLog(KnLogNotice, "SAMPLE_FILTER: Parameters = %s", filterParams.c_str());

KnLog(KnLogNotice, "SAMPLE_FILTER: Uri = %s", uri.c_str());

 

// Print the contents of the event to the log file.

KnLog(KnLogNotice, "SAMPLE_FILTER: Event kn_id: %s", event.getKnId().c_str());

KnLog(KnLogNotice, "SAMPLE_FILTER: Event kn_time_t: %s", event.getKnTimeT().c_str());

KnLog(KnLogNotice, "SAMPLE_FILTER: Event kn_expires: %s", event.getKnExpires().c_str());

KnLog(KnLogNotice, "SAMPLE_FILTER: Event kn_payload: %s", event.getKnPayload().c_str());

KnLog(KnLogNotice, "SAMPLE_FILTER: Event kn_route_id: %s", event.getKnRouteId().c_str());

KnLog(KnLogNotice, "SAMPLE_FILTER: Event kn_to: %s", event.getKnTo().c_str());

KnLog(KnLogNotice, "SAMPLE_FILTER: Event kn_from: %s", event.getKnFrom().c_str());

KnLog(KnLogNotice, "SAMPLE_FILTER: Event kn_route_location: %s", event.getKnRouteLocation().c_str());

KnLog(KnLogNotice, "SAMPLE_FILTER: Event expiration time: %u", event.getExpirationTime());

 

 

// Tell the router to keep the event for its intended destination

//

discard = false;

 

 

return KnErrorSuccess;

}

 

Sample Implementation of KnFilterRouteEvent

 

KN_EXPORT KnError KnFilterRouteEvent(const KnString &filterParams, const KnString &source, const KnString &dest, KnApiEvent &event, bool &discard)

{

KnLog(KnLogNotice, "SAMPLE_FILTER: KnFilterRouteEvent()");

KnLog(KnLogNotice, "SAMPLE_FILTER: Parameters = %s", filterParams.c_str());

KnLog(KnLogNotice, "SAMPLE_FILTER: Source Uri = %s", source.c_str());

KnLog(KnLogNotice, "SAMPLE_FILTER: Destination Uri = %s", dest.c_str());

 

// Print the contents of the event to the log file.

KnLog(KnLogNotice, "SAMPLE_FILTER: Event kn_id: %s", event.getKnId().c_str());

KnLog(KnLogNotice, "SAMPLE_FILTER: Event kn_time_t: %s", event.getKnTimeT().c_str());

KnLog(KnLogNotice, "SAMPLE_FILTER: Event kn_expires: %s", event.getKnExpires().c_str());

KnLog(KnLogNotice, "SAMPLE_FILTER: Event kn_payload: %s", event.getKnPayload().c_str());

KnLog(KnLogNotice, "SAMPLE_FILTER: Event kn_route_id: %s", event.getKnRouteId().c_str());

KnLog(KnLogNotice, "SAMPLE_FILTER: Event kn_to: %s", event.getKnTo().c_str());

KnLog(KnLogNotice, "SAMPLE_FILTER: Event kn_from: %s", event.getKnFrom().c_str());

KnLog(KnLogNotice, "SAMPLE_FILTER: Event kn_route_location: %s", event.getKnRouteLocation().c_str());

KnLog(KnLogNotice, "SAMPLE_FILTER: Event expiration time: %u", event.getExpirationTime());

 

 

// Tell the router to keep the event for its intended destination

//

discard = false;

        

 

return KnErrorSuccess;

}

Filter Naming Conventions

Each filter plug-in is named with a topic name under the /kn_filters topic. For example, an XSLT filter might be named /kn_filters/xslt. Since filters are named with topics, client applications can traverse the
/kn_filters/kn_filters hierarchy to determine the list of installed filters on a particular Event Router.

Configuring Filter Modules

For each Event Router filter you plan to make available to client applications, you must add an entry like the following to the nskn section of the Event Router's configuration file.

ns_param filter_module "${bindir}/sample_filter${ext}=/kn_filters/sample_filter"

 

Attaching and Detaching Filters

For information on the client application APIs for attaching filters, refer to the language guide that is appropriate for your client application:

·         C Microserver for Solaris Programmer's Guide

·         Microserver for Java Programmer's Guide

·         Chapters 6 and 7 of the Event Router Programmer's Guide

·         C Microserver for Solaris Programmer's Guide

Adding Authorization and Authentication

 

This section describes how you can create and use your own Event Router modules that provide authorization or authentication for all Event Router requests. This section covers the following topics:

·         Understanding Security

·         Understanding the Security API

·         Configuring the Security Module

·         Authorization Module

Understanding Security

The Event Router allows you to create security modules that provide user authentication or authorization. Authentication modules check the credentials supplied with a request, such as a user name and password, to validate a user. Authorization modules check the credentials supplied with a request to determine if access should be granted to a particular URL on the Event Router.

The security modules you create must be packaged as shared objects or DLLs, using the C++ API described in this chapter and in Event Router Module API.

 

Only one authentication module and only one authorization module can be configured for a given Event Router.

Prior to starting the Event Router, the Router's configuration file must be modified to define the security modules you wish the Router to use. The configuration file entries also specify parameters that you may wish to pass to the module, described later in this chapter

Understanding the Security API

The Event Router communicates with your security modules using well-defined callback functions for start-up and shutdown. Authorization and authentication modules must implement these callback functions. For more information on the module API, see Event Router Module API.

Start-up Processing

When your authorization module is initialized at startup time, the Event Router will invoke your module's KnModuleStart function.

As part of the initialization, the KnModuleStart implementation may do any necessary housekeeping, including connecting to an external system such as LDAP or RSA's SecurID®.

An authorization module will implement the KnModuleStart so that the KnSetRequestAuthorizeProc function is invoked to register the correct authorization function with the Event Router. The Event Router will pass control to the registered authorization function any time a request is received.

Authorization module's implementation of KnModuleStart

 

KN_EXPORT KnError KnModuleStart(

const KnString &path, const KnSet &serverInfo)

{

// get passwd file location from config

if (parseConfig(serverInfo) == KnErrorFailure)

return KnErrorFailure;

 

// parse passwd file

if (parsePermsFile() == KnErrorFailure)

return KnErrorFailure;

 

// register as the authorization procedure

if (KnSetRequestAuthorizeProc(authorizeProc) ==

KnErrorFailure)

return KnErrorFailure;

return KnErrorSuccess;

}

An authentication module will implement KnModuleStart so that the KnSetRequestAuthenticateProc function is invoked to register the correct authentication function with the Event Router.

 

The Event Router will not invoke the registered authentication function directly. Instead, the authentication function must be invoked by the Authorization module. Though the samples shown use two separate modules, you are not required to de-couple the authorization and authentication functions: You can design a single Authorization module to provide both functions.

Authentication module's implementation of KnModuleStart

 

KN_EXPORT KnError KnModuleStart(

const KnString &path, const KnSet &serverInfo)

{

// get passwd file location from config

if (parseConfig(serverInfo) == KnErrorFailure)

return KnErrorFailure;

 

// parse passwd file

if (parsePasswordFile() == KnErrorFailure)

return KnErrorFailure;

 

// register as the authentication procedure

if (KnSetUserAuthenticateProc(UserAuthProc) ==

KnErrorFailure)

return KnErrorFailure;

return KnErrorSuccess;

}

Upon completion, your module's KnModuleStart implementation should return an indication of the overall success or failure of the initialization processing. On a failure indication, the Event Router ignores the module from that point on.

Shutdown Processing

When the Event Router is shutting down, your module's KnModuleStop function will be called. Your module's implementation of this function should provide any necessary clean-up processing, such as disconnecting from any external system and freeing any resources that may have been allocated.

Understanding Request Authorization and Authentication

As the Event Router processes requests it receives, it passes control to the authorization function that was registered by your. In keeping with standard HTTP authentication conventions, control is passed to your registered authorization function before the Event Router has begun processing the request. The authorization function is given access to the unprocessed HTTP request in its entirety.

An authorization function is expected to return one of the following values:

·         KnErrorSuccess - access to the resource is allowed.

·         KnErrorUnauthorized - access to the resource cannot be granted because the supplied credentials are incomplete.

·         KnErrorForbidden - access to the resource is denied

Though the sample implementation shown in Sample implementation of an authorization function obtains password and permission information from static text files on a local file system, a module could obtain information from the Event Router's configuration file, HTTP request line parameters, cookies, or other sources.

 

The authorization callback is responsible for invoking the KnAuthenticateUser function. This will invoke the authentication callback registered by the authentication module.

Sample implementation of an authorization function

 

KnError authorizeProc(

const KnRequest &req, const KnSet &headers, const KnSet &parameters);

{

const KnString *denyString = 0;

const KnString *allowString = 0;

 

searchKeys(denyUser, req.url, &denyString);

searchKeys(allowUser, req.url, &allowString);

 

// We found no authorization entries for this url.

// Go forth and route!

if ((denyString == 0) && (allowString == 0))

return KnErrorSuccess;

 

// We have auth data, did the user supply a username?

// If no username, let the browser popup an auth window.

if (req.authUser.length() == 0)

return KnErrorUnauthorized;

 

// spit out debug info if we're in debug mode.

KnLog(KnLogDebug, "knauthorize: user %s attempts access ...

 

// If user's password is incorrect, return UNAUTHORIZED

// Call the authentication function to check password

if (KnAuthenticateUser(req.authUser, req.authPasswd)

== KnErrorFailure)

return KnErrorUnauthorized;

 

// is this user explicitly in the deny list?

if ((denyString != 0) &&

(searchUserList(denyString, req.authUser)))

return KnErrorForbidden;

 

// is this user in the allow list?

if ((allowString != 0) &&

(searchUserList(allowString, req.authUser)))

return KnErrorSuccess;

 

return KnErrorForbidden;

}

Configuring the Security Module

This section describes how you can set up the Authorization module and also describes different scenarios in which the Authorization module is invoked.

Authorization Module

The Authorization module is called every time an application publishes data to the Event Router and also when an event traverses a route between two topics and on subscription requests.

To use the default Authorization module, make sure you use a text editor to uncomment the following lines in the knrouter.conf file and verify the setup of the authorization file:

#

# Load Authorization module?

ns_param authorization_module "${bindir}/knauthorize${ext}"

After you have uncommented the above lines, ensure that the following settings are uncommented and point to the correct files:

# Authorization module settings

ns_section "ns/server/${servername}/module/knauthorize"

ns_param permsFilePath "${homedir}/conf/perms"

To use the default Authorization module, you will also need to uncomment the Authentication module. See below:

#

# Load Authentication module?

# ns_param authentication_module "${bindir}/knauthenticate${ext}"

 

# Authentication module settings

ns_section "ns/server/${servername}/module/knauthenticate"

ns_param passwordFilePath "${homedir}/conf/passwd"

Authorization Module Scenarios

The illustration below shows how the Authorization module is invoked using an example with an Event Router and two applications.

Using the above picture as an example, you see that:

·         Scenario #1: Application B creates a route from Topic X to Topic Y. The Authorization module in this instance is invoked to ensure that Application B can subscribe to Topic X and write to Topic Y.

·         Scenario #2: Application A publishes an event to Topic A and the Authorization module is called to ensure that the user can publish data to Topic A.

·         Scenario #3: Application A publishes an event to Topic X. In this scenario, the Authorization module is called before the event is placed in Topic X and also when the event traverses the route from Topic X to Topic Y. The credentials used event traversal are different:

·         Initial Route Population (IRP): Application B may have requested to receive existing events in Topic X (with do_max_n and do_max_age). Each event is passed through the Authorization module using Application B's credentials to write to Topic Y.

·         Posts to Topic X (after IRP is complete): Application A POSTs an event to Topic X. This causes the Router to attempt to deliver the event to Topic Y. In this scenario, Application A's credentials are used when placing the event in Topic Y.

 

Additionally, the Authorization module is also called when the Router generates status events and places them into the subscriber's journal.

API

KNError authorizeProc(const KnRequest &req, const KnSet &headers, const KnSet &parameters);

where KnRequest is:

struct KnRequest

{

KnString line;             /* request line sent by the client */

KnString method;           /* method requested by the client */

KnString protocol;         /* protocol part of URL or empty */

KnString host;             /* host part of URL or empty */

uint16_t port;             /* port specified in url, or 0 */

KnString srcUrl;           /* url where the request came from */

KnString dsturl;           /* normalized url, without any query data */

KnString query;            /* any query data appended to url */

KnString peer;             /* ip address of the client */

double version;            /* version of the client request */

KnString authUser;         /* decoded user name */

KnString authPasswd;       /* decoded user password */

size_t contentLength;      /* number of bytes sent by the client */

};

Refer to knset.h in the include directory for the definition of knset.h.

 

The headers variable contains the http headers (as key-value pairs) sent in the request. The parameters variable contains all the user supplied parameters sent in the request (i.e. kn_to =/kn/foo) as key-value pairs.

 

Authorization Module Operations

The Authorization Module is called to validate that you have rights to GET or POST to the Event Router. The dstUrl is set to "/kn" or to the value of the "url" specified in the nskn section of the Router's knrouter.conf file. The Authorization Module is also called every time an event is copied from one topic to another (traversing routes) and for every status event that is generated and written to your journal.

If the initial authorization passes, then the Router invokes the module again and specifies one of the following methods in the KnRequest argument:

·         notify

·         route

·         topic

Notify

The following calls and parameters are used when an event is published to the Event Router using POST and "do_method=notify ":

1.      Validate that the publisher can POST to the Router using the parameters:

Parameter

Value

line

"POST/kn HTTP/1.1"

method

"POST"

dstUrl

"/kn"

peer

IP address of the system running the publisher

authUser

user's ID (from the HTTP header)

authPasswd

user's password (from the HTTP header)

2.      Validate that the publisher can POST to the topic. The parameters are the same above, except as noted below:

Parameter

Value

method

"notify"

dstUrl

Reference to the topic, for example, "/kn/what/test"

If you POST an event to "/kn/what/test," but you do not have privileges to create "/kn/what/" but can create "/kn/what/test," then the Event Router will implicitly create "/kn/what." The Authorization Module will NOT be called when the topic "/kn/what " is created.

The following do_method commands will cause the authentication module to be invoked the " notify " method.

·         add_notify

·         clear_topic

·         delete_notify

·         notify

·         update_notify

For more information on these do_methods, refer to Available do_method settings.

Route

For an application to subscribe to a topic in the Router, a route from the source topic to the destination (could be the user's journal or another topic on this Router, or a URI) must be created.

This route is created in the kn_routes directory under the source topic. For example, if the application subscribes to "/kn/what/test," then the subtopic "/kn/what/test/kn_routes" will store the route that contains the details of this subscription.

The Authorization Module is invoked:

1.      To verify that you can POST to the Event Router. Similar to "notify."
2.      To verify that you can read from the source topic and write to the destination topic. The parameters in the request to the Authorization Module are set to the same values as in "notify", but for the following exceptions:

Parameter

Value

method

"route"

srcUrl

topic, for example, "/kn/what/test"

dstUrl

destination topic (could be kn_journal)

The following do_mthod commands will cause the Authorization module to be invoked using the "route " method:

·         add_route

·         delete_route

·         route

·         update_route

For more information on these do_methods, refer to Available do_method settings.

Topic

The "topic" operation includes the following do_method commands:

·         add_topic

·         delete_topic

·         set_topic_property

For more information on these do_methods, refer to Available do_method settings.

The Authorization Module is called,

·         Firstly, to verify if you can POST to the "/kn " topic, i.e. can you post to the Router. The parameters in this request are the same as in "notify".

·         Secondly, to verify the actual topic operation. The parameters are the same as in "notify ", except that:

dstUrl = is the topic that is being manipulated. For example, "/kn/what/test"

Other do_method Operations

The Authorization Module is invoked once for the following requests:

do_method

Preferred HTTP Method

Description

batch

POST

Sends multiple route requests, notify requests, or some of each type. Each request is contained in its own kn_batch parameter.

Generates a status event for the batch request itself, as well as a status event for each request contained in the batch.

 

 

 

blank

POST

Returns an empty HTML document with a JavaScript callback. Essential for enforcing the JavaScript same-domain security policy. This is useful because JavaScript access to about:blank is sometimes restricted.

help

GET

Returns a help document.

lib

GET

Returns the JavaScript Microserver library and includes the results of whoami.

This service is typically referenced near the beginning of an HTML page to make the page into an interactive web application.

noop

GET

Returns HTTP response 200 OK, with no content. This can be used to verify that the Router is running on a given host/port/path -prefix while consuming minimal resources.

whoami

GET

Returns JavaScript to set router- and session-specific window string properties. All returned string properties are optional and UTF-8 encoded.

Also returns a document.domain setting when the javascript_domain configuration file parameter is set.

Additional HTTP Headers

The Authorization Module is presented with all the HTTP headers that were sent with the requested operation. This allows applications to pass authentication credentials to the Router for use by the Authorization Module (for e.g. cookies).

JavaScript Microserver

The JavaScript Microserver uses status forwarding and batch mode to publish events. These cause the module to be invoked numerous times. The examples on the next few pages show invocations to the module for the following:

·         Subscribe (Subscribe)

·         Publish (Publish)

·         Delete Topic

Subscribe

A subscription request from an application that uses the JavaScript Microserver generates twelve (12) events. The following example shows an HTML page loading the Microserver and subscribing to a topic:

HTML Page (Subscribe)

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmins="http://www.w3.org/1999/xhtml">

<head>

<title>Auth Check: Unsubscribe</title>

<!- - This test checks on the

- ->

<script type="text/javascript" src="/kn/?do_method=lib">

</script>

 

<script type="text/javascript">

<!- -

rid = null;

function do_it()

{

topic = "/auth/check/subscribe";

rid = kn_subscribe(topic, receive_event);

}

 

function receive_event(e)

{

alert("got an event on the subscription");

}

// - ->

</script>

</head>

<body onload="do_it()">

<h1>Authorization check when subscribing</h1>

</body>

</html>

Authorization Calls

Following are various calls to the module when you view the previous page. Error cases have not been shown.

1.      A check by the Router to verify if you have rights to read the HTML file. Request parameters are:

Parameter

Value

line

"GET/AuthSubscribe.html HTTP/1.1"

method

"GET"

dstUrl

"/AuthSubscribe.html"

peer

IP address of the machine viewing this HTML page

2.      A check by the Router to verify if you can download the JavaScript Microserver. Request parameters that are different from #1 are:

Parameter

Value

line

"GET/kn/?do_method=lib HTTP/1.1"

dstUrl

"/kn/"

query

"do_method=lib"

3.      The JavaScript Microserver creates 3 frames; however, two of them are hidden. The first frame invokes the Authorization Module. Request parameters that are different from #1 are:

Parameter

Value

line

"GET /kn?do_method=blank HTTP/1.1"

dstUrl

"/kn/"

query

"do_method=blank"

4.      The JavaScript Microserver now loads the HTML page in the frame. Request parameters different from #1 are:

Parameter

Value

line

"GET /AuthSubscribe.html HTTP/1.1"

dstUrl

"/AuthSubscribe.html"

5.      The JavaScript Microserver creates tunnel connection to the Router to verify that you are allowed to " GET " from the Router. Parameters are:

Parameter

Value

line

"GET/kn?kn_from=http%3A%2Fpolaris.knownow.com% 3A8000%2Fkn%2Fwho%2Fanonymous%2Fs%2F94004593%2Fkn_journal;kn_id=68441626;kn_response_flush=4096;kn_status_from=http%3A%2Fs%2F94004593%2Fkn_journal%2Fkn_status%2F31469676_0 HTTP/1.1"

method

"GET"

dstUrl

"/kn"

query

"kn_from=http%3A%2F%2Fpolaris.knownow.com%3A8000
%2Fkn%2Fwho%2Fanonymous%2Fs%2F94004593%2Fkn_journal;kn_id=68441626;kn_response_flush=4096;kn_status_from=http%3A%2F%2Fpolaris.knownow.com%3A8000%2Fkn%2Fwho%2Fanonymous%2Fs%2F94004593%2Fkn_journal%2Fkn_status%2F31469676_0"

6.      Now the Router will verify if you can tunnel to the journal topic:

Parameter

Value

line

"GET /kn?kn_from=http%3A%2F%%2Fpolaris.knownow.com
%3A8000%2Fkn%2Fwho%2Fanonymous%2Fs%2F94004593%2Fkn_journal;kn_id=68441626;kn_response_flush=4096;kn_status_from=http%3A%2F%2Fpolaris.knownow.com%3A8000%2Fkn%2Fwho%2Fanonymous%2Fs%2F94004593%2Fkn_journal%2Fkn_status%2F31469676_0 HTTP/1.1"

method

"route"

dstUrl

"/kn/who/anonymous/s/94004593/kn_journal"

query

"kn_from=http%3A%2F%2Fpolaris.knownow.com%3A8000
%2Fkn%2Fwho%2Fanonymous%2Fs%2F94004593%2Fkn_journal;kn_id=68441626;kn_response_flush=4096;kn_status_from=http%3A%2F%2Fpolaris.knownow.com%3A8000%2Fkn%2Fwho%2Fanonymous%2Fs%2F94004593%2Fkn_journal%2Fkn_status%2F31469676_0"

7.      The route from the source topic to the destination topic is about to be created due to the kn_subscribe call invoked from HTML. The parameters are:

Parameter

Value

line

"POST /kn HTTP/1.1"

method

"POST"

dstUrl

"/kn"

peer

"10.10.13.9"

contentLength

"858"

8.      This call shows that a status event is being written to the journal. This status event is the result of step 5 and step 6.
 

Parameter

Value

line

"POST /kn HTTP/1.1"

method

"notify"

dstUrl

"/kn/who/anonymous/s/94004593/kn_journal"

peer

"10.10.13.9"

contentLength

"858"

9.      This is the authorization of the creation of the route from the source topic to your journal topic. Parameters different than step 8 are:

Parameter

Value

method

"route"

srcUrl

"/kn/auth/check/subscribe"

dstUrl

"/kn/who/anonymous/s/94004593/kn_journal"

10.  The module is called for every event in the topic that is delivered to the journal, resulting in Initial Route Population.
Publish

The following example shows an HTML page loading the JavaScript Microserver and publishing an event to the Router.

HTML Page (publish)

 

<!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.0 Strict//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title>POST an event in an effort to check out Authentication and Authorization engine of the KN Event Router</title>

<script type="text/javascript" src="/kn/?do_method=lib">

</script>

 

<script type="text/javascript">

<!- -

 

function waiting()

{

alert("setTimeout function called this in waiting module");

 

}

function do_it()

{

var topic = "/what/tests";

myEvent = new Object;

 

myEvent.kn_payload = "This is a auth check";

 

kn_publish(topic, myEvent, ({ onSuccess: function(e)

{alert("success"); succeed()},

onError: function(e)

{alert(e.status + " can't publish

to topic")}

));

}

 

// - ->

</script>

</head>

<body onload="do_it()">

<h1>Sending status event</h1>

</body>

</html>

Authorization Calls

These are the request parameters generated as a result of the "publish" action.

 

Execute steps 1 - 6 and 8 from the Subscribe authorization calls before executing #1 below.

1.      Validates that you can POST to the Router. The parameters are:

Parameter

Value

line

"POST /kn HTTP/1.1"

method

"POST"

dstUrl

"/kn"

peer

IP address of the client

contentLength

"604"

2.      This call is made to verify that the user can write to the topic. The parameters are:

Parameter

Value

line

"POST /kn HTTP/1.1"

method

"notify"

dstUrl

"/kn/what/auth/checks"

peer

IP address of the client

contentLength

"604"

3.      The status event sent to the user's journal due to the "publish" is generated. The parameters are:

Parameter

Value

line

"POST /kn HTTP/1.1"

method

"POST"

dstUrl

"/kn/who/anonymous/s/77850390/kn_journal"

peer

IP address of the client

contentLength

"604"

Delete Topic

These are the request parameters generated as a result of the "Delete Topic" action from the Event Explorer. Note that the initial invocations to verify access to the Router, to the Microserver, and the Microserver's setup are omitted (steps 1-6 and 8):

1.      Validates whether you can POST to the Router. The parameters are:

Parameter

Value

line

"POST /kn HTTP/1.1"

method

"POST"

dstUrl

"/kn"

peer

IP address of the client

2.      Validates whether you can perform a "topic" operation. The parameters are:

Parameter

Value

line

"POST /kn HTTP/1.1"

method

"topic"

dstUrl

"kn/what/test"

peer

IP address of the client

3.      The status event that is posted to the journal:

Parameter

Value

line

"POST /kn HTTP/1.1"

method

"notify"

dstUrl

"/kn/who/jenkins/s/56073163/kn_journal"

peer

IP address of the client

Troubleshooting

Q.   What happens when Topic X is full of events from several sources and a route is created to Topic X to Topic Y with do_max_age or do_max_n specified?

A.   This is referred to as Initial Route Population (IRP), where the creation of a route may involve a delivery of existing events from the source topic to the destination topic.

The Authorization Module is invoked to verify whether the creator of the route is allowed to read from Topic X. Additionally, the module is called for every event as it is read from Topic X and before it is written into Topic Y. At this time, the original publisher's credentials may be invalid (for example, cookie parameters). So for IRP, the route creator's credentials are used. Subsequent writes to Topic X will; however, use the credentials of the event publisher when the topic traverses this route.

Q.  KnowNow uses a special topic "kn_journal" to hold events that need to be delivered to the subscribers. How does the Authorization Module work for this topic?

A.   A journal topic is in essence a URL that is accessible on the Internet. Microservers use the journal topic to communicate between the Router and an application. Accordingly, the Microservers set up a route to the kn_journal topic when an application subscribes to a topic. The Event Router treats the kn_journal topic as just another topic and invokes the Authorization Module for every event traversing the routes to this kn_journal topic.

This functionality is useful for ensuring that you do not create a route from a topic into another user's journal.  

Using the JavaScript Microserver

 

This chapter describes how to use the JavaScript Microserver and contains the following sections:

·         Using the JavaScript Microserver

·         Using the kn Object

·         Publishing Events

·         Subscribing to Topics

·         Unsubcribing

·         Using Status Handlers

·         JavaScript ActiveX Shim

·         Simple Event Mapping Support

·         Writing Cross-Domain Web Applications

Using the JavaScript Microserver

The JavaScript Microserver enables an application running in a web browser to communicate with the Event Router. The JavaScript Microserver is installed when you install Event Router, described in Installing the Event Router.

You use the JavaScript Microserver in your application by including it in your application code as, shown in the following example. The Microserver <script> element must be included at the very beginning of your application, inside the HTML <head> element and before any other <script> elements.

inserting the JavaScript Microserver.

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

  <head>

<meta http-equiv="content-type" content="text/html; charset=utf-8" />

<title>MyApp</title>

<script src="/kn/?do_method=lib" type="text/javascript"></script>

. . .

Understanding the Microserver Frames

Once the JavaScript Microserver is loaded, the page will stop its normal loading process and will be wrapped in a frameset. The frameset contains three frames that enable communication with Event Router:

·         A visible frame where your application is loaded.

·         A hidden post frame for sending requests to the Event Router.

·         A hidden receive frame that receives events over a persistent HTTP connection to the Event Router.

JavaScript Microserver frames.

The JavaScript Microserver uses the top level of the hidden frameset, allowing the Microserver to persist even when frames in your application are reloaded. When your application is loaded in the visible frame of the frameset, the Microserver creates a kn object as a property of the browser window object.

Since your applications will always be contained within a frameset, this may affect the way you construct your DOM (Document Object Model) references to windows, frames, forms, and divs.

 

If you are using Microsoft's Internet Explorer and have installed the ActiveX Microserver for Windows, see JavaScript ActiveX Shim.

Using the kn Object

The kn object, described on kn, provides your application with several methods for publishing events to a topic, subscribing to a topic, and unsubscribing from a topic.

Publishing Events

Your application can use the kn.publish method to publish an event to a topic on the server. This method also gives you the option of providing status handler objects to be invoked after the event is published to handle the status event returned by the Event Router. This invokes the Router's notify method, and allows all parameters allowed by notify.

Your application must construct the event to be published as a JavaScript object and pass it to the kn.publish method. An event is simply a JavaScript object that has event header names as properties and corresponding event header values as property values. When you publish an event, the kn_id of the newly published event is returned.

The following example publishes an event with a user-defined kn_payload with the contents "Hello world!" and a custom property named specialProperty.

Publishing an event with kn.publish .

 

// first create the object...

myEvent = new Object;

 

// then add some data to it...

myEvent.kn_payload = "Hello world!";

myEvent.specialProperty = "extra special value";

 

// finally, publish it.

kn.publish("/my/topic", myEvent);

 

After your application publishes the event, the Event Router would receive an event with the headers shown below. The values set by your application are shown in boldface.

·         kn_time_t: 987107695

·         userid: test

·         kn_id: 26451550

·         kn_route_checkpoint: 987107695_12462_2224

·         specialProperty: extra special value

·         displayname: test

·         kn_payload: Hello world!

Event Identifiers

Since the sample application does not specify the kn_id , a unique identifier is automatically generated, added to the event, and returned as a string for later use by your application.

Saving the kn_id when publishing an event.

 

myEvent = new Object;

myEvent.kn_payload = "Hello world!";

 

eventId = kn.publish("/my/topic", myEvent);

Publishing Form Data

Your application can also use the kn.publishForm method to copy input elements from an HTML form into a new event object and then publish the event to a specified topic.

Subscribing to Topics

Your application can use the kn.subscribe method to subscribe to a topic and then receive events that are published to that topic. Any events published to the subscribed topic will be forwarded to your client and the appropriate destination function, specified by your application, will be invoked. This invokes the Router's route method, and allows all parameters allowed by route.

The kn.subscribe method also gives you the option of defining the maximum number or age of events that should be returned to your application. You may also provide optional status handler objects to be invoked to handle status events returned by the Event Router.

The following example defines an event handler that alerts the user of the kn_payload for each event received and then subscribes to the topic /my/topic.

Defining an event handler and subscribing to a topic.

 

function onMessage(e){

alert(e.kn_payload);

}

 

kn.subscribe("/my/topic", onMessage);

Understanding Destinations

The destination you specify for a subscription can be any of the following:

·         Another topic.

·         A JavaScript URL.

·         A function or closure that accepts the received event as a parameter, as shown above.

·         An object with an onMessage method that accepts the received event as a parameter.

 

Specifying subscription destinations.

 

topic: kn.subscribe("/my/topic", "/postit");

 

javascript URI : kn.subscribe("/my/topic",

"javascript:alert('OK')");

 

function or closure:

kn.subscribe("/my/topic", onMessage);

 

object with onMessage method:

kn.subscribe("/my/topic", { onMessage: function (e) { alert(e.kn_id) } } );

 

Subscription Options

The following properties modify a subscription:

Property

Description

do_max_n = number

Specifies the maximum number of previous events to be received on this subscription.

do_max_age = seconds

Fetches all events published to the topic up to the specified number of seconds before the subscription was opened. Specifying "infinity" will fetch all events in the topic regardless of their timestamp.

The following example shows how to specify options such that a maximum of ten (10) events will be received by the subscription.

Creating and using subscription options.

 

// first create the options object...

options = new Object;

 

// then set a do_max_n

options.do_max_n = 10;

 

// finally, subscribe to the topic and pass the options object

// as an argument

kn.subscribe("/my/topic", onMessage, options);

 

You may find it helpful to use the short form of object notation. Simply put the property:value pairs inside curly braces when you define the object, as shown below:

kn.subscribe("/my/topic", onMessage, { do_max_n:10 })

 

Unsubcribing

When your application no longer wants to receive events from a topic, it must invoke the kn.unsubscribe method, specifying the kn_uri associated with the subscription. You may also provide optional Status Handler Objects to be invoked to handle status events returned by the Event Router.

Unsubscribing from a topic.

 

function onMessage(e){

alert(e.kn_payload);

}

 

anRid = kn.subscribe("/my/topic", onMessage);

 

. . .

 

kn.unsubscribe(anRid);

Using Status Handlers

Your application can use a status handler object to attach functions to status events received from the Event Router. Your application must create an object with three methods and then pass it to the kn.publish, kn.publishForm, kn.subscribe, or kn.unsubscribe method when you are unsubscribing from a topic.

Method Description

·         onSuccess is called every time a request completes successfully.

·         onError is called every time a request fails.

·         onStatus is called whenever any status message is received. If onStatus is defined, onError and onSuccess will not be called.

JavaScript ActiveX Shim

If your have installed the ActiveX Microserver and your web browser supports ActiveX, you can configure your web browser and design your applications to use a JavaScript Microserver Shim instead of the event transport mechanism described in See Understanding the Microserver Frames.

 

The JavaScript Shim can only be used with web browsers that support ActiveX and on machines where the ActiveX Microserver is installed. The ActiveX Microserver is described in the Microserver for Windows Programmer's Guide .

Configuring the Browser

Microsoft Internet Explorer's security setting may be changed using the Internet Options dialog.

1.      Access the Tools pull-down menu and select the Internet Options menu item.
2.      In the Internet Options dialog, shown in Explorer Internet Options dialog, click on the Custom Level button.
3.      Locate the Run ActiveX controls and plug-ins item, shown in Enabling ActiveX controls and plug-ins, and click on Enable.

 

These settings may allow harmful programs to run on your computer, so you may wish to place the application's URL in the special Trusted Sites security zone, and only change the settings for that zone. Consult with your system administrator before making changes which affect your web browser's security settings.

Explorer Internet Options dialog.

Enabling ActiveX controls and plug-ins.

Application Configuration

To use the JavaScript Microserver ActiveX Shim, simply include the script element shown below, before including the JavaScript Microserver.

Including the ActiveX Shim.

 

<!-- KnowNow JavaScript Microserver ActiveX Shim -->

<script type="text/javascript" src="/kn_apps/kn_lib/activex.js"></script>

 

<!-- KnowNow JavaScript Microserver -->

<script type="text/javascript" src="/kn?do_method=lib"></script>

 

Shim API

This shim disables the frameset wrapping normally performed by the JavaScript Microserver. Most applications will not be affected by this change. None of the high-level API of the JavaScript Microserver is affected by the shim, with the following exceptions:

·         Due to a bug in the Internet Explorer JavaScript-ActiveX bridge, NUL characters in received event header names and values are not preserved, and prematurely terminate strings. If the kn_options flag single is present, NUL characters have the same effect in outbound event header names and values.

·         kn__submitRequest uses the ActiveX Microserver and ignores the kn_options flag noforward . The kn_options flag single still has the usual effect.

·         kn__restartTunnel has no effect.

·         Unless the kn_options flag quiet is present, failure to open the tunnel connection will present an informational dialog briefly describing the shim configuration properties, and instructing the user to make any necessary changes and reload the page.

Shim Properties

 

The shim has several properties which you can set using either the command-line parameters or window properties. Window properties must be UTF-8 encoded and set before loading the KnowNow JavaScript Microserver.

Shim Properties.

Property

Description

kn_server

The URI of the KnowNow Event Router to use, such as:
http://servername:8000/kn

kn_activexServerURI

The URI of the KnowNow Event Router to use, including username and password. This defaults to the kn_server value. To access a password-protected Event Router, you must encode the username and password in the URI:
http://uname:pword@srvrname:8000/kn

kn_activexUsername

The username with which to authenticate to the Event Router. (This property is ignored by the ActiveX Microserver).

kn_activexPassword

The password with which to authenticate to the Event Router. (This property is ignored by the ActiveX Microserver).

kn_activexProxy

URI of an HTTP proxy server to use for all accesses to the Event Router.

kn_activexProxyUsername

The username with which to authenticate to the proxy server.

kn_activexProxyPassword

The password with which to authenticate to the proxy server.

Simple Event Mapping Support

This feature is for developers who wish to move an object from one platform to another. MIME types are used as the typing scheme, and it is recommended that users serialize their objects into an appropriate MIME type.

The Simple Event Mapping Support feature provides support for applications to map inbound events (coming in from subscriptions the applications have made) into objects/data types. It also allows applications to map objects, which they are attempting to publish, into events.

The mapping does not happen automatically. The application registers certain callbacks with the Microserver, requesting that when an event with a particular header or value inside is received on a particular subscription, the Microserver should call a particular callback to map the event data into an object and then process that object.

The JavaScript Microserver supports plain MIME types ("text/plain," "application/xml", "image/gif", etc.) as well as the RFC-proposed "+xml" extensions for XML-derived content types.

Following is a list of examples (in an order of de-serialization preference):

·         text/x-my-dtd+xml [for XML formats]

·         text/x-my-dtd [for non-XML formats]

·         text/*+xml [for generic XML text handling]

·         text/* [for generic text handling]

·         */*+xml [for generic XML handling]

·         */* [the universal fallback]

The default MIME type of an event is "text/plain".

Mapping Outbound Objects to Events

On the publication side, the programmer will need to implement JavaScript serialization (toString) methods on all objects, then use them as kn_payload values, and specify appropriate MIME types in the content-type header.

Publisher side:

 

kn.publish( "/topic",

{ "content-type": "application/x-js-date",

  kn_payload: new Date });

kn.publish("/topic",

{ "content-type": "application/x-js-window",

  kn_payload: window });

kn.publish( "/topic", {}):

Mapping Inbound Events to Objects

On the subscription side, the programmer will need to register single-string-argument constructor functions corresponding to different MIME types or wildcards, and call kn.filter in event handlers to construct objects corresponding to events.

 

Subscriber side:

 

kn.setFilter("application/x-js-date", Date);

kn.setFilter("application/*", String);

kn.subscribe("/topic",

function (evt) {

var o = kn.filter(evt);

alert("[" + (o ? o.constructor : typeof o) + "] : " + o);

}

);

Writing Cross-Domain Web Applications

Cross-domain web applications are applications where the HTML lives on a standard web server (or is being generated by an application server), but the application wants to embed the KnowNow JavaScript Microserver. The problem that you face is that the JavaScript security model in the browser does not allow the application, which comes from " apps.biz.com", to communicate with the KnowNow Event Router at "kn.biz.com ".

The JavaScript Microserver library offers a built-in option to allow the HTML application and Microserver to sidestep the JavaScript security restrictions imposed by the browser, thus making your application a cross-domain application.

To create a cross-domain web application, you must have the following:

·         an intermediate level of knowledge of JavaScript

·         a knowledge of the basic steps for writing a web application

·         a web application that uses a single protocol, either HTTP or HTTPS

 

To run your application in Netscape 4, both servers must use the default port, either HTTP on port 80 or HTTPS on port 443. While you must use the default port, you must not specify the port in the URL.

To make your application a cross-domain application, you need to do the following:

1.      Make a small change to your Router's configuration, specially to the "javascript_domain" and "javascript_kn_server" parameters. For more information on modifying these parameters, refer to Router Configuration Changes.
2.      Modify your application code to request the JavaScript Microserver using the URL of the Router. For more information on modifying the application code, refer to Modifying the Application Code.

 

Router Configuration Changes

To enable cross-domain communication between your application and the Router, you must modify the javascript_domain and javascript_kn_server parameters in the Router's knrouter.conf file. You can modify the Router's configuration either by opening the knrouter.conf file in a text editor or by using the Event Router Configuration Utility packaged with the Router. For more information on using the Configuration Utility, please refer to the KnowNow Event Router Getting Started Guide.

javascript_domain Parameter

The Microserver uses the javascript_domain parameter to set the document.domain property, which signals to the browser that the Router is part of the same security domain as the HTML pages (loaded from the application server).

Set the javascript_domain parameter to the common suffix of the application server and Router domain names, or, if you are using a single IP address (see Using a Single IP Address), use the domain or machine name. This parameter must be entirely in lowercase:

ns_param javascript_domain "biz.com"

javascript_kn_server Parameter

The Microserver uses the javascript_kn_server parameter to determine the full URL for the Router's root event notification topic.

Set the javascript_kn_server parameter to the fully-qualified domain name for the Router followed by the kn_server pathname, "/kn ". If you are using a single IP address, use the domain or machine name and the portnumber (see Using a Single IP Address). This domain name must be identical to the one specified in the src attribute of the application's script tag, for example:

ns_param javascript_kn_server "http:\\kn.biz.com/kn"

 

 

It is important that you do not include a closing slash at the end of the kn_server pathname or any double slashes (other than the one following the "http:") when modifying the javascript_kn_server parameter because the value of kn_server is also used to resolve topic names.

Once you have finished modifying the knrouter.conf file, you must re-start the Router.

Modifying the Application Code

Let us assume that the Router is hosted at kn.biz.com, and the pages that make up the application are being served from apps.biz.com. The src attribute of the <script> tag should contain the URL of the Router location including fully-qualified domain name. This ensures that the Microserver library is loaded at the correct location.

<html>

<head>

<title>My KnowNow Application</title>

<script type="text/javascript"

src+"http://kn.biz.com/kn/?do_method=lib"></script>

</head>

 

Use the fully-qualified domain name corresponding to the IP address of the Router to avoid JavaScript security issues. Also, the domain name must be entirely in lowercase.

 

 

A cross-domain web application that uses document.open() may produce errors due to the browser's security limitations.

HTML Pages Not Using the Microserver

An application may contain HTML pages that do not use the Microserver functionality but need scripting access to the other pages. For example, an application may use JavaScript across frames and framesets. These pages should contain a script tag that calls the do_method=whoami action of the KnowNow Event Router. This way, the browser will allow any JavaScript within these pages to interact with the other pages of the application.

<script type="text/javascript"

src="http://kn.biz.com/kn/?do_method=whoami"></script>

Alternatively, you can add a script tag to your application code that sets the document.domain property to the common suffix of the application and the Router host domain names.

Using a Single IP Address

You can have the application server and the Router on the same IP address, for example, with the application server using port 80, and the Router using port 8000.

 

You cannot run a cross-domain application on a single IP address if you want to support Netscape 4.x because Netscape 4.x requires both the application server and the Router to use HTTP on port 80 or HTTPS on port 443.

The src attribute of the <script> tag should contain the URL of the Router, including fully-qualified domain name and portnumber. If you are not part of a domain, use the fully-qualified machine name instead.

<html>

<head>

<title>My KnowNow Application</title>

<script type="text/javascript"

src="http://kn.biz.com:8000/kn/?do_method=lib"></script>

</head>

JavaScript API

This section provides a quick reference to the JavaScript Microserver as well as the associated variables, properties, and objects. This section includes the following:

·         self

·         kn

·         KN

·         Status Handler Objects

·         String and Character Support

·         Using Command-Line Parameters

self

self refers to a Window, FRAME, or IFRAME object, where the JavaScript Microserver is active.

 

Properties

kn_appFrameAttributes

string

optional

set in UTF-8 before including the Microserver library

The value supplied with this property is inserted into the main application's <frame> tag. If you do not want scroll bars, for example, set it as follows:

noresize="noresize" scrolling="no"

kn_argv

object

The global argument object, initialized when the Microserver library is loaded.

kn_blank

string

Holds the URI of a blank page which can be used in your application as the initial source for a frame in a frameset. It is in the same JavaScript browser security domain as the kn_server URL and provides kn_redrawCallback.

kn_defaultOptions

string

optional

set in UTF-8 before including the Microserver library

Lists all of the options that will be enabled in the same format as used by kn_options, which overrides it.

kn_displayname

string

optional

set in UTF-8 before including the Microserver library

Describes the user identified by kn_userid in human-readable format. This may be a value supplied by the Event Router, a value given for the kn_displayname command-line argument, or a default value such as Guest User or Anonymous User.

kn_hashCache

string

optional

set in UTF-8 before including the Microserver library

Serialization of initial event hash cache contents, loaded by the Microserver at startup using kn.setHashCache().

kn_lang

string

optional

set in UTF-8 before including the Microserver library

A comma-separated list of language codes and optional quality values used when looking up localized messages; the default is the empty string (""), which disables localization. This is copied from the Accept-Language HTTP header by the Event Router. The following specification would indicate a preference for all types of Chinese, but an acceptance of U.S. English or other types of English when Chinese is unavailable.

zh, en-us;q=0.9, en;q=0.6 .

kn_lastTag_

string

optional

set in UTF-8 before including the Microserver library

Initial value for kn.lastTag, the do_since_checkpoint value for the tunnel route.

kn_maxHits

integer

The number of events allowed before a tunnel restart is performed. Used to tune memory consumption in older web browsers.

kn_queryString

string

optional

set in UTF-8 before including the Microserver library

Used in place of the URL query string, overriding the portion of the URL following the question mark.

kn_response_flush

integer

Controls the number of filler bytes (from 0 to 4,095) sent when the Router detects a lull in the event stream for a particular tunnel connection.

The number of filler bytes is configurable using the kn_response_flush request parameter. If no value is supplied, the number of bytes is determined automatically. The JavaScript Microserver allows this parameter to be set before loading the Microserver by storing the value in the kn_response_flush property of the self object. See also, Parameters for kn_response_format.

kn_server

string

optional

set in UTF-8 before including the Microserver library

The URI of the Event Router to use; this URI must not end in the slash character ("/"). By default, kn_server contains the URI of the Event Router that supplied the JavaScript Microserver. That is, the server which satisfied the request for the do_method=lib script.

kn_strings

object

Contains localized versions of messages indexed by language code, then context, then original message. Use the kn_localize() and kn_localizeDefault() methods to define this table; use the kn_createContext() method to define new localization contexts, and use the $$() and $$_() methods or contextual specializations (such as $() and $-() for the default context) to use localized strings in your JavaScript program.

kn_tunneIID

string

optional

set in UTF-8 before including the Microserver library

Initial value for kn.tunnelID, the tunnel route kn_id.

kn_tunnelMaxAge

string

optional

set in UTF-8 before including the Microserver library

Initial value for kn.tunnelMaxAge, the do_max_age value for the tunnel route.

kn_tunnelURI

string

optional

set in UTF-8 before including the Microserver library

Initial value for kn.tunnelURI, the tunnel route source topic URI.

kn_userid

string

optional

set in UTF-8 before including the Microserver library

Identifies the user in the context of the web application. This may be a value supplied by the Event Router, a value given for the kn_userid command-line argument, or a default value such as guest or anonymous.

 

Methods

$$

Usage

$$ ("ctx", "original" )

Description

Marks a string for possible localization in context ctx .

Arguments

ctx is the localization context

original is the string to be localized.

Returns

Returns a translation of the string or, if no localized version has been supplied, the original string.

$$_

Usage

$$_ ("ctx", "original", args...)

Description

Shorthand for formatting using a localized template in context ctx . Equivalent to:

kn_formatString($$( "ctx", "original" ), [ args... ] )

Arguments

ctx is the localization context.

original is the string to be localized.

args are optional arguments.

Returns

The arguments formatted using a translation of the string or, if no localized version has been supplied, the original string.

kn_ _debug

Usage

kn_ _debug(flag)

Description

This function checks for the presence of a particular word in the comma-separated
kn_debug=... value.

The special flag all causes true to be returned for all flags.

If flag is not specified, this function checks for the presence of the kn_debug parameter.

Arguments

flag is the list of comma-separated values.

Returns

true if the flag is present. Otherwise, false is returned.

kn_charCodesFromString

Usage

kn_charCodesFromString(string)

Description

Given a UTF-16 string, returns an array containing the corresponding UCS character codes.

Arguments

string is the input UTF-16 string.

Returns

An array of corresponding UCS character codes.

kn_ _consumeEvents()

Usage

kn_consumeEvents()

Description

Handle dispatches from the leader.

Arguments

 

kn_createContext

Usage

kn_createContext("ctx" )

Description

Creates helper functions for localization context "ctx". The functions created are:

ctx$ ("original" ), equivalent to $$ ("ctx", "original" )

and

ctx $_ ("original" , " args "...), equivalent to $$_( "ctx", "original" , " args "...). Helper methods for the default localization context. These default methods are: $("original" ), equivalent to $$("", "original" ) and $_ ("original") , args...), equivalent to $$_("", "original" , args...).

Arguments

ctx is the localization context.

kn_debug

Usage

kn_debug(flags)

Description

Changes the value of the kn_debug=... parameter to the value specified in flags.

Arguments

flag is set as follows:

An omitted value or true enables general debugging.
An empty string or false disables all debugging.
Any other string enables general debugging and is treated as a comma-separated list of specific debugging options to be enabled.

Note that the special debugging option all enables all debugging.

kn_defaultOnError

Usage

kn_defaultOnError(e)

Description

Default status handler for an unsuccessful event.

Arguments

e is the status event.

kn_defaultOnStatus

Usage

kn_defaultOnStatus(e, handler)

Description

Default status handler for handling the status event e. If handler is omitted, the status handler object is assumed to be this .

Arguments

e is the status event.

handler is an optional status-handler object to invoke.

kn_defaultOnSuccess

Usage

kn_defaultOnSuccess(e)

Description

Default status handler for successful status events. Returns without doing anything.

Arguments

e is the status event.

kn_doStatus

Usage

kn_doStatus(e, handler)

Description

Invokes status handlers for the status event e.

Arguments

e is the status event.

handler is an optional handler to invoke. If omitted, the default handlers are invoked.

kn_encodeRequest

Usage

kn_encodeRequest(e)

Description

Returns the application/x-www-form-urlencoded string for the router request e.

Arguments

e is the router request to be encoded.

kn_escape

Usage

kn_escape(string)

Description

Returns an escaped version of string suitable for inclusion in a URL.

Handles all UCS and Unicode characters for which UTF-16 representations exist and produces a URL-encoded UTF-8 representation which is portable across web browser platforms.

Arguments

string is the string to be converted.

kn_formatString

Usage

kn_formatString(string , object)

Description

Interpolates properties of an object into a string in place of %{names}. Returns a copy of strings with interpolated property values from object.

Use %% to include a literal %. Names cannot include the } character.

For example:

kn_formatString ("%{name} seeks %{goal}", {

                    name: 'Nomad', goal: 'perfection'})

returns the string

                Nomad seeks perfection
Arguments

string is the formatting string.

object is an object whose properties will be interpolated into the result based on string.

kn_htmlEscape

Usage

kn_htmlEscape(string)

Description

Returns an HTML/XML-style escaped copy of a string with unsafe characters encoded as named or numeric character references.

For characters outside the Unicode or UCS Basic Multilingual Plane, the UTF-16 surrogate pairs are decoded in the string to produce single UCS numeric character references in the escaped copy.

Arguments

string is the string to be converted.

kn_inspectAsHTML

Usage

kn_inspectAsHTML(object, depth)

Description

Returns an HTML representation of object recursive to the specified path.

Arguments

object is the object to be inspected.

depth is a numeric maximum depth.

kn_inspectAsText

Usage

kn_inspectAsText(object, depth)

Description

Returns a textual representation of object recursive to the specified path.

Arguments

object is the object to be inspected.

depth is a numeric maximum depth.

kn_inspectInWindow

Usage

kn_inspectInWindow(object, depth)

Description

Opens a pop-up window and uses document.write() to fill the window with an HTML representation of object recursive to the specified path.

Arguments

object is the object to be inspected.

depth is a numeric maximum depth.

kn_isReady(w)

Usage

kn_isReady(w)

Description

Returns true if the window w is open and ready to use. Otherwise, returns false.

Arguments

w is the window to test.

kn_localize

Usage

kn_localize(language, "ctx" , "original" , translation)

Description

Adds an entry to kn_strings containing a translation of the original message "original" using the context "ctx" into the specified language. If translation is null, the original message is used instead.

Arguments

language is language into which "original" is translated.

ctx is localization context name.

original is the original message.

translation is the translated message.

kn_localizeDefault

Usage

kn_localizeDefault(language, "ctx" , "original" , translation)

Description

Behaves exactly like kn_localize, except that it does not override existing message translations.

Arguments

language is language into which "original" is translated.

ctx is localization context name.

original is the original message.

translation is the translated message.

kn_ _object()

Usage

kn_ _object(args…)

Description

This function creates an object from a list of names and values.

Arguments

args are optional arguments.

Returns

 

kn_options

Usage

kn_options(flags)

Description

Changes the value of the kn_options=... parameter to the value specified by flags.

Arguments

flags is one of the following new values for kn_options:

An omitted value or true enables general speed options.

An empty string or false disables all speed options.

Any other string enables general speed options and is treated as a comma-separated list of specific speed options to enable.

The special option "all" enables all speed options.

kn_ _options(flag)

Usage

kn_ _options(flag)

Description

This function checks for the presence of a particular word in the comma-separated kn_options=... value.

The special flag =all causes true to be returned for all flags.

If flag is not specified, this function checks for the presence of the kn_options parameter.kn_options

Arguments

flag is the list of comma-separated values.

Returns

true if the flag is present. Otherwise, false is returned.

kn_publish

See kn.publish.

kn_publishForm

See kn.publishForm.

kn_redrawCallback

Usage

kn_redrawCallback(w)

Description

Called from kn_blank and used for kn.documents and KNDocument.

Arguments

w is the Window in which the kn_blank page is loading.

kn_resolvePath

Usage

kn_resolvePath(base, relative)

Description

Returns an absolute path name identifying the same resource named by the relative path name, resolved relative to the specified base path name.

Arguments

base is the base path name.

relative is a path name to resolve relative to base.

Returns

The absolute path.

kn_sendCallback

Usage

kn_sendCallback(theEvent [,theWindow])

Description

Accepts an event in form style and converts it to a simple object, then dispatches it to the appropriate subscriber.

Arguments

theEvent is the event.

theWindow is the Window generating the event.

kn_stringFromCharCode

Usage

kn_stringFromCharCode(codes...)

Description

This function is an implementation of String.fromCharCode for UTF-16 JavaScript implementations.

Note that the returned string may be longer than the list of codes due to UTF-16 surrogate pair encoding.

Arguments

codes is a list of UCS character values.

Returns

The UTF-16 string corresponding to the codes.

kn_ _submitRequest(e)

Usage

kn_ _submitRequest(e)

Description

Submit (or possibly batch) a KN server request.

Arguments

e is the router request to be submitted.

Returns

Returns false until the request has been sent (or at least batched).

kn_subscribe

Usage

kn_subscribe(topic, destination [,options, [status-handlers]])

Description

Subscribes the URL, closure, or object --specified by destination-- to the specified topic.

Arguments

topic is the topic which is being subscribed to.

destination is the URL, closure, or object.

options contains options for the subscription.

status-handlers is an optional handler to invoke for the resulting do_method=route request. If omitted, the default handlers are invoked. See also, Status Handler Objects.

Returns

The route identifier for the new subscription.

kn_tunnelLoadCallback

Usage

kn_tunnelLoadCallback(theWindow)

Description

Triggered by a tunnel frame's onLoad.

Arguments

theWindow is the Window generating the event.

kn_unescape

Usage

kn_unescape(value)

Description

Returns the original string, given an escaped string generated by kn_escape. Reverses the transformation performed by kn_escape in a way that is portable across web browsers.

Arguments

value is the escaped string.

kn_unsubscribe

Usage

kn_unsubscribe(rid [,status-handlers])

Description

Removes a subscription identified by rid, so that events published to that subscription's source topic will no longer be delivered.

Arguments

rid is the subscription's route identifier.

status-handlers is an optional status handler object to invoke. If omitted, the default handlers are invoked. See also, Status Handler Objects.

kn_utf8decode

Usage

kn_utf8decode(encoded )

Description

Given an encoded UTF-8 string, this method returns the corresponding decoded UTF-16 string.

Arguments

encoded is a UTF-8-encoded string to decode.

 

Note: The following optional user-supplied callbacks must be defined in the session leader window before loading the Microserver.

kn_defaultOnMessage(anEvent)

Usage

kn_defaultOnMessage(anEvent)

Description

This callback is invoked each time the Microserver receives an event (anEvent) with an unrecognized or missing kn_route_location value. Supplying this callback disables the Microserver's default automatic subscription behavior.

Arguments

anEvent is an event received by the Microserver.

kn_onTunnelStatus(aStatusEvent)

Usage

kn_onTunnelStatus(aStatusEvent)

Description

This callback is invoked when a tunnel route status event (aStatusEvent) is received.

Arguments

aStatusEvent is the status event generated by the do_method=route request.

kn_onTunnelStop()

Usage

kn_onTunnelStop

Description

This callback is invoked when the tunnel connection closes. This callback is not completely reliable in Netscape browsers.

kn

This object represents a the JavaScript Microserver instance and provides functions for publishing events, establishing subscriptions to topics, and removing established subscriptions. The same kn object usually appears as a property of all frames in a window which access the same Event Router, although programmer customization and complex frameset layout can cause multiple Microserver instances to be created.

Properties

kn.displayname

string

Describes the user identified by kn.userid. This may be a value supplied by the Event Router, a value given for the kn_displayname command-line argument, or a default value such as Guest User or Anonymous User.

kn.documents

object

The redraw string state for managed frames used for client-side content generation and for KNDocument, indexed by the Window name and containing these properties:

·         kn.documents[name].html - the redraw string.

·         kn.documents[name].state - a string describing the state of the managed frame as "drawing" , "loading" , or "ready" .

·         kn.document[name].kn_onLoad() - the function to call when the managed frame has finished reloading.

kn.lastError

object

If debugging is disabled, this property contains information on the most recent error. When an error occurs in a web application using the JavaScript Microserver, the Microserver attempts to suppress the browser's normal error-handling behavior and record the error message in this string. Replacing the onerror handler or supplying the kn_debug command-line argument allows the browser to handle the error normally. Contains these properties:

·         kn.lastError.message - the error message text.

·         kn.lastError.url - the URL of the resource containing the program that was running when the error occurred.

·         kn.lastError.line - the statement line number where the error was trapped.

kn.lastError.date

Date Object

A Date object containing the time when the most recent error was trapped.

kn.leaderWindow

window object

The browser window handle corresponding to the current session leader. When several interactive web applications are active in different windows of the same web browser session, only the session leader maintains a persistent connection to the Event Router. Closing the session leader window may cause a temporary disruption in event notification while a new window is chosen to lead the session, but no events should be lost.

kn.ownerWindow

window object

The browser window handle corresponding to the outer-most frame using the JavaScript Microserver instance.

kn.tunnelURI

string

Contains a URL of the topic corresponding to the session leader's persistent connection to the event notification service. Subscribing a handler in the web browser to a topic automatically routes events to this URL. By default, the Microserver's frameset wrapping function sets this to the topic: /who/<xxx>/s/<NNN>/kn_journal where <xxx> is the kn.userid and <NNN> is a pseudo-random number up to eight digits in length, but this behavior may be overridden by setting the kn_tunnelURI property of the session leader window.

kn.userid

string

Identifies the authenticated user in the context of the web application. This may be a value supplied by the Event Router and it may be overridden by a value supplied with the kn_userid command-line argument. The default value is guest or anonymous.

Methods

kn.ADD_JOURNAL

Usage

kn.ADD_JOURNAL(options, handlers)

Description

Adds a journal. This is the same as using the route command with a null kn_to or a kn_to that starts with javascript.

Arguments

options - An object containing request parameters.

Invokes the add_journal router method. See also, Available do_method settings.

kn.ADD_NOTIFY

Usage

kn.ADD_NOTIFY(options, handlers)

Description

Adds or replaces a notify event to a topic.

Arguments

options - An object containing request parameters.

Invokes the add_notify router method. See also, Available do_method settings.

kn.ADD_TOPIC

Usage

kn.ADD_TOPIC(options, handlers)

Description

Adds a new topic to the Event Router.

Arguments

options - An object containing request parameters.

Invokes the add_topic router method. See also, Available do_method settings.

kn.BATCH

Usage

kn.BATCH(options, handlers)

Description

Issues a batch request to the Event Router.

Arguments

options - An object containing request parameters.

Invokes the batch router method. See also, Available do_method settings.

kn.CLEAR_TOPIC

Usage

kn.CLEAR_TOPIC(options, handlers)

Description

Deletes all events from a topic on the Event Router.

 

Arguments

options - An object containing request parameters.

Invokes the clear_topic router method. See also, Available do_method settings.

kn.DELETE_NOTIFY

Usage

kn.DELETE_NOTIFY(options, handlers)

Description

Deletes a notify event from a topic.

Arguments

options - An object containing request parameters.

Invokes the delete_notify router method. See also, Available do_method settings.

Returns

If the event does not exist, a 404 is returned.

kn.DELETE_ROUTE

Usage

kn.DELETE_ROUTE(options, handlers)

Description

Deletes the specified route from the Event Router.

Arguments

options - An object containing request parameters.

Invokes the delete_route router method. See also, Available do_method settings.

Returns

If the route does not exist, a 404 is returned.

kn.NOTIFY

Usage

kn.NOTIFY(options, handlers)

Description

Posts an event to the specified destination.

Arguments

options - An object containing request parameters.

Invokes the notify router method. See also, Available do_method settings.

kn.ROUTE

Usage

kn.ROUTE(options, handlers)

Description

Establishes a route from kn_from to kn_to.

Arguments

options - An object containing request parameters.

Invokes the route router method. See also, Available do_method settings.

kn.SET_TOPIC_PROPERTY

Usage

kn.SET_TOPIC_PROPERTY(options, handlers)

Description

Modifies a topic's properties.

Arguments

options - An object containing request parameters.

Invokes the set_topic_property router method. See also, Available do_method settings.

kn.UPDATE_NOTIFY

Usage

kn.UPDATE_NOTIFY(options, handlers)

Description

Modifies a topic's properties on the Event Router.

Arguments

options - An object containing request parameters.

Invokes the update_notify router method. See also, Available do_method settings.

kn.UPDATE_ROUTE

Usage

kn.UPDATE_ROUTE(options, handlers)

Description

Updates an existing route. If the route does exist, only the headers that are set in the request will be changed. All other headers will remain the same.

Arguments

options - An object containing request parameters.

Returns

If the route does not exist, a 404 is returned.

Invokes the update_route router method.

kn.clearHandler

Usage

kn.clearHandler(rid)

Description

Removes the handler for the specified route location.

Arguments

rid is the route location for which the handler being removed.

kn.iw

Usage

kn.iw(target, depth)

Description

An abbreviation for kn_inspectInWindow.

Arguments

target is target object.

depth is the depth.

kn.publish

Usage

kn.publish(topic, event, [status-handlers])

Description

Publishes an event to a topic on the Event Router and optionally provides status-handlers to be called after the event is published.

The event to be published must be constructed as a JavaScript object before it is passed to the publish function.

Arguments

topic is a string containing the topic to which you want to publish, such as:

"/this/is/a/topic"

event is an object representing the event you want to publish. It should contain string properties for each do_method=notify parameter and event header you wish to send to the Event Router. See also, Status Handler Objects.

Returns

The kn_id of the newly published event.

Invokes the notify router method.

kn.publishForm

Usage

kn.publishForm(topic, form, [status-handlers])

Description

Copies element names and values from the specified form into a new event object, and uses kn.publish to publish the event to the specified topic.

This function will not work for multiple selections, submit, or buttons.

This function does not support file objects; it will publish a file's path, but not the file's contents.

Arguments

topic is a string containing the topic to which you want to publish, such as:

"/this/is/a/topic"

form is an object representing the form you want to publish.

status-handlers is an object with three functions, one for each possible status events returned by the Event Router for the request.

Returns

The kn_id of the newly published event.

Invokes the publishForm router method.

kn.sendQueue

Usage

kn.sendQueue(queue, options , handler)

Description

Submits a queue of requests using kn.BATCH.

Arguments

queue is an array of events.

options contains the options for the request.

See, Status Handler Objects

 

kn.setHandler

Usage

kn.setHandler(rid, fxn , obj)

Description

A low-level local-only equivalent to kn_subscribe.

Arguments

rid is a route location value.

fxn is the handler function to call for matching events. It is invoked with two arguments, an event and obj.

obj is the data object that is passed to fxn as the second argument.

kn.subscribe

Usage

kn.subscribe(topic, destination, [options, handlers])

Description

Subscribes the specified URL, closure, or object to the specified topic.

Arguments

topic is a string containing the topic to which you want to subscribe, such as:

"/this/is/a/topic"

destination is the URL, closure, or Object with an onMessage method to which each received event will be passed.

options defines the properties of this object which can modify the nature of the subscription. Specify only one of the following options:

     do_max_n specifies the maximum number of events to be received on this subscription.

     do_max_age specifies that all events published to the topic up to that many seconds before the subscription was opened should be fetched.

             Specifying "infinity" will fetch all events in the topic, regardless of their timestamp.

For more on status handlers, refer to Status Handler Objects.

Returns

A route URI that can later be passed to kn.unsubscribe to remove the subscription.

kn.unsubscribe

Usage

kn.unsubscribe(rid, [status-handlers])

Description

Removes a subscription identified by rid, so that events published to that subscription's source topic will no longer be delivered.

Arguments

rid is the subscription's route identifier associated with the subscription that was returned by an earlier call to kn.subscribe .

For more on status handlers, refer to Status Handler Objects.

KN

The KN object is a holder for some constants used in JavaScript string and character processing:

KN.hexDigits

string

The string 0123456789ABCDEFabcdef. All valid hexadecimal digits are contained in this string. The first 16 character positions contain the sixteen uppercase hexadecimal digits in ascending order. The Microserver uses this string when recognizing or generating hexadecimal escape sequences in URL-escaped strings.

KN.ucsMaxChar

integer

The maximum permitted UCS character value: 0x7FFFFFFF

KN.ucs2max

integer

The maximum permitted UTF-16/UCS-2 character value: 0xFFFF

KN.ucsNoChar

integer

The number 0xFFFD. U+FFFD is the UCS and Unicode replacement character. Unrecognized and unrepresentable characters are replaced by this character code in Unicode and UCS strings.

The kn_stringFromCharCode and kn_escape function automatically performs this mapping when given UCS character codes larger than KN.utf16max to encode. Similarly, the kn_unescape function produces this character in the UTF-16 output string for each illegal or unrepresentable URL-encoded UTF-8 sequence in the input string.

KN.utf16firstHighHalf

integer

The first character of the UTF-16 high-half surrogate range: 0xDC00

KN.utf16firstLowHalf

integer

The first character of the UTF-16 low-half surrogate range: 0xD800

KN.utf16max

integer

The number 0x10FFFF, corresponding to the UCS and Unicode character U+10FFFF. This is the largest character code for which a UTF-16 encoding exists. Character codes larger than this are replaced by the KN.ucsNoChar value in UTF-16 strings.

KN.utf16offset

integer

All UTF-16 surrogate pairs are offset by this value after decoding: 0x10000

KN.utf16mask

integer

Mask applied to UTF-16 surrogate halves to extract useful values: 0x3FF

KN.utf16shift

integer

Shift applied to UTF-16 high surrogate halves to extract useful values: 10

KN.utf8mask

integer

Mask for UTF-8 continuation bytes: 0x3F

KN.utf8shift

integer

Shift for residual value upon encountering UTF-8 continuation bytes: 6

Status Handler Objects

Create status handler objects to process the status events returned by the Event Router in response to requests. See also, Status Events.

Methods

onSuccess

Usage

onSuccess(event)

Description

This method is invoked by kn_defaultOnStatus in response to successful HTTP status codes in the status event. A callback method you define for handling successful status events received from the Event Router in response to an earlier request.

If no onSuccess method is provided, kn_defaultOnSuccess will be used instead.

Input

event is status event from the Event Router that is passed to this callback.

onError

Usage

onError(event)

Description

This method is invoked by kn_defaultOnSuccess in response to non-successful HTTP status codes in the status event. A callback method you define for handling error status events received from the Event Router in response to an earlier request.

If no onError method is provided, kn_defaultOnError will be used instead.

Input

event is status event from the Event Router that is passed to this callback.

onStatus

Usage

onStatus(event)

Description

This method is invoked by kn_doStatus. A callback method you define for handling status events received from the Event Router in response to an earlier request.

Input

event is status event from the Event Router that is passed to this callback.

If no onStatus is provided, kn_defaultOnStatus will be used instead.

String and Character Support

The KnowNow Event Service Page library uses UTF-16 encoding for Unicode and UCS characters in JavaScript strings, but there is no byte order mark visible at the JavaScript level. This is backward-compatible with the UCS-2 character encoding employed by older web browsers, thus providing cross-browser access to a rich character set.

As a result, binary data in events should be encoded using the MIME Base64 encoding or a similar technique.

Using Command-Line Parameters

Named parameters can be passed to your application using parameters in the query string part of the URL or in kn_queryString. The query string is optional and appears following the path part of the URL, separated by a question mark.

·         Each parameter has a name and a value separated by a single equals sign. Both the parameter name and the parameter value are UTF-8 encoded and URL-escaped. The same parameter may be set several times, but only the last value has any effect.

·         Multiple parameters can be given in either a semicolon-separated list or an ampersand-separated list.

·         Parameter values are available as string properties of the kn_argv object. For instance, the value for a parameter named foo would be stored in kn_argv.foo.

·         Parameter names starting with kn_ are reserved.

·         The name and equals sign are optional for the special parameter kn_topic.

·         For all other kn_ parameters the equals sign and value are optional. Supplying one of these parameters with the value omitted is the same as supplying the parameter with a boolean value of true.

The following command-line parameters have defined meanings:

Parameter

Meaning

kn_autostart

Requests that your application start running immediately, rather than waiting for user input. You must implement support for this feature in your application, if you want to support kn_autostart.

kn_debug

Comma-separated list of debugging options. Available options include:

all - Turn on all debugging flags.

events - Display an alert box every time an event is received

posts - Display the contents of sent events in the posting frame.

receipts - Display the contents of received events in the tunnel frame.

routes - Display an alert box every time a subscription is canceled by the default message handler.

kn_displayname

Describes the user identified by kn.userid in human-readable format. Overrides the default value of kn.displayname.

kn_options

Comma-separated list of speed options. Available options include:

all - Turn on all options.

fastdoc - Use document. open() for KNDocument

single - Do not batch multiple requests.

noforward - Do not forward status events to the tunnel frame.

escape - Use JavaScript escape() instead of kn_escape()

unescape - Use JavaScript unescape() instead of kn_unescape().

noswap - Do not swap tunnel and post frames periodically.

kn_hashCache

Initial event hash cache value, loaded by the Microserver at startup using kn.setHashCache().

kn_lang

A comma-separated list of language codes and optional quality values used when looking up localized messages. Overrides the default value of the kn_lang self property.

kn_lastTag_

Initial value for kn.lastTag_, a do_since_checkpoint value for the tunnel route. See also, kn_lastTag_.

kn_response_flush

Controls the number of filler bytes (from 0 to 4,096) sent when the Router detects a lull in the event stream for a particular tunnel (i.e. a persistent connection for event notification).

If this value is not supplied, the number of bytes is determined automatically. See also, kn_response_flush.

kn_target

Window name in which links to external resources should be followed, with _blank being the usual default. You must implement support for this feature in your application, if you want to support kn_target.

kn_timestamp

Requests that event timestamps be displayed. You must implement support for this feature in your application, if you want to support kn_timestamp.

kn_topic

Primary topic used by an application. You may choose to implement support for this feature in your application.

kn_tunnelID

Initial value for kn.tunnelID, the tunnel route kn_id. See also, kn_tunneIID.

kn_tunnelMaxAge

Initial value for kn.tunnelMaxAge, do_max_age value for the tunnel route. See also, kn_tunnelMaxAge.

kn_tunnelURI

Initial value for kn.tunnelURI, the tunnel route source topic URI. See also, kn_tunnelURI.

kn_userid

Identifies the user in the context of the web application. Overrides the default value of kn.userid. See also, kn_userid.

 

Examples

The following examples illustrate how to use the command-line options described above. All examples assume that your application's URL is
.../MyApp/.

Sample Command Line

Description

.../MyApp/?kn_debug

Basic debugging is enabled.

.../MyApp/?kn_debug=

All debugging is disabled.

.../MyApp/?kn_debug=all

All debugging flags are enabled.

.../MyApp/

or

.../MyApp/?

No parameters specified.

.../MyApp/?color=red

kn_argv.color is set to the string red .

.../MyApp/?color=red;flavor=spicy

or

.../MyApp/?color=red&flavor=spicy

kn_argv.color is set to the string red and kn_argv.flavor is set to the string spicy .

.../MyApp/?/foo/bar

or

.../MyApp/?kn_topic=/foo/bar

kn_argv.kn_topic is set to the string /foo/bar .

.../MyApp/?kn_options=escape,unescape

JavaScript escape() and unescape() will be used instead of kn_escape( ) and kn_unescape().

 

Event Router Module API

This section provides a quick reference to the C++ filter API functions provided for modules you can create for event filtering and security.

This section is broken into the following sections:

·         Module Functions

·         KnApiEvent

·         KnRequest

Module Functions

Your module provides implementations of the following functions. These functions will be invoked by the Event Router at various stages.

These functions are required of all modules:

·         KnModuleStart

·         KnModuleStop

These functions are required only for filter modules:

·         KnFilterTopicAttach

·         KnFilterTopicDetach

·         KnFilterTopicEvent

·         KnFilterRouteAttach

·         KnFilterRouteDetach

·         KnFilterRouteEvent

KnFilterTopicAttach

KN_EXPORT KnError KnFilterTopicAttach(
const KnString &filterParams,
const KnString &uri,
bool & transform);

Description

This function is invoked by the Event Router each time a filter module is attached to a topic.

Since this function can be invoked multiple times, its implementation must be threadsafe.

A filter can be attached to a topic by including the kn_filtername and kn_filterparams headers in the set_topic_properties command.

A filter may also be attached to a topic by adding the kn_filtername and kn_filterparams headers to a notify request to the topic's corresponding subtopic event. This subtopic event is located in the kn_subtopics topic of the parent topic.

Lastly, each of the KnowNow Microserver APIs provide language-specific interfaces for attaching filters.

Arguments

filterParams contains the filter parameters, if any were passed into the router via the kn_filterparams header.

uri contains the topic name, if the filter is being attached to a topic.

bool & transform: whether the filter is going to be used to transform the event. If false (by default), the filter prevents the contents of the event from modification (for that attachment) during any filtering.

Returns

KnErrorSuccess should be returned on success.

KnFilterTopicDetach

KN_EXPORT KnError KnFilterTopicDetach(
const KnString &filterParams,
const KnString &uri)

Description

This function is invoked by the Event Router when the filter module is detached from a topic.

Since this function can be invoked multiple times, its implementation must be threadsafe.

Each of the KnowNow Microserver APIs provide language-specific interfaces for detaching filters.

Arguments

filterParams contains the filter parameters, if any were passed into the router via the kn_filterparams header when the filter was attached.

uri contains the topic name, if the filter is being attached to a topic.

Returns

KnErrorSuccess should be returned on success.

KnFilterTopicEvent

KN_EXPORT KnError KnFilterTopicEvent(
const KnString &filterParams,
const KnString &uri,
KnApiEvent &event,
bool &discard)

Description

This function is invoked by the Event Router each time an event is passed to a topic that has the filter attached.

Your implementation of this function can access the contents of the event and do one of the following:

- Examine the event and do nothing

- Examine the event and discard it, preventing it from reaching its
destination.

- Modify the event and allow it to continue to its destination.

- Examine the event, then create and post one or more new events to any destination

For details on obtaining and setting event contents, see the KnApiEvent class get and set methods.

Arguments

filterParams is the filter parameters, if any were passed into the router when the filter was attached via the kn_filterparams header.

uri is the topic name.

event is the event that is being passed to the topic or along the route.

discard can be set to true (1) to discard the event and prevent it from reaching its destination. Set the discard flag to false to allow event, modified or not, to reach its destination.

Returns

KnErrorSuccess should be returned on success.

KnFilterRouteAttach

KN_EXPORT KnError KnFilterRouteAttach(
const KnString &filterParams,
const KnString &sourceUri,
const KnString &destUri,
bool & transform);

Description

This function is invoked by the Event Router each time a filter module is attached to a topic or a route.

Since this function can be invoked multiple times, its implementation must be threadsafe.

A filter can be attached to a route by posting a route command with the kn_filtername and kn_filterparams headers.

Lastly, each of the KnowNow Microserver APIs provide language-specific interfaces for attaching filters.

Arguments

filterParams contains the filter parameters, if any were passed into the router via the kn_filterparams header.

sourceUri: the topic that the event is originating from.

destUri: the route destination.

bool & transform: whether the filter is going to be used to transform the event. If false (by default), the filter prevents the contents of the event from modification (for that attachment) during any filtering.

Returns

KnErrorSuccess should be returned on success.

KnFilterRouteDetach

KN_EXPORT KnError KnFilterRouteDetach(
const KnString &filterParams,
const KnString &sourceUri,
const KnString &destUri);

Description

This function is invoked by the Event Router when the filter module is detached from a topic or a route.

Since this function can be invoked multiple times, its implementation must be threadsafe.

Each of the KnowNow Microserver APIs provide language-specific interfaces for detaching filters.

Arguments

filterParams contains the filter parameters, if any were passed into the router via the kn_filterparams header when the filter was attached.

sourceUri contains the topic name where the event originated from.

destUri contains the route destination.

Returns

KnErrorSuccess should be returned on success.

KnFilterRouteEvent

KN_EXPORT KnError KnFilterRouteEvent(
const KnString &filterParams,
const KnString &sourceUri,
const KnString &destUri,
KnApiEvent &event,
bool &discard)

Description

This function is invoked by the Event Router each time an event is passed along a route.

Your implementation of this function can access the contents of the event and do one of the following:

Examine the event and do nothing

Examine the event and discard it, preventing it from reaching its destination.

Modify the event and allow it to continue to its destination.

Examine the event, then create and post one or more new events to any destination

For details on obtaining and setting event contents, see the KnApiEvent class get and set methods.

Arguments

filterParams is the filter parameters, if any were passed into the router when the filter was attached via the kn_filterparams header.

sourceUri is the topic where the event originated from.

destUri is the route destination if the filter was attached to a route.

event is the event that is being passed to the topic or along the route.

discard can be set to true (1) to discard the event and prevent it from reaching its destination. Set the discard flag to false to allow event, modified or not, to reach its destination.

Returns

KnErrorSuccess should be returned on success.

  KnModuleStart

KN_EXPORT KnError KnModuleStart(
const KnString &path,
const KnSet &info)

Description

This function is invoked by the Event Router when a module is first loaded. In order for a module to be loaded, an appropriate entry must be added to the nskn section of the Event Router's configuration file.

Arguments

path is the module's path, such as /kn_filter/sample_filter.

info is optional module configuration data.

Returns

KnErrorSuccess should be returned if the module was successfully initialized.

KnModuleStop

KN_EXPORT KnError KnModuleStop( )

Description

This function is invoked when the Event Router is shutting down. Your implementation should perform any needed resource clean up.

Returns

KnErrorSuccess should be returned on success.

KnApiEvent

This class is used to represent an event and provides methods for retrieving and setting the event's contents.

Constructors/Destructors

KnApiEvent

KnApiEvent(const KnSet &set)

Description

Creates an event using the contents specified in set.

Parameters

set contains the contents for the newly created event.

Returns

The newly created event object.

Include File

kneventapi.h

KnApiEvent

KnApiEvent(const KnApiEvent &)

Description

Copy constructor.

Parameters

The event to be copied.

Returns

The newly created event object.

Include File

kneventapi.h

Methods

bool isEditable() const

bool isEditable() const

Description

Reflects whether the event can be modified. Permission is determined by the attach function.

Include File

 

See Also

 

getExpirationTime

time_t getExpirationTime() const

Description

Returns the events expiration time.

Include File

kneventapi.h

See Also

getKnExpires, setExpirationTime, setKnExpires

getHeader

const KnString *getHeader(const KnString &name) const

Description

Obtains the header value with the specified name.

Parameters

name is the name of the head whose value is to be retrieved.

Returns

A string representation of the value.

Include File

kneventapi.h

See Also

getHeaders, setHeader, setHeaders

getHeaders

const KnSet *getHeaders() const

Description

Returns all the name/value pairs in the event.

Returns

A KnSet containing all the name/value pairs in this event.

Include File

kneventapi.h

See Also

getHeader, setHeader, setHeaders

getKnExpires

const KnString &getKnExpires() const

Description

Returns the events expiration time.

Include File

kneventapi.h

See Also

bool isEditable() const, setExpirationTime, setKnExpires

getKnFrom

const KnString &getKnFrom() const

Description

Returns a string containing the source of the event.

Include File

kneventapi.h

See Also

setKnFrom

getKnId

const KnString &getKnId() const

Description

Returns a string containing the event's identifier.

Include File

kneventapi.h

See Also

setKnId

getKnPayload

const KnString &getKnPayload() const

Description

Returns a string containing the event's payload.

Include File

kneventapi.h

See Also

setKnPayload

getKnRouteId

const KnString &getKnRouteId() const

Description

Returns a string containing the event's route identifier.

Include File

kneventapi.h

See Also

setKnRouteId

getKnRouteLocation

const KnString &getKnRouteLocation() const

Description

Returns a string containing the event's route location.

Include File

kneventapi.h

See Also

setKnRouteLocation

getKnTimeT

const KnString &getKnTimeT() const

Description

Returns a string containing the event's time.

Include File

kneventapi.h

See Also

setKnTimeT

getKnTo

const KnString &getKnTo() const

Description

Returns a string containing the event's destination.

Include File

kneventapi.h

See Also

setKnTo

setExpirationTime

KnError setExpirationTime(time_t expiration)

Description

Sets the event's expiration time.

Parameters

expiration is the new expiration time.

Returns

KnError

Include File

kneventapi.h

See Also

bool isEditable() const

setHeader

KnError setHeader(
const KnString &name,
const KnString &value)

Description

Sets the value of the event header with the specified name.

Parameters

name is the name of the header whose value is to be modified.

value is the new value for the header.

Returns

KnError

Include File

kneventapi.h

See Also

setHeaders, getHeader, getHeaders

setHeaders

KnError setHeaders(const KnSet *headers)

Description

Sets the name/value pairs in the event header.

Parameters

header is the set of name/value pairs to be set.

Returns

KnError

Include File

kneventapi.h

See Also

setHeader, getHeader, getHeaders

setKnExpires

KnError setKnExpires(const KnString &knExpires)

Description

Sets the expiration date of the event.

Parameters

knExpires is the expiration date t o set.

Returns

KnError

Include File

kneventapi.h

See Also

setHeaders, getHeader, getHeaders

setKnFrom

KnError setKnFrom(const KnString &from)

Description

Sets the source of the event.

Parameters

from is the new source of the event.

Returns

KnError

Include File

kneventapi.h

See Also

getKnFrom

setKnId

KnError setKnId(const KnString &knId)

Description

Sets the event's identifier.

Parameters

knid is the new event identifier.

Returns

KnError

Include File

kneventapi.h

See Also

getKnId

setKnPayload

KnError setKnPayload(const KnString &knPayload)

Description

Sets the event's payload.

Parameters

knPayload is the new payload for the event.

Returns

KnError

Include File

kneventapi.h

See Also

getKnPayload

setKnRouteId

KnError setKnRouteId(const KnString &routeId)

Description

Sets the route identifier of the event.

Parameters

routeId is the new route identifier for the event.

Returns

KnError

Include File

kneventapi.h

See Also

getKnRouteId

setKnRouteLocation

KnError setKnRouteLocation(const KnString routeLocation)

Description

Sets the route location of the event.

Parameters

routeLocation is the new route location for the event.

Returns

KnError

Include File

kneventapi.h

See Also

getKnRouteLocation

setKnTimeT

KnError setKnTimeT(const KnString &knTimeT)

Description

Sets the expiration time of the event.

Parameters

knTimeT is the new expiration time for the event.

Returns

KnError

Include File

kneventapi.h

See Also

getKnExpires, getKnTimeT, setExpirationTime

setKnTo

KnError setKnTo(const KnString &to)

Description

Sets the destination of the event.

Parameters

to is the new destination for the event.

Returns

KnError

Include File

kneventapi.h

See Also

getKnTo

KnRequest

This structure is used to represent a request sent to an Event Router and contains members that represent the request's contents.

struct KnRequest

{

KnString line;             /* request line sent by the client */

KnString method;           /* method requested by the client */

KnString protocol;         /* protocol part of URL or empty */

KnString host;             /* host part of URL or empty */

uint16_t port;             /* port specified in url, or 0 */

KnString srcUrl;           /* url where the request came from */

KnString dsturl;           /* normalized url, without any query data */

KnString query;            /* any query data appended to url */

KnString peer;             /* ip address of the client */

double version;            /* version of the client request */

KnString authUser;         /* decoded user name */

KnString authPasswd;       /* decoded user password */

size_t contentLength;      /* number of bytes sent by the client */

};

Glossary 

authentication

The process of identifying an individual, usually based on a username and password. Authentication merely ensures that the user is who he or she claims to be, but says nothing about the access rights of the individual. Access rights are defined through authorization.

authorization

The process of granting or denying access to a network resource. Most computer security systems are based on a two-step process. The first stage is authentication, which ensures that a user is who he or she claims to be. The second stage is authorization, which allows the user access to various resources based on the user's identity.

batching

Allows an HTTP client to connect to the KnowNow Event Router and send a series of requests for different operations in one HTTP request. Batches can span multiple topics. The resulting codes for each batch request are sent as part of the HTTP body.

Always use the kn_status_to parameter with the JavaScript Microserver when batching. Outside the JavaScript Microserver, batching does not provide any benefits over multiple posts over a persistent connection.

certificate

A certificate contains a distinguished name, public key, private key, and information about the issuer of the certificate.

Certification Authority

An entity that issues certificates, usually associated with an Authentication Server. You can check the validity of an issued certificate by checking it against the appropriate Authentication Server.

certificate file

The storage location for one or more certificates. A certificate file can store certificates, trusted roots, and uncertified key-pairs. An uncertified key pair is one that has not yet been certified by the Certification Authority.

See also, trusted roots.

CLASSPATH

The environment variable that tells the Java compiler where to look for the classes it needs. -classpath is an option to the Java interpreter and the Java compiler that tells them (while compiling or running) where to look for a class. -classpath overrides CLASSPATH.

clients

A server, service, browser, device, or application.

control container

An ActiveX-enabled application or development environment that supports programmatic access to ActiveX controls.

do_max_n

Requests to the Router to deliver the last n events.

do_max_age

Requests to the Router to deliver all events seen in the previous n seconds.

duplicate event squashing

KnowNow Event Router property that allows once-only delivery of events.

encryption

The scrambling of data so that it can only be un-scrambled by an authorized recipient. Encryption strength is usually stated in bits.

event

Messages sent by an application or person specifically to trigger actions. Events have an identification string, timestamp, an expiration timestamp, metadata headers, and a content payload. Within the KnowNow event payload, events can contain data in any format. The KnowNow Event Router can handle events with non- kn_header. KnowNow reserves the right to all headers that begin with kn_ for its own use and definition.

event aggregation

Subscribing a topic to another topic. Using these inter-topic subscriptions, events can be aggregated from multiple topics to a single topic.

event forwarding

Distributed published events to all clients subscribed to a topic. The KnowNow Event Router maintains a table of subscribers for each topic so that it knows how to distribute published events.

Subscriptions are automatically deleted when they expire or when the KnowNow Event Router cannot deliver an event to the given subscriber. Clients can also delete subscriptions. KnowNow Event Routers send events as HTTP POST in KN event format (which is x-www.url-form-encoded with special KnowNow fields), or using a JavaScript tunnel or a simple tunnel for HTTP responses.

See tunnels.

event replay

A request submitted to the KnowNow Event Router to send all events that occurred since a specific point-in-time. You can specify a timestamp, request the last n events, or replay all stored events. This event replay request is executed immediately to only the specific subscriber that made the request.

event updating

KnowNow Event Router property that allows the contents of an event to be updated while maintaining the same event identification number.

filter

A filter can perform filtering and data transformation on events as they are routed. As events are moved into topics, out of topics, or across routes, these modules can filter, modify, and redirect the events to alternate destinations.

firewall

A system designed to prevent unauthorized access to or from a private network. Firewalls can be implemented in both hardware and software.

The Event Router requires you to open port 8000 for non-SSL connections. For SSL connections, port 8443 is used.

JavaScript Microserver Vendor

The KnowNow Event Router can vend the JavaScript Microserver, so that the Microserver downloads into a browser automatically with a KnowNow-enabled web page. As a result, end users can use KnowNow applications that do not require additional installs to their browsers.

kn_expires

Event or route expiration time. Expressed in the same format as kn_time_t or in seconds relative to the event's arrival (or route creation). Shipping default is 1 hour.

kn_id

Event id. Id's are unique to each topic; if an event is published or routed to a topic which already contains an event with the same kn_id, the new event is considered an update. Updated events are moved to the end of the topic's event stream such that a later "route" request with do_max_n or do_max_age parameters will return the updated events.

kn_journal

A journal topic is in essence a URL that is accessible on the Internet. Microservers use the journal topic to communicate between the Router and an application that cannot otherwise receive a POST from the Router.

kn_payload

Event payload, analogous to a message body. If kn_payload is not present, the Router inserts this header with the empty string as its value.

kn_route_checkpoint

Only added to events when added to a kn_journal topic. A globally unique identifier stamped onto the event before delivery is attempted down tunnels. By supplying a checkpoint value via the do_since_checkpoint optional parameter in a tunnel creation request, Microservers can ask the Router to replay events they may have missed during a short disconnection.

kn_route_from

Full URI of the topic the event was last routed from. Example: http://gravitar.knownow.com//kn/what/chat.

kn_route_id

kn_id of the route the event last traversed. Example: 00192016.

See kn_id.

kn_route_location

Full URI, including route id, of the route which the event last traversed. Example: http://gravitar.knownow.com/kn/what/chat/kn_routes/00192016.

kn_status_from

The KnowNow Event Router generates status events to indicate the success or failure of route, notify, and batch requests, as well as requests with unknown do_methods. Each such request, whether in a batch or by itself on an HTTP connection, generates a status event. kn_status_from is a value to place in the kn_route_location header of status events.

kn_time_t

Timestamp recording the event receipt time. Time is expressed as seconds since Jan 1 1970 00:00:00 (UNIX time ()format, e.g. "979273892" for an event created Fri Jan 12 04:31:32 2001). This header is supplied if it does not exist. The kn_time_t is not updated as the Router routes the event.

kn_to

Route or notify destination. e.g. /what/chat, http://foo/kn/what/chat. kn_to is basically used to set up routes.

kn_uri

If kn_uri is set as part of the HTTP header, it overrides the kn_route_location.

microserver

KnowNow component that connects an application to the KnowNow Event Router via HTTP. Allows application programmers to utilize the publish and subscribe features of the Router. Microservers for Solaris, Win32 (C++ and ActiveX interface), Java, and JavaScript programming environments are also available. See Developer.KnowNow.com for more information on downloading and working with these Microservers.

module

In software, a module is a part of a program. Programs are composed of one or more independently developed modules that are not combined until the program is linked.

persistent storage

Persistent storage uses operating system asynchronous I/O to write events to disk. This is used for events that should be delivered, but no significant problems will occur if they are not.

publish

The act of sending an event from a KnowNow Event Router. Any event that is sent to a topic is "pushed" to all subscribers listening on that topic. The routing of events happens instantly after the events are received. Events persist as long as the event expiration timestamp does not expire.

See topic and kn_expires.

route

The path an event travels during the publish/subscribe process.

secure sockets

A socket is a way of sending information over a network between two programs. Secure sockets make this communication safe. Data is encrypted so only people who the data is meant for can read it. See also encryption.

SOAP

Simple Object Access Protocol. SOAP is a lightweight protocol for exchange of information in a decentralized, distributed environment. It is an XML based protocol that consists of three parts: an envelope that defines a framework for describing what is in a message and how to process it, a set of encoding rules, and a convention for representing remote procedure calls and responses.

SSL

Secure Socket Layer standard. A protocol that delivers server authentication, data encryption, and message integrity. SSL is layered beneath application protocols such as HTTP, SMTP, Telnet, FTP, Gopher, and NNTP, and layered above the connection protocol TCP/IP. This strategy allows SSL to operate independently of the Internet application protocols. With SSL implemented on both the client and server, your Internet communications are transmitted in encrypted form. Information you send can be trusted to arrive privately and unaltered to the server you specify. See secure sockets.

subscribe

The act of receiving an event from the KnowNow Event Router. When a client connects to a KN Event Router and subscribes to a topic, the client begins to receive events that are published to that topic. The client continues to receive events, until the subscription has expired.

See topic.

timestamp

Timestamp recording the original event receipt time. Time is expressed as seconds since Jan 1 1970, 00:00:00 (UNIX time() format, e.g. "979273892" for an event created Fri Jan 12 04:31:32 2001).

topic

A collection of events to which KnowNow clients can subscribe or publish events. All events are published to a topic. A topic can be thought of as a database table where events are stored. As updates occur, all subscribers are notified of the changes. Subscribers also have the option of selecting a sub-set of the data. Duplicate events that are published to a topic are automatically deleted by the KnowNow Events Router. You can attach metadata to a topic by using the kn_metadata header. The KnowNow Event Router has a configurable payload size threshold to discard large events without overloading.

Clients can use a Uniform Resource Locator (URL) to refer to and access topics on the KnowNow Event Router. Topics are arranged in a naming hierarchy that uses forward slashes (/) to separate the levels. For example: /what/nasdaq/SUNW/bid.

topic management

Allows the user to create, edit, or delete topics and subtopics.

trusted root

A special certificate issued by a well-known and trusted Certification Authority.

tunnel

The physical route that connects a KnowNow Event Router to a client, like a Microserver or a standalone HTTP application. Tunnels use persistent connections to send events to desktops and applications while maintaining the policies of Internet administrators for their firewalls, Network Address Translators (NATs), and Web proxies. To maintain a persistent connection, tunnels occasionally send keepalives to the KnowNow Event Router. Keepalives are single byte events. A client can request that the KnowNow Event Router close a tunnel at a specific time by setting the kn_expires header parameter.

URI

Uniform Resource Identifier.


All brand names and product names used in this document are trade names, service marks, trademarks or registered trademarks of their respective owners.
Copyright © KnowNow, Inc. All rights reserved.
Printed in the U.S.A.
Last updated: August 22, 2002