❌

Normal view

There are new articles available, click to refresh the page.
Before yesterdayMain stream

HAProxy EP 1: Traffic Police for Web

9 September 2024 at 16:59

In the world of web applications, imagine you’re running a very popular pizza place. Every evening, customers line up for a delicious slice of pizza. But if your single cashier can’t handle all the orders at once, customers might get frustrated and leave.

What if you could have a system that ensures every customer gets served quickly and efficiently? Enter HAProxy, a tool that helps manage and balance the flow of web traffic so that no single server gets overwhelmed.

Here’s a straightforward guide to understanding HAProxy, installing it, and setting it up to make your web application run smoothly.

What is HAProxy?

HAProxy stands for High Availability Proxy. It’s like a traffic director for your web traffic. It takes incoming requests (like people walking into your pizza place) and decides which server (or pizza station) should handle each request. This way, no single server gets too busy, and everything runs more efficiently.

Why Use HAProxy?

  • Handles More Traffic: Distributes incoming traffic across multiple servers so no single one gets overloaded.
  • Increases Reliability: If one server fails, HAProxy directs traffic to the remaining servers.
  • Improves Performance: Ensures that users get faster responses because the load is spread out.

Installing HAProxy

Here’s how you can install HAProxy on a Linux system:

  1. Open a Terminal: You’ll need to access your command line interface to install HAProxy.
  2. Install HAProxy: Type the following command and hit enter

sudo apt-get update
sudo apt-get install haproxy

3. Check Installation: Once installed, you can verify that HAProxy is running by typing


sudo systemctl status haproxy

This command shows you the current status of HAProxy, ensuring it’s up and running.

Configuring HAProxy

HAProxy’s configuration file is where you set up how it should handle incoming traffic. This file is usually located at /etc/haproxy/haproxy.cfg. Let’s break down the main parts of this configuration file,

1. The global Section

The global section is like setting the rules for the entire pizza place. It defines general settings for HAProxy itself, such as how it should operate, what kind of logging it should use, and what resources it needs. Here’s an example of what you might see in the global section


global
    log /dev/log local0
    log /dev/log local1 notice
    chroot /var/lib/haproxy
    stats socket /run/haproxy/admin.sock mode 660
    user haproxy
    group haproxy
    daemon

Let’s break it down line by line:

  • log /dev/log local0: This line tells HAProxy to send log messages to the system log at /dev/log and to use the local0 logging facility. Logs help you keep track of what’s happening with HAProxy.
  • log /dev/log local1 notice: Similar to the previous line, but it uses the local1 logging facility and sets the log level to notice, which is a type of log message indicating important events.
  • chroot /var/lib/haproxy: This line tells HAProxy to run in a restricted area of the file system (/var/lib/haproxy). It’s a security measure to limit access to the rest of the system.
  • stats socket /run/haproxy/admin.sock mode 660: This sets up a special socket (a kind of communication endpoint) for administrative commands. The mode 660 part defines the permissions for this socket, allowing specific users to manage HAProxy.
  • user haproxy: Specifies that HAProxy should run as the user haproxy. Running as a specific user helps with security.
  • group haproxy: Similar to the user directive, this specifies that HAProxy should run under the haproxy group.
  • daemon: This tells HAProxy to run as a background service, rather than tying up a terminal window.

2. The defaults Section

The defaults section sets up default settings for HAProxy’s operation and is like defining standard procedures for the pizza place. It applies default configurations to both the frontend and backend sections unless overridden. Here’s an example of a defaults section


defaults
    log     global
    option  httplog
    option  dontlognull
    timeout connect 5000ms
    timeout client  50000ms
    timeout server  50000ms

Here’s what each line means:

  • log global: Tells HAProxy to use the logging settings defined in the global section for logging.
  • option httplog: Enables HTTP-specific logging. This means HAProxy will log details about HTTP requests and responses, which helps with troubleshooting and monitoring.
  • option dontlognull: Prevents logging of connections that don’t generate any data (null connections). This keeps the logs cleaner and more relevant.
  • timeout connect 5000ms: Sets the maximum time HAProxy will wait when trying to connect to a backend server to 5000 milliseconds (5 seconds). If the connection takes longer, it will be aborted.
  • timeout client 50000ms: Defines the maximum time HAProxy will wait for data from the client to 50000 milliseconds (50 seconds). If the client doesn’t send data within this time, the connection will be closed.
  • timeout server 50000ms: Similar to timeout client, but it sets the maximum time to wait for data from the server to 50000 milliseconds (50 seconds).

3. Frontend Section

The frontend section defines how HAProxy listens for incoming requests. Think of it as the entrance to your pizza place.


frontend http_front
    bind *:80
    default_backend http_back
  • frontend http_front: This is a name for your frontend configuration.
  • bind *:80: Tells HAProxy to listen for traffic on port 80 (the standard port for web traffic).
  • default_backend http_back: Specifies where the traffic should be sent (to the backend section).

4. Backend Section

The backend section describes where the traffic should be directed. Think of it as the different pizza stations where orders are processed.


backend http_back
    balance roundrobin
    server app1 192.168.1.2:5000 check
    server app2 192.168.1.3:5000 check
    server app3 192.168.1.4:5000 check
  • backend http_back: This is a name for your backend configuration.
  • balance roundrobin: Distributes traffic evenly across servers.
  • server app1 192.168.1.2:5000 check: Specifies a server (app1) at IP address 192.168.1.2 on port 5000. The check option ensures HAProxy checks if the server is healthy before sending traffic to it.
  • server app2 and server app3: Additional servers to handle traffic.

Testing Your Configuration

After setting up your configuration, you’ll need to restart HAProxy to apply the changes:


sudo systemctl restart haproxy

To check if everything is working, you can use a web browser or a tool like curl to send requests to HAProxy and see if it correctly distributes them across your servers.

4.Operators & Conditionals.py

16 July 2024 at 07:13

Python Operators

Operators are used to perform operations on variables and values.

Python language supports various types of operators, which are:
Arithmetic Operators.
Comparison (Relational) Operators.
Assignment Operators.
Logical Operators.
Bitwise Operators.
Membership Operators.
Identity Operators.

*Add Two Numbers '+' *

operand or the values to be added can be integer values or floating-point values. The '+' operator adds the values

Image description

Subtraction '-' ** in Python is as simple as it is in basic arithmetic. To subtract two numbers, **we use the '-' operator.

Image description

*multiply '' **
In Python, the most straightforward way to multiply two numbers is by using the * operator. This operator works with integers, floats,

Image description
Division
1 Integer division is represented by "//" and returns the quotient rounded down to the nearest integer.
2 Floating division is represented by "/" and returns the quotient as a floating-point number.
3Integer division is useful when dealing with quantities that cannot be represented as fractions or decimals.
4.Floating division is useful when dealing with quantities that are not integer values.
5 / 2 #output : 2.5
5 // 2 #output : 2

. *How to get the input from the user *?

In Python, we use the input() function to ask the user for input. As a parameter, we input the text we want to display to the user. Once the user presses β€œenter,” the input value is returned. We typically store user input in a variable so that we can use the information in our program.

Image description
]

input data type & type casting

`# Addition

num1 = float(input("Enter Number 1")
num2 = float(input("Enter Number 2 : ")

result = num1 + num2

print("result is", result)

Enter Number 1: 2

Enter Number 2: 4

result is 6.0`

`# subtract

num1 = float(input("Enter Number 1: ")

num2 = float(input("Enter Number 2: ")

result = num1 num2

print("result is", result)

Enter Number 1: 109

Enter Number 2 23

result is 2507.0`

`# division

num1= float(input("Enter Number 1")

num2 = float(input("Enter Number 2")

result = num1 % num2

print("result is", result)

Enter Number 1: 5

Enter Number 2: 2

result is 1.0`

`# remainder

num1 = float(input("Enter Number 1 : "))
num2 = float(input("Enter Number 2 : "))

result = num1 % num2

print("result is ", result)`

2 **3# 2 pow 3
8

If condition:
`The if-else statement is used to execute both the true part and the false part of a given condition. If the condition is true, the if block code is executed and if the condition is false, the else block code is executed.

`Elif' stands for 'else if' and is used in Python programming to test multiple conditions. It is written following an if statement in Python to check an alternative condition if the first condition is false. The code block under the elif statement will be executed only if its condition is true.

`# Trip to tirunelveli

if BUS_available:
go by bus
elif Train_aviable:
go by train
else
go by bike

if BUS_available:
go by bus
if Train_aviable:
go by train #
if bike avaialble
go by bike`

Let's create a calculator.

Show list of functionalities available
Get user inputs
based on user input, perform functionality.

print("Simple Calculator")
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Modulus")
print("6. Exponentiate")

choice = input("Enter choice(1/2/3/4/5/6): ")
num1 = float(input("Enter first number:"))
num2 = float(input("Enter second number:"))

"2"

if choice == "1": # no : 1 unit of work.
result = num1 + num2
print(result)
if choice == "2": # yes: 1 unit of work
result = num1 - num2
print(result)

if choice == "3": # no : 1 unit of work.

result = num1 * num2

print(result)

if choice == "4": # no : 1 unit of work.

result = num1 / num2

print(result)

if choice == "5": # no : 1 unit of work.

result = num1 ** num2

print(result)

"2" elif = else if.

elif choice == "2":
result = num1 - num2
print(result)

print("Simple Calculator")
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Modulus")
print("6. Exponentiate")

choice = input("Enter choice(1/2/3/4/5/6): ")
num1 = float(input("Enter first number:"))
num2 = float(input("Enter second number:"))

"2"

if choice == "1": # no : 1 unit of work.
result = num1 + num2
print(result)
elif choice == "2":
result = num1 - num2
print(result)
elif choice == "3":
result = num1 * num2
print(result)
elif choice == "4":
result = num1 / num2
print(result)
elif choice == "5":
result = num1 % num2
print(result)
elif choice == "6":
result = num1 ** num2
print(result)
else:
print("option not available")
total_times = 2

while (condition) # True

# False -> exit.

2 > 0 = True

1 > 0 = True

0 > 0 = False

while total_times > 0:
# 2 - 1 = 1
# 1 - 1 = 0
total_times = total_times - 1
print("Simple Calculator")
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Modulus")
print("6. Exponentiate")
print("7. Close Calculator")

choice = input("Enter choice(1/2/3/4/5/6): ")
num1 = float(input("Enter first number:"))
num2 = float(input("Enter second number:"))

#     "2"
if choice == "1": # no : 1 unit of work.
    result = num1 + num2
    print(result)
elif choice == "2":
    result = num1 - num2
    print(result)
elif choice == "3":
    result = num1 * num2
    print(result)
elif choice == "4":
    result = num1 / num2
    print(result)
elif choice == "5":
    result = num1 % num2
    print(result)
elif choice == "6":
    result = num1 ** num2
    print(result)
elif choice == "7":
    break
else:
    print("option not available")
    break

def calculator():
print("Simple Calculator")
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Modulus")
print("6. Exponentiate")

choice = input("Enter choice(1/2/3/4/5/6): ")
num1 = float(input("Enter first number:"))
num2 = float(input("Enter second number:"))

if choice == '1':
    print(f"Result: {add(num1, num2)}")
elif choice == '2':       

print(f"Result: {subtract(num1, num2)}")
elif choice == '3':
print(f"Result: {multiply(num1, num2)}")
elif choice == '4':
print(f"Result: {divide(num1, num2)}")
elif choice == '5':
print(f"Result: {remainder(num1, num2)}")
elif choice == '6':
print(f"Result: {power(num1, num2)}")

Simple Calculator
Select operation:

  1. Add
  2. Subtract
  3. Multiply
  4. Divide
  5. Modulus
  6. Exponentiate Enter choice(1/2/3/4/5/6): 1 Enter first number:2 Enter second number:3 Result: 5.0
❌
❌