zking2000 / NotePad

1 stars 0 forks source link

e2e call tracing #41

Closed zking2000 closed 3 months ago

zking2000 commented 3 months ago

FE

from flask import Flask, render_template, request, jsonify
import requests
import random
import time

app = Flask(__name__)

PRODUCT_SERVICE_URL = "http://product-service:5000"
ORDER_SERVICE_URL = "http://order-service:5000"
USER_SERVICE_URL = "http://user-service:5000"

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/products')
def get_products():
    response = requests.get(f"{PRODUCT_SERVICE_URL}/products")
    return jsonify(response.json())

@app.route('/place_order', methods=['POST'])
def place_order():
    order_data = request.json
    user_response = requests.get(f"{USER_SERVICE_URL}/user/{order_data['user_id']}")
    if user_response.status_code != 200:
        return jsonify({"error": "User not found"}), 404

    product_response = requests.get(f"{PRODUCT_SERVICE_URL}/product/{order_data['product_id']}")
    if product_response.status_code != 200:
        return jsonify({"error": "Product not found"}), 404

    order_response = requests.post(f"{ORDER_SERVICE_URL}/order", json=order_data)
    return jsonify(order_response.json())

@app.route('/user_activity/<int:user_id>')
def user_activity(user_id):
    time.sleep(random.uniform(0.1, 0.5))  # Simulate some processing time
    user_response = requests.get(f"{USER_SERVICE_URL}/user/{user_id}")
    if user_response.status_code != 200:
        return jsonify({"error": "User not found"}), 404

    orders_response = requests.get(f"{ORDER_SERVICE_URL}/user_orders/{user_id}")
    return jsonify({
        "user": user_response.json(),
        "orders": orders_response.json()
    })

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

PRODUCTION SERVICES

from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
import time
import random

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://user:password@postgres:5432/productdb'
db = SQLAlchemy(app)

class Product(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    price = db.Column(db.Float, nullable=False)

@app.route('/products')
def get_products():
    time.sleep(random.uniform(0.05, 0.2))  # Simulate DB query time
    products = Product.query.all()
    return jsonify([{"id": p.id, "name": p.name, "price": p.price} for p in products])

@app.route('/product/<int:product_id>')
def get_product(product_id):
    time.sleep(random.uniform(0.05, 0.2))  # Simulate DB query time
    product = Product.query.get(product_id)
    if product:
        return jsonify({"id": product.id, "name": product.name, "price": product.price})
    return jsonify({"error": "Product not found"}), 404

@app.route('/product', methods=['POST'])
def create_product():
    data = request.json
    new_product = Product(name=data['name'], price=data['price'])
    db.session.add(new_product)
    db.session.commit()
    return jsonify({"id": new_product.id, "name": new_product.name, "price": new_product.price}), 201

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

ORDER SERVICES

from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
import requests
import time
import random

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://user:password@postgres:5432/orderdb'
db = SQLAlchemy(app)

PRODUCT_SERVICE_URL = "http://product-service:5000"

class Order(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, nullable=False)
    product_id = db.Column(db.Integer, nullable=False)
    quantity = db.Column(db.Integer, nullable=False)

@app.route('/order', methods=['POST'])
def create_order():
    data = request.json
    time.sleep(random.uniform(0.1, 0.3))  # Simulate processing time

    # Check product availability
    product_response = requests.get(f"{PRODUCT_SERVICE_URL}/product/{data['product_id']}")
    if product_response.status_code != 200:
        return jsonify({"error": "Product not available"}), 400

    new_order = Order(user_id=data['user_id'], product_id=data['product_id'], quantity=data['quantity'])
    db.session.add(new_order)
    db.session.commit()
    return jsonify({"id": new_order.id, "user_id": new_order.user_id, "product_id": new_order.product_id, "quantity": new_order.quantity}), 201

@app.route('/user_orders/<int:user_id>')
def get_user_orders(user_id):
    time.sleep(random.uniform(0.05, 0.2))  # Simulate DB query time
    orders = Order.query.filter_by(user_id=user_id).all()
    return jsonify([{"id": o.id, "product_id": o.product_id, "quantity": o.quantity} for o in orders])

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

K8S MANIFEST

apiVersion: apps/v1
kind: Deployment
metadata:
  name: frontend-service
spec:
  replicas: 2
  selector:
    matchLabels:
      app: frontend-service
  template:
    metadata:
      labels:
        app: frontend-service
    spec:
      containers:
      - name: frontend-service
        image: frontend-service:latest
        ports:
        - containerPort: 5000
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: product-service
spec:
  replicas: 2
  selector:
    matchLabels:
      app: product-service
  template:
    metadata:
      labels:
        app: product-service
    spec:
      containers:
      - name: product-service
        image: product-service:latest
        ports:
        - containerPort: 5000
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: order-service
spec:
  replicas: 2
  selector:
    matchLabels:
      app: order-service
  template:
    metadata:
      labels:
        app: order-service
    spec:
      containers:
      - name: order-service
        image: order-service:latest
        ports:
        - containerPort: 5000
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: user-service
spec:
  replicas: 2
  selector:
    matchLabels:
      app: user-service
  template:
    metadata:
      labels:
        app: user-service
    spec:
      containers:
      - name: user-service
        image: user-service:latest
        ports:
        - containerPort: 5000
---
apiVersion: v1
kind: Service
metadata:
  name: frontend-service
spec:
  selector:
    app: frontend-service
  ports:
    - protocol: TCP
      port: 80
      targetPort: 5000
  type: LoadBalancer
---
apiVersion: v1
kind: Service
metadata:
  name: product-service
spec:
  selector:
    app: product-service
  ports:
    - protocol: TCP
      port: 5000
      targetPort: 5000
---
apiVersion: v1
kind: Service
metadata:
  name: order-service
spec:
  selector:
    app: order-service
  ports:
    - protocol: TCP
      port: 5000
      targetPort: 5000
---
apiVersion: v1
kind: Service
metadata:
  name: user-service
spec:
  selector:
    app: user-service
  ports:
    - protocol: TCP
      port: 5000
      targetPort: 5000
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: postgres 
spec:
  replicas: 1
  selector:
    matchLabels:
      app: postgres
  template:
    metadata:
      labels:
        app: postgres
    spec:
      containers:
      - name: postgres
        image: postgres:13
        ports:
        - containerPort: 5432
        env:
        - name: POSTGRES_USER
          value: user
        - name: POSTGRES_PASSWORD
          value: password
        - name: POSTGRES_DB
          value: productdb
---
apiVersion: v1
kind: Service
metadata:
  name: postgres
spec:
  selector: 
    app: postgres
  ports:
    - protocol: TCP
      port: 5432
      targetPort: 5432
zking2000 commented 3 months ago
from flask import Flask, jsonify, request
import requests
import time
import random

app = Flask(__name__)

def call_service_2():
    time.sleep(random.uniform(0.5, 1.5))  # Simulate network latency
    response = requests.get('http://service2:5001/api/v1/process')
    return response.json()

def call_service_3():
    time.sleep(random.uniform(0.5, 1.5))  # Simulate network latency
    response = requests.get('http://service3:5002/api/v1/compute')
    return response.json()

@app.route('/api/v1/start', methods=['GET'])
def start_process():
    service2_result = call_service_2()
    service3_result = call_service_3()
    final_result = {
        "service1": "start_process",
        "service2_result": service2_result,
        "service3_result": service3_result
    }
    return jsonify(final_result)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
from flask import Flask, jsonify, request
import requests
import time
import random

app = Flask(__name__)

def call_service_3():
    time.sleep(random.uniform(0.5, 1.5))  # Simulate network latency
    response = requests.get('http://service3:5002/api/v1/analyze')
    return response.json()

@app.route('/api/v1/process', methods=['GET'])
def process_data():
    service3_result = call_service_3()
    result = {
        "service2": "process_data",
        "service3_result": service3_result
    }
    return jsonify(result)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5001)
from flask import Flask, jsonify, request
import time
import random

app = Flask(__name__)

@app.route('/api/v1/compute', methods=['GET'])
def compute():
    time.sleep(random.uniform(0.5, 1.5))  # Simulate processing time
    return jsonify({"service3": "compute"})

@app.route('/api/v1/analyze', methods=['GET'])
def analyze():
    time.sleep(random.uniform(0.5, 1.5))  # Simulate processing time
    return jsonify({"service3": "analyze"})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5002)
# Base image
FROM python:3.9-slim

# Set working directory
WORKDIR /app

# Copy all files to the container
COPY . /app

# Install dependencies
RUN pip install flask requests

# Expose the port
EXPOSE 5000

# Command to run the app
CMD ["python", "service1.py"]
curl http://localhost:5000/api/v1/start
zking2000 commented 3 months ago
RUN mkdir -p ~/.pip && \
    echo "[global]" > ~/.pip/pip.conf && \
    echo "index-url = https://pypi.tuna.tsinghua.edu.cn/simple" >> ~/.pip/pip.conf
zking2000 commented 3 months ago
apiVersion: apps/v1
kind: Deployment
metadata:
  name: service1-deployment
  labels:
    app: service1
spec:
  replicas: 3
  selector:
    matchLabels:
      app: service1
  template:
    metadata:
      labels:
        app: service1
    spec:
      containers:
      - name: service1
        image: service1:latest  # 替换为实际的镜像名称和标签
        ports:
        - containerPort: 5000
        resources:
          limits:
            cpu: "500m"
            memory: "512Mi"
          requests:
            cpu: "200m"
            memory: "256Mi"
        env:
        - name: APPDYNAMICS_AGENT_ACCOUNT_ACCESS_KEY
          valueFrom:
            secretKeyRef:
              name: appd-secret
              key: account-access-key
        - name: APPDYNAMICS_AGENT_ACCOUNT_NAME
          value: "your_account_name"  # 替换为您的AppD账户名
        - name: APPDYNAMICS_CONTROLLER_HOST_NAME
          value: "your_controller_hostname"  # 替换为您的AppD控制器主机名
        - name: APPDYNAMICS_CONTROLLER_PORT
          value: "8090"
        - name: APPDYNAMICS_CONTROLLER_SSL_ENABLED
          value: "false"
        - name: APPDYNAMICS_AGENT_APPLICATION_NAME
          value: "YourApplicationName"  # 替换为您的应用程序名称
        - name: APPDYNAMICS_AGENT_TIER_NAME
          value: "Service1"
        - name: APPDYNAMICS_AGENT_NODE_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
      - name: appd-agent
        image: appdynamics/java-agent:latest  # 使用适当的AppD代理镜像
        imagePullPolicy: Always
        env:
        - name: APPDYNAMICS_AGENT_ACCOUNT_ACCESS_KEY
          valueFrom:
            secretKeyRef:
              name: appd-secret
              key: account-access-key
        - name: JAVA_OPTS
          value: "-javaagent:/opt/appdynamics/javaagent.jar"
        volumeMounts:
        - mountPath: /opt/appdynamics
          name: appd-agent-repo
      volumes:
      - name: appd-agent-repo
        emptyDir: {}
---
apiVersion: v1
kind: Service
metadata:
  name: service1-service
spec:
  selector:
    app: service1
  ports:
    - protocol: TCP
      port: 80
      targetPort: 5000
  type: ClusterIP