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

feat(run): add Cloud Run + Filestore sample #3288

Merged
merged 110 commits into from
Jul 25, 2023
Merged
Show file tree
Hide file tree
Changes from 93 commits
Commits
Show all changes
110 commits
Select commit Hold shift + click to select a range
1c6c01e
initial package.json
rogerthatdev Jun 16, 2023
8a8a22b
basic express with test
rogerthatdev Jun 16, 2023
a4150f2
add testing dependencies
rogerthatdev Jun 16, 2023
30a721f
add nonexistant path test
rogerthatdev Jun 16, 2023
e2f513a
refactor test to use chai expect as assert
rogerthatdev Jun 16, 2023
01daf73
add chai to package.json
rogerthatdev Jun 16, 2023
41cc5fe
hide console.log output from test output
rogerthatdev Jun 16, 2023
a340920
label console output
rogerthatdev Jun 16, 2023
c27bb45
semi-colons ;;;;
rogerthatdev Jun 16, 2023
f74b6af
add redirects to mount dir
rogerthatdev Jun 20, 2023
155877b
writeFile function
rogerthatdev Jun 20, 2023
133a300
test for new file write
rogerthatdev Jun 20, 2023
abb8703
return list of files and links
rogerthatdev Jun 20, 2023
f65b681
add test for files
rogerthatdev Jun 20, 2023
c943c48
add Dockerfile and wrapper script
rogerthatdev Jun 20, 2023
b33d1b8
add header
rogerthatdev Jun 21, 2023
6b1b89c
eslint --fix
rogerthatdev Jun 21, 2023
e244cae
add rate limit to app
rogerthatdev Jun 21, 2023
6d8737e
add testing workflows
rogerthatdev Jun 21, 2023
ae52f26
dont store value for path
rogerthatdev Jun 21, 2023
1539b75
Merge branch 'main' into filesystems-sample
pattishin Jun 22, 2023
8a15aed
Merge branch 'main' into filesystems-sample
rogerthatdev Jun 27, 2023
6f2689b
add missing #!
rogerthatdev Jun 27, 2023
a226df9
refactor to use serve-index
rogerthatdev Jun 27, 2023
6224f8c
eslint
rogerthatdev Jun 27, 2023
ac92606
🦉 Updates from OwlBot post-processor
gcf-owl-bot[bot] Jun 27, 2023
0e963df
Merge branch 'filesystems-sample' of https://github.com/GoogleCloudPl…
gcf-owl-bot[bot] Jun 27, 2023
0af99cd
Merge branch 'main' into filesystems-sample
kweinmeister Jun 27, 2023
4af4979
Merge branch 'main' into filesystems-sample
pattishin Jun 28, 2023
963d85e
Update run/filesystem/package.json
rogerthatdev Jun 28, 2023
ad60445
Update run/filesystem/package.json
rogerthatdev Jun 28, 2023
709e007
remove fs from package.json
rogerthatdev Jun 28, 2023
69a73b6
Merge branch 'filesystems-sample' of github.com:GoogleCloudPlatform/n…
rogerthatdev Jun 28, 2023
476c028
typo
rogerthatdev Jun 28, 2023
b4b112c
move port var down
rogerthatdev Jun 28, 2023
668acab
change filename format
rogerthatdev Jun 28, 2023
4efdda0
🦉 Updates from OwlBot post-processor
gcf-owl-bot[bot] Jun 28, 2023
eadcc86
refactor: redirect all to mnt path
rogerthatdev Jun 29, 2023
4c82d59
eslint
rogerthatdev Jun 29, 2023
10322c8
Merge branch 'main' into filesystems-sample
kweinmeister Jun 29, 2023
9b9b813
additional comments
rogerthatdev Jul 5, 2023
1be7a10
separate function for index
rogerthatdev Jul 5, 2023
76748e8
eslint
rogerthatdev Jul 5, 2023
e8eaa58
fix hrefs
rogerthatdev Jul 5, 2023
eebb278
move file prefix var
rogerthatdev Jul 5, 2023
667095d
period
rogerthatdev Jul 5, 2023
b604c04
Merge branch 'main' into filesystems-sample
rogerthatdev Jul 5, 2023
62c676c
rename wrapper script
rogerthatdev Jul 5, 2023
0d3d1b6
update wrapper
rogerthatdev Jul 5, 2023
926cd1f
comments and sample description
rogerthatdev Jul 6, 2023
51eec6b
cross-site scripting
rogerthatdev Jul 6, 2023
890a349
add try catch
rogerthatdev Jul 6, 2023
c68f1c1
better error response
rogerthatdev Jul 6, 2023
07b5329
sanitize res
rogerthatdev Jul 6, 2023
93df837
use node:20-slim
rogerthatdev Jul 6, 2023
acfe819
rm unused dep
rogerthatdev Jul 7, 2023
757c389
arrow functions and consts
rogerthatdev Jul 8, 2023
0657f82
eslint
rogerthatdev Jul 8, 2023
605f059
no mutations
rogerthatdev Jul 8, 2023
5a403b7
unused var
rogerthatdev Jul 8, 2023
df0e6ec
Merge branch 'filesystems-sample' of github.com:GoogleCloudPlatform/n…
rogerthatdev Jul 8, 2023
daaf07d
remove unneeded async
rogerthatdev Jul 11, 2023
9eafb7c
Merge branch 'filesystems-sample' of github.com:GoogleCloudPlatform/n…
rogerthatdev Jul 11, 2023
18e9695
lint
rogerthatdev Jul 11, 2023
1b81ef0
Merge branch 'main' into filesystems-sample
rogerthatdev Jul 11, 2023
d90097d
add sigterm handling
rogerthatdev Jul 11, 2023
789d088
Merge branch 'filesystems-sample' of github.com:GoogleCloudPlatform/n…
rogerthatdev Jul 11, 2023
e901a4c
fix sigterm handling
rogerthatdev Jul 11, 2023
dc441f7
formatting
rogerthatdev Jul 11, 2023
5b58bfe
e2e test cloudbuild config
rogerthatdev Jul 13, 2023
b86fbc9
parallel delete resources
rogerthatdev Jul 13, 2023
736d884
fix cleanup step
rogerthatdev Jul 13, 2023
f187d8d
add waitfor
rogerthatdev Jul 13, 2023
38deec6
break cleanup into 3 steps
rogerthatdev Jul 13, 2023
8b46152
clean up AR Repo build
rogerthatdev Jul 13, 2023
671d85e
split build config into setup and cleanup
rogerthatdev Jul 13, 2023
577e217
e2e test boilerplate
rogerthatdev Jul 13, 2023
a6e4fc9
remove unused subs from cleanup yaml
rogerthatdev Jul 13, 2023
4c40164
update waitFor in cleanup yaml
rogerthatdev Jul 13, 2023
de5585f
recombine build yamls
rogerthatdev Jul 13, 2023
a868e08
lint
rogerthatdev Jul 13, 2023
f993889
split cloudbuild config
rogerthatdev Jul 13, 2023
dabf84a
split tests to system.test.js
rogerthatdev Jul 14, 2023
65be250
lint
rogerthatdev Jul 14, 2023
b7f67d9
system.test add auth
rogerthatdev Jul 14, 2023
8363f5d
add before and after to e2e test
rogerthatdev Jul 14, 2023
637dd10
add endpoint test to e2e
rogerthatdev Jul 15, 2023
6c237fe
update package.json
rogerthatdev Jul 15, 2023
79d6047
headers
rogerthatdev Jul 15, 2023
286563c
typo
rogerthatdev Jul 17, 2023
2f0c3b5
add to system e2e tests
rogerthatdev Jul 17, 2023
572f490
kokoro config
rogerthatdev Jul 17, 2023
85d5044
Merge branch 'main' into filesystems-sample
rogerthatdev Jul 17, 2023
b434296
remove cfg
rogerthatdev Jul 18, 2023
6ac4972
typo
rogerthatdev Jul 18, 2023
fde18ff
remove server.close
rogerthatdev Jul 18, 2023
fe899cd
refactor system.test.js to match other samples
rogerthatdev Jul 19, 2023
48f76ec
add test for generated txt to e2e
rogerthatdev Jul 19, 2023
404e6f9
add comment re: rate limit
rogerthatdev Jul 19, 2023
c63a493
remove allow unauthenticated
rogerthatdev Jul 19, 2023
bff9835
lint: unused var
rogerthatdev Jul 19, 2023
c7e312c
add unit test for file generation
rogerthatdev Jul 19, 2023
06e4f41
Merge branch 'main' into filesystems-sample
rogerthatdev Jul 19, 2023
b9d0595
clarify rate limit comment
rogerthatdev Jul 20, 2023
8336b7d
🦉 Updates from OwlBot post-processor
gcf-owl-bot[bot] Jul 20, 2023
84c8dbf
add wait -n to run script
rogerthatdev Jul 20, 2023
3ac013a
use fs/promises
rogerthatdev Jul 22, 2023
8280e8a
write file before generating html
rogerthatdev Jul 22, 2023
0053c40
Merge branch 'main' into filesystems-sample
rogerthatdev Jul 24, 2023
5470c1f
Merge branch 'main' into filesystems-sample
rogerthatdev Jul 25, 2023
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
62 changes: 62 additions & 0 deletions .github/workflows/run-filesystem.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
# Copyright 2023 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

name: run-filesystem
on:
push:
branches:
- main
paths:
- 'run/filesystem/**'
- '.github/workflows/run-filesystem.yaml'
pull_request:
paths:
- 'run/filesystem/**'
- '.github/workflows/run-filesystem.yaml'
pull_request_target:
types: [labeled]
paths:
- 'run/filesystem/**'
- '.github/workflows/run-filesystem.yaml'
schedule:
- cron: '0 0 * * 0'
jobs:
test:
# Ref: https://github.com/google-github-actions/auth#usage
permissions:
contents: 'read'
id-token: 'write'
if: github.event.action != 'labeled' || github.event.label.name == 'actions:force-run'
uses: ./.github/workflows/test.yaml
with:
name: 'run-filesystem'
path: 'run/filesystem'
remove_label:
# Ref: https://github.com/google-github-actions/auth#usage
permissions:
contents: 'read'
id-token: 'write'
if: |
github.event.action == 'labeled' &&
github.event.label.name == 'actions:force-run' &&
always()
uses: ./.github/workflows/remove-label.yaml
flakybot:
# Ref: https://github.com/google-github-actions/auth#usage
permissions:
contents: 'read'
id-token: 'write'
if: github.event_name == 'schedule' && always() # always() submits logs even if tests fail
uses: ./.github/workflows/flakybot.yaml
needs: [test]
1 change: 1 addition & 0 deletions .github/workflows/utils/workflows.json
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@
"monitoring/snippets",
"opencensus",
"retail",
"run/filesystem",
"scheduler",
"secret-manager",
"service-directory/snippets",
Expand Down
7 changes: 7 additions & 0 deletions .kokoro/run/filesystem.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Format: //devtools/kokoro/config/proto/build.proto

# Set the folder in which the tests are run
env_vars: {
rogerthatdev marked this conversation as resolved.
Show resolved Hide resolved
key: "PROJECT"
value: "run/filesystem"
}
51 changes: 51 additions & 0 deletions run/filesystem/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Copyright 2023 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# [START cloudrun_fs_dockerfile]

# Use the official Node.js image.
# https://hub.docker.com/_/node
FROM node:20-slim

# Install system dependencies
RUN apt-get update -y && apt-get install -y \
tini \
nfs-common \
libtool \
&& apt-get clean

# Set fallback mount directory
ENV MNT_DIR /mnt/nfs/filestore

# Copy local code to the container image.
ENV APP_HOME /app
WORKDIR $APP_HOME
COPY package*.json ./

# Install production dependencies.
RUN npm install --only=production

# Copy local code to the container image.
COPY . ./

# Ensure the script is executable
RUN chmod +x /app/run.sh

# Use tini to manage zombie processes and signal forwarding
# https://github.com/krallin/tini
ENTRYPOINT ["/usr/bin/tini", "--"]

# Pass the wrapper script as arguments to tini
CMD ["/app/run.sh"]
# [END cloudrun_fs_dockerfile]
97 changes: 97 additions & 0 deletions run/filesystem/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
// Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* Express webapp that generates files to a mounted NFS when deployed to Cloud Run.
*
* See https://cloud.google.com/run/docs/tutorials/network-filesystems-filestore before running the code snippet.
*/

const express = require('express');
const rateLimit = require('express-rate-limit');
const fs = require('fs');
const app = express();
const mntDir = process.env.MNT_DIR || '/mnt/nfs/filestore';
const port = parseInt(process.env.PORT) || 8080;
const limit = rateLimit({
rogerthatdev marked this conversation as resolved.
Show resolved Hide resolved
windowMs: 15 * 60 * 1000,
max: 100,
message: 'Rate limit exceeded',
headers: true,
});

app.use(limit);
app.use(mntDir, express.static(mntDir));

const server = app.listen(port, () => {
console.log(`Listening on port ${port}`);
});

app.get(mntDir, async (req, res) => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't add the "back" button to get back to the mount directory index.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This sample can't add the back button because it's returning the actual file which is a plain-text .txt without HTML

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The canonical does this differently. Do you have a reason to break from the canonical?

// Have all requests to mount directory generate a new file on the filesystem.
try {
await writeFile(mntDir);
// Respond with html listing files.
res.send(generateIndex(mntDir));
Fixed Show fixed Hide fixed
Fixed Show fixed Hide fixed
} catch (error) {
console.error(error);
res
.status(500)
.send(
'Something went wrong when writing to the filesystem. Refresh the page to try again.'
);
}
});

app.all('*', (req, res) => {
// Redirect all requests to the mount directory
res.redirect(mntDir);
});

const writeFile = (path, filePrefix = 'test') => {
// Write a test file to the provided path.
const date = new Date();
const formattedDate = date.toString().split(' ').slice(0, 5).join('-');
const filename = `${filePrefix}-${formattedDate}.txt`;
const contents = `This test file was created on ${formattedDate}.\n`;

fs.writeFile(`${path}/${filename}`, contents, err => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Callbacks seem a bit outdated. A Node.js SME should weigh in

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sofisl can you weigh in here? Thanks!

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we could use promises here! We could use the new fs promises module, like so, with a try-catch block.

if (err) {
return err;
}
});
};

const generateIndex = mntDir => {
// Return html for page with a list of files on the mounted filesystem.
const header =
'<html><body>A new file is generated each time this page is reloaded.<p>Files created on filesystem:<p>';
const footer = '</body></html>';
// Get list of files on mounted filesystem.
const existingFiles = fs.readdirSync(mntDir);
const htmlBody = existingFiles.map(fileName => {
const sanitized = encodeURIComponent(fileName);
return `<a href="${mntDir}/${sanitized}">${decodeURIComponent(
sanitized
)}</a><br>`;
});
return header + htmlBody.join(' ') + footer;
};

process.on('SIGTERM', () => {
server.close(() => {
rogerthatdev marked this conversation as resolved.
Show resolved Hide resolved
console.error('Received SIGTERM signal. Exiting.');
rogerthatdev marked this conversation as resolved.
Show resolved Hide resolved
});
});

rogerthatdev marked this conversation as resolved.
Show resolved Hide resolved
module.exports = app;
26 changes: 26 additions & 0 deletions run/filesystem/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"name": "filesystem",
"description": "Demonstrate accessing a mounted network filesystem from a Cloud Run service.",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "node index.js",
"test": "c8 mocha test/index.test.js --exit",
"system-test": "NAME=Cloud c8 mocha test/system.test.js --timeout=360000 --exit"
rogerthatdev marked this conversation as resolved.
Show resolved Hide resolved
},
"author": "Google LLC",
"license": "Apache-2.0",
"dependencies": {
"express": "^4.18.2",
"express-rate-limit": "^6.7.0"
},
"devDependencies": {
"c8": "^7.14.0",
"chai": "^4.3.7",
"chai-http": "^4.4.0",
"google-auth-library": "^8.0.0",
"mocha": "^10.2.0",
"mock-fs": "^5.2.0",
"supertest": "^6.3.3"
}
}
28 changes: 28 additions & 0 deletions run/filesystem/run.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#!/usr/bin/env bash
# Copyright 2023 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# [START cloudrun_fs_script]
#!/usr/bin/env bash
set -eo pipefail

# Create mount directory for service.
mkdir -p $MNT_DIR

echo "Mounting Cloud Filestore."
mount -o nolock $FILESTORE_IP_ADDRESS:/$FILE_SHARE_NAME $MNT_DIR
echo "Mounting completed."

node index.js
# [END cloudrun_fs_script]
38 changes: 38 additions & 0 deletions run/filesystem/test/e2e_test_cleanup.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Copyright 2023 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

steps:
- id: 'Delete Cloud Run service'
name: 'gcr.io/cloud-builders/gcloud:latest'
entrypoint: /bin/bash
waitFor: ['-']
args:
- '-c'
- |
gcloud run services delete $_RUN_SERVICE --region $_REGION --quiet

- id: 'Delete Artifact Registry build'
name: 'gcr.io/cloud-builders/gcloud:latest'
entrypoint: /bin/bash
waitFor: ['-']
args:
- '-c'
- |
gcloud artifacts docker images delete \
us-central1-docker.pkg.dev/$PROJECT_ID/cloud-run-source-deploy/$_RUN_SERVICE:latest --quiet

substitutions:
_REGION: us-central1
_RUN_SERVICE: filesystem-app

35 changes: 35 additions & 0 deletions run/filesystem/test/e2e_test_setup.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Copyright 2023 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

steps:
- id: 'Build and deploy to Cloud Run'
name: 'gcr.io/cloud-builders/gcloud:latest'
entrypoint: /bin/bash
args:
- '-c'
- |
gcloud run deploy $_RUN_SERVICE --source . \
--region $_REGION \
--vpc-connector $_CONNECTOR_NAME \
--execution-environment gen2 \
--allow-unauthenticated \
rogerthatdev marked this conversation as resolved.
Show resolved Hide resolved
--update-env-vars FILESTORE_IP_ADDRESS=$_FILESTORE_IP_ADDRESS,FILE_SHARE_NAME=$_SHARE_NAME

substitutions:
_REGION: us-central1
_FILESTORE_IP_ADDRESS: 10.103.89.66 # Existing long-standing resource
_SHARE_NAME: filestoresamples # Existing long-standing resource
_CONNECTOR_NAME: run-filesystem-e2e-test # Existing long-standing resource
_RUN_SERVICE: filesystem-app

Loading