Example #1
0
def handler(ctx, data: io.BytesIO = None):
    try:
        ORDS_HOSTNAME = ctx.Config()['ORDS_HOSTNAME']
        APEX_WORKSPACE = ctx.Config()['APEX_WORKSPACE']
        API_USER = ctx.Config()['API_USER']
        API_PASSWORD = ctx.Config()['API_PASSWORD']
        body = json.loads(data.getvalue())
        res = requests.post('https://' + ORDS_HOSTNAME + '/ords/' +
                            APEX_WORKSPACE + '/oauth/token',
                            data={'grant_type': 'client_credentials'},
                            auth=HTTPBasicAuth(API_USER, API_PASSWORD))
        access_token = res.json()['access_token']
        res = requests.post(
            'https://' + ORDS_HOSTNAME + '/ords/' + APEX_WORKSPACE +
            '/event_table/',
            body,
            headers={'Authorization': 'Bearer ' + access_token})
        return response.Response(ctx,
                                 response_data=res.json(),
                                 headers={"Content-Type": "application/json"})
    except (Exception, ValueError) as ex:
        logging.getLogger().info('error parsing json payload: ' + str(ex))
        return response.Response(ctx, str(ex))

    logging.getLogger().info("Inside Python Hello World function")
Example #2
0
async def handler(ctx, data: io.BytesIO = None):
    logger.info("Launching function")

    token = None
    try:
        body = json.loads(data.getvalue())
        token = body.get("token")
    except (Exception, ValueError) as ex:
        logger.error(f"error; {str(ex)}")

    if token != auth_token:
        return response.Response(
            ctx, response_data=json.dumps(
                {"message": "Error"}),
            headers={"Content-Type": "application/json"}
        )

    learning_sites = load_learning_sites()

    async with aiohttp.ClientSession() as client:
        await asyncio.gather(*(fetch(client, site) for site in learning_sites))

    return response.Response(
        ctx, response_data=json.dumps(
            {"message": "Success"}),
        headers={"Content-Type": "application/json"}
    )
def handler(ctx, data: io.BytesIO = None):

    resp = None

    try:
        body = json.loads(data.getvalue())
        jsondata = body.get("data")

        print("event type          : " + body["eventType"], flush=True)
        print("Instance Id         : " + body["data"]["resourceId"],
              flush=True)
        print("Instance Name       : " + body["data"]["resourceName"],
              flush=True)
        print("Availability Domain : " + body["data"]["availabilityDomain"],
              flush=True)

        print(jsondata.get("resourceId"), flush=True)
        print(jsondata.get("resourceName"), flush=True)
        print(jsondata.get("availabilityDomain"), flush=True)

        print(json.dumps(body, indent=4), flush=True)

        instanceId = body["data"]["resourceId"]
        signer = oci.auth.signers.get_resource_principals_signer()

        resp = do(signer, instanceId)

        return response.Response(ctx,
                                 response_data=json.dumps(resp),
                                 headers={"Content-Type": "application/json"})
    except (Exception, ValueError) as e:
        print("Error " + str(e), flush=True)
Example #4
0
def handler(ctx, data: io.BytesIO = None):
    try:
        requestbody_str = data.getvalue().decode('UTF-8')
        body = json.loads(requestbody_str)
        bucketName = "Bucket-for-crop-health-project"
        objectName = "check_health_file_obj.csv"
        logging.getLogger().info(
            "------------------------------------------------------------------"
        )
        logging.getLogger().info(json.dumps(body))
        loc = body["loc"]
        mail = body["mail"]
        a = get_object(bucketName, objectName)
        b = io.StringIO(a.decode(encoding='UTF-8'))
        df1 = pandas.read_csv(b, index_col=0)
        df = pandas.DataFrame()
        df['mail id'] = [mail]
        df['location'] = [loc]
        df2 = df1.append(df)
        df2.reset_index(drop=True, inplace=True)
        wf = df2.to_csv()
    except Exception:
        error = """
                Input a JSON object in the format: '{"bucketName": "<bucket name>",
                "content": "<content>", "objectName": "<object name>"}'
                """
        raise Exception(error)
    resp = put_object(bucketName, objectName, wf)
    logging.getLogger().info(
        "------------------------------------------------------------------")
    logging.getLogger().info(json.dumps(resp))
    return response.Response(ctx,
                             response_data=json.dumps(resp),
                             headers={"Content-Type": "application/json"})
Example #5
0
def handler(ctx, data: io.BytesIO = None):
    resp = "No data"
    try:
        body = json.loads(data.getvalue())
        fld_id = body.get("fld_id")
        fld_str = body.get("fld_str")
    except (Exception) as ex:
        logging.getLogger().error('ERROR: Missing key in payload' + str(ex))
        raise

    try:
        provider = borneo.iam.SignatureProvider.create_with_resource_principal()
        compartment_id = provider.get_resource_principal_claim(
            borneo.ResourcePrincipalClaimKeys.COMPARTMENT_ID_CLAIM_KEY)
        tenant_id = provider.get_resource_principal_claim(
            borneo.ResourcePrincipalClaimKeys.TENANT_ID_CLAIM_KEY)
        config = borneo.NoSQLHandleConfig(
            'us-ashburn-1', provider).set_logger(None).set_default_compartment(compartment_id)
        handle = borneo.NoSQLHandle(config)
        request = borneo.PutRequest().set_table_name('user_eva')
        value = {'fld_id': fld_id, 'fld_str': fld_str}
        request.set_value(value)
        handle.put(request)
        resp = json.dumps(value)
    except (Exception, ValueError) as ex:
        logging.getLogger().error(str(ex))
        resp = str(ex)
    return response.Response(
        ctx, response_data=resp,
        headers={"Content-Type": "application/json"}
    )
Example #6
0
async def handle_request(handler_code, format_def, **kwargs):
    """
    Handles a function's request
    :param handler_code: customer's code
    :type handler_code: fdk.customer_code.Function
    :param format_def: function's format
    :type format_def: str
    :param kwargs: request-specific parameters
    :type kwargs: dict
    :return: function's response
    :rtype: fdk.response.Response
    """
    log.log("in handle_request")
    ctx, body = context.context_from_format(format_def, **kwargs)
    log.log("context provisioned")
    try:
        response_data = await with_deadline(ctx, handler_code, body)
        log.log("function result obtained")
        if isinstance(response_data, response.Response):
            return response_data

        headers = ctx.GetResponseHeaders()
        log.log("response headers obtained")
        return response.Response(ctx,
                                 response_data=response_data,
                                 headers=headers,
                                 status_code=200)

    except (Exception, TimeoutError) as ex:
        log.log("exception appeared: {0}".format(ex))
        traceback.print_exc(file=sys.stderr)
        return errors.DispatchException(ctx, 502, str(ex)).response()
Example #7
0
def handler(ctx, data: io.BytesIO=None):
    signer = oci.auth.signers.get_resource_principals_signer()
    resp = do(signer)
    return response.Response(
        ctx, response_data=json.dumps(resp),
        headers={"Content-Type": "application/json"}
    )
Example #8
0
def handler(ctx, data: io.BytesIO = None):
    ordsbaseurl = dbuser = dbpwdcypher = dbpwd = sql = ""
    try:
        cfg = ctx.Config()
        ordsbaseurl = cfg["ords-base-url"]
        dbschema = cfg["db-schema"]
        dbpwdcypher = cfg["db-pwd-cypher"]
        dbpwd = dbpwdcypher  # The decryption of the db password using OCI KMS would have to be done, however it is addressed here
    except Exception:
        print('Missing function parameters: ords-base-url, db-user and db-pwd',
              flush=True)
        raise
    try:
        body = json.loads(data.getvalue())
        sql = body["sql"]
    except Exception:
        print(
            'The data to pass to this function is a JSON object with the format: \'{"sql": "<SQL statement>"}\' ',
            flush=True)
        raise
    result = ords_run_sql(ordsbaseurl, dbschema, dbpwd, sql)

    return response.Response(ctx,
                             response_data=json.dumps(result),
                             headers={"Content-Type": "application/json"})
Example #9
0
def handler(ctx, data: io.BytesIO=None):
    # get 2 arguments from invoke: name and sessionid, for example {"name": "Greg", "sessionid":"S101"}
    try:
        body = json.loads(data.getvalue())
        name = body.get("name")
        sessionid = body.get("sessionid")
    except (Exception, ValueError) as ex:
        logging.error(str(ex))

    # create a PAR for bucket defined in UPLOAD_BUCKET
    signer = oci.auth.signers.get_resource_principals_signer()
    object_storage = oci.object_storage.ObjectStorageClient(config={}, signer=signer)
    time_expires = datetime.utcnow() + timedelta(minutes=5)
    par_details = CreatePreauthenticatedRequestDetails(name="par-"+name+"-"+sessionid, access_type='AnyObjectWrite', time_expires=time_expires )
    namespace = object_storage.get_namespace().data
    par = object_storage.create_preauthenticated_request(namespace, UPLOAD_BUCKET, par_details)
    par_url = OBJECT_STORAGE_URL + par.data.access_uri

    # prepare the HTML page to return to the user
    var_dict = { 'name':name, 'sessionid':sessionid, 'PAR_URL':par_url }
    html_file = open( 'fileupload.html' )
    templ_response = Template( html_file.read() )
    resp = templ_response.substitute(var_dict)

    # return the response in HTML
    return response.Response(
        ctx,
        response_data=resp,
        headers={"Content-Type": "text/html"}
    )
Example #10
0
def handler(ctx, data: io.BytesIO = None):
    try:
        payload_bytes = data.getvalue()
        if payload_bytes==b'':
            raise KeyError('No keys in payload')
        payload = json.loads(payload_bytes)
        sql_statement = payload["sql_statement"]
    except Exception as ex:
        print('ERROR: Missing key in payload', ex, flush=True)
        raise

    start_acquire = timer()
    with dbpool.acquire() as dbconnection:
        end_acquire = timer()
        print("INFO: DB connection acquired in {} sec".format(end_acquire - start_acquire), flush=True)
        start_cursor = timer()
        with dbconnection.cursor() as dbcursor:
            end_cursor = timer()
            print("INFO: DB cursor created in {} sec".format(end_cursor - start_cursor), flush=True)
            start_query = timer()
            result = dbcursor.execute(sql_statement)
            dbcursor.rowfactory = lambda *args: dict(zip([d[0] for d in dbcursor.description], args))
            result = dbcursor.fetchall()
            end_query = timer()
            print(result, flush=True)
            print("INFO: DB query executed in {} sec".format(end_query - start_query), flush=True)

    return response.Response(
        ctx,
        response_data=json.dumps(
            {"sql_statement": "{}".format(sql_statement), "result": "{}".format(result)}),
        headers={"Content-Type": "application/json"}
    )
Example #11
0
def handler(ctx, data: io.BytesIO=None):
    compartmentID = "ocid1.compartment.oc1..aaaaaaaa4gk5fmtbrfnkfrwwkoef5pmrvxu7dauh52hbisvnhx6rgas5jxja"
    namespace = "oci_computeagent"
    query = "CPUUtilization[1m]{resourceId = \"ocid1.instance.oc1.eu-frankfurt-1.antheljrqtij3macskkzfsvile75zoka7hmrga3opeuwcycogz5s62hfczva\"}.mean()"
    try:
        body = json.loads(data.getvalue())
        # query = body.get("query")
        name = body.get("name")
        metrics_obj = OCIGetMetrics(compartmentID, namespace, query)
        if sys.getsizeof(name) > 40:
           name = "Toni"
        databeta = metrics_obj.get_metrics().data

    except (Exception, ValueError) as ex:
        print(str(ex))

    return response.Response(
        ctx, response_data=json.dumps(
            {"availabilityDomain": "VrTN:EU-FRANKFURT-1-AD-3", 
             "cpu_mean": 6.094046517476844, 
             "faultDomain": "FAULT-DOMAIN-3", 
             "host": "Ubuntu-madhack-vrx", 
             "mem_mean": 3.931413040783038, 
             "net_in": 18619.02, 
             "net_out": 20041.54, 
             "region": "eu-frankfurt-1", 
             "shape": "VM.Standard2.4", 
             "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")}),
          #    {"message": "hola {0}".format(name)}),
        headers={"Content-Type": "application/json"}
    )
def handler(ctx, data: io.BytesIO = None):
    body = json.loads(data.getvalue())
    body = json.loads(data.getvalue())
    oci_audit_events_payload = body
    oci_audit_events_JSON = http_event_collector(
        token=os.environ["splunk_hec_token"],
        host=os.environ["source_host_name"],
        input_type="json",
        http_event_port=os.environ["splunk_hec_port"],
        http_event_server=os.environ["splunk_url"],
    )
    oci_audit_events_JSON.SSL_verify = False
    oci_audit_events_JSON.popNullFields = False
    oci_audit_events_JSON.index = "main"
    payload = {}
    payload.update({"index": os.environ["splunk_index_name"]})
    payload.update({"sourcetype": "_json"})
    payload.update({"source": os.environ["splunk_source_name"]})
    payload.update({"host": os.environ["source_host_name"]})
    payload.update({"event": oci_audit_events_payload})
    oci_audit_events_JSON.batchEvent(payload)
    oci_audit_events_JSON.flushBatch()
    return response.Response(
        ctx,
        response_data=json.dumps({"event": "success"}),
        headers={"Content-Type": "application/json"},
    )
def handler(ctx, data: io.BytesIO = None):
    body = json.loads(data.getvalue())
    signer = auth.signers.get_resource_principals_signer()
    streaming_endpoint = os.environ['streaming_endpoint']
    stream_ocid = os.environ['stream_ocid']
    body = json.loads(data.getvalue())
    offset = body['offset']
    num_records = body['num_records']
    oci_audit_events_payload = read_from_stream(signer, streaming_endpoint,
                                                stream_ocid, offset,
                                                num_records)
    oci_audit_events_JSON = http_event_collector(
        token=os.environ["splunk_hec_token"],
        host=os.environ["source_host_name"],
        input_type="json",
        http_event_port=os.environ["splunk_hec_port"],
        http_event_server=os.environ["splunk_url"],
    )
    oci_audit_events_JSON.SSL_verify = False
    oci_audit_events_JSON.popNullFields = False
    oci_audit_events_JSON.index = "main"
    for i in oci_audit_events_payload:
        payload = {}
        payload.update({"index": os.environ["splunk_index_name"]})
        payload.update({"sourcetype": "_json"})
        payload.update({"source": os.environ["splunk_source_name"]})
        payload.update({"host": os.environ["source_host_name"]})
        payload.update({"event": i})
        oci_audit_events_JSON.batchEvent(payload)
    oci_audit_events_JSON.flushBatch()
    return response.Response(
        ctx,
        response_data=json.dumps({"event": "success"}),
        headers={"Content-Type": "application/json"},
    )
def handler(ctx, data: io.BytesIO = None):
    signer = oci.auth.signers.get_resource_principals_signer()
    incomingBody = json.loads(data.getvalue())
    vcn_flowlog_data = read_from_objectStorage(signer, incomingBody)
    oci_audit_events_JSON = http_event_collector(
        token=os.environ["splunk_hec_token"],
        host=os.environ["source_host_name"],
        input_type="json",
        http_event_port=os.environ["splunk_hec_port"],
        http_event_server=os.environ["splunk_url"],
    )
    oci_audit_events_JSON.SSL_verify = False
    oci_audit_events_JSON.popNullFields = False
    oci_audit_events_JSON.index = "main"
    for i in vcn_flowlog_data:
        payload = {}
        payload.update({"index": os.environ["splunk_index_name"]})
        payload.update({"sourcetype": "_json"})
        payload.update({"source": os.environ["splunk_source_name"]})
        payload.update({"host": os.environ["source_host_name"]})
        payload.update({"event": i})
        oci_audit_events_JSON.batchEvent(payload)
    oci_audit_events_JSON.flushBatch()
    return response.Response(
        ctx,
        response_data=json.dumps({"event":"success"}),
        headers={"Content-Type": "application/json"},
    )
Example #15
0
def handler(ctx, data: io.BytesIO = None):
    try:
        alarm_msg = json.loads(data.getvalue())
        print("INFO: Alarm message: ")
        print(alarm_msg, flush=True)
    except (Exception, ValueError) as ex:
        print(str(ex), flush=True)

    if alarm_msg["type"] == "OK_TO_FIRING":
        if alarm_msg["alarmMetaData"][0]["dimensions"]:
            alarm_metric_dimension = alarm_msg["alarmMetaData"][0]["dimensions"][
                0]  #assuming the first dimension matches the boot vol to resize
            print("INFO: Boot Vol to resize: ",
                  alarm_metric_dimension["resourceId"],
                  flush=True)
            func_response = increase_bv_vpus(
                alarm_metric_dimension["resourceId"])
            print("INFO: ", func_response, flush=True)
        else:
            print('ERROR: There is no metric dimension in this alarm message',
                  flush=True)
            func_response = "There is no metric dimension in this alarm message"
    else:
        print('INFO: Nothing to do, alarm is not FIRING', flush=True)
        func_response = "Nothing to do, alarm is not FIRING"

    return response.Response(ctx,
                             response_data=func_response,
                             headers={"Content-Type": "application/json"})
Example #16
0
def handler(ctx, data: io.BytesIO = None):
    try:
        #no user input
        if len(data.getvalue()) == 0:
            input_data = "No user input data"
        else:
            #log user input
            logging.getLogger().info("Read data : %s", data.getvalue())
            body = json.loads(data.getvalue())
            input_data = body.get("input")

        url = "Your REST API Endpoint"
        # resp = get_data(url)
        resp = delete_data(url)

    except (Exception, ValueError) as ex:
        print(str(ex))

    return response.Response(ctx,
                             response_data=json.dumps({
                                 "Input data":
                                 input_data,
                                 "ctx.AppID":
                                 ctx.AppID(),
                                 "ctx.FnID":
                                 ctx.FnID(),
                                 "ctx.CallID":
                                 ctx.CallID(),
                                 "ctx.Config":
                                 dict(ctx.Config()),
                                 "response code":
                                 resp.status_code
                             }),
                             headers={"Content-Type": "application/json"})
Example #17
0
def handler(ctx, data: io.BytesIO = None):
    signer = oci.auth.signers.get_resource_principals_signer()
    bucket_name = os.environ.get("OCI_BUCKETNAME")
    resp = do(signer, bucket_name)
    return response.Response(ctx,
                             response_data=json.dumps(resp),
                             headers={"Content-Type": "application/json"})
def handler(ctx, data: io.BytesIO = None):

    key_ocid = cryptographic_endpoint = cipher = decryptedtext = ""
    try:
        # Retrieve key OCID and cryptographic endpoint
        cfg = ctx.Config()
        key_ocid = cfg["key_ocid"]
        cryptographic_endpoint = cfg["cryptographic_endpoint"]
    except Exception as ex:
        print('ERROR: Missing configuration key', ex, flush=True)
        raise
    try:
        # Retrieve Cipher text to decrypt
        payload_bytes = data.getvalue()
        if payload_bytes == b'':
            raise KeyError('No keys in payload')
        payload = json.loads(payload_bytes)
        cipher = payload["cipher"]
    except Exception as ex:
        print('ERROR: Missing key in payload', ex, flush=True)
        raise

    decryptedtext = decrypt(key_ocid, cryptographic_endpoint, cipher)

    return response.Response(ctx,
                             response_data=json.dumps(
                                 {"decrypted_text": decryptedtext}),
                             headers={"Content-Type": "application/json"})
Example #19
0
def handler(ctx, data: io.BytesIO = None):

    resp = None

    try:
        signer = oci.auth.signers.get_resource_principals_signer()
        searches = oci.resource_search.ResourceSearchClient(config={},
                                                            signer=signer)
        search_details = oci.resource_search.models.StructuredSearchDetails(
            type="Structured",
            query=
            "query instance resources where (definedTags.namespace = 'autoschedule' && definedTags.key = 'AUTOSCHEDULE'  && definedTags.value = 'TRUE')",
        )
        search_matches = searches.search_resources(
            search_details=search_details)
        computes = search_matches.data.items
        print("Compute OCID: {0}".format(computes), flush=True)
        for compute in computes:
            print("Compute OCID: {0}".format(compute.identifier), flush=True)
            instanceId = compute.identifier
            resp = perform_action(signer, instanceId, "STOP")

        return response.Response(
            ctx,
            response_data=json.dumps(resp),
            headers={"Content-Type": "application/json"},
        )
    except (Exception, ValueError) as e:
        print("Error " + str(e), flush=True)
Example #20
0
def handler(ctx, data: io.BytesIO = None):
    iot_key = "mykey"
    iot_data = "mydata"
    stream_ocid = os.getenv('OCIFN_STREAM_OCID')
    stream_endpoint = os.getenv('OCIFN_STREAM_ENDPOINT')

    fnErrors = "No Error"
    try:
        body = json.loads(data.getvalue())
        iot_key = str(body.get("iot_key"))
        iot_data = str(body.get("iot_data"))
        signer = oci.auth.signers.get_resource_principals_signer()
        stream_client = oci.streaming.StreamClient({},
                                                   str("https://" +
                                                       stream_endpoint),
                                                   signer=signer)
        msg_entry = oci.streaming.models.PutMessagesDetailsEntry()
        msg_entry.key = b64encode(bytes(str(iot_key), 'utf-8')).decode('utf-8')
        msg_entry.value = b64encode(bytes(str(iot_data),
                                          'utf-8')).decode('utf-8')
        msgs = oci.streaming.models.PutMessagesDetails()
        msgs.messages = [msg_entry]
        stream_client.put_messages(stream_ocid, msgs)
    except (Exception, ValueError) as ex:
        fnErrors = str(ex)

    return response.Response(
        ctx,
        response_data=json.dumps({
            "message":
            "Message sent to the OCI Stream (iot_key={}, iot_data={}, fnErrors={})"
            .format(iot_key, iot_data, fnErrors)
        }),
        headers={"Content-Type": "application/json"})
Example #21
0
def handler(ctx, data: io.BytesIO = None):
    global app_name, func_name, apm_domain_url, apm_service_name, apm_binary_annotations
    app_name = ctx.AppName()
    func_name = ctx.FnName()
    logging.getLogger().info("Inside app: " + app_name + " | function: " +
                             func_name + " | method: handler")
    tracing_context = ctx.TracingContext()
    apm_domain_url = tracing_context.trace_collector_url()
    apm_service_name = tracing_context.service_name()
    logging.getLogger().info("Inside app: " + app_name + " | function: " +
                             func_name +
                             " | method: handler | apm_service_name: " +
                             apm_service_name)
    apm_binary_annotations = tracing_context.annotations()

    with zipkin_span(service_name=apm_service_name,
                     span_name="handler method (custom child span)",
                     transport_handler=apm_transport_handler,
                     zipkin_attrs=tracing_context.zipkin_attrs(),
                     encoding=Encoding.V2_JSON,
                     binary_annotations=apm_binary_annotations):
        # this is the actual unit of work performed by the function
        message = say_hello(data)
        logging.getLogger().info("Inside app: " + app_name + " | function: " +
                                 func_name +
                                 " | method: handler | returned message: " +
                                 message)
        return response.Response(ctx,
                                 response_data=json.dumps({"message":
                                                           message}),
                                 headers={"Content-Type": "application/json"})
def handler(ctx, data: io.BytesIO=None):
    signer = auth.signers.get_resource_principals_signer()
    compartment_name = ""
    instance_name = ""
    action = ""

    try:
        body = json.loads(data.getvalue())
        compartment_name = str(body["compartment"])
        instance_name = str(body["instance"])
        action = str(body["action"]).upper()


    except Exception as ex:
        print(str(ex), file=sys.stderr)
        usage = (" usage: echo -n '{\"compartment\":"
                "\"<compartment name>\", \"instance\": \"<instance name>\","
                "\"action\": \"<action type>\"}' | fn invoke --app "
                "<app name> <function name> ")
        raise Exception(usage)

    resp = do(signer, compartment_name, instance_name, action)
    return response.Response(
        ctx, response_data=json.dumps(resp),
        headers={"Content-Type": "application/json"}
    )
def handler(ctx, data: io.BytesIO = None):
    cust_id = "All"
    try:
        body = json.loads(data.getvalue())
        cust_id = str(body.get("cust_id"))
    except (Exception, ValueError) as ex:
        print(str(ex))

    if ctx.Method() == "GET":
        resp = select_customer(cust_id)

    if ctx.Method() == "DELETE":
        resp = delete_customer(cust_id)

    if ctx.Method() == "PUT":
        try:
            body = json.loads(data.getvalue())
            cust_name = str(body.get("cust_name"))
        except (Exception, ValueError) as ex:
            print(str(ex))
        resp = update_customer(cust_id, cust_name)

    if ctx.Method() == "POST":
        try:
            body = json.loads(data.getvalue())
            cust_name = str(body.get("cust_name"))
        except (Exception, ValueError) as ex:
            print(str(ex))
        resp = insert_customer(cust_name)

    return response.Response(ctx,
                             response_data=json.dumps({"message": resp}),
                             headers={"Content-Type": "application/json"})
Example #24
0
def handler(ctx, data: io.BytesIO=None):
    try:
        body = json.loads(data.getvalue())
        instance_ocid = body.get("instance_ocid")
        command = body.get("command")
    except (Exception, ValueError) as ex:
        print(str(ex), flush=True)
        print("Two arguments need to be passed to the function, instance_ocid and the command")
        raise

    signer = oci.auth.signers.get_resource_principals_signer()
    compute_client = oci.core.ComputeClient(config={}, signer=signer)

    if command == 'status':
        resp = instance_status(compute_client, instance_ocid)
    elif command == 'start':
        resp = instance_start(compute_client, instance_ocid)
    elif command == 'stop':
        resp = instance_stop(compute_client, instance_ocid)
    else:
        print("command not supported")
        raise

    return response.Response(
        ctx, 
        response_data=json.dumps({"status": "{0}".format(resp)}),
        headers={"Content-Type": "application/json"}
    )
Example #25
0
def handler(ctx, data: io.BytesIO = None):
    event_type = "mockEventType"
    body = ""

    try:
        body = json.loads(data.getvalue())
        event_type = body["eventType"]
    except (Exception, ValueError) as ex:
        logging.getLogger().info('error parsing json payload: ' + str(ex))

    ts = str(datetime.utcnow())
    signer = oci.auth.signers.get_resource_principals_signer()
    resp = json.dumps(
        {
            "UTC": "{0}".format(ts),
            "Event Type": "{0}".format(event_type),
            "body": "{0}".format(body),
            "URL context": ctx.RequestURL(),
            "Header context": ctx.Headers()
        },
        indent=4)
    save_log(signer, resp, event_type)
    return response.Response(ctx,
                             response_data=resp,
                             headers={"Content-Type": "application/json"})
def handler(ctx, data: io.BytesIO = None):

    signer = oci.auth.signers.get_resource_principals_signer()

    try:
        cfg = ctx.Config()
        cfg_namespace = cfg["OCI_NAMESPACE"]
        cfg_bucketname = cfg["OCI_BUCKETNAME"]
    except Exception as ex:
        print("Error: Configuration key has not been set.", ex, flush=True)
        raise

    try:
        info = json.load(data)
        firstname = info.get("firstname")
        lastname = info.get("lastname")
        workemail = info.get("workemail")
        hiredate = info.get("hiredate")
        effectivestartdate = info.get("effectivestartdate")
        personid = info.get("personid")

    except (Exception, ValueError) as ex:
        return str(ex)

    filename = personid + "_data.csv"
    personinfo = personid + ", " + firstname + ", " + lastname + ", " + workemail + ", " + hiredate + ", " + effectivestartdate

    return_output = put_object(signer,
                               cfg_bucketname,
                               filename,
                               personinfo,
                               cfg_namespace=cfg_namespace)
    return response.Response(ctx,
                             response_data=json.dumps(return_output),
                             headers={"Content-Type": "application/json"})
def handler(ctx, data: io.BytesIO=None):
    logging.getLogger().info("function start")

    secret_ocid = secret_type = resp = ""
    try:
        cfg = dict(ctx.Config())
        secret_ocid = cfg["secret_ocid"]
        logging.getLogger().info("Secret ocid = " + secret_ocid)
        secret_type = cfg["secret_type"]
        logging.getLogger().info("Secret type = " + secret_type)
    except Exception as e:
        print('ERROR: Missing configuration keys, secret ocid and secret_type', e, flush=True)
        raise

    if secret_type == "text":
        resp = get_text_secret(secret_ocid)
    elif secret_type == "binary":
        resp = get_binary_secret_into_file(secret_ocid, "/tmp/secret")
    else:
        raise ValueError('the value of the configuration parameter "secret_type" has to be either "text" or "binary"')

    logging.getLogger().info("function end")
    return response.Response(
        ctx, 
        response_data=resp,
        headers={"Content-Type": "application/json"}
    )
Example #28
0
def handler(ctx, data: io.BytesIO = None):
    logging.getLogger().info("Costi-model: vers. 1.2")

    try:
        input = json.loads(data.getvalue())['input']

        # logga l'input, per poter controllare
        input_json = json.dumps(input)
        logging.getLogger().info("Costi-model: Invoked with input %s",
                                 input_json)

        # check num columns
        num_cols = len(input[0])

        # attende 12 colonne per vettore
        if num_cols != NUM_COLS:
            logging.getLogger().error("Costi-model: num_cols in input not OK.")
        else:
            prediction = scorefn.predict(model, input)

            logging.getLogger().info("Costi-model: prediction %s",
                                     json.dumps(prediction))

    except (Exception, ValueError) as ex:
        logging.getLogger().error("%s", str(ex))

    return response.Response(ctx,
                             response_data=json.dumps(prediction),
                             headers={"Content-Type": "application/json"})
Example #29
0
def handler(ctx, data: io.BytesIO = None):
    signer = oci.auth.signers.get_resource_principals_signer()
    bucket_name = PAR_name = ""
    lifetime = 0
    try:
        cfg = ctx.Config()
        bucket_name = cfg["bucket-name"]
        lifetime = int(cfg["lifetime"])
    except Exception as e:
        print(
            'Missing function parameters: bucket-name and lifetime (in minutes)',
            flush=True)
        raise
    try:
        body = json.loads(data.getvalue())
        PAR_name = body["PAR name"]
    except Exception as e:
        print(
            'Input a JSON object with the format: \'{"PAR name": "<PAR name>"}\' ',
            flush=True)
        raise
    par_url = create_PAR(signer, bucket_name, PAR_name, lifetime)
    return response.Response(ctx,
                             response_data=json.dumps({"PAR URL": par_url}),
                             headers={"Content-Type": "application/json"})
Example #30
0
 def response(self):
     resp_headers = {
         constants.CONTENT_TYPE: "application/json; charset=utf-8",
     }
     return response.Response(self.ctx,
                              response_data=self.message,
                              headers=resp_headers,
                              status_code=self.status)