MartinSahlen/cloud-functions-python

finished with status code: 500

santhoshdc1590 opened this issue ยท 3 comments

I was successful in running the python code I want by deploying it on cloud function. ๐ŸŽ‰๐ŸŽ‰๐ŸŽ‰๐ŸŽ‰

This is my function.py file content.

from FTUL import mainP
from cloudfn.google_account import get_credentials
from cloudfn.http import handle_http_event, Response
from google.cloud import bigquery
import json

def handle_http(req):
    
    biquery_client = bigquery.Client(credentials=get_credentials())
       
    if req.method == 'POST':
        #extract information from the body of the POST request
        rBody = json.loads(req.body)
        im = rBody['image']
        rID = rBody['refID']
        rTable = rBody['refTable']
        # Do the required operation from the extracted info
        mainP(im,rID,rTable)

        return Response(
            status_code=200,
        )


handle_http_event(handle_http)

The cloud function runs as expected, but always ends with error code 500

When I check the logs of google.

this is what is being printed

{
insertId: "some code"
labels: {
execution_id: "some id"
}
logName: "projects/network-api-production/logs/cloudfunctions.googleapis.com%2Fcloud-functions"
receiveTimestamp: "2018-03-28T11:34:48.880241330Z"
resource: {
labels: {
function_name: "handle_http"
project_id: "network-api-production"
region: "us-central1"
}
type: "cloud_function"
}
severity: "DEBUG"
textPayload: "Function execution took 5026 ms, finished with status code: 500"
timestamp: "2018-03-28T11:34:43.524350461Z"

severity: "DEBUG" can be seen here in LogSeverity as (100) Debug or trace information

Can anyone help me resolve the issue?

shimHandler inside index.js in cloudfn/template is returning 500

index.js content

var googleAuth = require('google-auto-auth')();
//Handle Background events according to spec
function shimHandler(data) { console.log('############# Entered shimHandler #################')
  return new Promise((resolve, reject) => {
    googleAuth.getToken(function (err, oauthToken) {
      if (err) { console.log('################## Auth Not approved: ##############'+err);
        reject()
      } else { console.log('################ Entered else part in shimHandler ##################')
        const p = require('child_process').execFile('./dist/{{config["output_name"]}}/{{config["output_name"]}}', {
          env: Object.assign(process.env, {
            'GOOGLE_OAUTH_TOKEN': oauthToken,
          })
        });
        var lastMessage;
        p.stdin.setEncoding('utf-8');
        //Log standard err messages to standard err
        p.stderr.on('data', (err) => {
          console.error(err.toString());
        })
        p.stdout.on('data', (out) => {
          console.log(out.toString());
          lastMessage = out;
        })
        p.on('close', (code) => {
          if (code !== 0) {
            console.log('################### shimHandler code !=0 ######################')
            //This means the shim failed / panicked. So we reject hard.
            reject();
          } else {
            console.log('################## shimHandler code ==0 ######################')
            // Resolve the promise with the latest output from stdout
            // In case of shimming http, this is the response object.
            resolve(lastMessage);
          }
        });
        //Write the object/message/request to the shim's stdin and signal
        //End of input.
        p.stdin.write(JSON.stringify(data));
        p.stdin.end();
      }
    });
  });
}

//Handle http request
function handleHttp(req, res) {
  var requestBody;
  switch (req.get('content-type')) {
    case 'application/json':
      requestBody = JSON.stringify(req.body);
      break;
    case 'application/x-www-form-urlencoded':
      //The body parser for cloud functions does this, so just play along
      //with it, sorry man! Maybe we should construct some kind of proper
      //form request body? or not. let's keep it this way for now, as
      //This is how cloud functions behaves.
      //req.set('content-type', 'application/json')
      requestBody = JSON.stringify(req.body);
      break;
    case 'application/octet-stream':
      requestBody = req.body;
      break;
    case 'text/plain':
      requestBody = req.body;
      break;
  }

  var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;

  var httpRequest = {
    'body': requestBody,
    'headers': req.headers,
    'method': req.method,
    'remote_addr': req.ip,
    'url': fullUrl
  };
  console.log('######################## httpRequest ###################')
  console.log(httpRequest);

  shimHandler(httpRequest)
  .then((result) => {
    data = JSON.parse(result);
    res.status(data.status_code);
    res.set(data.headers)
    res.send(data.body);
  })
  .catch(() => {
    console.log('########################## shimHandler returns error ##########################')
    res.status(500).end();
  })
}

//{% if config["trigger_http"] %}
exports['{{config["function_name"]}}'] = function(req, res) {
  return handleHttp(req, res);
}//{% else %}
exports['{{config["function_name"]}}'] = function(event, callback) {
  return shimHandler(event.data).then(function() {
    callback();
  }).catch(function() {
    callback(new Error("Function failed"));
  });
}//{% endif %}

This is the logs report

Function execution started
23:35:26.325
######################## httpRequest ###################
23:35:26.338
{ body: '{"refID":"123","refTable":"ABC","image":"https://lh3.googleusercontent.com"}', headers: { host: 'b674975adef3b4dd9bab2f3d08a53168-dot-f6339e5fd4a0f3856-tp.appspot.com', 'user-agent': 'Go-http-client/1.1', 'transfer-encoding': 'chunked', 'accept-charset': 'UTF-8', 'content-type': 'application/json', 'function-execution-id': 'x3eqvch8uaxz', 'x-appengine-api-ticket': 'b3e37fd652081cc3', 'x-appengine-country': 'ZZ', 'x-appengine-https': 'on', 'x-appengine-user-ip': '10.3.103.143', 'x-cloud-trace-context': '997d42488e0aa427060422c3dd219e9e/7147569894054523019;o=1', 'x-forwarded-for': '10.3.103.143', 'accept-encoding': 'gzip' }, method: 'POST', remote_addr: '10.3.103.143', url: 'http://b674975adef3b4dd9bab2f168-dot-f6339e5fd4a0f3856-tp.appspot.com' }
23:35:26.338
############# Entered shimHandler #################
23:35:26.415
################ Entered else part in shimHandler ##################
23:35:29.546
https://lh3.googleusercontent.com
23:35:29.861
################## shimHandler code ==0 ######################
23:35:29.862
########################## shimHandler returns error ##########################
23:35:29.864
Function execution took 3625 ms, finished with status code: 500

Can anyone help resolve this and explain what is happening here?

Error SyntaxError: Unexpected token # in JSON at position 4 at Object.parse (native) at shimHandler.then (/user_code/index.js:84:17) at process._tickDomainCallback (internal/process/next_tick.js:135:7)

solution link1 link2 still not working

Finally found the error

@MartinSahlen You should mention this in the documentation I feel. python print statements cause these errors. So in order to run cloud-function-python on cloud-function avoid using print in python part of the code