utility

Migrating ReplicationController Between Openshift Cluster

For this scenario, im trying to migrate replicationcontroller (RC) between two OCP with different version. One OCP is on version 3.x, while the other one is 4.x.
So, it’s actually quite tricky. This is the first method that im doing, a simple export on OCP 3

oc get rc -o yaml -n projectname --export > rc.yaml

And do a simple import on OCP 4

oc create -n projectname -f rc.yaml

But there are some error happens,

Error from server (Forbidden): replicationcontrollers "rc-1" is forbidden: 
cannot set blockOwnerDeletion if an ownerReference refers to a resource you can't set finalizers on: no RBAC policy matched, <nil>

It seems like despite im using –export parameter, somehow still exporting the previous DC uid on rc.yaml

    labels:
      app: HelloWorld
      group: com.redhat.edw
      openshift.io/deployment-config.name: helloworld
      provider: fabric8
      version: "1.0"
    name: helloworld-5
    namespace: project
    ownerReferences:
    - apiVersion: apps.openshift.io/v1
      blockOwnerDeletion: true
      controller: true
      kind: DeploymentConfig
      name: helloworld
      uid: 8a96de62-9be4-11ea-a05c-0a659b38d468
    resourceVersion: "65350349"
    selfLink: /api/v1/namespaces/project/replicationcontrollers/helloworld-5
    uid: 257eda84-9be7-11ea-a05c-0a659b38d468

The solution is by removing ownerReferences tag from yaml,

sed -i '/ownerReferences/,+6 d' rc.yaml

It will regenerate ownerReference tag once successfully imported to a new project.


But another problem arise. It seems like despite i’ve successfully import all my RCs, they are not showing when i do a oc get rc command. The culprit is revisionHistoryLimit, removing it from our dc solve this problem.

oc patch  dc helloworld -n project --type json --patch '[{ "op": "remove", "path": "/spec/revisionHistoryLimit" }]'

Migrating Image Stream from One Openshift Image Registry to Another Image Registry with Skopeo

I have a requirement where i need to move all images from Image Registry on Openshift 3, to Image Registry on Openshift 4. There are a lot of ways to do it, such as mounting the same disk to multiple Openshift instance or move in manually using docker pull, tag and then push.

After brainstorming for quite some time, i come up with a solution of using Skopeo as a tools to do image migration. It’s a very convenient tool for handling image copying from one image registry to another.

It is actually a very simple script, first we need to capture all images within every OCP3 project,

	
oc get project -o template --template='{{range.items}}{{.metadata.name}}{{"\n"}}{{end}}' | while read line
do
	oc get imagestreamtag -n $line -o template \ 
		--template='{{range.items}}{{.metadata.namespace}}{{"/"}}{{.metadata.name}}{{"\n"}}{{end}}' > images.txt
done

Use this command to capture your OCP username and token,

# capturing your username
oc whoami 

#capturing your token
oc whoami -t

And then we need to iterate the content of generated file with the username and token you get from previous command.

cat images.txt | while read line
do
	skopeo copy  --src-creds ocp3username:ocp3token --src-tls-verify=false \
		--dest-creds ocp4username:ocp4token  --dest-tls-verify=false \
		docker://docker-registry-from.ocp3/$line \
		docker://image-registry-target.apps.ocp4/$line
done

After all is done, what is left is do a simple validation to count how many images has been migrated.

 oc get imagestreamtag --no-headers | wc -l

Deploy a New Application and Building It Using Openshift S2I Feature and a Custom Base Image

Lots of ways to deploy apps to Openshift, one of it is by using oc new-app command. We are trying now to create a new app using corresponding command, but specifying a custom base image for it. For this example, im using a OpenJDK 11 and RHEL 7 base image.

The command is quite easy, run it on your code folder

D:\source> oc new-app registry.access.redhat.com/openjdk/openjdk-11-rhel7~. --name=spring-boot-2

D:\source> oc start-build spring-boot-2 --from-dir=.

It will create a BuildConfig with the name of spring-boot-2,

D:\source> oc get bc spring-boot-2
NAME            TYPE      FROM      LATEST
spring-boot-2   Source    Binary    3

We can see the detail of our BuildConfig by running this command,

D:\source> oc describe bc spring-boot-2

....
Strategy:       Source
From Image:     ImageStreamTag openjdk-11-rhel7:latest
Output to:      ImageStreamTag spring-boot-2:latest
Binary:         provided on build
....

And if we have some code change and want to redeploy, we can run this command

D:\source> oc start-build spring-boot-2 --from-dir=.

It will rebuild the whole image, and using new code which are uploaded from existing source directory.

[Openshift] Changing revisionHistoryLimit on DeploymentConfig using OC Command

DeploymentConfig on Openshift, and Kubernetes, have revisionHistoryLimit variable which shows how many history a DeploymentConfig should keep. By default it stores 10 last version of application deployment, but sometimes we have to stores less number of revision for saving storage space. Therefore we need to create a hard limit for number of revisionHistoryLimit allowed.

Given below yaml structure on DC,

Based on above image we can change directly on deploymentconfig’s Yml file, but for you who allergic to Yaml (such as me), OC command is much more convenient. This is how i change existing deploymentconfig’s configuration by utilizing OC patch command

oc patch dc starter-v0 -p '{"spec":{"revisionHistoryLimit":2}}'

It will reduce number of revision to two version before,

And this is what happen when changed into one version,

oc patch dc starter-v0 -p '{"spec":{"revisionHistoryLimit":1}}'

[Java] Generate XML From XSD using xjc

For example i have an xsd, and i want to generate an XML based on it using java. This is my xsd example, and i save it as “my.xsd”

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
           xmlns:tns="http://tempuri.org/PurchaseOrderSchema.xsd"
           targetNamespace="http://tempuri.org/PurchaseOrderSchema.xsd"
           elementFormDefault="qualified">
 <xsd:element name="PurchaseOrder" type="tns:PurchaseOrderType"/>
 <xsd:complexType name="PurchaseOrderType">
  <xsd:sequence>
   <xsd:element name="ShipTo" type="tns:USAddress" maxOccurs="2"/>
   <xsd:element name="BillTo" type="tns:USAddress"/>
  </xsd:sequence>
  <xsd:attribute name="OrderDate" type="xsd:date"/>
 </xsd:complexType>

 <xsd:complexType name="USAddress">
  <xsd:sequence>
   <xsd:element name="name"   type="xsd:string"/>
   <xsd:element name="street" type="xsd:string"/>
   <xsd:element name="city"   type="xsd:string"/>
   <xsd:element name="state"  type="xsd:string"/>
   <xsd:element name="zip"    type="xsd:integer"/>
  </xsd:sequence>
  <xsd:attribute name="country" type="xsd:NMTOKEN" fixed="US"/>
 </xsd:complexType>
</xsd:schema>

Next step is generate java bean using xjc using below command

xjc -p com.edw.bean my.xsd

And it will gives below output,

parsing a schema...
compiling a schema...
com\edw\bean\ObjectFactory.java
com\edw\bean\PurchaseOrderType.java
com\edw\bean\USAddress.java
com\edw\bean\package-info.java

Import those generated java files, and print a simple xml on console based on it.

package com.edw;

import com.edw.bean.ObjectFactory;
import com.edw.bean.PurchaseOrderType;
import com.edw.bean.USAddress;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Marshaller;
import javax.xml.datatype.DatatypeFactory;
import java.math.BigInteger;
import java.util.Date;

public class Main {
    public static void main(String[] args) throws Exception {
        new Main().doSomething();
    }

    private void doSomething() throws Exception {
        PurchaseOrderType purchaseOrderType = new PurchaseOrderType();
        USAddress address = new USAddress();
        address.setCity("aaa");
        address.setCountry("US");
        address.setName("cccc");
        address.setState("dddd");
        address.setStreet("eee");
        address.setZip(BigInteger.ONE);

        purchaseOrderType.setBillTo(address);
        purchaseOrderType.getShipTo().add(address);
        purchaseOrderType.setOrderDate(DatatypeFactory.newInstance().newXMLGregorianCalendar(new Date().toInstant().toString()));

        JAXBElement<PurchaseOrderType> element = new ObjectFactory().createPurchaseOrder(purchaseOrderType);
        toXml(element);
    }

    private void toXml(JAXBElement<PurchaseOrderType> element) throws Exception {
        JAXBContext ctx = JAXBContext.newInstance(PurchaseOrderType.class);
        Marshaller marshaller = ctx.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.marshal(element, System.out);
    }
}

It will print below output,

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<PurchaseOrder xmlns="http://tempuri.org/PurchaseOrderSchema.xsd" OrderDate="2019-11-11Z">
    <ShipTo country="US">
        <name>cccc</name>
        <street>eee</street>
        <city>aaa</city>
        <state>dddd</state>
        <zip>1</zip>
    </ShipTo>
    <BillTo country="US">
        <name>cccc</name>
        <street>eee</street>
        <city>aaa</city>
        <state>dddd</state>
        <zip>1</zip>
    </BillTo>
</PurchaseOrder>

Final step is we can validate our generated xml with provided xsd, and see whether generated xml is valid.