I am having difficulties with deploying my application which needs to know inside state of the cluster regarding the particular statefulset and behave accordingly. So in my deployment.yml file, I add
spec:
serviceName: "my-service"
replicas: 3
Which kubernetes will create 3 pods instantly ( it will not wait until the application inside the container starts) which is not desired in my case. So I have a logic in the application like if its the first replica, do behavior1 if its the second (or any other than first) pick up the last ip of the spawned pod in the statefulset and then connect to it.
Below is my code
String containerRingLastNodeIP = null;
ApiClient client = null;
Configuration.setDefaultApiClient( client );
V1PodList list = null;
try
{
client = Config.defaultClient();
}
catch ( IOException e )
{
SystemLogger.logSystemErrorMessege( e );
}
CoreV1Api api = new CoreV1Api( client );
try
{
list = api
.listNamespacedPod( "mynamespace", null, null, null, null, null, null, null,
null, null );
}
catch ( ApiException e )
{
SystemLogger.logSystemErrorMessege( e );
}
if ( list == null )
{
SystemLogger.logSystemInfoMessege( "PODS list is empty" );
}
List<V1Pod> containersList = list.getItems().stream()
.filter( x -> x.getMetadata().getName().contains( CONTAINER_NAME_TAG ) ).sorted( ( o1, o2 ) -> {
int pod1Id = Integer.parseInt( o1.getMetadata().getName().split( "-" )[1] );
int pod2Id = Integer.parseInt( o2.getMetadata().getName().split( "-" )[1] );
return pod1Id > pod2Id ? 1 : ( pod1Id < pod2Id ? -1 : 0 );
} ).collect(
Collectors.toList() );
String[] containerArguments;
if ( containersList.size() == 1 )
{
//do logic 1
}
else
{
V1Pod recentlyInitializedContainer = containersList
.get( containersList.size() - 2 );//remove the existing pod from the list
containerRingLastNodeIP = recentlyInitializedContainer.getStatus().getPodIP();
//do logic 2
}
So as kubernetes do not wait until my code runs in a pod and it just starts pods, my logic fails and it does not work as expected.
The only way at the moment I see is to put replicas = 1 and scale it up manually which I don't think is good. scaling in the deployment time wont help as the same issue raises. Any idea of getting this done through kubernetes ?