From ed385606dc59749171f1c344d03e06debee7e5ad Mon Sep 17 00:00:00 2001 From: MichalKalke Date: Mon, 22 Apr 2024 13:21:24 +0200 Subject: [PATCH] Delete examples dir --- .../Dockerfile | 13 -- .../custom-serverless-runtime-image/README.md | 28 --- .../kubeless/ce.py | 95 --------- .../kubeless/kubeless.py | 193 ------------------ .../kubeless/requirements.txt | 11 - .../kubeless/tracing.py | 92 --------- examples/incluster_eventing/Makefile | 2 - examples/incluster_eventing/README.md | 51 ----- .../k8s-resources/emitter-fn.yaml | 32 --- .../k8s-resources/receiver-fn.yaml | 35 ---- .../src/emitter-fn/config.yaml | 18 -- .../src/emitter-fn/handler.js | 43 ---- .../src/emitter-fn/package.json | 7 - .../src/receiver-fn/config.yaml | 22 -- .../src/receiver-fn/handler.js | 11 - .../src/receiver-fn/package.json | 5 - examples/python-text2img/Makefile | 3 - examples/python-text2img/README.md | 29 --- examples/python-text2img/config.yaml | 26 --- examples/python-text2img/handler.py | 17 -- examples/python-text2img/requirements.txt | 1 - .../python-text2img/resources/function.yaml | 46 ----- .../resources/kustomization.yaml | 3 - .../resources/secrets/deepai-template.env | 2 - .../resources/secrets/kustomization.yaml | 6 - 25 files changed, 791 deletions(-) delete mode 100644 examples/custom-serverless-runtime-image/Dockerfile delete mode 100644 examples/custom-serverless-runtime-image/README.md delete mode 100644 examples/custom-serverless-runtime-image/kubeless/ce.py delete mode 100644 examples/custom-serverless-runtime-image/kubeless/kubeless.py delete mode 100644 examples/custom-serverless-runtime-image/kubeless/requirements.txt delete mode 100644 examples/custom-serverless-runtime-image/kubeless/tracing.py delete mode 100644 examples/incluster_eventing/Makefile delete mode 100644 examples/incluster_eventing/README.md delete mode 100644 examples/incluster_eventing/k8s-resources/emitter-fn.yaml delete mode 100644 examples/incluster_eventing/k8s-resources/receiver-fn.yaml delete mode 100644 examples/incluster_eventing/src/emitter-fn/config.yaml delete mode 100644 examples/incluster_eventing/src/emitter-fn/handler.js delete mode 100644 examples/incluster_eventing/src/emitter-fn/package.json delete mode 100644 examples/incluster_eventing/src/receiver-fn/config.yaml delete mode 100644 examples/incluster_eventing/src/receiver-fn/handler.js delete mode 100644 examples/incluster_eventing/src/receiver-fn/package.json delete mode 100644 examples/python-text2img/Makefile delete mode 100644 examples/python-text2img/README.md delete mode 100644 examples/python-text2img/config.yaml delete mode 100644 examples/python-text2img/handler.py delete mode 100644 examples/python-text2img/requirements.txt delete mode 100644 examples/python-text2img/resources/function.yaml delete mode 100644 examples/python-text2img/resources/kustomization.yaml delete mode 100644 examples/python-text2img/resources/secrets/deepai-template.env delete mode 100644 examples/python-text2img/resources/secrets/kustomization.yaml diff --git a/examples/custom-serverless-runtime-image/Dockerfile b/examples/custom-serverless-runtime-image/Dockerfile deleted file mode 100644 index 8f9ea43a..00000000 --- a/examples/custom-serverless-runtime-image/Dockerfile +++ /dev/null @@ -1,13 +0,0 @@ -FROM python:3.10-bullseye - -COPY kubeless/requirements.txt /kubeless/requirements.txt -RUN pip install -r /kubeless/requirements.txt -RUN pip install protobuf==3.20.* --force-reinstall - -COPY kubeless/ / - -WORKDIR / - -USER 1000 - -CMD ["python", "/kubeless.py"] diff --git a/examples/custom-serverless-runtime-image/README.md b/examples/custom-serverless-runtime-image/README.md deleted file mode 100644 index 7c984ce4..00000000 --- a/examples/custom-serverless-runtime-image/README.md +++ /dev/null @@ -1,28 +0,0 @@ -# Custom Serverless Runtime Image - -## Overview - -This example shows how to create own custom runtime for a Serverless Function based on the Python runtime and the `debian:bullseye-slim` base image to provide support for glibc. - -## Prerequisites - -- Docker as a build tool - -## Build an Example Runtime - -1. Export the following environments: - - ```bash - export IMAGE_NAME= - export IMAGE_TAG= - ``` - -2. Build and push the image: - - ```bash - docker build -t "${IMAGE_NAME}/${IMAGE_TAG}" . - docker push "${IMAGE_NAME}/${IMAGE_TAG}" - ``` - -> [!NOTE] -> You can use it to define your Functions in Kyma. To learn more, read [how to override runtime image](https://kyma-project.io/#/serverless-manager/user/resources/06-20-serverless-cr?id=custom-resource-parameters). diff --git a/examples/custom-serverless-runtime-image/kubeless/ce.py b/examples/custom-serverless-runtime-image/kubeless/ce.py deleted file mode 100644 index 7ebefebd..00000000 --- a/examples/custom-serverless-runtime-image/kubeless/ce.py +++ /dev/null @@ -1,95 +0,0 @@ -import requests -import bottle -import io -import os -import json - -publisher_proxy_address = os.getenv('PUBLISHER_PROXY_ADDRESS') - -class PicklableBottleRequest(bottle.BaseRequest): - '''Bottle request that can be pickled (serialized). - - `bottle.BaseRequest` is not picklable and therefore cannot be passed directly to a - python multiprocessing `Process` when using the forkserver or spawn multiprocessing - contexts. So, we selectively delete components that are not picklable. - ''' - - def __init__(self, data, *args, **kwargs): - super().__init__(*args, **kwargs) - # Bottle uses either `io.BytesIO` or `tempfile.TemporaryFile` to store the - # request body depending on whether the length of the body is less than - # `MEMFILE_MAX` or not, but `tempfile.TemporaryFile` is not picklable. - # So, we override it to always store the body as `io.BytesIO`. - self.environ['bottle.request.body'] = io.BytesIO(data) - - def __getstate__(self): - env = self.environ.copy() - - # File-like objects are not picklable. - del env['wsgi.errors'] - del env['wsgi.input'] - - # bottle.ConfigDict is not picklable because it contains a lambda function. - del env['bottle.app'] - del env['bottle.route'] - del env['route.handle'] - - return env - - def __setstate__(self, env): - setattr(self, 'environ', env) - - -class Event: - ceHeaders = dict() - tracer = None - - def __init__(self, req, tracer): - data = req.body.read() - picklable_req = PicklableBottleRequest(data, req.environ.copy()) - if req.get_header('content-type') == 'application/json': - data = req.json - - self.req = req - self.tracer = tracer - self.ceHeaders = { - 'data': data, - 'ce-type': req.get_header('ce-type'), - 'ce-source': req.get_header('ce-source'), - 'ce-eventtypeversion': req.get_header('ce-eventtypeversion'), - 'ce-specversion': req.get_header('ce-specversion'), - 'ce-id': req.get_header('ce-id'), - 'ce-time': req.get_header('ce-time'), - 'extensions': {'request': picklable_req} - } - - def __getitem__(self, item): - return self.ceHeaders[item] - - def __setitem__(self, name, value): - self.ceHeaders[name] = value - - def publishCloudEvent(self, data): - return requests.post( - publisher_proxy_address, - data = json.dumps(data), - headers = {"Content-Type": "application/cloudevents+json"} - ) - - def resolveDataType(self, event_data): - if type(event_data) is dict: - return 'application/json' - elif type(event_data) is str: - return 'text/plain' - - def buildResponseCloudEvent(self, event_id, event_type, event_data): - return { - 'type': event_type, - 'source': self.ceHeaders['ce-source'], - 'eventtypeversion': self.ceHeaders['ce-eventtypeversion'], - 'specversion': self.ceHeaders['ce-specversion'], - 'id': event_id, - 'data': event_data, - 'datacontenttype': self.resolveDataType(event_data) - } - diff --git a/examples/custom-serverless-runtime-image/kubeless/kubeless.py b/examples/custom-serverless-runtime-image/kubeless/kubeless.py deleted file mode 100644 index fd3cbab5..00000000 --- a/examples/custom-serverless-runtime-image/kubeless/kubeless.py +++ /dev/null @@ -1,193 +0,0 @@ -#!/usr/bin/env python - -import importlib -import os -import queue -import threading - -import bottle -import prometheus_client as prom -import sys - -import tracing -from ce import Event -from tracing import set_req_context - - -def create_service_name(pod_name: str, service_namespace: str) -> str: - # remove generated pods suffix ( two last sections ) - deployment_name = '-'.join(pod_name.split('-')[0:pod_name.count('-') - 1]) - return '.'.join([deployment_name, service_namespace]) - - -# The reason this file has an underscore prefix in its name is to avoid a -# name collision with the user-defined module. -module_name = os.getenv('MOD_NAME') -if module_name is None: - print('MOD_NAME have to be provided', flush=True) - exit(1) -current_mod = os.path.basename(__file__).split('.')[0] -if module_name == current_mod: - print('Module cannot be named {} as current module'.format(current_mod), flush=True) - exit(2) - -sys.path.append('/kubeless') - -mod = importlib.import_module(module_name) -func_name = os.getenv('FUNC_HANDLER') -if func_name is None: - print('FUNC_HANDLER have to be provided', flush=True) - exit(3) - -func = getattr(mod, os.getenv('FUNC_HANDLER')) - -func_port = os.getenv('FUNC_PORT', 8080) -timeout = float(os.getenv('FUNC_TIMEOUT', 180)) -memfile_max = int(os.getenv('FUNC_MEMFILE_MAX', 100 * 1024 * 1024)) -bottle.BaseRequest.MEMFILE_MAX = memfile_max - -app = application = bottle.app() - -function_context = { - 'function-name': func.__name__, - 'timeout': timeout, - 'runtime': os.getenv('FUNC_RUNTIME'), - 'memory-limit': os.getenv('FUNC_MEMORY_LIMIT'), -} - -tracecollector_endpoint = os.getenv('TRACE_COLLECTOR_ENDPOINT') -pod_name = os.getenv('HOSTNAME') -service_namespace = os.getenv('SERVICE_NAMESPACE') -service_name = create_service_name(pod_name, service_namespace) - -tracer_provider = None -# To not create several tracer providers, when the server start forking. -if __name__ == "__main__": - tracer_provider = tracing.ServerlessTracerProvider(tracecollector_endpoint, service_name) - - -def func_with_context(e, function_context): - ex = e.ceHeaders["extensions"] - with set_req_context(ex["request"]): - return func(e, function_context) - - -@app.get('/healthz') -def healthz(): - return 'OK' - - -@app.get('/metrics') -def metrics(): - bottle.response.content_type = prom.CONTENT_TYPE_LATEST - return prom.generate_latest(prom.REGISTRY) - - -@app.error(500) -def exception_handler(): - return 'Internal server error' - - -@app.route('/<:re:.*>', method=['GET', 'POST', 'PATCH', 'DELETE']) -def handler(): - req = bottle.request - tracer = tracer_provider.get_tracer(req) - event = Event(req, tracer) - - method = req.method - func_calls.labels(method).inc() - with func_errors.labels(method).count_exceptions(): - with func_hist.labels(method).time(): - que = queue.Queue() - t = threading.Thread(target=lambda q, e: q.put(func_with_context(e, function_context)), args=(que, event)) - t.start() - try: - res = que.get(block=True, timeout=timeout) - if hasattr(res, 'headers') and res.headers["content-type"]: - bottle.response.content_type = res.headers["content-type"] - except queue.Empty: - return bottle.HTTPError(408, "Timeout while processing the function") - else: - t.join() - return res - - -def preload(): - """This is a no-op function used to start the forkserver.""" - pass - - -if __name__ == '__main__': - import logging - import multiprocessing as mp - import requestlogger - - mp_context = os.getenv('MP_CONTEXT', 'forkserver') - - if mp_context == "fork": - raise ValueError( - '"fork" multiprocessing context is not supported because cherrypy is a ' - 'multithreaded server and safely forking a multithreaded process is ' - 'problematic' - ) - if mp_context not in ["forkserver", "spawn"]: - raise ValueError( - f'"{mp_context}" is an invalid multiprocessing context. Possible values ' - 'are "forkserver" and "spawn"' - ) - - try: - ctx = mp.get_context(mp_context) - - if ctx.get_start_method() == 'forkserver': - # Preload the current module and consequently also the user-defined module - # so that all the child processes forked from the forkserver in response to - # a request immediately have access to the global data in the user-defined - # module without having to load it for every request. - ctx.set_forkserver_preload([current_mod]) - - # Start the forkserver before we start accepting requests. - d = ctx.Process(target=preload) - d.start() - d.join() - - except ValueError: - # Default to 'spawn' if 'forkserver' is unavailable. - ctx = mp.get_context('spawn') - logging.warn( - f'"{mp_context}" multiprocessing context is unavailable. Using "spawn"' - ) - - func_hist = prom.Histogram( - 'function_duration_seconds', 'Duration of user function in seconds', ['method'] - ) - func_calls = prom.Counter( - 'function_calls_total', 'Number of calls to user function', ['method'] - ) - func_errors = prom.Counter( - 'function_failures_total', 'Number of exceptions in user function', ['method'] - ) - - # added by Kyma team - if os.getenv('KYMA_INTERNAL_LOGGER_ENABLED'): - # default that has been used so far - loggedapp = requestlogger.WSGILogger( - app, - [logging.StreamHandler(stream=sys.stdout)], - requestlogger.ApacheFormatter(), - ) - else: - loggedapp = app - # end of modified section - - bottle.run( - loggedapp, - server='cherrypy', - host='0.0.0.0', - port=func_port, - # Set this flag to True to auto-reload the server after any source files change - reloader=os.getenv('CHERRYPY_RELOADED', False), - # Number of requests that can be handled in parallel (default = 50). - numthreads=int(os.getenv('CHERRYPY_NUMTHREADS', 50)), - quiet='KYMA_BOTTLE_QUIET_OPTION_DISABLED' not in os.environ, - ) \ No newline at end of file diff --git a/examples/custom-serverless-runtime-image/kubeless/requirements.txt b/examples/custom-serverless-runtime-image/kubeless/requirements.txt deleted file mode 100644 index dbb5d6b4..00000000 --- a/examples/custom-serverless-runtime-image/kubeless/requirements.txt +++ /dev/null @@ -1,11 +0,0 @@ -setuptools==69.1.1 -requests -bottle==0.12.21 -cherrypy==8.9.1 -wsgi-request-logger==0.4.6 -prometheus_client==0.8.0 -opentelemetry-api==1.9.1 -opentelemetry-sdk==1.9.1 -opentelemetry-exporter-otlp-proto-http==1.9.1 -opentelemetry-propagator-b3==1.9.1 -opentelemetry-instrumentation-requests==0.28b1 diff --git a/examples/custom-serverless-runtime-image/kubeless/tracing.py b/examples/custom-serverless-runtime-image/kubeless/tracing.py deleted file mode 100644 index 5e713cdb..00000000 --- a/examples/custom-serverless-runtime-image/kubeless/tracing.py +++ /dev/null @@ -1,92 +0,0 @@ -import logging -from contextlib import contextmanager -from typing import Iterator - -import requests -from opentelemetry import trace -from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter -from opentelemetry.instrumentation.requests import RequestsInstrumentor -from opentelemetry.propagate import extract -from opentelemetry.propagate import set_global_textmap -from opentelemetry.propagators.b3 import B3MultiFormat -from opentelemetry.sdk.resources import SERVICE_NAME, Resource -from opentelemetry.sdk.trace import TracerProvider, _Span -from opentelemetry.sdk.trace.export import BatchSpanProcessor -from opentelemetry.trace import context_api -from opentelemetry.trace.propagation import _SPAN_KEY - -_TRACING_SAMPLE_HEADER = "x-b3-sampled" - - -class ServerlessTracerProvider: - def __init__(self, tracecollector_endpoint: str, service_name: str): - self.noop_tracer = trace.NoOpTracer() - if _is_tracecollector_available(tracecollector_endpoint): - self.tracer = _get_tracer(tracecollector_endpoint, service_name) - else: - logging.info("tracecollector is not available") - self.tracer = trace.NoOpTracer() - - def get_tracer(self, req): - val = req.get_header(_TRACING_SAMPLE_HEADER) - if val is not None and val == "1": - return self.tracer - - return self.noop_tracer - - -def _get_tracer(tracecollector_endpoint: str, service_name: str) -> trace.Tracer: - set_global_textmap(B3MultiFormat()) - RequestsInstrumentor().instrument() - - trace.set_tracer_provider( - TracerProvider( - resource=Resource.create({SERVICE_NAME: service_name}) - ) - ) - - otlp_exporter = OTLPSpanExporter( - endpoint=tracecollector_endpoint, - ) - - span_processor = BatchSpanProcessor(otlp_exporter) - - trace.get_tracer_provider().add_span_processor(span_processor) - - return trace.get_tracer(__name__) - - -def _is_tracecollector_available(tracecollectorEndpoint) -> bool: - try: - res = requests.get(tracecollectorEndpoint, timeout=2) - # 405 is the right status code for the GET method if jaeger service exists - # because the only allowed method is POST and usage of other methods are not allowe - # https://github.com/jaegertracing/jaeger/blob/7872d1b07439c3f2d316065b1fd53e885b26a66f/cmd/collector/app/handler/http_handler.go#L60 - if res.status_code == 405: - return True - except: - pass - - return False - - -@contextmanager # type: ignore -def set_req_context(req) -> Iterator[trace.Span]: - '''Propagates incoming span from the request to the current context - - This method allows to set up a context in any thread based on the incoming request. - By design, span context can't be moved between threads and because we run every function - in the separated thread we have to propagate the context manually. - ''' - span = _Span( - "request-span", - trace.get_current_span( - extract(req.headers) - ).get_span_context() - ) - - token = context_api.attach(context_api.set_value(_SPAN_KEY, span)) - try: - yield span - finally: - context_api.detach(token) diff --git a/examples/incluster_eventing/Makefile b/examples/incluster_eventing/Makefile deleted file mode 100644 index 164db075..00000000 --- a/examples/incluster_eventing/Makefile +++ /dev/null @@ -1,2 +0,0 @@ -deploy: - kubectl apply -f ./k8s-resources \ No newline at end of file diff --git a/examples/incluster_eventing/README.md b/examples/incluster_eventing/README.md deleted file mode 100644 index e0a89367..00000000 --- a/examples/incluster_eventing/README.md +++ /dev/null @@ -1,51 +0,0 @@ -# Asynchronous Communication Between Functions - -## Overview - -This example provides a simple scenario of asynchronous communication between two Functions, where: - -- The first Function accepts the incoming traffic using HTTP, sanitizes the payload, and publishes the content as an in-cluster event by the [Kyma Eventing module](https://kyma-project.io/docs/kyma/latest/01-overview/eventing/). -- The second Function is a message receiver. It subscribes to the given event type and stores the payload. - -This example also provides a template for a git project with Kyma Functions. Please refer to the Deploy section below. - -## Prerequisites - -- [Kyma CLI](https://github.com/kyma-project/cli) -- Kyma installed locally or on a cluster - -## Deploy - -### Deploy Using Kyma CLI - -You can deploy each Function separately using Kyma CLI by running `kyma apply function` in each of the Function's source folders. - -You can find all installation steps in the [Set Asynchronous Communication Between Functions](https://kyma-project.io/#/serverless-manager/user/tutorials/01-90-set-asynchronous-connection) tutorial. - -### Deploy Using kubectl - -Deploy to Kyma runtime manually using `kubectl apply` or `make deploy` target. - -### Auto-Deploy Code Changes - -Changes pushed to the `handler.js` files should be automatically pulled by Kyma Serverless as both Functions are of a Git type and reference this Git repository as the source. - -### Test the Application - -Send an HTTP request to the emitter Function. - - ```bash - curl -H "Content-Type: application/cloudevents+json" -X POST https://incoming.{your cluster domain} -d '{"foo":"bar"}' - Event sent% - ``` - -Fetch the logs of the receiver Function to observe the incoming message. - - ```bash - > nodejs16-runtime@0.1.0 start - > node server.js - - user code loaded in 0sec 0.649274ms - storing data... - {"foo":"bar"} - ``` diff --git a/examples/incluster_eventing/k8s-resources/emitter-fn.yaml b/examples/incluster_eventing/k8s-resources/emitter-fn.yaml deleted file mode 100644 index 203d0a90..00000000 --- a/examples/incluster_eventing/k8s-resources/emitter-fn.yaml +++ /dev/null @@ -1,32 +0,0 @@ -apiVersion: serverless.kyma-project.io/v1alpha2 -kind: Function -metadata: - labels: - app.kubernetes.io/name: event-emitter - name: event-emitter - namespace: default -spec: - runtime: nodejs20 - source: - gitRepository: - url: https://github.com/kyma-project/examples.git - baseDir: /incluster_eventing/src/emitter-fn/ - reference: main ---- -apiVersion: gateway.kyma-project.io/v1beta1 -kind: APIRule -metadata: - name: incoming-http-trigger - namespace: default -spec: - gateway: kyma-gateway.kyma-system.svc.cluster.local - host: incoming - rules: - - accessStrategies: - - handler: allow - methods: - - GET - path: /.* - service: - name: event-emitter - port: 80 diff --git a/examples/incluster_eventing/k8s-resources/receiver-fn.yaml b/examples/incluster_eventing/k8s-resources/receiver-fn.yaml deleted file mode 100644 index 0091fb19..00000000 --- a/examples/incluster_eventing/k8s-resources/receiver-fn.yaml +++ /dev/null @@ -1,35 +0,0 @@ -apiVersion: serverless.kyma-project.io/v1alpha2 -kind: Function -metadata: - labels: - app.kubernetes.io/name: event-receiver - name: event-receiver - namespace: default -spec: - runtime: nodejs20 - source: - gitRepository: - url: https://github.com/kyma-project/examples.git - baseDir: /incluster_eventing/src/receiver-fn/ - reference: main ---- -apiVersion: eventing.kyma-project.io/v1alpha1 -kind: Subscription -metadata: - name: event-receiver - namespace: default -spec: - filter: - filters: - - eventSource: - property: source - type: exact - value: "" - eventType: - property: type - type: exact - value: sap.kyma.custom.acme.payload.sanitised.v1 - protocol: "" - protocolsettings: {} - sink: http://event-receiver.default.svc.cluster.local - diff --git a/examples/incluster_eventing/src/emitter-fn/config.yaml b/examples/incluster_eventing/src/emitter-fn/config.yaml deleted file mode 100644 index a941b096..00000000 --- a/examples/incluster_eventing/src/emitter-fn/config.yaml +++ /dev/null @@ -1,18 +0,0 @@ -name: event-emitter -namespace: default -runtime: nodejs20 -source: - sourceType: git - url: https://github.com/kwiatekus/examples.git - repository: kyma-examples-repo - reference: reflect-changes-in-cloudevents-api - baseDir: /incluster_eventing/src/emitter-fn/ -apiRules: - - name: incoming-http-trigger - service: - host: incoming - rules: - - methods: - - GET - accessStrategies: - - handler: allow diff --git a/examples/incluster_eventing/src/emitter-fn/handler.js b/examples/incluster_eventing/src/emitter-fn/handler.js deleted file mode 100644 index 684efb06..00000000 --- a/examples/incluster_eventing/src/emitter-fn/handler.js +++ /dev/null @@ -1,43 +0,0 @@ -const { SpanStatusCode } = require("@opentelemetry/api/build/src/trace/status"); - -module.exports = { - main: async function (event, context) { - let sanitisedData = sanitise(event.data) - - const eventType = "sap.kyma.custom.acme.payload.sanitised.v1"; - const eventSource = "kyma"; - - //optional cloud event params - const eventtypeversion = "v1"; - const datacontenttype = "application/json"; - - const span = event.tracer.startSpan('call-to-kyma-eventing'); - - // you can pass additional cloudevents attributes - // return await event.emitCloudEvent(eventType, eventSource, sanitisedData, {eventtypeversion, datacontenttype}) - - return await event.emitCloudEvent(eventType, eventSource, sanitisedData) - .then(resp => { - console.log(resp.status); - span.addEvent("Event sent"); - span.setAttribute("event-type", eventType); - span.setAttribute("event-source", eventSource); - span.setStatus({code: SpanStatusCode.OK}); - return "Event sent"; - }).catch(err=> { - console.error(err) - span.setStatus({ - code: SpanStatusCode.ERROR, - message: err.message, - }); - return err.message; - }).finally(()=>{ - span.end(); - }); - } -} -let sanitise = (data)=>{ - console.log(`sanitising data...`) - console.log(data) - return data -} \ No newline at end of file diff --git a/examples/incluster_eventing/src/emitter-fn/package.json b/examples/incluster_eventing/src/emitter-fn/package.json deleted file mode 100644 index 9c1dff70..00000000 --- a/examples/incluster_eventing/src/emitter-fn/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "sanitise-fn", - "version": "0.0.1", - "dependencies": { - "@opentelemetry/api": "^1.0.4" - } -} \ No newline at end of file diff --git a/examples/incluster_eventing/src/receiver-fn/config.yaml b/examples/incluster_eventing/src/receiver-fn/config.yaml deleted file mode 100644 index 7e034810..00000000 --- a/examples/incluster_eventing/src/receiver-fn/config.yaml +++ /dev/null @@ -1,22 +0,0 @@ -name: event-receiver -namespace: default -runtime: nodejs20 -source: - sourceType: git - url: https://github.com/kwiatekus/examples.git - repository: kyma-examples-repo - reference: reflect-changes-in-cloudevents-api - baseDir: /incluster_eventing/src/receiver-fn/ -subscriptions: - - name: event-receiver - protocol: "" - filter: - filters: - - eventSource: - property: source - type: exact - value: "" - eventType: - property: type - type: exact - value: sap.kyma.custom.acme.payload.sanitised.v1 diff --git a/examples/incluster_eventing/src/receiver-fn/handler.js b/examples/incluster_eventing/src/receiver-fn/handler.js deleted file mode 100644 index 8d0f67fb..00000000 --- a/examples/incluster_eventing/src/receiver-fn/handler.js +++ /dev/null @@ -1,11 +0,0 @@ -module.exports = { - main: function (event, context) { - store(event.data) - return 'Stored' - } -} -let store = (data)=>{ - console.log(`storing data...`) - console.log(data) - return data -} \ No newline at end of file diff --git a/examples/incluster_eventing/src/receiver-fn/package.json b/examples/incluster_eventing/src/receiver-fn/package.json deleted file mode 100644 index 81a1a13d..00000000 --- a/examples/incluster_eventing/src/receiver-fn/package.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "name": "store-fn", - "version": "0.0.1", - "dependencies": {} -} \ No newline at end of file diff --git a/examples/python-text2img/Makefile b/examples/python-text2img/Makefile deleted file mode 100644 index ab388182..00000000 --- a/examples/python-text2img/Makefile +++ /dev/null @@ -1,3 +0,0 @@ -deploy: - kyma apply function --dry-run -oyaml > resources/function.yaml - kubectl apply -k resources \ No newline at end of file diff --git a/examples/python-text2img/README.md b/examples/python-text2img/README.md deleted file mode 100644 index 03420c90..00000000 --- a/examples/python-text2img/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# Overview - -The Function uses [Deep AI API](https://deepai.org/machine-learning-model/text2img) for image generation from the text. -Its purpose is to demonstrate how to achieve basic development tasks as a Python Function developer, such as: - - - How to consume a request - - How to customize a response - - How to read ENVs - - How to configure libraries as dependencies - - How to send requests from the Function code - - How to configure Function in the Kyma context - - function API exposure - - function ENVs injection - -## Deploy Function - -1. Copy `resources/secrets/deepai-template.env` into `resources/secrets/deepai.env` and fill in `API-KEY`. - -2. Deploy the application. -``` -make deploy -``` -## Test - -```bash - curl \ - -F 'text=Teddy bear' \ - https://function-text2img.{KYMA_RUNTIME_DOMAIN} -``` \ No newline at end of file diff --git a/examples/python-text2img/config.yaml b/examples/python-text2img/config.yaml deleted file mode 100644 index da5c24fe..00000000 --- a/examples/python-text2img/config.yaml +++ /dev/null @@ -1,26 +0,0 @@ -name: function-text2img -namespace: default -runtime: python312 -source: - sourceType: inline -schemaVersion: v0 -apiRules: - - name: function-text2img - service: - host: function-text2img - rules: - - methods: - - GET - accessStrategies: - - handler: allow -env: - - name: URL - valueFrom: - secretKeyRef: - name: deepai-secret - key: URL - - name: API-KEY - valueFrom: - secretKeyRef: - name: deepai-secret - key: API-KEY diff --git a/examples/python-text2img/handler.py b/examples/python-text2img/handler.py deleted file mode 100644 index 196863fe..00000000 --- a/examples/python-text2img/handler.py +++ /dev/null @@ -1,17 +0,0 @@ -import requests -import os -from bottle import HTTPResponse - -def main(event, context): - text = event['extensions']['request'].params.get('text') - - if not text: - return HTTPResponse(body={'"text" parameter is mandatory'}, status=400) - - url = os.getenv('URL') - apiKey = os.getenv('API-KEY') - print(f'Trying to query {url} with "{text}"') - # Send request to the external service - response = requests.post(url, files={'text': text}, headers={'api-key': apiKey}) - return response.json() - diff --git a/examples/python-text2img/requirements.txt b/examples/python-text2img/requirements.txt deleted file mode 100644 index 2c24336e..00000000 --- a/examples/python-text2img/requirements.txt +++ /dev/null @@ -1 +0,0 @@ -requests==2.31.0 diff --git a/examples/python-text2img/resources/function.yaml b/examples/python-text2img/resources/function.yaml deleted file mode 100644 index e34ff846..00000000 --- a/examples/python-text2img/resources/function.yaml +++ /dev/null @@ -1,46 +0,0 @@ -apiVersion: serverless.kyma-project.io/v1alpha2 -kind: Function -metadata: - creationTimestamp: null - labels: - app.kubernetes.io/name: function-text2img - name: function-text2img - namespace: default -spec: - env: - - name: URL - valueFrom: - secretKeyRef: - key: URL - name: deepai-secret - - name: API-KEY - valueFrom: - secretKeyRef: - key: API-KEY - name: deepai-secret - runtime: python312 - source: - inline: - dependencies: requests==2.31.0 - source: "import requests\nimport os\nfrom bottle import HTTPResponse\n\ndef main(event, context):\n text = event['extensions']['request'].params.get('text')\n\n if not text:\n return HTTPResponse(body={'\"text\" parameter is mandatory'}, status=400)\n\n url = os.getenv('URL')\n apiKey = os.getenv('API-KEY')\n print(f'Trying to query {url} with \"{text}\"')\n # Send request to the external service\n response = requests.post(url, files={'text': text}, headers={'api-key': apiKey})\n return response.json()\n \n" - ---- -apiVersion: gateway.kyma-project.io/v1beta1 -kind: APIRule -metadata: - creationTimestamp: null - name: function-text2img -spec: - gateway: kyma-gateway.kyma-system.svc.cluster.local - host: function-text2img - rules: - - accessStrategies: - - handler: allow - methods: - - GET - path: /.* - service: - name: function-text2img - namespace: default - port: 80 - diff --git a/examples/python-text2img/resources/kustomization.yaml b/examples/python-text2img/resources/kustomization.yaml deleted file mode 100644 index 2183305b..00000000 --- a/examples/python-text2img/resources/kustomization.yaml +++ /dev/null @@ -1,3 +0,0 @@ -resources: -- secrets -- function.yaml diff --git a/examples/python-text2img/resources/secrets/deepai-template.env b/examples/python-text2img/resources/secrets/deepai-template.env deleted file mode 100644 index a03b384b..00000000 --- a/examples/python-text2img/resources/secrets/deepai-template.env +++ /dev/null @@ -1,2 +0,0 @@ -URL=https://api.deepai.org/api/text2img -API-KEY= \ No newline at end of file diff --git a/examples/python-text2img/resources/secrets/kustomization.yaml b/examples/python-text2img/resources/secrets/kustomization.yaml deleted file mode 100644 index 8131a19e..00000000 --- a/examples/python-text2img/resources/secrets/kustomization.yaml +++ /dev/null @@ -1,6 +0,0 @@ -generatorOptions: - disableNameSuffixHash: true -secretGenerator: -- name: deepai-secret - envs: - - deepai.env \ No newline at end of file