Skip to content

Commit

Permalink
Fix #44 Express quickstart add Nodejs. Limit app cpu
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisjsimpson committed Apr 1, 2024
1 parent 8bbf237 commit 6891dc1
Show file tree
Hide file tree
Showing 10 changed files with 913 additions and 10 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ venv
*.db
target
workspace
node_modules
22 changes: 22 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ async def homepage(request):
state_rails = f"{secrets.token_urlsafe(30)}---rails"
state_django = f"{secrets.token_urlsafe(30)}---django"
state_flask = f"{secrets.token_urlsafe(30)}---flask"
state_expressFramework = f"{secrets.token_urlsafe(30)}---expressFramework"
# UNTRUSTED_REPO_INFO gets replaced by the users given git host, org name and repo name
state_existing_repo = f"{secrets.token_urlsafe(30)}---existing_repo-UNTRUSTED_GIT_HOST|UNTRUSTED_GIT_ORG_NAME|UNTRUSTED_GIT_REPO_NAME"

Expand All @@ -125,6 +126,7 @@ async def homepage(request):
github_authorize_url_rails = f"{github_oauth_auth_url}client_id={client_id}&state={state_rails}&scope=workflow%20repo%20user:email" # noqa: E501
github_authorize_url_django = f"{github_oauth_auth_url}client_id={client_id}&state={state_django}&scope=workflow%20repo%20user:email" # noqa: E501
github_authorize_url_flask = f"{github_oauth_auth_url}client_id={client_id}&state={state_flask}&scope=workflow%20repo%20user:email" # noqa: E501
github_authorize_url_expressFramework = f"{github_oauth_auth_url}client_id={client_id}&state={state_expressFramework}&scope=workflow%20repo%20user:email" # noqa: E501
github_authorize_url_existing_repo = f"{github_oauth_auth_url}client_id={client_id}&state={state_existing_repo}&scope=workflow%20repo%20user:email" # noqa: E501

return templates.TemplateResponse(
Expand All @@ -134,6 +136,7 @@ async def homepage(request):
"github_authorize_url_rails": github_authorize_url_rails,
"github_authorize_url_django": github_authorize_url_django,
"github_authorize_url_flask": github_authorize_url_flask,
"github_authorize_url_expressFramework": github_authorize_url_expressFramework,
"github_authorize_url_existing_repo": github_authorize_url_existing_repo,
"request": request,
},
Expand Down Expand Up @@ -576,6 +579,22 @@ def add_flask_quickstart():
index.add([f"{BASE_PATH}tmp-cloned-repos/{APP_NAME}/src/requirements.txt"])
index.commit("Added flask quickstart")

def add_expressFramework_quickstart():
# add framework quickstart files
shutil.copytree(
f"{BASE_PATH}/repo-template-files/quickstarts/express-quickstart/src",
f"./tmp-cloned-repos/{APP_NAME}/src",
dirs_exist_ok=True,
)
# add/commit framework files to repo
index = repo.index
index.add([f"{BASE_PATH}tmp-cloned-repos/{APP_NAME}/src/package.json"])
index.add([f"{BASE_PATH}tmp-cloned-repos/{APP_NAME}/src/package-lock.json"])
index.add([f"{BASE_PATH}tmp-cloned-repos/{APP_NAME}/src/index.js"])
index.add([f"{BASE_PATH}tmp-cloned-repos/{APP_NAME}/src/entrypoint.sh"])
index.add([f"{BASE_PATH}tmp-cloned-repos/{APP_NAME}/src/Dockerfile"])
index.commit("Added express framework quickstart")

if "rails" in state:
# add framework quickstart files
shutil.copytree(
Expand Down Expand Up @@ -609,6 +628,9 @@ def add_flask_quickstart():
if "flask" in state:
add_flask_quickstart()

if "expressFramework" in state:
add_expressFramework_quickstart()

if "---existing_repo-" in state:
# In this case don't create a new repo, only
# add to the existing repo provided in ---existing_repo-.. metadata
Expand Down
28 changes: 19 additions & 9 deletions dokku-wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,13 @@
print("Unable to find app, perhaps your CONTAINER_HOSTING_API_KEY is wrong?")
exit()

print(f"🐌 Limiting app CPU resources for app: {APP_NAME}")
subprocess.run(f"dokku resource:limit --cpu 1.5 {APP_NAME}", shell=True)

print(f"🧠 Limiting app memory resources for app: {APP_NAME}")
subprocess.run(f"dokku resource:limit --memory 500m {APP_NAME}", shell=True)


try:
print(f"✅ Located APP_NAME: {APP_NAME}")
except KeyError as e:
Expand All @@ -83,22 +90,26 @@
cur = con.cursor()

cur.execute(
f"select * from key_value_store WHERE key = '{APP_NAME}:GIT_USERNAME_OR_ORG'"
f"select * from key_value_store WHERE key = '{APP_NAME}:GIT_USERNAME_OR_ORG'"
)

FOUND_GIT_USERNAME_OR_ORG = False
for row in cur.fetchall():
try:
GIT_USERNAME_OR_ORG = row[1]
logging.info(f"Found GIT_USERNAME_OR_ORG: {GIT_USERNAME_OR_ORG} for container {row[0]}")
logging.info(
f"Found GIT_USERNAME_OR_ORG: {GIT_USERNAME_OR_ORG} for container {row[0]}"
)
FOUND_GIT_USERNAME_OR_ORG = True

except (IndexError, Exception) as e:
logging.error(f"Could not locate GIT_USERNAME_OR_ORG: {e}")

if FOUND_GIT_USERNAME_OR_ORG is False:
logging.error("Unable to find GIT_USERNAME_OR_ORG")
print("Unable to find GIT_USERNAME_OR_ORG, perhaps your CONTAINER_HOSTING_API_KEY is wrong?")
print(
"Unable to find GIT_USERNAME_OR_ORG, perhaps your CONTAINER_HOSTING_API_KEY is wrong?"
)
exit()


Expand All @@ -107,30 +118,29 @@

print("👀 Getting GIT_REPO_NAME")

cur.execute(
f"select * from key_value_store WHERE key = '{APP_NAME}:GIT_REPO_NAME'"
)
cur.execute(f"select * from key_value_store WHERE key = '{APP_NAME}:GIT_REPO_NAME'")

FOUND_GIT_REPO_NAME = False
for row in cur.fetchall():
try:
GIT_REPO_NAME = row[1]
logging.info(f"Found GIT_REPO_NAME: {GIT_REPO_NAME} for container {row[0]}")
FOUND_GIT_REPO_NAME= True
FOUND_GIT_REPO_NAME = True

except (IndexError, Exception) as e:
logging.error(f"Could not locate GIT_REPO_NAME: {e}")

if FOUND_GIT_REPO_NAME is False:
logging.error("Unable to find GIT_REPO_NAME")
print("Unable to find GIT_REPO_NAME, perhaps your CONTAINER_HOSTING_API_KEY is wrong?")
print(
"Unable to find GIT_REPO_NAME, perhaps your CONTAINER_HOSTING_API_KEY is wrong?"
)
exit()


print("✅ Matched GIT_REPO_NAME")



# dokku config:set --no-restart container-fjxt9w4 ALLOWED_HOSTS=container-fjxt9w4.containers.anotherwebservice.com

commands_allowlist = [
Expand Down
1 change: 1 addition & 0 deletions repo-template-files/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ Need some help to get started?
- [**Flask** quickstart guide](https://flask.palletsprojects.com/en/2.2.x/quickstart/) ⚗️ 🐍
- [**Django** quide](https://docs.djangoproject.com/en/4.1/topics/http/views/) 📰
- [**Ruby** quickstart guide](https://github.com/KarmaComputing/rails-quickstart) 💎
- [**Express** quickstart guide](https://expressjs.com/en/starter/hello-world.html) 🟢

# Debugging

Expand Down
14 changes: 14 additions & 0 deletions repo-template-files/quickstarts/express-quickstart/src/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
FROM node:20-alpine

WORKDIR /app/src
COPY . /app/src

RUN npm install

RUN chown -R node:node /app

USER node

ENTRYPOINT /app/src/entrypoint.sh

EXPOSE 3000
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#!/bin/sh

exec node index.js
47 changes: 47 additions & 0 deletions repo-template-files/quickstarts/express-quickstart/src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
const express = require("express")
const app = express()
const port = 3000

const mysql = require('mysql2')

DB_USER = process.env.DB_USER;
DB_PASSWORD = process.env.DB_PASSWORD;
DB_HOST = process.env.DB_HOST;
DB_PORT = process.env.DB_PORT;
DB_NAME = process.env.DB_NAME;

app.get("/", (req, res) => {
res.send("Hello World!<br />Check /health to verify database connection is also OK")
})

app.get("/health", (req, res) => {
// Create connection to database
// Get database settings from environment
let health = "BAD"
const connection = mysql.createConnection({
host: DB_HOST,
port: DB_PORT,
user: DB_USER,
database: DB_NAME,
password: DB_PASSWORD,
});

connection.query(
'SELECT NOW() AS now',
function (err, results, fields) {
if (err) {
console.error(err)
res.send(health)
} else {
console.log(results) // results contains rows returned by server
console.log(fields) // fields contains extra meta data about results, if available
health = "OK"
res.send(health)
}
}
);
})

app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
Loading

0 comments on commit 6891dc1

Please sign in to comment.