2021-07-02

Packer and package installs

Problem: 
When using Packer to generate an Ubuntu AWS AMI, I use a shell script provisioner to install and update packages via apt-get. When executing apt commands in the script, I was getting the errors such as: 
"Package has no installation candidate"
"Unable to locate package" 

 Solution: 
The error in the shell script was that I was executing apt-get commands before the AWS cloud-init completed.

To check that cloud-init finished before running apt-get, modify the script via

while [ ! -f  /var/lib/cloud/instance/boot-finished ];
do
    echo "Waiting for cloud-init to finish ..."
    sleep 2
done

apt-get update -y
apt-get install -y package

2018-10-29

Ruby on Rails json LoadError

Problem:
Running Ruby on Rails 'bin/rails s' and you get an error

in require: cannot load such file -- json (LoadError)


Solution:
Edit the Gemfile and add

gem 'json'


Installing Ruby on Rails on AWS Linux

To install Ruby on Rails on the AWS Linux VM, you need to install some prerequisites first.

sudo su -
yum install -y ruby24
alternatives --set ruby /usr/bin/ruby2.4
yum install -y ruby24-devel rubygems ruby24-devel gcc zlib-devel patch sqlite-devel
curl -sL https://rpm.nodesource.com/setup | bash -
yum install -y nodejs

gem install rails
rails --version

2018-10-26

Add hard disk to VMware CentOS 7 VM

There are two easy steps to add a hard disk for a a VMware CentOS 7 VM

  1.  Assign a new hard disk in VMware vSphere
  2.  Configure the new hard disk in CentOS
See the full picture tutorial at
https://dev.to/juttayaya/add-hard-disk-to-vmware-centos-7-vm-22m8

2018-10-25

Get the original username of sudo

For auditing and logging purposes, I needed to get the original Unix login username and not the sudo account name.

The Unix command to get the original login username is

logname 

With the logname command, the operator can su and sudo to various accounts and it will still display the original login.

To try it on a Unix prompt

sudo su - oracle
echo My sudo id is $(whoami) and my login id is $(logname)

Output:
My sudo id is oracle and my login id is juttayaya



Reference:https://stackoverflow.com/questions/4598001/how-do-you-find-the-original-user-through-multiple-sudo-and-su-commands

2018-02-04

MacBook Pro 2012 broken GPU fix

I have a 17" 2011 MacBook Pro that suffers from the notorious GPU video failure (https://www.bit-tech.net/news/tech/laptops/apple-admits-gpu-design-flaw/1/)

Here is the work-around to turn off the GPU. Credit to PeytonPlaysMc

  1. Boot into Recovery Mode
    For High Sierra 10.13.4 or earlier:
    Hold Command+R+S keyboard buttons while pressing the power button

    For High Sierra 10.13.5 or later:
    Command+R+S (Recovery mode Single-user) no longer works.
    https://apple.stackexchange.com/questions/332587/single-user-recovery-mode-on-high-sierra-10-13-6

    To get to Recovery Mode,
    * Hold Command+S and press the power button
    * On prompt, type command
    nvram fa4ce28d-b62f-4c99-9cc3-6815686e30f9:gpu-power-prefs=%01%00%00%00
    reboot
    * Hold Command+R to enter Recovery Mode GUI
    * Click on "Utilities" on the top menu bar and pick "Terminal"
    * Goto Step 2 below
  2.  Disable System Integrity Protection (SIP)
     
    Type on the command prompt
    csrutil disable
  3. Reboot MacBook Pro into Single User mode
    Type on the command prompt
    reboot
    Then hold Command+S keyboard buttons
  4. Hard disk check
    Type on the command prompt
    /sbin/fsck -fy
  5. Mount root file system in read-write mode
    Type on the command prompt
    /sbin/mount -uw /
  6. Make a directory to save the AMD drivers
    Type on the command prompt
    mkdir /AMD_save
  7. Move AMD drivers to the save directory
    Type on the command prompt
    mv /System/Library/Extensions/AMD* /AMD_save
  8. Delete AMD driver cache
    Type on the command prompt
    rm -rf /System/Library/Caches/com.apple.kext.caches/
  9. Create AMD drive cache directory
    Type on the command prompt
    mkdir /System/Library/Caches/com.apple.kext.caches/
  10. Force refresh of drive cache and reboot
    Type on the command prompt
    touch /System/Library/Extensions/
    nvram fa4ce28d-b62f-4c99-9cc3-6815686e30f9:gpu-power-prefs=%01%00%00%00
    reboot
  11. Boot into Recovery ModeFor High Sierra 10.13.4 or earlier:
    Hold Command+R+S keyboard buttons

    For High Sierra 10.13.5 or later:
    See step 1 above
  12. Enable System Integrity Protection (SIP)Type on the command prompt
    csrutil enable
  13. Reboot MacBook Pro to normal mode.Type on the command prompt
    reboot
  14. Launch Terminal in UI and type
    sudo nvram fa4ce28d-b62f-4c99-9cc3-6815686e30f9:gpu-power-prefs=%01%00%00%00
  15. Restart MacBook Pro one final time

2017-11-28

Debugging sshd and sssd

After patching a CentOS 7 server with the latest rpms, ssh would not authenticate with Active Directory.

To debug,

1. Become root on the Unix server.
  sudo su -

2. Stop the sshd service (Note: this will not kill your current session)
  systemctl stop sshd

3. Start sshd in debug mode. The debug output will print on the terminal
  /sbin/sshd -d

4. From another terminal, ssh into the server
  ssh username@server

5. The sshd debug messages showed that the username could not get authenticated with AD. The first place to look is sssd (System Security Services Daemon)

6. Restart sssd. Got an error message stating sssd failed to start
  systemctl restart sssd

7. First view the sssd error log status. The logs did not provide much debug info
  systemctl -l status sssd

8. Start sssd in debug mode. The debug output will print on the terminal
  sssd -i -d 4

9. The error message in this case was "PAM unable to dlopen /usr/lib/samba/libreplace-samba4.so: version 'SAMBA_4.4.4 not found"

10. Checked the version of the samba-client. This showed that yum update installed both samba-client 4.4.4 and 4.6.2
  yum --showduplicates list samba-client


11. Reinstalled samba-client to only have one version
   yum remove samba-client
   yum install samba-client


12. sssd now success starts and users can AS authenticate on ssh
  systemctl start sssd
  systemctl start sshd


2017-07-30

My quick Boston DevOps talk

I gave a quick talk at the Boston DevOps MeetUp on July 26, 2017 about how my Ansible installer side project became the official product installer at HealthEdge.

https://www.youtube.com/watch?v=Q7sDcU4--l8&t


Forcing Oracle to drop user

If there are sessions currently connected to an Oracle user schema, then you cannot drop the user. For example, if the Oracle user 'mytest' is currently logged in, then

DROP USER mytest CASCADE;

ORA-01940: cannot drop a user that is currently connected 

If you cannot get the Oracle user to voluntarily log off, then as the Oracle admin, you will have to kill the Oracle user session.

There are two ways to kill an Oracle session

ALTER SYSTEM KILL SESSION 'sid,serial#' IMMEDIATE;
ALTER SYSTEM DISCONNECT SESSION 'sid,serial#' IMMEDIATE;

With "kill session", Oracle will request the session to end. With "disconnect session", Oracle will terminate the server process associated with the session.

The Oracle script at https://github.com/juttayaya/oracle/blob/master/drop-user/drop_user_force.sql will both kill and disconnect all Oracle sessions for a user then drop it.  Example of usage:

sqlplus sys as sysdba @drop_user_force.sql mytest

If you are using AWS Oracle RDS, then use the equivalent script https://github.com/juttayaya/oracle/blob/master/drop-user/drop_user_force_aws_rds.sql . Example of usage:

sqlplus sys as sysdba@aws-rds-hostname:1521/ORCL @drop_user_force_aws_rds.sql mytest

2017-07-22

Ansible ssh connection closed error

Problem:
Ansible returns the error "Failed to connect to the host via ssh: Shared connection to host closed"


Solution:
Modify ansible.cfg to send a SSH keep-alive ping every 2 minutes.

ssh_args = -C -o ControlMaster=auto -o ControlPersist=60s -o ServerAliveInterval=120

2017-07-09

AWS terraform: Use DynamoDB locking

Please see the previous post on how to set up terraform to use a remote AWS S3 bucket to store the terraform.tfstate file (http://www.javajirawat.com/2017/07/aws-terraform-use-s3-remote-tfstate-file.html) . This example continues from the S3 bucket article.

Remote terraform state file allows multiple terraform servers to manage the same resources. However if two people try to modify the same terraform state at the same time, it may lead to corruption and errors. Terraform can be configured to use AWS DynamoDB to lock the state file and prevent concurrent edits.

AWS Dynamo DB is a cloud NoSQL key-value database.

Setup:

Create an AWS DynamoDB with terraform to lock the terraform.tfstate.

provider "aws" {
  region = "us-east-1"
}

resource "aws_dynamodb_table" "dynamodb-terraform-lock-example" {
  name = "terraform-lock-example"
  hash_key = "LockID"
  read_capacity = 5
  write_capacity = 5

  attribute {
    name = "LockID"
    type = "S"
  }

  tags {
    Name = "Terraform Lock Table Example"
    Org = "JavaJirawat"
  }
}

You can name the DynamoDB table to anything you wish. The hash_key must be a String attribute named LockID


2.) Execute main.tf to create the DynamoDB table on AWS
      Run the command

      terraform apply

      The AWS account that executes terraform needs AmazonDynamoDBFullAccess permission in the region you are creating the database table
https://console.aws.amazon.com/iam/home?region=us-east-1#/policies/arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess

Usage:

Here is an example of using the DynamoDB table we just created to lock a terraform.tfstate for a AWS EC2 resource.

1.) Create terraform main.tf for AWS EC2 server with a S3 backend to store the terraform.tfstate file and a DynamoDB table to lock it.

terraform {
  backend "s3" {
    bucket = "terraform-s3-tfstate-example"
    region = "us-east-1"
    key = "example/ec2-with-locking/terraform.tfstate"
    dynamodb_table = "terraform-lock-example"
    encrypt = true
  }
}

provider "aws" {
  region = "us-east-1"
}

# Amazon Linux AMI
resource "aws_instance" "ec2-with-locking-example" {
    count = 1
    ami = "ami-a4c7edb2"
    instance_type = "t2.micro"
    
    lifecycle {
      create_before_destroy = true
    }

    tags {
      Name = "Example for DynamoDB lock"
      Org = "JavaJirawat"
    }      
}

The dynamodb_table value must match the name of the DynamoDB table we created.

2.) Initialize the terraform S3 backend
     Run the command

     terraform init

     Type in "yes" for any prompt.

3.) Execute main.tf to create the EC2 server on AWS
      Run the command

      terraform apply

      The AWS account that executes terraform needs AmazonEC2FullAccess permission in the region you are creating the EC2 server
https://console.aws.amazon.com/iam/home?region=us-east-1#/policies/arn:aws:iam::aws:policy/AmazonEC2FullAccess

AWS Terraform: Use S3 remote tfstate file

Terraform uses an text file called terraform.tfstate to store the state of the infrastructure it manages.  (https://www.terraform.io/docs/state/) . If multiple terraform servers manage the same resources, this file needs to be remotely accessible. To prevent accidental deletion or corruption, terraform.tfstate should be versioned.

Amazon S3 (Simple Storage Service) fulfills the above requirements. S3 is a cloud file storage service; basically the AWS version of Dropbox.

Setup:

Create an AWS S3 bucket with terraform to store terraform.tfstate
1.) Create terraform main.tf for AWS S3 bucket.
     See https://github.com/juttayaya/devops/blob/master/hashicorp/terraform/s3-tfstate-example/s3/main.tf

provider "aws" {
  region = "us-east-1"
}

resource "aws_s3_bucket" "s3-tfstate-example" {
    bucket = "terraform-s3-tfstate-example"
    acl = "private"

    versioning {
      enabled = true
    }

    lifecycle {
      prevent_destroy = true
    }

    tags {
      Name = "Terraform S3 tfstate Example"
      Org = "JavaJirawat"
    }      
}

The above configuration turns on S3 versioning so you can query for the history of infrastructure changes. The prevent_destroy = true guards against accidental deletion.

2.) Execute main.tf to create the S3 bucket on AWS
      Run the command

      terraform apply

      The AWS account that executes terraform needs AmazonS3FullAccess permission in the region you are creating the S3 bucket
https://console.aws.amazon.com/iam/home?region=us-east-1#/policies/arn:aws:iam::aws:policy/AmazonS3FullAccess

Usage:

Here is an example of using the S3 bucket we just created to store a terraform.tfstate for a AWS EC2 resource.

1.) Create terraform main.tf for AWS EC2 server with a S3 backend to store the terraform.tfstate file.
     See https://github.com/juttayaya/devops/blob/master/hashicorp/terraform/s3-tfstate-example/ec2/main.tf

terraform {
  backend "s3" {
    bucket = "terraform-s3-tfstate-example"
    region = "us-east-1"
    key = "example/ec2/terraform.tfstate"
    encrypt = true
  }
}

provider "aws" {
  region = "us-east-1"
}

# Amazon Linux AMI
resource "aws_instance" "ec2-example" {
    count = 1
    ami = "ami-a4c7edb2"
    instance_type = "t2.micro"
    
    lifecycle {
      create_before_destroy = true
    }

    tags {
      Name = "Example for S3 tfstate"
      Org = "JavaJirawat"
    }      
}

The terraform backend bucket name and region must match the S3 bucket name and region we created. The key is the full folder path and filename to store the terraform.tfstate file

2.) Initialize the terraform S3 backend
     Run the command

     terraform init

     Type in "yes" for any prompt.

3.) Execute main.tf to create the EC2 server on AWS
      Run the command

      terraform apply

      The AWS account that executes terraform needs AmazonEC2FullAccess permission in the region you are creating the EC2 server
https://console.aws.amazon.com/iam/home?region=us-east-1#/policies/arn:aws:iam::aws:policy/AmazonEC2FullAccess

2016-10-28

Ansible Online Notes

Online notes on technical issues I encountered using Ansible and the resolution. Posting online in case I need to refer to it again
1.)    The remote machine needs to have python simplejson or json module
Resolution: Run command to remote install module
ansible hostname -i inventory/hosts -m raw -a "sudo yum install -y python-simplejson"  -k  -u root -vvvv
2.) authorized_keys does not work on target ssh server
Symptom: When ssh from Ansible server to target server, it ask for a password even when .ssh/authorized_keys are set
Make sure the permissions on the ~/.ssh directory and its contents are proper. When I first set up my ssh key auth, I didn't have the ~/.ssh folder properly set up, and it yelled at me.
  • Your home directory ~, your ~/.ssh directory and the ~/.ssh/authorized_keys file on the remote machine must be writable only by you: rwx------ and rwxr-xr-x are fine, but rwxrwx--- is no good¹, even if you are the only user in your group (if you prefer numeric modes: 700 or 755, not 775).
    If ~/.ssh or authorized_keys is a symbolic link, the canonical path (with symbolic links expanded) is checked.
  • Your ~/.ssh/authorized_keys file (on the remote machine) must be readable (at least 400), but you'll need it to be also writable (600) if you will add any more keys to it.
  • Your private key file (on the local machine) must be readable and writable only by you: rw-------, i.e. 600.
  • Also, if SELinux is set to enforcing, you may need to run restorecon -R -v ~/.ssh (see e.g. Ubuntu bug 965663 and Debian bug report #658675; this is patched in CentOS 6).
 If that does not work, on the target server
sudo su -
service sshd stop   (Note: this will not kill your current session)
/use/sbin/sshd -d   (Note: debug mode)
service sshd start  (Note: do this when finished debugging or else no one can ssh into the VM. Try ssh from a new terminal before exiting the main root terminal)
In debug mode, you will see what sshd is doing when it is trying to read the authorized_keys file
In my case, sshd was reading the wrong file. To fix I had to
Edit /etc/ssh/sshd_config, and uncomment
RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile      .ssh/authorized_keys
Then restart sshd

service sshd stop
service sshd start
3.)    Issue: The remote user needs to be able to “sudo su –“ without password. Needed to  configure iptables firewall and other super-admin commands

Resolution: Have user add entry in /etc/sudoers file
Backlog Enhancement: Have precondition check for root access. Or find a way to make root access unnecessary
4.)    Ansible 2.2.0 had a bug
https://github.com/ansible/ansible/issues/16128
Resolution: Updated Ansible from Git with the latest version
git pull --rebase
git submodule update --init –recursive
5.) Ansible has issues transfering files to target server.
Ansible uses sftp to transfer files behind the scenes. Try
sftp user@target-server
to see if you can sftp without a password.
If you cannot, sftp sometimes has issues with echo in .bashrc . Comment out the echo in .bashrc and try again.
If that does not work, force Ansible to use scp instead of sftp.
In /etc/ansible/ansible.cfg, add the line
scp_if_ssh = True
or if you cannot edit the ansible.cfg file, then from shell type
export ANSIBLE_SCP_IF_SSH=y

2016-03-06

Oracle foreign key analysis

Find Oracle foreign key by name
For Oracle error

SQL Error: ORA-02291: integrity constraint (SCHEMA_OWNER.FOREIGN_KEY_NAME) violated - parent key not found

Find the source and reference Oracle table of the foreign key name using the SQL query below

select uc.CONSTRAINT_NAME, 
  src_ucc.OWNER source_schema ,src_ucc.TABLE_NAME source_table, 
  src_ucc.COLUMN_NAME source_column, src_ucc.POSITION, 
  dest_ucc.TABLE_NAME reference_table, dest_ucc.COLUMN_NAME reference_column,
  dest_ucc.POSITION reference_position,
  uc.DELETE_RULE, uc.STATUS, uc.DEFERRABLE, uc.DEFERRED, uc.VALIDATED  
from sys.USER_CONSTRAINTS uc 
  join sys.USER_CONS_COLUMNS src_ucc 
  on uc.OWNER=src_ucc.OWNER and uc.CONSTRAINT_NAME=src_ucc.CONSTRAINT_NAME
  join sys.USER_CONS_COLUMNS dest_ucc 
  on uc.OWNER=dest_ucc.OWNER and uc.R_CONSTRAINT_NAME=dest_ucc.CONSTRAINT_NAME  
where uc.OWNER='SCHEMA_OWNER' and uc.CONSTRAINT_NAME='FOREIGN_KEY_NAME'
  and uc.CONSTRAINT_TYPE='R' 
  and src_ucc.POSITION=dest_ucc.POSITION
order by src_ucc.TABLE_NAME ,src_ucc.POSITION, dest_ucc.POSITION;

Find all Oracle foreign keys on a table
To find all the foreign keys that a Oracle table has, use the SQL query below

select uc.CONSTRAINT_NAME, 
  src_ucc.OWNER source_schema ,src_ucc.TABLE_NAME source_table, 
  src_ucc.COLUMN_NAME source_column, src_ucc.POSITION, 
  dest_ucc.TABLE_NAME reference_table, dest_ucc.COLUMN_NAME reference_column,
  dest_ucc.POSITION reference_position,
  uc.DELETE_RULE, uc.STATUS, uc.DEFERRABLE, uc.DEFERRED, uc.VALIDATED  
from sys.USER_CONSTRAINTS uc 
  join sys.USER_CONS_COLUMNS src_ucc 
  on uc.OWNER=src_ucc.OWNER and uc.CONSTRAINT_NAME=src_ucc.CONSTRAINT_NAME
  join sys.USER_CONS_COLUMNS dest_ucc 
  on uc.OWNER=dest_ucc.OWNER and uc.R_CONSTRAINT_NAME=dest_ucc.CONSTRAINT_NAME  
where src_ucc.OWNER='SCHEMA_OWNER' and src_ucc.TABLE_NAME='SOURCE_TABLE_NAME'
  and uc.CONSTRAINT_TYPE='R' 
  and src_ucc.POSITION=dest_ucc.POSITION
order by src_ucc.TABLE_NAME ,src_ucc.POSITION, dest_ucc.POSITION;

Find all Oracle foreign keys referenced to a table
To find all the Oracle tables that references a table via foreign key, use the SQL query below

select uc.CONSTRAINT_NAME, 
  src_ucc.OWNER source_schema ,src_ucc.TABLE_NAME source_table, 
  src_ucc.COLUMN_NAME source_column, src_ucc.POSITION, 
  dest_ucc.TABLE_NAME reference_table, dest_ucc.COLUMN_NAME reference_column,
  dest_ucc.POSITION reference_position,
  uc.DELETE_RULE, uc.STATUS, uc.DEFERRABLE, uc.DEFERRED, uc.VALIDATED  
from sys.USER_CONSTRAINTS uc 
  join sys.USER_CONS_COLUMNS src_ucc 
  on uc.OWNER=src_ucc.OWNER and uc.CONSTRAINT_NAME=src_ucc.CONSTRAINT_NAME
  join sys.USER_CONS_COLUMNS dest_ucc 
  on uc.OWNER=dest_ucc.OWNER and uc.R_CONSTRAINT_NAME=dest_ucc.CONSTRAINT_NAME  
where dest_ucc.OWNER='SCHEMA_OWNER' and dest_ucc.TABLE_NAME='REFERENCE_TABLE_NAME'
  and uc.CONSTRAINT_TYPE='R' 
  and src_ucc.POSITION=dest_ucc.POSITION
order by src_ucc.TABLE_NAME ,src_ucc.POSITION, dest_ucc.POSITION;
Column meaning
CONSTRAINT_NAMEThe foreign key name
SOURCE_SCHEMA The schema of the foreign key source table
SOURCE_TABLE The table that has the foreign key
SOURCE_COLUMN The column in the source table enforced by the foreign key
POSITION For foreign keys with multiple columns, the order of the columns in the foreign key
REFERENCE_TABLE The table referenced by the foreign key
REFERENCE_COLUMN The column of the table referenced by the foreign key
REFERENCE_POSITION For foreign keys with multiple columns, the order of the referenced columns in the foreign key
DELETE_RULE The action Oracle performs with the row associated with the foreign key in the reference table is deleted
  • NO ACTION: Oracle respond with a referential integrity error and will not allow the row to be removed
  • CASCADE: Oracle automatically deletes the row in the tables with the associated foreign key
  • SET NULL: Oracle automatically sets the foreign key column value to NULL
STATUS Is the foreign key enforced
  • ENABLED: The foreign key is enforced and active
  • DISABLED: The foreign key is not enforced and inactive
DEFERRABLE If a transaction can use SET CONSTRAINT[S] to dynamically defer a foreign key referential integrity check
  • DEFERRABLE: Yes you can use SET CONSTRAINTS
  • NOT DEFERRABLE: No you cannot use SET CONSTRAINTS
DEFERRED If a foreign key is DEFERRABLE, when in the transaction will Oracle check for foreign key referential integrity violations by default. NOT DEFERRABLE is always IMMEDIATE.
  • DEFERRED: Oracle will check when after a commit has been issued
  • IMMEDIATELY Oracle will immediately check when the SQL is executed.
VALIDATED When adding foreign keys to a Oracle table with existing data, checks to see if the existing data violates foreign key referential integrity.
  • VALIDATED: Oracle will check to see if the existing data violates integrity. If it does then the foreign key will not be created
  • NOT VALIDATED: Oracle will not check to see if the existing data violates integrity. The foreign key will be created even if there is existing bad data

See the Oracle language reference on constraints for more details.

2015-10-04

OSGi Tutorial: Make Classes and Interfaces public

What you will do:
  • Create an OSGi bundle that exports classes and interfaces
What you will learn:
  • What is an OSGi bundle
  • How to create an OSGi bundle using maven-bundle-plugin
  • How to install an OSGi bundle
  • How to expose classes and interfaces so other bundles can use it
  • Learn to use Export-Package in MANIFEST.MF
Code at: https://github.com/juttayaya/osgi/tree/master/api
This code is primarily tested on JBoss Fuse. ServiceMix and Karaf 3 and 4 are also supported.

An OSGi bundle is just a JAR file with custom entries in the META-INF/MANIFEST.MF file.

For this example, we want to make the Java interface com.jirawat.osgi.api.Echo and Java class com.jirawat.osgi.exception.EchoException public so that it can be reused. The end result is a JAR file with Echo and EchoException in it, just like you would normally package any Java classes in a JAR file.  The OSGi difference is that this JAR file contains an entry in META-INF/MANIFEST.MF called Export-Package.  As the name suggests, the Export-Package entry tells OSGi that classes in this Java package are public.

Step 1: Configure maven-bundle-plugin to export public packages
Configure maven-bundle-plugin to specify which Java package to make public by adding it to the Export-Package entries.

Step 2: Configure pom.xml for bundle packaging
Set maven-bundle-plugin extensions to true. Then add bundle as the packaging option

The pom.xml should look like this
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.jirawat.osgi</groupId>
    <artifactId>api</artifactId>
    <version>1.0.0</version>
    <packaging>bundle</packaging>
    <name>jirawat.com :: tutorial :: ${project.artifactId} Bundle</name>
    <description>Tutorial Bundle for ${project.artifactId}</description>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <version>3.0.0</version>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Bundle-SymbolicName>${project.groupId}.${project.artifactId}</Bundle-SymbolicName>
                        <Export-Package>
                            com.jirawat.osgi.api,
                            com.jirawat.osgi.exception
                        </Export-Package>
                        <Import-Package>*</Import-Package>
                    </instructions>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Step 3: Build it
mvn clean package

This produces a JAR file with the Java classes and interfaces and a META-INF/MANIFEST.MF .  Notice the Export-Package entry exports the classes in the com.jirawat.osgi.api and com.jirawat.osgi.exception as public and reusable by other bundles. The MANIFEST.MF looks like

Manifest-Version: 1.0
Bnd-LastModified: 1443617839644
Build-Jdk: 1.7.0_45
Built-By: juttayaya
Bundle-Description: Tutorial Bundle for api
Bundle-ManifestVersion: 2
Bundle-Name: jirawat.com :: tutorial :: api Bundle
Bundle-SymbolicName: com.jirawat.osgi.api
Bundle-Version: 1.0.0
Created-By: Apache Maven Bundle Plugin
Export-Package: com.jirawat.osgi.api;version="1.0.0",com.jirawat.osgi.exception;version="1.0.0"
Require-Capability: osgi.ee;filter:="(&(osgi.ee=JavaSE)(version=1.5))"
Tool: Bnd-3.0.0.201509101326

Step 4: Install it
Put the JAR file from step 3 in any directory and use the osgi:install JBoss Fuse command to install it

For example:
osgi:install -s file:/usr/local/osgi/api-1.0.0.jar

Note for ServiceMix and Karaf 3 and 4, use the bundle:install command

bundle:install -s file:/usr/local/osgi/api-1.0.0.jar

The osgi:list command shows the bundle installed. (bundle:list for ServiceMix and Karaf)

osgi:list

[ 268] [Active     ] [            ] [       ] [   80] jirawat.com :: tutorial :: api Bundle (1.0.0)

2015-09-29

How to build an offline Karaf server

What you will do:
  • Create an offline version of Apache Karaf
What you will learn:
  • Configure karaf-maven-plugin and maven-dependency-plugin
  • Override Karaf default behavior with Maven 
The default behavior of Apache Karaf is to download Java library dependencies as needed from Maven repositories such as http://repo1.maven.org/ . To perform this functionality, Karaf will use the Maven ~/.m2/settings.xml file and store dependencies in the ~/.m2/repository directory.

The confirm this behavior empirically
mv ~/.m2 ~/.m2_save

And disable internet access.
If you start a new version of Karaf and try to install any feature such as
feature:install jndi

you will get the error message
Error executing command: Can't install feature jndi/0.0.0: 
Error resolving artifact org.apache.xbean:xbean-naming:jar:3.18: Could not transfer artifact org.apache.xbean:xbean-naming:jar:3.18 from/to central (http://repo1.maven.org/maven2/): repo1.maven.org: nodename nor servname provided, or not known

If you turn internet access back on and rerun feature:install jndi, Karaf will create the directory ~/.m2/repository and put the library dependencies for Karaf jndi in that directory.

This may be undesirable behavior, especially in secured production, when servers typically cannot download artifacts freely from the internet.  From a developer perspective, it can be surprising that changing Maven settings.xml for another unrelated project can affect the runtime behavior of Karaf.

Follow the instructions below to create an offline version of Apache Karaf where the dependencies are preloaded at compile time and is not dependent on Maven.

This tutorial is based on Karaf 3.0.4 . The procedure for Karaf 2 and 4 are similar
Karaf 2: Coming Soon
Karaf 3: https://github.com/juttayaya/karaf/tree/master/karaf3/offline-karaf
Karaf 4: https://github.com/juttayaya/karaf/tree/master/karaf4/offline-karaf4

Step 1: Configure karaf-maven-plugin to generate an offline version of Karaf
Configure the setting ignoreDependencyFlag of karaf-maven-plugin to true. This configures the karaf-maven-plugin to download library dependencies into the directory ${karaf.home}/system
<plugin>
    <groupId>org.apache.karaf.tooling</groupId>
    <artifactId>karaf-maven-plugin</artifactId>
    <!-- Plugin requires at minimum 3.0.3 version for dependency=true bug fix
    https://issues.apache.org/jira/browse/KARAF-2596 -->
    <version>${karaf.plugin.version}</version>
    <extensions>true</extensions>
    <configuration>
      <karafVersion>${karaf.version}</karafVersion>
      <!-- ignoreDependencyFlag is true forces plugin to also
           download feature dependent libraries -->
      <ignoreDependencyFlag>true</ignoreDependencyFlag>
    </configuration>
</plugin>

Step 2: Add the Karaf features.xml you want to install as dependencies.
For example, to add camel to Karaf, add this dependency
<!-- https://repo1.maven.org/maven2/org/apache/camel/karaf/apache-camel/2.15.2/apache-camel-2.15.2-features.xml -->
<dependency>
    <groupId>org.apache.camel.karaf</groupId>
    <artifactId>apache-camel</artifactId>
    <version>${camel.version}</version>
    <classifier>features</classifier>
    <type>xml</type>
    <scope>runtime</scope>
</dependency>

Step 3:  Add the feature as bootFeatures or installedFeatures in karaf-maven-plugin
BootFeatures automatically begins on Karaf startup. InstalledFeatures just installs the library dependencies in the ${karaf.home}/system directory. The user will have to start it up manually via the command feature:install

For example, to start up camel at boot time but manually start up camel-quartz2
<bootFeatures>
    <feature>camel</feature>
</bootFeatures>
<installedFeatures>
    <feature>camel-quartz2</feature>
</installedFeatures>


Step 4: Add Maven repository http://svn.apache.org/repos/asf/servicemix/m2-repo
The dependency org.eclipse.equinox:region:jar:1.0.0.v20110506 for the "region" Karaf feature is not uploaded to the normal repo1.maven.org. Add this servicemix repository so Karaf can download the correct file
<repositories>
    <repository>
      <id>servicemix</id>
      <name>ServiceMix Repo for Karaf</name>
      <url>http://svn.apache.org/repos/asf/servicemix/m2-repo</url>
    </repository>
</repositories>

Step 5: Configure Karaf not to use external Maven
Create file src/main/resources/etc/org.ops4j.pax.url.mvn.cfg and add the following lines
org.ops4j.pax.url.mvn.settings=${karaf.home}/etc/karaf_maven_settings.xml
org.ops4j.pax.url.mvn.repositories=

This configures Karaf to not use the default Maven ~/.m2/settings.xml and not to try to download from any external Maven repositories like repo1.maven.org

See https://github.com/juttayaya/karaf/blob/master/karaf3/offline-karaf/src/main/resources/etc/org.ops4j.pax.url.mvn.cfg for a full example.

Create file src/main/resources/etc/karaf_maven_settings.xml with no Maven settings
<settings 
    xmlns="http://maven.apache.org/SETTINGS/1.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http:/maven.apache.org/SETTINGS/1.0.0 
        http://maven.apache.org/xsd/settings-1.0.0.xsd">
</settings>

See https://github.com/juttayaya/karaf/blob/master/karaf3/offline-karaf/src/main/resources/etc/karaf_maven_settings.xml for a full example

Step 6: Manually add any missing dependencies
Not all Karaf runtime dependencies are listed in features.xml (Probably a bug). We have to help offline Karaf by manually downloading the missing dependencies.

For example, https://repo1.maven.org/maven2/org/apache/karaf/features/standard/3.0.4/standard-3.0.4-features.xml is missing org.apache.karaf.jaas.boot.jar. To download it manually and put it in the ${karaf.home}/system directory, configure the maven-dependency-plugin
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-dependency-plugin</artifactId>
    <executions>
      <execution>
        <id>copy</id>
        <phase>generate-resources</phase>
        <goals>
         <goal>copy</goal>
        </goals>
        <configuration>
         <artifactItems>
          <artifactItem>
          <groupId>org.apache.karaf.jaas</groupId>
          <artifactId>org.apache.karaf.jaas.boot</artifactId>
          <version>${karaf.version}</version>
          <outputDirectory>
          target/assembly/system/org/apache/karaf/jaas/org.apache.karaf.jaas.boot
          </outputDirectory>
          </artifactItem>
         </artifactItems>
        </configuration>
      </execution>
    </executions>
</plugin>



2015-09-28

How to uncompress tar.gz with one command

Problem:
I have a file called "thefiles.tar.gz" and I want to uncompress and unarchive in one Unix command.

Solution:
Use the command

tar xzpvf thefiles.tar.gz


Problem:
I have a directory called "thefiles" and I want to compress and archive it into a file called "thefiles.tar.gz" in one command.

Solution:
Use the command

tar czpvf thefiles.tar.gz thefiles

2015-09-21

Change Apache Karaf default logging options

What you will do:
  • Change the location of the Karaf log file
  • Change the Karaf log file name, size, and retention rate
  • Write Karaf system output to a log file
What you will learn:
  • Overwrite default Karaf configuration files
  • Create new directories in custom Karaf server
  • Set Karaf environment variables
Please see the post "Create a custom Apache Karaf server" for the initial setup.

Apache Karaf has poor initial logging configurations for production.  Below are instructions on how to change it.

Step 1: Overwrite default Karaf logging configuration file
The default Karaf logging configuration file is etc/org.ops4j.pax.logging.cfg . The default Karaf log settings is to write to data/log/karaf.log , with a 1MB file size limit and a 10 file retention. To overwrite, create the file src/main/resources/etc/org.ops4j.pax.logging.cfg .  We are changing the log file to logs/dekantar.log, with a daily rotating log. 

The contents of etc/org.ops4j.pax.logging.cfg should look like
# Root logger
log4j.rootLogger=INFO, daily, osgi:*
log4j.throwableRenderer=org.apache.log4j.OsgiThrowableRenderer

# Daily File appender
log4j.appender.daily=org.apache.log4j.DailyRollingFileAppender
log4j.appender.daily.layout=org.apache.log4j.PatternLayout
log4j.appender.daily.layout.ConversionPattern=%d{ISO8601} | %-5.5p | %-16.16t | %-32.32c{1} | %X{bundle.id} - %X{bundle.name} - %X{bundle.version} | %m%n
log4j.appender.daily.file=${karaf.home}/logs/dekantar.log
log4j.appender.daily.datePattern='.'yyyy-MM-dd


Step 2: Create the logs directory
Create the logs directory in /src/main/resources/logs.


Step 3: Create the Karaf system output logfile
In Karaf 3.0.4, the Karaf system output log file is defined in the file bin/setenv as the variable KARAF_REDIRECT . If the variable is not defined, then the system output goes to /dev/null . In previous versions of Karaf 3, the system output logfile was hardcoded as data/log/karaf.out . 

To change the system output logfile to logs/dekantar.out , create the file src/main/resources/bin/setenv 

The content of bin/setenv should look like
#!/bin/sh

ENVHOME=`dirname $0`
LOG_HOME=`cd $ENVHOME/..;pwd`
export KARAF_REDIRECT=${LOG_HOME}/logs/dekantar.out

2015-09-20

Migrating JAXB from WebLogic 11g to WebLogic 12c

From WebLogic 11g to WebLogic 12c, the default JAXB implementation changed from Glassfish RI to EclipseLink MOXy. (1)

EclipseLink MOXy has some fun surprises and bugs if you are not expecting it. The JAXB bindings and data population may not work as previously expected. Click the links below for some examples.


To revert to the previous version of Glassfish RI in WebLogic 12, try one of the solutions below.

Use Glassfish RI at the application level
1. Add the following section to the weblogic-application.xml of the EAR archive

<prefer-application-resources>
    <resource-name>
      META-INF/services/com.sun.xml.ws.spi.db.BindingContextFactory
    </resource-name>

    <resource-name>
      META-INF/services/javax.xml.bind.JAXBContext

    </resource-name>
</prefer-application-resources>

2. In the EAR archive, create the file
META-INF/services/com.sun.xml.ws.spi.db.BindingContextFactory

In this file, just add this one line

com.sun.xml.ws.db.glassfish.JAXBRIContextFactory

3. In the EAR archive, create the file
META-INF/services/javax.xml.bind.JAXBContext

In this file, just add this one line

com.sun.xml.bind.v2.ContextFactory

Use Glassfish RI at the Weblogic Server level
In the file user_projects/domain/mydomain/bin/setDomainEnv.sh, change the following

from
WL_HOME="/mypath/Oracle/Middleware/Oracle_Home/wlserver"
export WL_HOME

to
WL_HOME="/mypath/Oracle/Middleware/Oracle_Home/wlserver"
export WL_HOME

PRE_CLASSPATH="${WL_HOME}/modules/databinding.override_1.2.0.0.jar
export PRE_CLASSPATH

Use Glassfish RI with WebLogic client tools like jwsc
Add the Java system properties to the jwsc tool classpath

-Dcom.sun.xml.ws.spi.db.BindingContextFactory=
com.sun.xml.ws.db.glassfish.JAXBRIContextFactory,
javax.xml.bind.JAXBContext=
com.sun.xml.bind.v2.ContextFactory


Source
(1) http://docs.oracle.com/cd/E24329_01/web.1211/e24964/data_types.htm#WSGET345