Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Kubernetes #46

Open
wants to merge 21 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion backend/matching-backend/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@ RUN npm install

COPY . .

EXPOSE 4000
EXPOSE 3002

CMD ["npm", "start"]
26 changes: 17 additions & 9 deletions backend/matching-backend/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,23 @@ app.use(express.json());
let channel, connection;
let wss;

async function initRabbitMQ() {
try {
connection = await amqp.connect('amqp://rabbitmq:5672');
channel = await connection.createChannel();
await channel.assertQueue('matching-queue', { durable: true });
console.log('Connected to RabbitMQ');
startConsumer(channel, notifyMatch); // Start consumer
} catch (error) {
console.error('Error connecting to RabbitMQ: ', error);
async function initRabbitMQ(retries = 5, delay = 5000) {
const rabbitmqUrl = process.env.RABBITMQ_URL || 'amqp://localhost:5672';
while (retries > 0) {
try {
console.log(`Attempting to connect to RabbitMQ at ${rabbitmqUrl}`);
connection = await amqp.connect(rabbitmqUrl);
channel = await connection.createChannel();
await channel.assertQueue('matching-queue', { durable: true });
console.log('Connected to RabbitMQ');
startConsumer(channel, notifyMatch); // Start consumer
break; // Exit loop on success
} catch (error) {
console.error(`Error connecting to RabbitMQ: ${error}. Retrying in ${delay / 1000} seconds...`);
retries -= 1;
if (retries === 0) throw new Error('Could not connect to RabbitMQ after multiple attempts');
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}

Expand Down
26 changes: 21 additions & 5 deletions backend/user-backend/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,31 @@ const app = express();

app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// app.use(cors({
// origin: "http://localhost:3000", // Explicitly allow your frontend origin
// credentials: true // Allow credentials (cookies, headers, etc.)
// })); // config cors so that front-end can use
// app.options("*", cors());

const allowedOrigins = ["http://localhost:3000", "http://35.240.237.167.nip.io"];

app.use(cors({
origin: "http://localhost:3000", // Explicitly allow your frontend origin
credentials: true // Allow credentials (cookies, headers, etc.)
})); // config cors so that front-end can use
app.options("*", cors());
origin: function (origin, callback) {
if (!origin) return callback(null, true);
if (allowedOrigins.indexOf(origin) === -1) {
var msg = "The CORS policy for this site does not allow access from the specified Origin.";
return callback(new Error(msg), false);
}
return callback(null, true);
},
credentials: true
}));

app.options("*", cors()); // Pre-flight check for all routes

// To handle CORS Errors
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "http://localhost:3000"); // "*" -> Allow all links to access
res.header("Access-Control-Allow-Origin", req.headers.origin); // "*" -> Allow all links to access

res.header(
"Access-Control-Allow-Headers",
Expand Down
2 changes: 2 additions & 0 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ services:
- /app/node_modules
environment:
- NODE_ENV=production
- REACT_APP_API_URL=http://user-service:3001
- REACT_APP_QUESTION_API_URL=http://question-service:4000
- USER_AUTH_URL=http://user-service:3001/auth/verify-token
networks:
- common-network
Expand Down
11 changes: 6 additions & 5 deletions frontend/src/components/history/HistoryTable.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,16 @@ export default function HistoryTable() {
const [open, setOpen] = useState(false);
const [selectedQuestion, setSelectedQuestion] = useState(null);
const [selectedSolution, setSelectedSolution] = useState(null);


const apiUrl = process.env.REACT_APP_API_URL || "http://localhost:3004";

useEffect(() => {
const fetchUserHistory = async () => {
const user = await getUserById(userId, cookies.token);
const { data } = await axios.post(`http://localhost:3004/bulk`, {
"ids": user.history,
withCredentials: true,
});
const { data } = await axios.post(`${apiUrl}/bulk`,
{"ids": user.history},
{withCredentials: true}
);

historyService.sortByLatestDate(data.data);
setHistory(data.data);
Expand Down
5 changes: 4 additions & 1 deletion frontend/src/hooks/useAuth.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ const useAuth = () => {
const [userId, setUserId] = useState("");
const [email, setEmail] = useState("");

const apiUrl = process.env.REACT_APP_API_URL || "http://localhost:3001";

useEffect(() => {
const verifyCookie = async () => {
if (!cookies.token) {
Expand All @@ -19,7 +21,7 @@ const useAuth = () => {
}
try {
const response = await axios.get(
"http://localhost:3001/auth/verify-token",
`${apiUrl}/auth/verify-token`,
{
headers: {
Authorization: `Bearer ${cookies.token}`
Expand All @@ -28,6 +30,7 @@ const useAuth = () => {
}
);
if (response.status === 200) {
console.log(response);
const { data } = response.data;
setUsername(data.username);
setPrivilege(data.isAdmin);
Expand Down
3 changes: 2 additions & 1 deletion frontend/src/pages/ForgotPassword.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import AuthLayout from "../components/auth/AuthLayout";
import '../styles/AuthForm.css';

const ForgotPassword = () => {
const apiUrl = process.env.REACT_APP_API_URL || "http://localhost:3001";
const navigate = useNavigate();
const [inputValue, setInputValue] = useState({
email: "",
Expand Down Expand Up @@ -42,7 +43,7 @@ const ForgotPassword = () => {
}
try {
const response = await axios.post(
"http://localhost:3001/auth/forget-password",
`${apiUrl}/auth/forget-password`,
{
email,
password,
Expand Down
5 changes: 3 additions & 2 deletions frontend/src/pages/ForgotPasswordOTP.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import AuthLayout from "../components/auth/AuthLayout";
import '../styles/AuthForm.css';

const ForgotPasswordOTP = () => {
const apiUrl = process.env.REACT_APP_API_URL || "http://localhost:3001";
const navigate = useNavigate();
const location = useLocation();
const [otp, setOtp] = useState("");
Expand All @@ -16,7 +17,7 @@ const ForgotPasswordOTP = () => {
e.preventDefault();
try {
const response = await axios.post(
"http://localhost:3001/auth/forget-password/confirm-otp",
`${apiUrl}/auth/forget-password/confirm-otp`,
{
email,
otp,
Expand All @@ -39,7 +40,7 @@ const ForgotPasswordOTP = () => {
setIsResending(true);
try {
const response = await axios.post(
"http://localhost:3001/auth/forget-password/resend-otp",
`${apiUrl}/auth/forget-password/resend-otp`,
{
email,
}
Expand Down
3 changes: 2 additions & 1 deletion frontend/src/pages/Login.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,12 @@ const Login = () => {
position: "bottom-left",
});

const apiUrl = process.env.REACT_APP_API_URL || "http://localhost:3001";
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await axios.post(
"http://localhost:3001/auth/login",
`${apiUrl}/auth/login`,
{
...inputValue,
},
Expand Down
10 changes: 6 additions & 4 deletions frontend/src/pages/Profile.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import useAuth from "../hooks/useAuth";
import "../styles/Profile.css";

const Profile = () => {
const apiUrl = process.env.REACT_APP_API_URL || "http://localhost:3001";

const { userId, cookies } = useAuth();
const [userData, setUserData] = useState({
username: "",
Expand All @@ -24,7 +26,7 @@ const Profile = () => {
useEffect(() => {
const fetchUserProfile = async () => {
try {
const { data } = await axios.get(`http://localhost:3001/users/${userId}`, {
const { data } = await axios.get(`${apiUrl}/users/${userId}`, {
headers: {
Authorization: `Bearer ${cookies.token}`,
},
Expand Down Expand Up @@ -66,7 +68,7 @@ const Profile = () => {

// Send PATCH request to the backend
const response = await axios.patch(
`http://localhost:3001/users/${userId}`,
`${apiUrl}/users/${userId}`,
updatedData, // Only include username and email
{
headers: {
Expand Down Expand Up @@ -103,7 +105,7 @@ const Profile = () => {
formData.append('profileImage', file);
try {
const response = await axios.patch(
`http://localhost:3001/users/${userId}/profileImage`,
`${apiUrl}/users/${userId}/profileImage`,
formData,
{
headers: {
Expand Down Expand Up @@ -145,7 +147,7 @@ const Profile = () => {
toDefault: true,
};
const response = await axios.patch(
`http://localhost:3001/users/${userId}/profileImage`,
`${apiUrl}/users/${userId}/profileImage`,
updatedData,
{
headers: {
Expand Down
3 changes: 2 additions & 1 deletion frontend/src/pages/SendVerification.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import AuthLayout from "../components/auth/AuthLayout";
import '../styles/AuthForm.css';

const SendVerification = () => {
const apiUrl = process.env.REACT_APP_API_URL || "http://localhost:3001";
const navigate = useNavigate();
const [email, setEmail] = useState('');

Expand Down Expand Up @@ -37,7 +38,7 @@ const SendVerification = () => {

try {
const response = await axios.post(
"http://localhost:3001/auth/resend-verification",
`${apiUrl}/auth/resend-verification`,
{ email: email },
{ withCredentials: true }
);
Expand Down
4 changes: 3 additions & 1 deletion frontend/src/pages/Signup.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import AuthLayout from "../components/auth/AuthLayout";
import '../styles/AuthForm.css';

const SignUp = () => {
const apiUrl = process.env.REACT_APP_API_URL || "http://localhost:3001";

const navigate = useNavigate();
const [inputValue, setInputValue] = useState({
username: "",
Expand Down Expand Up @@ -50,7 +52,7 @@ const SignUp = () => {

try {
const response = await axios.post(
"http://localhost:3001/users/",
`${apiUrl}/users/`,
{
...inputValue,
},
Expand Down
3 changes: 2 additions & 1 deletion frontend/src/pages/VerifyEmail.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import AuthLayout from "../components/auth/AuthLayout";
import '../styles/AuthForm.css';

const VerifyEmail = () => {
const apiUrl = process.env.REACT_APP_API_URL || "http://localhost:3001";
const navigate = useNavigate();
const [result, setResult] = useState(undefined);
const [statusMessage, setStatusMessage] = useState('Verifying account...');
Expand All @@ -18,7 +19,7 @@ const VerifyEmail = () => {
const token = urlParams.get('token');

axios.post(
"http://localhost:3001/auth/verify-email",
`${apiUrl}/auth/verify-email`,
null,
{
headers: { Authorization: `Bearer ${token}` },
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/services/history-service.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import axios from 'axios';
import { addUserHistory } from './user-service';

const BASE_URL = 'http://localhost:3004';
const BASE_URL = process.env.REACT_APP_API_URL || "http://localhost:3004";

const formatDatetime = datetime => {
const [date, time] = datetime.split(':');
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/services/question-service.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import axios from 'axios';
import QuestionNotFoundError from '../errors/QuestionNotFoundError';

const BASE_URL = 'http://localhost:4000/api/questions';
const BASE_URL = process.env.REACT_APP_QUESTION_API_URL || 'http://localhost:4000/api/questions';

// Reformat and log error
const reformatError = (action, error) => {
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/services/user-service.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import axios from 'axios';

const BASE_URL = 'http://localhost:3001';
const BASE_URL = process.env.REACT_APP_API_URL || "http://localhost:3001";

export const validateUsername = (username) => {
return username.trim() === ''
Expand Down
28 changes: 28 additions & 0 deletions kubernetes/collab-service/collab-deployment.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: collab-service
namespace: peerprep
labels:
app: collab-service
spec:
replicas: 1
selector:
matchLabels:
app: collab-service
template:
metadata:
labels:
app: collab-service
spec:
containers:
- name: collab-service
image: asia-southeast1-docker.pkg.dev/peerprep-userservice-436407/peerprep/miljyy/collab-service:latest
ports:
- name: collab-svc-8200
containerPort: 8200
- name: collab-svc-8201
containerPort: 8201

imagePullSecrets:
- name: gcr-json-key
18 changes: 18 additions & 0 deletions kubernetes/collab-service/collab-service.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
apiVersion: v1
kind: Service
metadata:
name: collab-service
namespace: peerprep
labels:
app: collab-service
spec:
selector:
app: collab-service
ports:
- name: collab-service-8200
port: 8200
targetPort: 8200
- name: collab-service-8201
port: 8201
targetPort: 8201
type: ClusterIP
33 changes: 33 additions & 0 deletions kubernetes/frontend-service/frontend-deployment.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: frontend-service
namespace: peerprep
labels:
app: frontend-service
spec:
replicas: 1
selector:
matchLabels:
app: frontend-service
template:
metadata:
labels:
app: frontend-service
spec:
containers:
- name: frontend-service
image: asia-southeast1-docker.pkg.dev/peerprep-userservice-436407/peerprep/miljyy/frontend-service:latest
ports:
- name: fe-service
containerPort: 3000
env:
- name: NODE_ENV
value: "production"
- name: USER_AUTH_URL
value: "http://user-service:3001/auth/verify-token"
- name: REACT_APP_API_URL
value: "http://35.240.237.167.nip.io"

imagePullSecrets:
- name: gcr-json-key
Loading