I am using Cloud Build to deploy my firebase project (hosting and cloud functions) trigged by a commit to a branch in a github repo. The deploy is successful and the site works, but the cloud functions don't run after the deploy. They don't even show up in the log as being called, so there are no errors.
I click a button from the UI that calls a cloud function, which saves some data to the real-time database. The code to call the function is run in a try catch, and the catch code runs. The logs for the cloud function show nothing -- the function isn't even run. When I then deploy the project locally from my laptop instead of via cloud build, the cloud function runs when the button is clicked and the data is saved to the database and the logs indicate that the function was invoked. None of the cloud functions are invoked when triggering an event from the front end, however, when I have deployed from Cloud Build
It's only when the project is deployed by Cloud Build that the functions don't run when they are called. I am wondering if this could be a permissions issue?
Front end code:
const createTeam = (payload) => {
return async (dispatch, getState, getFirebase) => {
debugger;
const createTeam = getFirebase().functions().httpsCallable("createTeam");
console.log("create team===>", createTeam);
try {
console.log("about to run");
await createTeam(payload);
dispatch(
sendNotification({
severity: "success",
message: "Team Created",
isOpen: true,
})
);
} catch (e) {
dispatch(
sendNotification({
severity: "error",
message: "An error occurred and team was not created.",
isOpen: true,
})
);
}
};
};
Build file:
steps:
- name: "gcr.io/cloud-builders/npm"
dir: "functions"
args: ["install"]
# Install
- name: "gcr.io/cloud-builders/npm"
args: ["install"]
# Build
- name: "gcr.io/cloud-builders/npm"
args: ["run", "build"]
# Deploy
- name: "gcr.io/$PROJECT_ID/firebase"
args: ["deploy", "--project=$PROJECT_ID"]
from the deployment logs:
Hosting URL: xxxx
Project Console: xxxx
✔ Deploy complete!
✔ hosting[agile-boost]: release complete
i hosting[agile-boost]: releasing new version...
✔ hosting[agile-boost]: version finalized
i hosting[agile-boost]: finalizing version...
✔ functions[launchAssessments(us-central1)]: Successful update operation.
✔ functions[createTeam(us-central1)]: Successful update operation.
✔ functions[sendParticipantEmailWhenAssessmentOpens(us-central1)]: Successful update operation.
✔ functions[completeAssessments(us-central1)]: Successful update operation.
✔ functions[refreshMetricCategoryAvg(us-central1)]: Successful update operation.
✔ functions[saveParticipantAnswer(us-central1)]: Successful update operation.
✔ functions[updateParticipant(us-central1)]: Successful update operation.
✔ functions[closeAssessmentsWhenTeamIsDeleted(us-central1)]: Successful update operation.
✔ functions[getParticipantsData(us-central1)]: Successful update operation.
✔ functions[createAccount(us-central1)]: Successful update operation.
✔ functions[addParticipantToAssessment(us-central1)]: Successful update operation.
✔ functions[createAssessment(us-central1)]: Successful update operation.
✔ functions[reviseAssessmentMetrics(us-central1)]: Successful update operation.
✔ functions[refreshMetricQuestionAvg(us-central1)]: Successful update operation.
✔ functions[updateParticipantWhenTeamParticipantUpdates(us-central1)]: Successful update operation.
✔ functions[refreshMetricTagAvg(us-central1)]: Successful update operation.
✔ functions[updateMetricsWhenParticipantStatusChanges(us-central1)]: Successful update operation.
✔ functions[addNewTeamParticipantToActiveAssessments(us-central1)]: Successful update operation.
✔ functions[getSurveyData(us-central1)]: Successful update operation.
i functions: scheduler job firebase-schedule-completeAssessments-us-central1 is up to date, no changes required
i functions: scheduler job firebase-schedule-launchAssessments-us-central1 is up to date, no changes required
✔ pubsub: required API pubsub.googleapis.com is enabled
✔ scheduler: required API cloudscheduler.googleapis.com is enabled
i pubsub: ensuring required API pubsub.googleapis.com is enabled...
i scheduler: ensuring required API cloudscheduler.googleapis.com is enabled...
i functions: updating Node.js 10 function completeAssessments(us-central1)...
i functions: updating Node.js 10 function launchAssessments(us-central1)...
i functions: updating Node.js 10 function getParticipantData(us-central1)...
i functions: updating Node.js 10 function getParticipantsData(us-central1)...
i functions: updating Node.js 10 function closeAssessmentsWhenTeamIsDeleted(us-central1)...
i functions: updating Node.js 10 function updateParticipantWhenTeamParticipantUpdates(us-central1)...
i functions: updating Node.js 10 function updateMetricsWhenParticipantStatusChanges(us-central1)...
i functions: updating Node.js 10 function sendParticipantEmailWhenAssessmentOpens(us-central1)...
i functions: updating Node.js 10 function addNewTeamParticipantToActiveAssessments(us-central1)...
i functions: updating Node.js 10 function saveParticipantAnswer(us-central1)...
i functions: updating Node.js 10 function getSurveyData(us-central1)...
i functions: updating Node.js 10 function updateParticipant(us-central1)...
i functions: updating Node.js 10 function addParticipantToAssessment(us-central1)...
i functions: updating Node.js 10 function createAssessment(us-central1)...
i functions: updating Node.js 10 function createTeam(us-central1)...
i functions: updating Node.js 10 function createAccount(us-central1)...
i functions: updating Node.js 10 function reviseAssessmentMetrics(us-central1)...
i functions: updating Node.js 10 function refreshMetricQuestionAvg(us-central1)...
i functions: updating Node.js 10 function refreshMetricTagAvg(us-central1)...
i functions: updating Node.js 10 function refreshMetricCategoryAvg(us-central1)...
✔ database: rules for database xxxx released successfully
i database: releasing rules...
✔ hosting[agile-boost]: file upload complete
i hosting: uploading new files [4/6] (66%)
i hosting: hashing files [34/35] (97%)
i hosting: hashing files [34/35] (97%)
i hosting[agile-boost]: found 35 files in build
i hosting[agile-boost]: beginning deploy...
✔ functions: functions folder uploaded successfully
i functions: packaged functions (52.61 KB) for uploading
i functions: preparing functions directory for uploading...
✔ functions: required API cloudbuild.googleapis.com is enabled
✔ functions: required API cloudfunctions.googleapis.com is enabled
i functions: ensuring required API cloudbuild.googleapis.com is enabled...
i functions: ensuring required API cloudfunctions.googleapis.com is enabled...
✔ database: rules syntax for database agile-boost is valid
i database: checking rules syntax...
✔ functions: Finished running predeploy script.
> tsc
> functions# build /workspace/functions
Running command: npm --prefix "$RESOURCE_DIR" run build
> tslint --project tsconfig.json
> functions# lint /workspace/functions
Running command: npm --prefix "$RESOURCE_DIR" run lint
i deploying database, functions, hosting
=== Deploying to 'xxxx'...
gcr.io/agile-boost/firebase:latest
Status: Downloaded newer image for gcr.io/agile-boost/firebase:latest
Digest: sha256:063a10dfecc2b3bb4245316fb89ae1588f594bb8bb6e950ecf6a9488015e20bb
38ee9b020816: Pull complete
ddf8c3713c7d: Pull complete
9819791ca1ba: Pull complete
19c9987a828c: Pull complete
40ba0f817ab5: Pull complete
8cdf70a16731: Pull complete
9819791ca1ba: Download complete
9819791ca1ba: Verifying Checksum
8cdf70a16731: Download complete
8cdf70a16731: Verifying Checksum
38ee9b020816: Download complete
38ee9b020816: Verifying Checksum
ddf8c3713c7d: Download complete
ddf8c3713c7d: Verifying Checksum
40ba0f817ab5: Download complete
40ba0f817ab5: Verifying Checksum
19c9987a828c: Download complete
19c9987a828c: Verifying Checksum
38ee9b020816: Waiting
ddf8c3713c7d: Waiting
9819791ca1ba: Waiting
38ee9b020816: Pulling fs layer
ddf8c3713c7d: Pulling fs layer
9819791ca1ba: Pulling fs layer
19c9987a828c: Pulling fs layer
40ba0f817ab5: Pulling fs layer
8cdf70a16731: Pulling fs layer
e5c5821cd889: Already exists
55abbc6cc158: Already exists
8439168fd8dc: Already exists
c159512f4cc2: Already exists
1b49aa113642: Already exists
4f250268ed6a: Already exists
latest: Pulling from agile-boost/firebase
Using default tag: latest
Pulling image: gcr.io/agile-boost/firebase
Related
I am trying to run a github actions workflow on each push to the main branch. The workflow is supposed to deploy firebase cloud functions (in the /functions dir).
The whole workflow gets triggered by the push correctly and runs without errors, but the functions do not get deployed.
deploy-cloud-functions-merge.yml
name: Deploy Cloud Functions
on:
workflow_dispatch:
push:
branches:
- main
paths:
- 'functions/**'
jobs:
build_and_deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout#v3
- uses: actions/setup-node#v3
with:
node-version: 16.x
- name: Build Cloud Functions
run: cd functions && npm ci
- name: Create SA key
run: echo '${{ secrets.CLOUD_FUNCTIONS_SERVICE_ACCOUNT }}' > $HOME/gcloud.json
- name: Deploy Cloud Functions
run: export GOOGLE_APPLICATION_CREDENTIALS=$HOME/gcloud.json && cd functions && npx firebase-tools deploy --only functions --project default --json && npx firebase-tools --version
The output in github actions from the Deploy Cloud Functions step:
Run export GOOGLE_APPLICATION_CREDENTIALS=$HOME/gcloud.json && cd functions && npx firebase-tools deploy --only functions --project default --json && npx firebase-tools --version
npm WARN exec The following package was not found and will be installed: firebase-tools#11.23.0
npm WARN deprecated uuid#3.4.0: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details.
npm WARN deprecated request#2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
npm WARN deprecated har-validator#5.1.3: this library is no longer supported
npm WARN deprecated debug#4.1.1: Debug versions >=3.2.0 <3.2.7 || >=4 <4.3.1 have a low-severity ReDos regression when used in a Node.js environment. It is recommended you upgrade to 3.2.7 or 4.3.1. (https://github.com/visionmedia/debug/issues/797)
> lint
> eslint
11.23.0
So after the predeploy script (lint + eslint), there is no output, but also no error.
When I run firebase deploy --only functions --project default on the same project locally, this is what the output looks like:
=== Deploying to '[projectname]'...
i deploying functions
Running command: npm --prefix "$RESOURCE_DIR" run lint
> lint
> eslint
✔ functions: Finished running predeploy script.
i functions: ensuring required API cloudfunctions.googleapis.com is enabled...
i functions: ensuring required API cloudbuild.googleapis.com is enabled...
i artifactregistry: ensuring required API artifactregistry.googleapis.com is enabled...
✔ artifactregistry: required API artifactregistry.googleapis.com is enabled
✔ functions: required API cloudbuild.googleapis.com is enabled
✔ functions: required API cloudfunctions.googleapis.com is enabled
i functions: preparing codebase default for deployment
⚠ functions: package.json indicates an outdated version of firebase-functions. Please upgrade using npm install --save firebase-functions#latest in your functions directory.
i functions: preparing functions directory for uploading...
i functions: packaged /home/stanley/[projectname]/functions (82.34 KB) for uploading
✔ functions: functions folder uploaded successfully
i functions: updating Node.js 16 function getFileParts(europe-west1)...
i functions: updating Node.js 16 function getCustomMeta(europe-west1)...
i functions: updating Node.js 16 function getCSVParts(europe-west1)...
i functions: updating Node.js 16 function getTemplates(europe-west1)...
i functions: updating Node.js 16 function getCSVLink(europe-west1)...
✔ functions[getCustomMeta(europe-west1)] Successful update operation.
✔ functions[getTemplates(europe-west1)] Successful update operation.
✔ functions[getCSVParts(europe-west1)] Successful update operation.
✔ functions[getCSVLink(europe-west1)] Successful update operation.
✔ functions[getFileParts(europe-west1)] Successful update operation.
Function URL [functionurl]
Function URL [functionurl]
Function URL [functionurl]
Function URL [functionurl]
Function URL [functionurl]
i functions: cleaning up build files...
✔ Deploy complete!
Project Console: [console-link]
I am using --project default, to fix a previous error:
***
"status": "error",
"error": "No project active, but project aliases are available.\n\nRun \u001b[1mfirebase use <alias>\u001b[22m with one of these options:\n\n default ([projectname])\n staging ([projectname])"
***
this is what my .firebaserc looks like:
{
"projects": {
"default": "[projectname]",
"staging": "[projectname]"
},
"targets": {
"[projectname]": {
"hosting": {
"[projectname]": [
"[otherprojectname]"
]
}
}
},
"etags": {}
}
I am basically out of solutions and would appreciate any suggestions.
I've been away from firebase for about 2 years and just got back trying to fix couple of things in my firebase-functions. There was a plenty to update with my packages, but I got to the point where I am not sure what to do next to deploy the fixed function.
Here is the error that happens after trying to deploy a function in terminal:
lukasstateczny#Lukass-MacBook-Pro admin-pukinn % firebase deploy --only functions:mpiEnrollment
=== Deploying to 'pukinn2'...
i deploying functions
Running command: npm --prefix "$RESOURCE_DIR" run lint
> lint
> tslint --project tsconfig.json
Tried to lint /Users/lukasstateczny/Desktop/Pukinn/admin-pukinn/functions/src/index.ts but found no valid, enabled rules for this file type and file path in the resolved configuration.
Running command: npm --prefix "$RESOURCE_DIR" run build
> build
> tsc
✔ functions: Finished running predeploy script.
i functions: preparing codebase default for deployment
i functions: ensuring required API cloudfunctions.googleapis.com is enabled...
i functions: ensuring required API cloudbuild.googleapis.com is enabled...
i artifactregistry: ensuring required API artifactregistry.googleapis.com is enabled...
✔ artifactregistry: required API artifactregistry.googleapis.com is enabled
✔ functions: required API cloudfunctions.googleapis.com is enabled
✔ functions: required API cloudbuild.googleapis.com is enabled
Error: Failed to load function definition from source: Failed to generate manifest from function source: Error: Cannot find module '../config/pukinn2-1b14e9a65ea1.json'
Require stack:
- /Users/lukasstateczny/Desktop/Pukinn/admin-pukinn/functions/lib/index.js
- /Users/lukasstateczny/Desktop/Pukinn/admin-pukinn/node_modules/firebase-functions/lib/runtime/loader.js
- /Users/lukasstateczny/Desktop/Pukinn/admin-pukinn/node_modules/firebase-functions/lib/bin/firebase-functions.js
lukasstateczny#Lukass-MacBook-Pro admin-pukinn %
Now the config folder exists, but there is no file with this name. Also I'm not sure about these weird numbers after the app name, but I guess it's probably something like a cashed file. I don't know at this point how to get this file and what values should be in it.
ANSWER: After a few helpful comments I realize I was missing serviceAccount.json file that can be found in Firebase Console -> App Settings -> Service Accounts [Tab]
I thought first firebaseConfig was enough but I was wrong.
Also couple of dependencies were outdated, so I needed to upgrade that as well, but after including the .json file the deployment was smooth as ever.
Service account template in case you are not sure how it should look:
{
"type": "service_account",
"project_id": "yourProjectName",
"private_key_id": "...a89fds980asddfs890dsa...",
"private_key": "-----BEGIN PRIVATE KEY-----\n...ahjk8123hdjak91hjkdsa...\n-----END PRIVATE KEY-----\n",
"client_email": "firebase-adminsdk-0000f#yourProject.iam.gserviceaccount.com",
"client_id": "...1234567...",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/000/firebase-adminsdk-0000%40yourproject.iam.gserviceaccount.com"
}
Obviously make sure not to share real values with anyone.
I would try removing your .firebase folder which may contain a very old hosting cache file and retry the deployment if you are able to build the app locally just fine.
Additionally, prior to deploying those functions, I would verify in development that they are working as you intend using your Functions Emulator. In the React client you obviously need to use the connectEmulator function for development to be able to test you functions if you haven't already.
You also may want to go inside your functions folder, remove the build folder, run npm run build and ensure your functions are building just fine.
When I run firebase deploy I get the following output:
> build
> tsc
✔ functions: Finished running predeploy script.
i functions: ensuring required API cloudfunctions.googleapis.com is enabled...
i functions: ensuring required API cloudbuild.googleapis.com is enabled...
i artifactregistry: ensuring required API artifactregistry.googleapis.com is enabled...
✔ artifactregistry: required API artifactregistry.googleapis.com is enabled
✔ functions: required API cloudbuild.googleapis.com is enabled
✔ functions: required API cloudfunctions.googleapis.com is enabled
i functions: preparing codebase default for deployment
Error: Failed to load function definition from source: Failed to generate manifest from function source: Error: username is required
Which is odd because the same command has been working for weeks. Is there some "username" field that I need to put into firebase.json or something?
The proper way to initialize Firebase within a Cloud Function would be to use the firebase-admin client as shown here.
I would recommend you try using the below while initializing the app and see if this works:
import {initializeApp} from "firebase-admin/app";
Another thing to check are the firebase function dependencies whether they are still built intact.
As seen per your code, it looks like you're trying to use the Cloud Functions for TypeScript, and npm run build -- --watch takes care of updating the built code as you are coding. Cloud Functions would run with the built JS code and not the TypeScript code.
The problem could be that the setup at the entry point of Cloud Functions is a .ts file and not .js. In your package.json for Functions, you have
"main": "src/index.ts"
Try changing it to:
"main": "lib/index.js"
That way the entry point of Cloud Functions will be a JavaScript file, and also, will be the JavaScript that was built from your TypeScript code. lib/index.js is used because, by default, that is where the tsc command will build your src/index.ts file into.
Also do check this helpful document for troubleshooting the function deploy issues.
I have a fresh project but was looking to test scheduled functions. Am I missing anything?
$ firebase deploy
=== Deploying to 'testing-db'...
i deploying functions
i functions: ensuring required API cloudfunctions.googleapis.com is enabled...
i functions: ensuring required API cloudbuild.googleapis.com is enabled...
! functions: missing required API cloudbuild.googleapis.com. Enabling now...
+ functions: required API cloudfunctions.googleapis.com is enabled
+ functions: required API cloudbuild.googleapis.com is enabled
i functions: preparing functions directory for uploading...
i functions: packaged functions (24.45 KB) for uploading
i functions: ensuring required API pubsub.googleapis.com is enabled...
i functions: ensuring required API cloudscheduler.googleapis.com is enabled...
! functions: missing required API cloudscheduler.googleapis.com. Enabling now...
+ functions: required API pubsub.googleapis.com is enabled
+ functions: required API cloudscheduler.googleapis.com is enabled
+ functions: functions folder uploaded successfully
i functions: creating Node.js 14 function scheduledFunction(us-central1)...
Functions deploy had errors with the following functions:
scheduledFunction(us-central1)
i functions: cleaning up build files...
Error: There was an error deploying functions
Index.js
const functions = require('firebase-functions');
exports.scheduledFunction = functions.pubsub
.schedule('every 1 minutes')
.onRun((context) => {
return console.log('This will be run every 1 minutes!');
});
Firebase log shows:
Error: Failed to upsert schedule function scheduledFunction in region europe-west1
I ran into this issue as well, but the solution was not region related like #Priyashree's answer. Rather, when I ran firebase deploy --only functions --debug the logs revealed that my scheduler had an error.
The bottom of the log had this error:
Error: Failed to upsert schedule function foo in region us-central1
But scrolling up a bit revealed:
<<< HTTP RESPONSE BODY {"error":{"code":400,"message":"Schedule or time zone is invalid.","status":"INVALID_ARGUMENT"}}
I had a typo in my function schedule:
functions.pubsub.schedule("every 1 minute").onRun((context) => {}
every 1 minute should have been every 1 minutes. Note the missing 's'.
In general, I think it's useful to enable '--debug' on the firebase deploy command so you can see detailed log output of the exact error.
When you are using scheduled functions in Firebase Functions, an App Engine instance is created that is needed for Cloud Scheduler to work. You can read about it here.They use the location that has been set by default for resources. I think that you are getting that error because there is a difference between the default GCP resource location you specified and the region of your scheduled cloud function. If you click on the cogwheel next to project-overview in Firebase you can see where your resources are located.
Check your Cloud Scheduler function details and see which region it has been deployed to. By default, functions run in the us-central1 region. Check this link to see how we can change the region of the function.
I am trying to create a Cloud function which sends a firebase cloud message to the users when a new document is created. Somehow I can not deploy the function to Firebase.
Here is my index.js:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);
exports.sendAll = functions.region("europe-west3").firestore
.document("NewsCard/{docId}")
.onCreate((snapshot) => {
const title = snapshot.get("Title");
const subject = snapshot.get("Text");
const payload = {
notification: {
title: title,
body: subject,
sound: "default",
},
};
return admin.messaging().sendToTopic("Announcement", payload);
});
This is the error I get when I type firebase deploy:
✔ functions: Finished running predeploy script.
i functions: ensuring required API cloudfunctions.googleapis.com is enabled...
i functions: ensuring required API cloudbuild.googleapis.com is enabled...
✔ functions: required API cloudbuild.googleapis.com is enabled
✔ functions: required API cloudfunctions.googleapis.com is enabled
i functions: preparing functions directory for uploading...
i functions: packaged functions (64.26 KB) for uploading
✔ functions: functions folder uploaded successfully
i functions: updating Node.js 12 function sendAll(europe-west3)...
⚠ functions[sendAll(europe-west3)]: Deployment error.
...
Error: Functions did not deploy properly.
What is causing this problem? I read somewhere on the internet, that the firestore path .document("NewsCard/{docId}") could be wrong. But I dont know what to use instead.
Here is my Firestore:
Figured it out myself. Seems to be a problem with Node. See #3120 for more information. Downgrade Node to 14 helps.