Archive for the ‘linux’ Category

  • Add A record
import boto3

client = boto3.client('route53', aws_access_key_id="AWS_KEY", aws_secret_access_key="AWS_SEC_KEY")
hostedZoneId = 'HOSTED_ZONE_ID'

ip= '123.123.123.123'


if aws_region == "US":
    #US is my default region. So cont_code is blank
    cont_code = {}
elif aws_region == "EU":
    cont_code = {'ContinentCode':'EU'}
elif aws_region == "AP":
    cont_code = {'ContinentCode':'AS'}

response = client.change_resource_record_sets(
    HostedZoneId = hostedZoneId,
    ChangeBatch={
        'Comment': 'comment',
        'Changes': [
            {
                'Action': 'CREATE',
                'ResourceRecordSet': {
                    'Name': domain,
                    'Type': 'A',
                    'SetIdentifier': 'my_a_record',
                    'GeoLocation': cont_code,
                    'TTL': 60,
                    'ResourceRecords': [
                        {
                            'Value': ip
                        },
                        ],
                    }
            },
            ]
    }
)


print("DNS record status %s "  % response['ChangeInfo']['Status'])
print("DNS record response code %s " % response['ResponseMetadata']['HTTPStatusCode'])
  • Delete A record

When deleting the A record you only have to change the action to DELETE

'Action': 'DELETE'

The SSL ciphers supported by are the ciphers supported by¬†internal Tomcat server. However you may sometime want customize the ciphers that your server should support. For instance Tomcat support export grade ciphers which will make your server vulnerable to recent FREAK attack. Let’s see how you can define the ciphers.

  • How to view the supporting ciphers

1) Download TestSSLServer.jar jar at http://www.bolet.org/TestSSLServer/TestSSLServer.jar

2) Start the WSO2 server

List the supported ciphers
3) java -jar TestSSLServer.jar localhost 9443

Supported cipher suites (ORDER IS NOT SIGNIFICANT):
TLSv1.0
RSA_WITH_RC4_128_MD5
RSA_WITH_RC4_128_SHA
RSA_WITH_3DES_EDE_CBC_SHA
DHE_RSA_WITH_3DES_EDE_CBC_SHA
RSA_WITH_AES_128_CBC_SHA
DHE_RSA_WITH_AES_128_CBC_SHA
RSA_WITH_AES_256_CBC_SHA
DHE_RSA_WITH_AES_256_CBC_SHA
TLS_ECDHE_RSA_WITH_RC4_128_SHA
TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
(TLSv1.1: idem)
TLSv1.2
RSA_WITH_RC4_128_MD5
RSA_WITH_RC4_128_SHA
RSA_WITH_3DES_EDE_CBC_SHA
DHE_RSA_WITH_3DES_EDE_CBC_SHA
RSA_WITH_AES_128_CBC_SHA
DHE_RSA_WITH_AES_128_CBC_SHA
RSA_WITH_AES_256_CBC_SHA
DHE_RSA_WITH_AES_256_CBC_SHA
RSA_WITH_AES_128_CBC_SHA256
RSA_WITH_AES_256_CBC_SHA256
DHE_RSA_WITH_AES_128_CBC_SHA256
DHE_RSA_WITH_AES_256_CBC_SHA256
TLS_ECDHE_RSA_WITH_RC4_128_SHA
TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
———————-
Server certificate(s):
6bf8e136eb36d4a56ea05c7ae4b9a45b63bf975d: CN=localhost, O=WSO2, L=Mountain View, ST=CA, C=US
———————-

  • Configure the preffered ciphers

1) Open [CARBON_HOME]/repository/conf/tomcat/catalina-server.xml and find the Connector configuration corresponding to SSL/TLS. Most probably this is the connector which has port 9443

2) Add a attribute called ciphers which have allowed ciphers in comma separated

<Connector protocol=”org.apache.coyote.http11.Http11NioProtocol”
port=”9443″
bindOnInit=”false”
sslEnabledProtocols=”TLSv1,TLSv1.1,TLSv1.2″
ciphers=”SSL_RSA_WITH_RC4_128_MD5″

Here I have added just one cipher for the simplicity.

3) List the supported ciphers now
java -jar TestSSLServer.jar localhost 9443

Supported versions: TLSv1.0 TLSv1.1 TLSv1.2
Deflate compression: no
Supported cipher suites (ORDER IS NOT SIGNIFICANT):
TLSv1.0
RSA_WITH_RC4_128_MD5
(TLSv1.1: idem)
(TLSv1.2: idem)
———————-
Server certificate(s):
6bf8e136eb36d4a56ea05c7ae4b9a45b63bf975d: CN=localhost, O=WSO2, L=Mountain View, ST=CA, C=US

 

References : http://blog.facilelogin.com/2014/10/poodle-attack-and-disabling-ssl-v3-in.html

Let’s assume you are running a SOAP service at the URL ¬†¬†http://localhost:8081/axis2/services/SimpleStockQuoteService?wsdl

SOAP UI  is a very good tool to access web services.

SoapUI 4.6.1 _095

However you have to install SOAP UI ¬†or there may be situations where you don’t have access to tools, for instance when you have longed in to an server by SSH. Then you have access only to command line. Here come the curl command handy.

Let’s see how you can access the above web service using curl command.

curl ¬†–header “Content-Type: text/xml;charset=UTF-8” –data @request.xml¬†http://localhost:8081/axis2/services/SimpleStockQuoteService

(Please note that there are two (not one) dashes before parameters.)

request.xml files contains the request payload. Below is the payload for the SimpleStockQuoteService service.

<ser:getQuote xmlns:ser=”http://services.samples”&gt;
<!–Optional:–>
<ser:request>
<!–Optional:–>
<xsd:symbol>IBM</xsd:symbol>
</ser:request>
</ser:getQuote>

This turotial explains how to run multiple ActiveMQ brokers within the same machine.
Prerequisites
Download ActiveMQ packs from http://activemq.apache.org/download.html
Below are the minimum commands we required for this set up.
create                   РCreates a runnable broker instance in the specified path.

setup                    Р Create the specified configuration file for this init script

You can view all the available commands by executing  bin/activemq

Step 1: Create broker 1 and 2

cd $active_mq_installation_folder // this is where you extract the apache-activemq-x.x.x.tar.gz
 
#create a runnable broker called “broker1”
bin/activemq create broker1
# Create the configuration file for the init script of broker1.
bin/activemq setup ~/.activemqrc-instance-broker1
#create a symbolic link
ln -s activemq bin/activemq-instance-broker1
 
#create the broker2
bin/activemq create broker2
bin/activemq setup ~/.activemqrc-instance-broker2
ln -s activemq bin/activemq-instance-broker2
Step 2: Change ports

grep 16 broker[12]/conf/*.xml

broker1/conf/activemq.xml: <transportConnector name=”openwire” uri=”tcp://0.0.0.0:61616?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600″/>
broker1/conf/activemq.xml: <transportConnector name=”stomp” uri=”stomp://0.0.0.0:61613?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600″/>
broker1/conf/activemq.xml: <transportConnector name=”ws” uri=”ws://0.0.0.0:61614?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600″/>
broker1/conf/jetty.xml: <property name=”port” value=”8161″/>
broker1/conf/jetty.xml: <property name=”port” value=”8162″ />
broker2/conf/activemq.xml: <transportConnector name=”openwire” uri=”tcp://0.0.0.0:61616?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600″/>
broker2/conf/activemq.xml: <transportConnector name=”stomp” uri=”stomp://0.0.0.0:61613?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600″/>
broker2/conf/activemq.xml: <transportConnector name=”ws” uri=”ws://0.0.0.0:61614?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600″/>
broker2/conf/jetty.xml: <property name=”port” value=”8161“/>
broker2/conf/jetty.xml: <property name=”port” value=”8161” />

You can see that both broker1 and broker2 has same configurations. For instance both have the tcp runs on port 61616. This will be a problem when we start the broker2 since broker1 is already running on port 61616.
Also we need to edit the webConsole port(which is by default 8162) in one of the brokers. This is the port the web console runs. You can point to http://localhost:8161 to view the ActiveMQ web console.
So we need to edit either broker1 or broker2 configurations in a way that same port number does not appear in both the brokers.
Start the multiple instances
Start broker 1:
sh broker1/bin/broker1 console
Start broker 2 (in another console):
sh broker2/bin/broker2 console
You may see the logs printing in the console.
Locate your browser to https://localhost:8161 to view the web console. This port (8161) is configured in conf/jetty.xml
broker1

Start carbon servers with OSGI console

./wso2server.sh -DosgiConsole

You will see below are the set of commands that are currently available

—Server Admin (WSO2 Carbon)—
listAdminServices – List admin services deployed on this Carbon instance
listHiddenServices – List hidden services deployed on this Carbon instance
listSystemServicesInfo – List all the systems services deployed on this Carbon instance
dumpAdminServices – Dump all the wsdls of admin services on this Carbon instance
restartCarbon – Forcefully restart this Carbon instance
restartCarbonGracefully – Gracefully restart this Carbon instance. All client connections will be served before restarting the server
shutdownCarbon – Forcefully shutdown this Carbon instance
shutdownCarbonGracefully – Gracefully shutdown this Carbon instance. All client connections will be served before shutting down the server
startCarbonMaintenance – Switch a Carbon instance to maintenance mode.
endCarbonMaintenance – Change the state of a Carbon instance from “maintenance” to “normal”

However you may want to add a command of your own. It may be helpfull for you to view runtime data.

Add a custom command
Write the command  class

You are required to implement org.eclipse.osgi.framework.console.CommandProvider interface in order to add a command of your own. You need to implement

String getHelp()This return the help text of the command which will be showned when you type “help customCommand”.Now comes your command. You must add a public method with void as the return type and method name must start with the _(underscore) before the name of the command. Method argument must be “org.eclipse.osgi.framework.console.CommandInterpreter” type. As an example if I want to add a “sayHello” command, my method is like below.public void _sayHello (CommandInterpreter ci)

package org.apache.stratos.autoscaler.commands;

import org.eclipse.osgi.framework.console.CommandInterpreter;
import org.eclipse.osgi.framework.console.CommandProvider;

public class EchoCommand implements CommandProvider{

public String getHelp() {
return "\necho - echoes the String provided. \n" + "\t parameters : \n" + "\t\t String text to be echoed.\n";
}
public void _echo(CommandInterpreter cli){
String text = ci.nextArgument();
cli.println(text);
}
}

nextArgument() gets the argument the user has given with the command (Ex “echo hellowWorld”)
println prints the text in the console.

Register the new service in OSGI

The below code will inform the OSGI framework about the new command class.

package org.apache.stratos.autoscaler.internal;
public class CommandBundleActivater implements BundleActivator{

private static final Log log = LogFactory.getLog(CommandBundleActivater.class);

@Override
public void start(BundleContext context) throws Exception {
if(log.isDebugEnabled())
log.debug("AutoScaler bundle is activated.");

context.registerService(CommandProvider.class.getName(),new EchoCommand(), null);
}
}
Add the bundle activater

Now add the foloowing lines to the required pom.xml file, so

<Bundle-Activator>org.apache.stratos.autoscaler.internal.CommandBundleActivater</Bundle-Activator>

Below are the output of the command.

osgi> help echo

echo - echoes the String provided.
 parameters :
 String text to be echoed.

osgi> echo HellowWorld
HellowWorld

Singleton pattern inside out using Java

Posted: January 15, 2014 in linux, ubuntu
Tags: , ,
  • Naive approach

Singleton is a software design pattern which ensures only one object of a type is created. This is useful in when we want to create an object which manages or co ordinates some tasks in the system.

private static Singleton instance = null;
protected Singleton() {
}
public static Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}

The call to Singleton.getInstance() will create a new Singleton type object if the varirable “instance” is null and return it, if “instance” is not null getInstance() just return the “instance”.
The variable “instnace” which is null at the startup is assigned an object at the first call to Singleton.getInstance(), subsequent call to Singleton.getInstance() return the object created at the first call.
Thus ensures only one object of Singleton is there no matter the number of time the getInstance() is called.
This works as expected in a single threaded environment, if only one thread calls getInstance(). If there are multiple threads say A and B, thread A may reach at the null check at which point thread B start executes.
At this point instance is still null to the thread A. Now thread B executes null check the instance and create a new Singleton. Then thread a again executes and create another Singleton since
instance is still null for A. So if there are multiple thread accessing the Singleton class, above code does not ensures the Singletoness.

  • Multi threaded approach.

In order to solve the problem mentioned above, we have to make sure only one thread accesses the getInstance() at a moment. The solution to ensure mutual exclusion for threads in Java is synchronizing the getInstance().

class Singleton {
private Singleton instance;
public Singleton getInstance() {
if (instance == null) {
synchronized(this) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}

The above methods works and provide singletonness. However there is a performance issue. Each and every call need to execute synchronized block which slows down the execution.
In a environment where get instance() is called frequently this will cause a considerable performance degrade.

  • ¬†Double check approach

Double check is introduced to avoid above performance hit. It Go inside synchronized block only after performing instance null check. If it is not null it won’t go inside synchronized block.

class Singleton {
private Singleton instance;
public Singleton getInstance() {
if (instance == null) {
synchronized(this) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}

Double check may also cause problems due many reasons, compiler optimization is one of them. Instance = new type() seems just one operation for us. But there are multiple¬† operations hidden inside. They are a locating memory for the instance, creating the new object by calling the constructor, assigning the newly created object to the “instance” reference. The compiler optimization may reorder these operations depending on the compiler implementation.

Step 1) Assign object to the “instance” reference

Step 2) Constructor code
If the compiler order in above way, if another thread start executed get instance() it may see the instance as Not null (since step1 is over) but only see the default values of the attribute s of the object, not the values specified in the constructor. So the other objects get the wrong values.

  • Make instance volatile
class Singleton {
private volatile Singleton instance;
public Singleton getInstance() {
if (instance == null) {
synchronized(this) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}

By making the instance variable volatile above issue can be resolved since  partial values of volatile variables are not visible to other threads.

  • ¬†A better solution with java class loading(lazy initialization)
    class Singleton {
    private static class InstanceHolder {
    public static Singleton instance = new Singleton();
    }
    
    public static Singleton getInstance() {
    return InstanceHolder.instance;
    }
    }
    

JVM guarantees a class is loaded only once. We add a inner class to store the instance. Since instance is static it is initialized at the time of class loading, thus guaranteed only one instance is created since class is loaded only once. One important thing to notice is InstanceHolder inner class is loaded only at the first call to getinstance(), so delay the instance creation until the object is needed which we call lazy initialization.

  • Create a “New Axis2 Service Project” from WSO2 developer Studio dashboard.
Selection_002
  • Enter project name and service class to expose
    • TestAxis2Service will be the name of the axis2 service and the “TestService” will be the class that will be exposed.

service-class

  • Add operation to expose
    • “sayHello” method will be exposed as a web service.
implemet-service
  • Have a look at the services.xml generated for you.
    • This is the services.xml file which is needed for a axis2 service. Service name and service class are configured according to the values you entered in earlier step. You can change here if you wish.
    services_xml
  • Export the project as a deployable file(.aar file) to into $AXIS2_HOME/repository/services folder.
    • Export the service as a “.aar” file which can be deployed in axis2 engine. Put the “TestAxis2Service_1.0.0.aar” file to the “services” directory of the axis2.
  • rightclick
  • Congratulations ! your service is deployed successfully.
    service_in_axis2