Skip to content

andre-l-mm/nd064-c2-message-passing-projects-starter

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

38 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

UdaConnect

Instructions for Evaluator

Running the final solution

Deploy to Kubernetes

# Configuration
kubectl apply -f deployment/db-configmap.yaml
kubectl apply -f deployment/db-secret.yaml
kubectl apply -f deployment/postgres.yaml
kubectl apply -f deployment/kafka.yaml

# Wait Kafka pods to start pods before proceeding 
kubectl wait pod --timeout 300s --for=condition=Ready -l app.kubernetes.io/name=kafka

# Create locations topic in the kubernetes broker
kubectl exec -it kafka-0 -- kafka-topics.sh --create --bootstrap-server kafka-headless:9092 --replication-factor 1 --partitions 1 --topic locations

# Apis
kubectl apply -f deployment/udaconnect-locations-api.yaml
kubectl apply -f deployment/udaconnect-locations-grpc.yaml
kubectl apply -f deployment/udaconnect-persons-api.yaml
kubectl apply -f deployment/udaconnect-connections-api.yaml

# Web Application
kubectl apply -f deployment/udaconnect-app.yaml

Verifying it works

  • http://localhost:30002/ - Locations API - OpenAPI Documentation
  • http://localhost:30002/api/ - Locations API - Base path for API
  • http://localhost:30003/ - Persons API - OpenAPI Documentation
  • http://localhost:30003/api/ - Persons API - Base path for API
  • http://localhost:30004/ - Connections API - OpenAPI Documentation
  • http://localhost:30004/api/ - Connections API - Base path for API
  • http://localhost:30000/ - Frontend ReactJS Application

Locations GRPC

Run script create_test_locations.py. It connects to locations GRPC server on exposed node port 30005 and creates a new location.

cd modules/apis/locations-grpc
python create_test_locations.py

Important Notes

  • Because connections are now derived as locations are added, you will need to first create at least one new location using provided script above before being able to retrieve connections using the connections api.
  • Connections are persisted to connection table. You can verify the process worked by querying this table once a new location is created.
  • Connection table is provisioned automatically at startup of connections api using SQLAlchemy create_all method.
  • Connections are bidirectional. As an example, assuming we have two locations L1 and L2 in proximity and associated with persons P1 and P2 respectively. In this case, person P1 is connected to location L2 while person P2 is connected to location L1. Therefore, when L2 is added, the system computes and adds two connections to the database table.
  • Connections need to be computed based on the distance between the new location and existing locations. The system computes the distances and stores in the connection table limited to a maximum of 100 m. That means any two locations at more 100 m apart will not be considered. It also means that it only makes sense to search for connections with distance parameter set to a maximum of 100 as we do not save anything above that anyway.

Overview

Background

Conferences and conventions are hotspots for making connections. Professionals in attendance often share the same interests and can make valuable business and personal connections with one another. At the same time, these events draw a large crowd and it's often hard to make these connections in the midst of all of these events' excitement and energy. To help attendees make connections, we are building the infrastructure for a service that can inform attendees if they have attended the same booths and presentations at an event.

Goal

You work for a company that is building a app that uses location data from mobile devices. Your company has built a POC application to ingest location data named UdaTracker. This POC was built with the core functionality of ingesting location and identifying individuals who have shared a close geographic proximity.

Management loved the POC so now that there is buy-in, we want to enhance this application. You have been tasked to enhance the POC application into a MVP to handle the large volume of location data that will be ingested.

To do so, you will refactor this application into a microservice architecture using message passing techniques that you have learned in this course. It’s easy to get lost in the countless optimizations and changes that can be made: your priority should be to approach the task as an architect and refactor the application into microservices. File organization, code linting -- these are important but don’t affect the core functionality and can possibly be tagged as TODO’s for now!

Technologies

  • Flask - API webserver
  • SQLAlchemy - Database ORM
  • PostgreSQL - Relational database
  • PostGIS - Spatial plug-in for PostgreSQL enabling geographic queries]
  • Vagrant - Tool for managing virtual deployed environments
  • VirtualBox - Hypervisor allowing you to run multiple operating systems
  • K3s - Lightweight distribution of K8s to easily develop against a local cluster

Running the app

The project has been set up such that you should be able to have the project up and running with Kubernetes.

Prerequisites

We will be installing the tools that we'll need to use for getting our environment set up properly.

  1. Install Docker
  2. Set up a DockerHub account
  3. Set up kubectl
  4. Install VirtualBox with at least version 6.0
  5. Install Vagrant with at least version 2.0

Environment Setup

To run the application, you will need a K8s cluster running locally and to interface with it via kubectl. We will be using Vagrant with VirtualBox to run K3s.

Initialize K3s

In this project's root, run vagrant up.

$ vagrant up

The command will take a while and will leverage VirtualBox to load an openSUSE OS and automatically install K3s. When we are taking a break from development, we can run vagrant suspend to conserve some ouf our system's resources and vagrant resume when we want to bring our resources back up. Some useful vagrant commands can be found in this cheatsheet.

Set up kubectl

After vagrant up is done, you will SSH into the Vagrant environment and retrieve the Kubernetes config file used by kubectl. We want to copy the contents of this file into our local environment so that kubectl knows how to communicate with the K3s cluster.

$ vagrant ssh

You will now be connected inside of the virtual OS. Run sudo cat /etc/rancher/k3s/k3s.yaml to print out the contents of the file. You should see output similar to the one that I've shown below. Note that the output below is just for your reference: every configuration is unique and you should NOT copy the output I have below.

Copy the contents from the output issued from your own command into your clipboard -- we will be pasting it somewhere soon!

$ sudo cat /etc/rancher/k3s/k3s.yaml

apiVersion: v1
clusters:
- cluster:
    certificate-authority-data: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUJWekNCL3FBREFnRUNBZ0VBTUFvR0NDcUdTTTQ5QkFNQ01DTXhJVEFmQmdOVkJBTU1HR3N6Y3kxelpYSjIKWlhJdFkyRkFNVFU1T1RrNE9EYzFNekFlRncweU1EQTVNVE13T1RFNU1UTmFGdzB6TURBNU1URXdPVEU1TVROYQpNQ014SVRBZkJnTlZCQU1NR0dzemN5MXpaWEoyWlhJdFkyRkFNVFU1T1RrNE9EYzFNekJaTUJNR0J5cUdTTTQ5CkFnRUdDQ3FHU000OUF3RUhBMElBQk9rc2IvV1FEVVVXczJacUlJWlF4alN2MHFseE9rZXdvRWdBMGtSN2gzZHEKUzFhRjN3L3pnZ0FNNEZNOU1jbFBSMW1sNXZINUVsZUFOV0VTQWRZUnhJeWpJekFoTUE0R0ExVWREd0VCL3dRRQpBd0lDcERBUEJnTlZIUk1CQWY4RUJUQURBUUgvTUFvR0NDcUdTTTQ5QkFNQ0EwZ0FNRVVDSVFERjczbWZ4YXBwCmZNS2RnMTF1dCswd3BXcWQvMk5pWE9HL0RvZUo0SnpOYlFJZ1JPcnlvRXMrMnFKUkZ5WC8xQmIydnoyZXpwOHkKZ1dKMkxNYUxrMGJzNXcwPQotLS0tLUVORCBDRVJUSUZJQ0FURS0tLS0tCg==
    server: https://127.0.0.1:6443
  name: default
contexts:
- context:
    cluster: default
    user: default
  name: default
current-context: default
kind: Config
preferences: {}
users:
- name: default
  user:
    password: 485084ed2cc05d84494d5893160836c9
    username: admin

Type exit to exit the virtual OS and you will find yourself back in your computer's session. Create the file (or replace if it already exists) ~/.kube/config and paste the contents of the k3s.yaml output here.

Afterwards, you can test that kubectl works by running a command like kubectl describe services. It should not return any errors.

Steps

  1. kubectl apply -f deployment/db-configmap.yaml - Set up environment variables for the pods
  2. kubectl apply -f deployment/db-secret.yaml - Set up secrets for the pods
  3. kubectl apply -f deployment/postgres.yaml - Set up a Postgres database running PostGIS
  4. kubectl apply -f deployment/udaconnect-api.yaml - Set up the service and deployment for the API
  5. kubectl apply -f deployment/udaconnect-app.yaml - Set up the service and deployment for the web app
  6. sh scripts/run_db_command.sh <POD_NAME> - Seed your database against the postgres pod. (kubectl get pods will give you the POD_NAME)

Manually applying each of the individual yaml files is cumbersome but going through each step provides some context on the content of the starter project. In practice, we would have reduced the number of steps by running the command against a directory to apply of the contents: kubectl apply -f deployment/.

Note: The first time you run this project, you will need to seed the database with dummy data. Use the command sh scripts/run_db_command.sh <POD_NAME> against the postgres pod. (kubectl get pods will give you the POD_NAME). Subsequent runs of kubectl apply for making changes to deployments or services shouldn't require you to seed the database again!

Verifying it Works

Once the project is up and running, you should be able to see 3 deployments and 3 services in Kubernetes: kubectl get pods and kubectl get services - should both return udaconnect-app, udaconnect-api, and postgres

These pages should also load on your web browser:

  • http://localhost:30001/ - OpenAPI Documentation
  • http://localhost:30001/api/ - Base path for API
  • http://localhost:30000/ - Frontend ReactJS Application

Deployment Note

You may notice the odd port numbers being served to localhost. By default, Kubernetes services are only exposed to one another in an internal network. This means that udaconnect-app and udaconnect-api can talk to one another. For us to connect to the cluster as an "outsider", we need to a way to expose these services to localhost.

Connections to the Kubernetes services have been set up through a NodePort. (While we would use a technology like an Ingress Controller to expose our Kubernetes services in deployment, a NodePort will suffice for development.)

Development

New Services

New services can be created inside of the modules/ subfolder. You can choose to write something new with Flask, copy and rework the modules/api service into something new, or just create a very simple Python application.

As a reminder, each module should have:

  1. Dockerfile
  2. Its own corresponding DockerHub repository
  3. requirements.txt for pip packages
  4. __init__.py

Docker Images

udaconnect-app and udaconnect-api use docker images from isjustintime/udaconnect-app and isjustintime/udaconnect-api. To make changes to the application, build your own Docker image and push it to your own DockerHub repository. Replace the existing container registry path with your own.

Configs and Secrets

In deployment/db-secret.yaml, the secret variable is d293aW1zb3NlY3VyZQ==. The value is simply encoded and not encrypted -- this is not secure! Anyone can decode it to see what it is.

# Decodes the value into plaintext
echo "d293aW1zb3NlY3VyZQ==" | base64 -d

# Encodes the value to base64 encoding. K8s expects your secrets passed in with base64
echo "hotdogsfordinner" | base64

This is okay for development against an exclusively local environment and we want to keep the setup simple so that you can focus on the project tasks. However, in practice we should not commit our code with secret values into our repository. A CI/CD pipeline can help prevent that.

PostgreSQL Database

The database uses a plug-in named PostGIS that supports geographic queries. It introduces GEOMETRY types and functions that we leverage to calculate distance between ST_POINT's which represent latitude and longitude.

You may find it helpful to be able to connect to the database. In general, most of the database complexity is abstracted from you. The Docker container in the starter should be configured with PostGIS. Seed scripts are provided to set up the database table and some rows.

Database Connection

While the Kubernetes service for postgres is running (you can use kubectl get services to check), you can expose the service to connect locally:

kubectl port-forward svc/postgres 5432:5432

This will enable you to connect to the database at localhost. You should then be able to connect to postgresql://localhost:5432/geoconnections. This is assuming you use the built-in values in the deployment config map.

Software

To manually connect to the database, you will need software compatible with PostgreSQL.

  • CLI users will find psql to be the industry standard.
  • GUI users will find pgAdmin to be a popular open-source solution.

Architecture Diagrams

Your architecture diagram should focus on the services and how they talk to one another. For our project, we want the diagram in a .png format. Some popular free software and tools to create architecture diagrams:

  1. Lucidchart
  2. Google Docs Drawings (In a Google Doc, Insert - Drawing - + New)
  3. Diagrams.net

Tips

  • We can access a running Docker container using kubectl exec -it <pod_id> sh. From there, we can curl an endpoint to debug network issues.
  • The starter project uses Python Flask. Flask doesn't work well with asyncio out-of-the-box. Consider using multiprocessing to create threads for asynchronous behavior in a standard Flask application.

Local Development Instructions

Installing psql

# MacOS Install and add folder to path in your bash profile configuration
brew install libpq
echo 'export PATH="/usr/local/opt/libpq/bin:$PATH"' >> /Users/andremagalhaes/.bash_profile

Connecting with psql

# Keep port-forward running in a separate terminal to allow for connections on localhost:5432
kubectl port-forward svc/postgres 5432:5432

# Connect with psql
psql -h localhost -p 5432 -U ct_admin geoconnections

Running apis locally

# Create virtual environment
python3 -m venv .venv

# Activate virtual environment (always run this when openning a new terminal)
cd .venv
source bin/activate

# Upgrade pip
pip install --upgrade pip

# Geos package required by some of the python packages
brew install geos

# Go to api folder
cd modules/api

# Install required packages - Exporting LDFLAGS required to install psycopg2
env LDFLAGS="-I/usr/local/opt/openssl/include -L/usr/local/opt/openssl/lib" pip install -r requirements.txt

# Make sure database is accessible on localhost by running this command on a separate terminal
kubectl port-forward svc/postgres 5432:5432

# Create .env file with the following settings
DB_USERNAME=ct_admin
DB_NAME=geoconnections
DB_HOST=localhost
DB_PORT=5432
DB_PASSWORD=wowimsosecure

# Using flask command line to start the application
# This can be used to automatically apply source code changes but runs on port 5000
FLASK_ENV=dev flask run

# Go to http://127.0.0.1:5000/api/

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Python 75.0%
  • JavaScript 17.4%
  • CSS 2.7%
  • Dockerfile 2.3%
  • HTML 1.7%
  • Shell 0.9%