Tuesday, 31 October 2023

Applying Color to PlantUML Connectors

Using parenthesis, we can denote a connector.

Example

(someCharacter)

 

Using #color notation, we can apply colors to the connector.

 

addColorToConnector.txt

@startuml

start

:Activity1;
#aqua:(A)
:Activity2;
#gold:(G)
:Activity3;
#silver:(S)

stop

@enduml

 

Above snippet generate below diagram.

 


 

Previous                                                    Next                                                    Home

PlantUML: How to denote a connector in activity diagram using parentheses

Using parenthesis, we can denote a connector.

Example

(someCharacter)

 

connector.txt

@startuml

start

:Activity1;
:Activity2;
(C)
kill
(C)
:Activity3;


stop

@enduml

 

Above snippet generate below diagram.


 

 

Previous                                                    Next                                                    Home

PlantUML Activity Diagram Arrows

Using [], we can specify arrow color and style to the arrows in the activity diagram.

 

arrowColorAndStyle.txt

@startuml

start

:Activity1;
-[#blue]->

:Activity2;
-[#red,bold]->red and bold color;

:Activity3;
-[#green,dotted]-> green and dotted;

:Activity4;
-[#gold,dashed]-> gold and dashed;

stop

@enduml

Above snippet generate below diagram.



 


Previous                                                    Next                                                    Home

What happen when readiness and liveness probe will not respond after sometime?

Readiness probe

Readiness probe determines whether a container is ready to receive the traffic or not. Internally, Kubernetes checks the readiness probe periodically and validate the response. By any chance if the readiness probe fails, then Kubernetes remove this pod from serving the traffic.

 

Following properties can be configured for a readiness probe.

 

Property

Description

initialDelaySeconds

Specifies number of seconds to wait before running the readiness probe for the first time. This helps in giving container some time to start up.

periodSeconds

Specifies the number of seconds between readiness probe checks.

timeoutSeconds

Specifies the number of seconds to wait for a readiness probe to respond before marking the pod as unhealthy.

failure Threshold

Specifies the number of consecutive readiness probe failures that must occur before the pod state is set to unhealthy.

 

Example

readinessProbe:
  httpGet:
    path: /healthz
    port: 80
    initialDelaySeconds: 5
    periodSeconds: 10
    timeoutSeconds: 1
    failureThreshold: 3

 

Above snippet used to perform HTTP GET requests to the "/healthz" path on port 80 of the container to check the health of readiness probe. This check starts 5 seconds after the container starts and repeating every 10 seconds. The probe will time out after 1 second of waiting for a response, and if it fails 3 times in a row, the container will be considered not ready for incoming network traffic.

 

What happen when a readiness probe does not respond?

The pod longer able to serve traffic. Once the readiness probe is able to respond successfully, then Kubernetes will mark the pod as Ready and it will start receiving traffic again.

 

Liveness probe

Liveness probe helps Kubernetes to check whether a container is still alive or not. Kubernetes will periodically run the liveness probe, and if the probe fails, Kubernetes will restart the container. Liveness probes are used to detect unhealthy containers.

 

Property

Description

initialDelaySeconds

Specifies number of seconds to wait before running the liveness probe for the first time. This helps in giving container some time to start up.

periodSeconds

Specifies the number of seconds between liveness probe checks.

timeoutSeconds

Specifies the number of seconds to wait for a liveness probe to respond before marking the pod as unhealthy.

failure Threshold

Specifies the number of consecutive liveness probe failures that must occur before the pod state is set to unhealthy.

 

Example
livenessProbe:
  httpGet:
    path: /healthz
    port: 80
    initialDelaySeconds: 10
    periodSeconds: 15
    timeoutSeconds: 1
    failureThreshold: 3

 

In the above snippet, liveness probe is configured to perform an HTTP GET request to the "/healthz" path on port 80 of the container. The initialDelaySeconds parameter dictates that the first liveness probe check will start 10 seconds after the container is launched. Subsequent checks will occur at 15-second intervals (periodSeconds). The probe will consider itself failed if it doesn't receive a response within 1 second (timeoutSeconds) and will tolerate up to 3 consecutive failures (failureThreshold) before marking the container as unhealthy, potentially triggering actions like restarting the container to maintain the overall system's reliability.

 

What happen when a liveness probe does not respond?

Kubernetes will restart the container.


 

                                                             System Design Questions

How to store the password securely in a database?

Storing passwords or any sensitive information securely is a critical aspect in any application. In this post, I am going to talk about various approaches to store the passwords, and the pros and cons in each approach.

Hash the passwords

Use one-way hash algorithms to convert the given password into a fixed length of string.

 

Collision resistance

One way hash algorithms are designed in such a way that it is very difficult to find two different inputs that produce the same hash value.

 

What are the popular one-way hash algorithms?

some popular one-way hash algorithms include:

 

a.   SHA-2 (Secure Hash Algorithm 2)

b.   MD5 (Message Digest 5)

c.    RIPEMD-160 (RACE Integrity Primitives Evaluation Message Digest)

d.   BLAKE2

 

Following snippet generate a hash using SHA-256 algorithm

MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(string.getBytes());

Find the complete working application below.

 

HashGenerationDemo.java

package com.sample.app;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class HashGenerationDemo {
	public static String generateSHA2Hash(String string) throws NoSuchAlgorithmException {
		MessageDigest digest = MessageDigest.getInstance("SHA-256");
		byte[] hash = digest.digest(string.getBytes());
		return toHexString(hash);
	}

	private static String toHexString(byte[] hash) {
		StringBuilder hexString = new StringBuilder();
		for (byte b : hash) {
			hexString.append(String.format("%02x", b));
		}
		return hexString.toString();
	}

	public static void main(String[] args) throws NoSuchAlgorithmException {
		String message = "This is message is very sensitive and should be transferred securily";
		String hash = generateSHA2Hash(message);

		System.out.printf("Original message : %s\n", message);
		System.out.printf("Hash : %s", hash);

	}
}

Output

Original message : This is message is very sensitive and should be transferred securily
Hash : 129a200ca934a67d74d68ba04977151f3c2ad5cfac1f92d4a5675ba93a6855ad

Drawback of this approach

Rainbow table attacks: Attacker can create pre-computed tables of hash values for common passwords, and can then use this dictionary to generate collisions, which can be used to crack other passwords.

How to address this problem?

We can solve this problem by salting the password.

 

Salting the password

Salting the password makes the attacker task much more difficult to crack passwords using rainbow table attacks and collision attacks.

 


In this procedure, you generate a random text/value and add it to the actual password before hashing it.

 

hashedValue = hash(password+random_value)

 

Scenario 1: User 'A' register with username and password

When a person 'A' registers your website with the username and password. You are going to generate a random text/value, add it to the password and compute the hash. Your table looks like below.

 

id

username

salt

hased_password










                                            

Scenario 2: What if two different users registered with same password.

As the salt value generated for the two users is different, our application generates two different hashed passwords. You can confirm the same from below application.

 

HashGenerationUsingSalt.java

package com.sample.app;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class HashGenerationUsingSalt {

	public static String generateSalt() {
		SecureRandom random = new SecureRandom();
		byte[] salt = new

		byte[32];
		random.nextBytes(salt);
		return new String(salt, StandardCharsets.UTF_8);
	}

	public static String generateSHA2Hash(final String password) throws NoSuchAlgorithmException {
		String salt = generateSalt();
		String saltedPassword = password + salt;
		MessageDigest digest = MessageDigest.getInstance("SHA-256");
		byte[] hash = digest.digest(saltedPassword.getBytes());
		return toHexString(hash);
	}

	private static String toHexString(byte[] hash) {
		StringBuilder hexString = new StringBuilder();
		for (byte b : hash) {
			hexString.append(String.format("%02x", b));
		}
		return hexString.toString();
	}

	public static void main(String[] args) throws NoSuchAlgorithmException {
		String password = "password@334GT123";

		int count = 10;
		System.out.printf("Experiment by generating hash for the same password %d times\n", count);

		for (int i = 0; i < count; i++) {
			String hash = generateSHA2Hash(password);
			System.out.printf("%d. Generated hash : %s\n", i, hash);
		}

	}
}

Output

Experiment by generating hash for the same password 10 times
0. Generated hash : d0e9e10d549df962f06b6c810612a3639bff3949639a370dcf1a8ecc68f1c1d8
1. Generated hash : 7dfdb5815ba7c06258f9added188cc1ab918eeab9c2cf511ca9a86720042ce96
2. Generated hash : a9c3151cf5885c16f0e127cf0e444275a3e486fce47767b08ca11eb2733de69c
3. Generated hash : 02f9dbebde4e20fcd5b9b283ba51fcdc60e242a087c72475a8f24d5d7ae301d5
4. Generated hash : 3780aebc82a37eecb321875e8480f4a98717ccad8a203118780e6bbe4b381a4b
5. Generated hash : 6a1fbc126321b0ac14f2074f13b5b83dc43c72b08acf04872896c91c3ced6b75
6. Generated hash : 0d44d7e2add6c7233de8f735f6374c46bf1827db0f6c6c59f356fb1333fc15e0
7. Generated hash : 3deeaac8f2ab8297333458592eb9ca02c40e9a6fda4289dcf349e523bff96f7b
8. Generated hash : 52588d3fd5ea7c319faa7fdf98ac7ec4e2a04b5bf4ae78e802d0a0788a389a9a
9. Generated hash : a6f2c3d22b6b40ae006496d23fc6a3d1608c51cc5ac35cf97f7da88e3325cef2

References

Digital Signature

How to generate SHA-1 hash of a file?



                                                             System Design Questions

Sunday, 29 October 2023

Pandas: categorical columns in a DataFrame

Category columns are used to define categorical data like gender, month etc., It is mainly used for efficient storage and manipulation of categorical data.

Example

df['Gender'] = df['Gender'].astype("category")

 

categorical_column.py

import pandas as pd
import numpy as np

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Sailu', 'Joel', 'Chamu', 'Jitendra', "Raj"],
        'Age': [34, 35, 29, 41, 52, 31],
        'City': ['Bangalore', 'Hyderabad', 'Hyderabad', 'Chennai', 'Bangalore', 'Chennai'],
        'Gender': ['Male', 'Female', 'Male', 'Female', 'Male', 'Male']}

df = pd.DataFrame(data)

# Add 1000000 rows
rows = []
i = 0
while i < 10000000:
    new_row = {}
    if i % 2 == 0:
        new_row = {'Name': 'Name ' + str(i), 'Age': 28, 'City': 'Bangalore', 'Gender': 'Female'}
    else:
        new_row = {'Name': 'Name ' + str(i), 'Age': 28, 'City': 'Hyderabad', 'Gender': 'Male'}

    rows.append(new_row)
    i = i + 1

df = pd.concat([df, pd.DataFrame(rows)])
df.info()

print('\nChange the Gender to categorical column\n')
df['Gender'] = df['Gender'].astype("category")
df.info()

In this example, the ‘Gender’ column is initially created as a regular object column. We then converted it to the categorical data type using the astype() method.

 

Output

<class 'pandas.core.frame.DataFrame'>
Index: 10000006 entries, 0 to 9999999
Data columns (total 4 columns):
 #   Column  Dtype 
---  ------  ----- 
 0   Name    object
 1   Age     int64 
 2   City    object
 3   Gender  object
dtypes: int64(1), object(3)
memory usage: 381.5+ MB

Change the Gender to categorical column

<class 'pandas.core.frame.DataFrame'>
Index: 10000006 entries, 0 to 9999999
Data columns (total 4 columns):
 #   Column  Dtype   
---  ------  -----   
 0   Name    object  
 1   Age     int64   
 2   City    object  
 3   Gender  category
dtypes: category(1), int64(1), object(2)
memory usage: 314.7+ MB

As you see the above output, DataFrame with categorical type took 314.7+ MB whereas with non-categorical type took 381.5+ MB.

 

Benefits of categorical column

a.   Efficient memory usage

b.   Faster the computations


  

Previous                                                 Next                                                 Home

Pandas: Convert column type of a DataFrame

Using ‘asType’ method, we can change the column type of a DataFrame.

Example

df['Age'] = df['Age'].astype('int')

 

Above snippet change the column type of ‘Age’ to int, It works only when the column Age do not have missing values.

 

change_column_type.py

import pandas as pd
import numpy as np

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Ram', 'Joel', 'Gopi', 'Jitendra', "Raj"],
        'Age': [34, np.nan, 29, 41, 52, np.nan],
        'City': ['Bangalore', None, 'Hyderabad', None, 'Bangalore', 'Chennai']}

df = pd.DataFrame(data)
print(df)

print('\nGet the DataFrame information')
df.info()

if df['Age'].hasnans == True:
    print('\nFound missing values, replacing them with 0')
    df['Age'].fillna(0, inplace=True)

print('\nSet the type of "age" column as int\n')
df['Age'].astype('int')
df.info()

 

Output

       Name   Age       City
0   Krishna  34.0  Bangalore
1       Ram   NaN       None
2      Joel  29.0  Hyderabad
3      Gopi  41.0       None
4  Jitendra  52.0  Bangalore
5       Raj   NaN    Chennai

Get the DataFrame information
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 6 entries, 0 to 5
Data columns (total 3 columns):
 #   Column  Non-Null Count  Dtype  
---  ------  --------------  -----  
 0   Name    6 non-null      object 
 1   Age     4 non-null      float64
 2   City    4 non-null      object 
dtypes: float64(1), object(2)
memory usage: 272.0+ bytes

Found missing values, replacing them with 0

Set the type of "age" column as int

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 6 entries, 0 to 5
Data columns (total 3 columns):
 #   Column  Non-Null Count  Dtype 
---  ------  --------------  ----- 
 0   Name    6 non-null      object
 1   Age     6 non-null      int64 
 2   City    4 non-null      object
dtypes: int64(1), object(2)
memory usage: 272.0+ bytes

 

 

Previous                                                 Next                                                 Home