### Command-Line Usage Examples Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/api-reference/CLI.md Examples demonstrating how to use the function-dummy CLI with various configurations. ```APIDOC ## Command-Line Usage Examples ```bash # Run with default settings (no mTLS) function-dummy --insecure # Run with debug logging and custom address function-dummy --debug --address=:8443 # Run with mTLS certificates function-dummy --tls-server-certs-dir=/etc/tls/server # Run with Unix socket function-dummy --network=unix --address=/var/run/function.sock ``` ``` -------------------------------- ### DeepCopy Example Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/api-reference/Response.md Example demonstrating how to use the DeepCopy method to create a new deep copy of an existing Response object. ```go original := &v1beta1.Response{...} copy := original.DeepCopy() ``` -------------------------------- ### DeepCopyInto Example Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/api-reference/Response.md Example demonstrating how to use the DeepCopyInto method to create a deep copy of a Response object. ```go source := &v1beta1.Response{...} dest := &v1beta1.Response{} source.DeepCopyInto(dest) ``` -------------------------------- ### Start the Function Server Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/usage-examples.md Starts the dummy function server in the background. The PID is stored for later cleanup. ```bash cd /workspace/home/function-dummy go run . --insecure & FUNCTION_PID=$! ``` -------------------------------- ### Start Development Server Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/README.md Run the function in development mode. Use `--insecure` for testing without TLS and `--debug` for verbose output. ```bash go run . --insecure --debug ``` -------------------------------- ### CLI.Run Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/modules.md Starts the server based on the configuration held within the CLI struct. It returns an error if the server fails to start. ```APIDOC ## CLI.Run ### Description Starts the server based on the configuration held within the CLI struct. It returns an error if the server fails to start. ### Method (Not specified, likely command execution) ### Endpoint (Not specified) ### Parameters (None) ### Request Example (Not specified) ### Response #### Success Response (200) (Not applicable, returns error on failure) #### Response Example (Not specified) ERROR HANDLING: - Returns an error if the server fails to start. ``` -------------------------------- ### Example Execution: Insecure Mode Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/api-reference/Main.md Runs the function in insecure mode for development, starting a gRPC server on port 9443 without mTLS. Debug logs are enabled. ```bash $ go run . --insecure --debug 2024/06/26 10:00:00 DEBUG Starting gRPC server on :9443 without mTLS 2024/06/26 10:00:00 INFO Server started ``` -------------------------------- ### Install Crossplane CLI Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/usage-examples.md Installs the Crossplane CLI ('crank') on Linux AMD64 by downloading the latest release. ```bash # Install Crossplane CLI curl https://releases.crossplane.io/download/latest/bin/linux_amd64/crank -o crank chmod +x crank # Or use the legacy command: # crossplane xpkg build ``` -------------------------------- ### Example Invocation: Run function-dummy Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/api-reference/Main.md Demonstrates various ways to invoke the function-dummy executable, including default settings, debug logging, and mTLS configuration. ```bash # Run with default settings (insecure mode, port 9443) ./function-dummy --insecure ``` ```bash # Run with debug logging ./function-dummy --insecure --debug ``` ```bash # Run with mTLS ./function-dummy \ --network=tcp \ --address=:9443 \ --tls-server-certs-dir=/etc/tls/server ``` -------------------------------- ### DeepCopyObject Example Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/api-reference/Response.md Example demonstrating how to use the DeepCopyObject method to create a deep copy and cast it back to a Response object. ```go original := &v1beta1.Response{...} obj := original.DeepCopyObject() if obj != nil { resp := obj.(*v1beta1.Response) // Use resp... } ``` -------------------------------- ### Create Function Logger and Instance Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/api-reference/Function.md This example demonstrates how to create a logger instance and then use it to initialize a new Function object. Ensure the 'debug' variable is appropriately set. ```go log, err := function.NewLogger(debug) if err != nil { return err } fn := &Function{log: log} ``` -------------------------------- ### Initialize Function Instance Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/api-reference/Function.md Instances of the Function type are created during server initialization. This example shows how to instantiate a Function with a logger. ```go f := &Function{log: log} ``` -------------------------------- ### Import and Initialize Response Type Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/modules.md Demonstrates how to import the `v1beta1` input package and initialize a `Response` object. This example shows setting the `TypeMeta` and `Response` fields, which is typical when preparing input for a composition function. ```go import "github.com/crossplane-contrib/function-dummy/input/v1beta1" resp := &v1beta1.Response{ TypeMeta: metav1.TypeMeta{ APIVersion: "dummy.fn.crossplane.io/v1beta1", Kind: "Response", }, Response: runtime.RawExtension{Raw: []byte(`...`)} } ``` -------------------------------- ### Deploy Function Server with Docker Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/usage-examples.md Build and run the function-dummy server using Docker. Examples show deployment in both insecure mode and with mTLS, including volume mounting for certificates. ```bash # Build the Docker image docker build . --tag=function-dummy:latest # Run in insecure mode docker run -p 9443:9443 function-dummy:latest --insecure # Run with mTLS (mount certificate directory) docker run \ -p 9443:9443 \ -v /etc/tls/server:/etc/tls/server:ro \ function-dummy:latest \ --tls-server-certs-dir=/etc/tls/server ``` -------------------------------- ### Multi-Step Pipeline with Dummy Function Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/usage-examples.md This example demonstrates a multi-step pipeline where the dummy function is used for enrichment alongside other functions like patch-and-transform and auto-ready. ```yaml apiVersion: apiextensions.crossplane.io/v1 kind: Composition metadata: name: multi-step spec: compositeTypeRef: apiVersion: example.crossplane.io/v1beta1 kind: WebApp pipeline: - step: patch-and-transform functionRef: name: crossplane-contrib-function-patch-and-transform input: apiVersion: pt.fn.crossplane.io/v1beta1 kind: Resources resources: - name: web-server base: apiVersion: compute.gcp.upbound.io/v1beta1 kind: Instance spec: forProvider: machineType: n1-standard-1 - step: dummy-enrichment functionRef: name: function-dummy input: apiVersion: dummy.fn.crossplane.io/v1beta1 kind: Response response: desired: composite: resource: status: message: "Enriched by dummy function" results: - severity: SEVERITY_NORMAL message: "Applied custom enrichment" - step: auto-ready functionRef: name: crossplane-contrib-function-auto-ready ``` -------------------------------- ### Composition Input Example Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/errors.md Example of how to provide input to the function-dummy in a Composition pipeline. The input must include at least an empty response object. ```yaml apiVersion: apiextensions.crossplane.io/v1 kind: Composition spec: pipeline: - step: dummy-step functionRef: name: function-dummy input: apiVersion: dummy.fn.crossplane.io/v1beta1 kind: Response response: {} # Must provide at least an empty response ``` -------------------------------- ### Log Format Example Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/api-reference/Main.md Illustrates the expected format for log messages, including timestamp, level, message, and key-value pairs. ```text 2024-06-26T10:00:00Z INFO Running Function tag=step-1 ``` -------------------------------- ### Logger Initialization Failure Example Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/errors.md This error occurs when the logger cannot be created with the specified debug level. The server exits before starting the gRPC listener. ```go ctx.FatalIfErrorf(err) ``` -------------------------------- ### Example Execution: mTLS Mode Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/api-reference/Main.md Runs the function with mTLS enabled for production. It loads TLS certificates from a specified directory and establishes an mTLS server on the configured network and address. ```bash $ go run . \ --network=tcp \ --address=:9443 \ --tls-server-certs-dir=/etc/tls/server 2024/06/26 10:00:00 INFO Loading TLS certificates from /etc/tls/server 2024/06/26 10:00:00 INFO Server started with mTLS ``` -------------------------------- ### Install Function in Crossplane Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/usage-examples.md Installs the built function package into Crossplane, either by pushing it to a registry or installing it locally. ```bash # Push to a registry or install locally kubectl crossplane install function \ xpkg.upbound.io/crossplane-contrib/function-dummy:v0.2.1 ``` -------------------------------- ### Run Function Dummy with mTLS Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/usage-examples.md Starts the function-dummy server with mTLS authentication enabled, suitable for production environments. Requires TLS certificates to be configured. ```bash # Production: with mTLS function-dummy --tls-server-certs-dir=/etc/tls/server ``` -------------------------------- ### In-Code Response Creation and Copying Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/api-reference/Response.md Example of creating a new Response object in Go and then making a deep copy of it using the DeepCopy method. Includes necessary imports. ```go import "github.com/crossplane-contrib/function-dummy/input/v1beta1" // Create a new Response resp := &v1beta1.Response{ TypeMeta: metav1.TypeMeta{ APIVersion: "dummy.fn.crossplane.io/v1beta1", Kind: "Response", }, ObjectMeta: metav1.ObjectMeta{ Name: "my-response", }, Response: runtime.RawExtension{ Raw: []byte(`{ "desired": { "composite": { "resource": {"spec": {"widgets": 200}} } } }`), }, } // Make a copy respCopy := resp.DeepCopy() ``` -------------------------------- ### Execute Composition Function Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/api-reference/Function.md This example shows how to call the RunFunction method on a Function instance. It includes setting up a background context, a mock request, and handling the response, particularly checking for fatal errors within the results. ```go import ( "context" fnv1 "github.com/crossplane/function-sdk-go/proto/v1" "github.com/crossplane/function-sdk-go/logging" ) log := logging.NewNopLogger() fn := &Function{log: log} // Assuming req is a properly constructed RunFunctionRequest // with Input containing a v1beta1.Response with desired state ctx := context.Background() response, err := fn.RunFunction(ctx, req) // err will always be nil, check response.Results for fatality if len(response.GetResults()) > 0 { for _, result := range response.GetResults() { if result.Severity.String() == "SEVERITY_FATAL" { // Handle fatal error } } } ``` -------------------------------- ### Merge Semantics Example Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/README.md Demonstrates how `proto.Merge()` combines base and overlay states, highlighting which fields are overwritten and which are preserved. Useful for understanding state management in the function. ```text Base: {status: {phase: "Running", region: "us-west"}} Overlay: {status: {phase: "Ready"}} Result: {status: {phase: "Ready", region: "us-west"}} ↑ overwritten ↑ preserved ``` -------------------------------- ### Composition Example with Response Input Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/api-reference/Response.md An example of a Crossplane Composition definition that uses a Response object as input for a function. ```yaml apiVersion: apiextensions.crossplane.io/v1 kind: Composition metadata: name: example-composition spec: compositeTypeRef: apiVersion: example.crossplane.io/v1beta1 kind: XR pipeline: - step: dummy-step functionRef: name: function-dummy input: apiVersion: dummy.fn.crossplane.io/v1beta1 kind: Response response: desired: composite: resource: status: widgets: 200 connectionDetails: secret-key: secret-value resources: my-resource: resource: apiVersion: example.org/v1 kind: ManagedResource spec: data: value ready: READY_TRUE results: - severity: SEVERITY_NORMAL message: "Function executed successfully" output: custom-field: custom-value ``` -------------------------------- ### Function Dummy Directory Structure Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/README.md This outlines the standard directory structure for the Function Dummy project. It includes key files for the entry point, implementation, tests, input types, module definition, Dockerfile, and example configurations. ```text function-dummy/ ├── main.go # Entry point, CLI ├── fn.go # Function implementation ├── fn_test.go # Tests ├── input/ │ └── v1beta1/ │ ├── response.go # Input type │ └── zz_generated.deepcopy.go ├── go.mod # Module definition ├── go.sum # Dependency checksums ├── Dockerfile # Container image ├── package/ │ ├── crossplane.yaml # Function metadata │ └── input/ │ └── *.yaml # Generated CRD └── example/ ├── composition.yaml ├── functions.yaml └── xr.yaml ``` -------------------------------- ### Valid Response Example Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/errors.md Example of a valid response structure that can be successfully unmarshaled. This demonstrates the correct format for the desired composite resource. ```yaml apiVersion: dummy.fn.crossplane.io/v1beta1 kind: Response response: desired: composite: resource: apiVersion: example.org/v1 kind: XR spec: key: value ``` -------------------------------- ### Error Handling Example Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/README.md Illustrates how fatal errors are represented within the RunFunctionResponse. Use this to understand how to interpret error conditions from the function. ```go // Error condition: invalid input // Result: RunFunctionResponse.Results[0].Severity = SEVERITY_FATAL // Result: RunFunctionResponse.Results[0].Message = "cannot get Function input from ..." ``` -------------------------------- ### Run CLI with Debug Logging and Custom Address Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/api-reference/CLI.md Starts the function-dummy CLI with debug logging enabled and specifies a custom network address for the gRPC server. ```bash # Run with debug logging and custom address function-dummy --debug --address=:8443 ``` -------------------------------- ### Run Function with TLS Security Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/README.md Starts the function-dummy with TLS enabled for secure communication in production. Requires server certificates and client certificate verification (mTLS). ```bash function-dummy --tls-server-certs-dir=/etc/tls/server ``` -------------------------------- ### Test Composition Locally with Crossplane CLI Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/usage-examples.md Create test XR and Composition YAML files, start the function server, and then use the Crossplane CLI to render the composition. This is useful for testing composition logic without deploying to a cluster. ```bash # Create test files mkdir -p /tmp/test-composition cat > /tmp/test-composition/xr.yaml <<'EOF' apiVersion: example.crossplane.io/v1beta1 kind: Database metadata: name: test-db spec: region: us-west-2 EOF cat > /tmp/test-composition/composition.yaml <<'EOF' apiVersion: apiextensions.crossplane.io/v1 kind: Composition metadata: name: test spec: compositeTypeRef: apiVersion: example.crossplane.io/v1beta1 kind: Database pipeline: - step: dummy-step functionRef: name: function-dummy input: apiVersion: dummy.fn.crossplane.io/v1beta1 kind: Response response: desired: composite: resource: status: phase: Available EOF # Before rendering, start the function server in another terminal: # go run . --insecure # Test the composition crossplane beta render \ /tmp/test-composition/xr.yaml \ /tmp/test-composition/composition.yaml ``` -------------------------------- ### Run Function Dummy without mTLS (Development) Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/usage-examples.md Starts the function-dummy server without mTLS authentication, intended for development and testing purposes only. Use with caution. ```bash # Development only: without mTLS function-dummy --insecure ``` -------------------------------- ### Example gRPC RunFunction Call Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/grpc-interface.md This pseudocode illustrates a typical gRPC RunFunction call from a Composition Pipeline client to a function server. It shows the structure of the request and the expected response. ```pseudocode Client (Composition Pipeline) │ └─> RunFunction(RunFunctionRequest{ meta: {tag: "step-1"}, input: Struct{ fields: { "apiVersion": "dummy.fn.crossplane.io/v1beta1", "kind": "Response", "response": Struct{ fields: { "desired": Struct{...}, "results": ListValue{...} } } } }, desired: State{...} }) │ └─> Server (function-dummy) │ └─> Function.RunFunction() ├─ request.GetInput() ← v1beta1.Response ├─ protojson.Unmarshal() ← RunFunctionResponse ├─ proto.Merge() ← merged response └─ return (RunFunctionResponse, nil) │ └─> Client receives RunFunctionResponse{ meta: {tag: "step-1"}, desired: State{...}, results: [Result{...}], output: Struct{...} } ``` -------------------------------- ### Configure function-dummy Response Source: https://github.com/crossplane-contrib/function-dummy/blob/main/README.md Example of a Composition resource that uses the function-dummy. The input specifies the desired composite resource, connection details, and other resources to be created, along with a message. ```yaml apiVersion: apiextensions.crossplane.io/v1 kind: Composition metadata: name: test-crossplane spec: compositeTypeRef: apiVersion: example.crossplane.io/v1beta1 kind: XR pipeline: - step: return-some-results functionRef: name: function-dummy input: apiVersion: dummy.fn.crossplane.io/v1beta1 kind: Response response: desired: composite: resource: status: widgets: 200 connectionDetails: very: secret resources: cool-resource: resource: apiVersion: example.org/v1 kind: Composed spec: {} # etc... ready: READY_TRUE results: - severity: SEVERITY_NORMAL message: "I did the thing!" ``` -------------------------------- ### Kubernetes Deployment Configuration Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/configuration.md Deploy the function-dummy in Kubernetes by defining a ConfigMap for TLS certificates and a Deployment that mounts the certificates and configures the container. Ensure the image and paths match your setup. ```yaml apiVersion: v1 kind: ConfigMap metadata: name: function-tls-certs data: tls.crt: | -----BEGIN CERTIFICATE----- ... -----END CERTIFICATE----- tls.key: | -----BEGIN PRIVATE KEY----- ... -----END PRIVATE KEY----- ca.crt: | -----BEGIN CERTIFICATE----- ... -----END CERTIFICATE----- --- apiVersion: apps/v1 kind: Deployment metadata: name: function-dummy spec: template: spec: containers: - name: function image: xpkg.upbound.io/crossplane-contrib/function-dummy:v0.2.1 args: - --network=tcp - --address=:9443 - --tls-server-certs-dir=/etc/tls/server ports: - containerPort: 9443 volumeMounts: - name: tls-certs mountPath: /etc/tls/server readOnly: true volumes: - name: tls-certs configMap: name: function-tls-certs ``` -------------------------------- ### Configure TCP Network Listener Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/configuration.md Configures the server to listen on a TCP network. Examples show listening on all interfaces, a specific interface, or localhost only. ```bash # Listen on all interfaces, port 9443 function-dummy --network=tcp --address=:9443 ``` ```bash # Listen on specific interface function-dummy --network=tcp --address=192.168.1.100:9443 ``` ```bash # Listen on localhost only function-dummy --network=tcp --address=localhost:9443 ``` -------------------------------- ### Composition: Conditional Response with Results Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/usage-examples.md An example composition that uses the dummy function to apply VM configurations and return warnings based on the specified machine type. It also includes a normal success message. ```yaml apiVersion: apiextensions.crossplane.io/v1 kind: Composition metadata: name: with-warnings spec: compositeTypeRef: apiVersion: example.crossplane.io/v1beta1 kind: VM pipeline: - step: check-configuration functionRef: name: function-dummy input: apiVersion: dummy.fn.crossplane.io/v1beta1 kind: Response response: desired: composite: resource: status: state: Creating resources: compute-instance: resource: apiVersion: compute.gcp.upbound.io/v1beta1 kind: Instance metadata: name: vm-instance spec: forProvider: machineType: n1-standard-1 zone: us-central1-a results: - severity: SEVERITY_WARNING message: "Machine type n1-standard-1 may be underpowered for production" - severity: SEVERITY_NORMAL message: "VM configuration applied successfully" ``` -------------------------------- ### Protobuf Merge Semantics Example Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/grpc-interface.md Demonstrates how `proto.Merge` combines a base response with an overlay response. Fields in the overlay overwrite corresponding fields in the base, while non-conflicting fields are preserved. ```protobuf desired { composite { resource { spec { field1: "from_pipeline" field2: "from_pipeline" } } } } results { message: "step 1 completed" } ``` ```protobuf desired { composite { resource { spec { field1: "from_function" } status { ready: true } } } } ``` ```protobuf desired { composite { resource { spec { field1: "from_function" # Overwritten field2: "from_pipeline" # Preserved from base } status { ready: true # Added from overlay } } } } results { message: "step 1 completed" # Preserved from base } ``` -------------------------------- ### main Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/modules.md The entry point of the application. It parses command-line flags and initiates the server startup process. ```APIDOC ## main ### Description The entry point of the application. It parses command-line flags and initiates the server startup process. ### Method (Not specified, Go runtime entry point) ### Endpoint (Not specified) ### Parameters (None) ### Request Example (Not specified) ### Response (None) ### Response Example (Not specified) ERROR HANDLING: (Not specified, errors likely handled by CLI.Run) ``` -------------------------------- ### Startup Flow Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/api-reference/Main.md Illustrates the sequence of operations during the function's startup, from parsing CLI arguments to the gRPC server becoming ready to handle requests. ```text main() ↓ kong.Parse(&CLI{}) ↓ ctx.Run() → CLI.Run() ↓ function.NewLogger(c.Debug) ↓ function.Serve(&Function{log: log}, function.Listen(c.Network, c.Address), function.MTLSCertificates(c.TLSCertsDir), function.Insecure(c.Insecure)) ↓ gRPC Server Running ↓ Function.RunFunction() called per request ``` -------------------------------- ### Use Function Type Instance Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/modules.md Demonstrates how to create and call a function instance. Note that the log field is unexported and typically set during server initialization by the SDK. ```go import ( "context" fnv1 "github.com/crossplane/function-sdk-go/proto/v1" "github.com/crossplane/function-sdk-go/logging" "github.com/crossplane-contrib/function-dummy" ) // Create function instance log := logging.NewNopLogger() fn := &main.Function{ // log is unexported, use reflection or alternative constructor } // Call function ctx := context.Background() req := &fnv1.RunFunctionRequest{...} rsp, err := fn.RunFunction(ctx, req) ``` -------------------------------- ### Run CLI with Default Settings Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/api-reference/CLI.md Initializes and runs the composition function server with default settings, including mTLS enabled. Requires TLS certificates to be configured. ```go import ( "github.com/alecthomas/kong" ) cli := &CLI{ Debug: true, Network: "tcp", Address: ":9443", TLSCertsDir: "/etc/tls/certs", Insecure: false, } err := cli.Run() if err != nil { // Handle error } ``` -------------------------------- ### Develop function-dummy with Go and Docker Source: https://github.com/crossplane-contrib/function-dummy/blob/main/README.md Commands for developing the function-dummy, including code generation, testing, building the runtime image, and packaging the function. ```shell # Run code generation - see input/generate.go $ go generate ./... # Run tests - see fn_test.go $ go test ./... # Build the function's runtime image - see Dockerfile $ docker build . --tag=runtime # Build a function package - see package/crossplane.yaml $ crossplane xpkg build -f package --embed-runtime-image=runtime ``` -------------------------------- ### Install Function CRD in Crossplane Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/README.md This YAML defines the Function Custom Resource Definition (CRD) for installation within Crossplane. It specifies the package to be used for the function. ```yaml apiVersion: pkg.crossplane.io/v1beta1 kind: Function metadata: name: function-dummy spec: package: xpkg.upbound.io/crossplane-contrib/function-dummy:v0.2.1 ``` -------------------------------- ### CLI.Run() Method Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/api-reference/CLI.md Initializes and runs the composition function server with the configured settings. ```APIDOC ## CLI.Run() Method ### Signature ```go func (c *CLI) Run() error ``` ### Description Initializes the composition function server with the configured settings and starts serving gRPC requests. ### Behavior 1. Creates a new logger with the `Debug` flag setting. 2. Initializes the gRPC server with the `Function` instance. 3. Applies server options for listening, mTLS certificates, and insecure mode. 4. Blocks until the server is shut down or encounters a fatal error. ### Returns - `error`: An error if logger initialization or server startup fails. ### Example ```go import ( "github.com/alecthomas/kong" ) cli := &CLI{ Debug: true, Network: "tcp", Address: ":9443", TLSCertsDir: "/etc/tls/certs", Insecure: false, } err := cli.Run() if err != nil { // Handle error } ``` ``` -------------------------------- ### Invalid Response Example Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/errors.md Example of an invalid response structure that will cause a protobuf unmarshaling error. This demonstrates malformed JSON syntax within the response field. ```yaml apiVersion: dummy.fn.crossplane.io/v1beta1 kind: Response response: # Invalid JSON syntax desired: composite: resource: {invalid json here} ``` -------------------------------- ### Create Response Type Instance Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/modules.md Shows how to create a Response object for use in composition, including setting TypeMeta, ObjectMeta, and the Response field with desired configuration. A DeepCopy method is also demonstrated. ```go import ( "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" v1beta1 "github.com/crossplane-contrib/function-dummy/input/v1beta1" ) // Create Response in composition resp := &v1beta1.Response{ TypeMeta: v1.TypeMeta{ APIVersion: "dummy.fn.crossplane.io/v1beta1", Kind: "Response", }, ObjectMeta: v1.ObjectMeta{ Name: "my-response", }, Response: runtime.RawExtension{ Raw: []byte(`{"desired": {...}}`), }, } // Deep copy respCopy := resp.DeepCopy() ``` -------------------------------- ### Function Entry Points Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/modules.md Illustrates the call chain from the main entry point to the function's request handling logic. ```go main() └─> CLI.Run() └─> function.Serve(&Function{...}) └─> Function.RunFunction() [called per request] ``` -------------------------------- ### Composition: Creating Composed Resources Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/usage-examples.md This composition demonstrates how to use the dummy function to define and create multiple managed resources, such as an S3 bucket and its policy. Note the `READY_FALSE` status indicating initial creation. ```yaml apiVersion: apiextensions.crossplane.io/v1 kind: Composition metadata: name: create-resources spec: compositeTypeRef: apiVersion: example.crossplane.io/v1beta1 kind: Bucket pipeline: - step: create-bucket functionRef: name: function-dummy input: apiVersion: dummy.fn.crossplane.io/v1beta1 kind: Response response: desired: resources: s3-bucket: resource: apiVersion: s3.aws.upbound.io/v1beta1 kind: Bucket metadata: name: my-bucket spec: forProvider: region: us-west-2 acl: private ready: READY_FALSE bucket-policy: resource: apiVersion: s3.aws.upbound.io/v1beta1 kind: BucketPolicy metadata: name: my-bucket-policy spec: forProvider: bucketRef: name: my-bucket policy: | { "Version": "2012-10-17", "Statement": [...] } ready: READY_FALSE results: - severity: SEVERITY_NORMAL message: "S3 bucket and policy created" ``` -------------------------------- ### Securely Storing Connection Details Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/usage-examples.md Example of how sensitive connection details, like passwords, are handled securely within Crossplane's desired state. This data should not be logged or exposed. ```yaml desired: composite: connectionDetails: password: "secret-value" # Stored securely by Crossplane ``` -------------------------------- ### Run Production Server (mTLS, Custom Port) Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/configuration.md Configure the server for production with mTLS enabled and a custom network address. Ensure the specified TLS certificate directory exists and contains the necessary certificate files. ```bash function-dummy \ --network=tcp \ --address=:8443 \ --tls-server-certs-dir=/etc/tls/function-dummy ``` -------------------------------- ### Configure Connection Details with Dummy Function Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/usage-examples.md This snippet shows how to configure connection details for a resource using the dummy function. It specifies username, password, endpoint, port, and database for a PostgreSQL instance. ```yaml apiVersion: apiextensions.crossplane.io/v1 kind: Composition metadata: name: with-connection-details spec: compositeTypeRef: apiVersion: example.crossplane.io/v1beta1 kind: PostgreSQL pipeline: - step: setup-connection functionRef: name: function-dummy input: apiVersion: dummy.fn.crossplane.io/v1beta1 kind: Response response: desired: composite: connectionDetails: username: admin password: "$(RANDOM_PASSWORD)" endpoint: "postgres.example.com" port: "5432" database: "myapp" resources: postgres-instance: resource: apiVersion: rds.aws.upbound.io/v1beta1 kind: DBInstance metadata: name: postgres-db spec: forProvider: engine: postgres engineVersion: "14.7" ready: READY_FALSE connectionDetails: username: admin ``` -------------------------------- ### Build XPkg Package and Runtime Image Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/README.md Builds a Docker image for the runtime and then packages the function as an XPkg. This is used for Crossplane package management. ```bash docker build . --tag=function-dummy-runtime:latest crossplane xpkg build -f package --embed-runtime-image=function-dummy-runtime:latest ``` -------------------------------- ### Run Go Tests Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/usage-examples.md Execute all tests within the function-dummy project. This command is typically run from the project's root directory. ```bash cd /workspace/home/function-dummy go test ./... -v ``` -------------------------------- ### Compile to Executable Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/api-reference/Main.md Command to compile the Go project into a standalone executable named 'function-dummy'. ```bash go build -o function-dummy . ``` -------------------------------- ### Programmatic Integration with Response Type Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/usage-examples.md Shows how to construct and manipulate the `Response` type from the `function-dummy` package for programmatic integration. This includes creating a `Response` object, setting its fields, and making a deep copy. ```go package main import ( "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" v1beta1 "github.com/crossplane-contrib/function-dummy/input/v1beta1" ) func main() { // Create a Response resp := &v1beta1.Response{ TypeMeta: v1.TypeMeta{ APIVersion: "dummy.fn.crossplane.io/v1beta1", Kind: "Response", }, ObjectMeta: v1.ObjectMeta{ Name: "test-response", }, Response: runtime.RawExtension{ Raw: []byte(`{ "desired": { "composite": { "resource": {"status": {"ready": true}} } } }`), }, } // Make a copy respCopy := resp.DeepCopy() // Use the copy respCopy.ObjectMeta.Name = "copied-response" } ``` -------------------------------- ### Run CLI with Unix Socket Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/api-reference/CLI.md Launches the function-dummy CLI using a Unix domain socket for communication instead of a TCP network. ```bash # Run with Unix socket function-dummy --network=unix --address=/var/run/function.sock ``` -------------------------------- ### Run function-dummy CLI Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/README.md Execute the function-dummy CLI. Use `--insecure` for development or specify TLS certificates for secure operation. ```bash go run . --insecure ``` ```bash go run . --tls-server-certs-dir=/etc/tls/server ``` -------------------------------- ### Build Docker Image Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/api-reference/Main.md Command to build a Docker image for the function-dummy application. The Dockerfile ensures a static binary is included in a distroless image. ```bash docker build . --tag=function-dummy:latest ``` -------------------------------- ### Run function-dummy CLI Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/README.md Use these commands to run the function-dummy CLI for development or production. Options include disabling TLS, enabling debug logging, specifying a custom port, or using a Unix socket. ```bash # Development (no TLS) function-dummy --insecure --debug ``` ```bash # Production (with mTLS) function-dummy --tls-server-certs-dir=/etc/tls/server ``` ```bash # Custom port function-dummy --address=:8443 --insecure ``` ```bash # Unix socket function-dummy --network=unix --address=/var/run/fn.sock --insecure ``` -------------------------------- ### Function: main Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/api-reference/Main.md Parses command-line arguments using the alecthomas/kong library and executes the CLI's Run() method. Handles errors by calling ctx.FatalIfErrorf() for logging and exiting. ```go func main() ``` -------------------------------- ### Run Tests Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/api-reference/Main.md Command to execute all tests within the project. This includes a test case for the basic request/response flow. ```bash go test ./... ``` -------------------------------- ### Build Function Package Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/README.md Build a Docker image for the function runtime and then package the function using Crossplane's build command. The runtime image is embedded into the package. ```bash docker build . --tag=runtime crossplane xpkg build -f package --embed-runtime-image=runtime ``` -------------------------------- ### CLI Methods Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/modules.md Lists the exported methods of the CLI struct, including the main Run method. ```go `CLI.Run` | method | Exported | line 21 | `main` | function | Exported | line 33 | ``` -------------------------------- ### Programmatic Integration with Function Type Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/usage-examples.md Demonstrates how to programmatically integrate with the Crossplane Function Dummy using the `RunFunction` method from the function-sdk-go. This involves creating a logger, function instance, and a `RunFunctionRequest`. ```go package main import ( "context" "log" "github.com/crossplane/function-sdk-go/logging" fnv1 "github.com/crossplane/function-sdk-go/proto/v1" "github.com/crossplane/function-sdk-go/resource" "github.com/crossplane-contrib/function-dummy" ) func main() { // Create logger log, err := logging.NewLogger(true) if err != nil { log.Fatal(err) } // Create function instance fn := &main.Function{log: log} // Create a request req := &fnv1.RunFunctionRequest{ Meta: &fnv1.RequestMeta{Tag: "test-step"}, Input: resource.MustStructJSON(`{ "apiVersion": "dummy.fn.crossplane.io/v1beta1", "kind": "Response", "response": { "desired": { "composite": { "resource": { "status": { "ready": true } } } } } }`), } // Run the function ctx := context.Background() rsp, err := fn.RunFunction(ctx, req) if err != nil { log.Fatalf("Function failed: %v", err) } // Check response log.Infof("Got %d results", len(rsp.Results)) log.Infof("Desired state: %+v", rsp.Desired) } ``` -------------------------------- ### Resource Structure Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/grpc-interface.md Defines a resource within the desired state, including its definition, readiness status, and connection details. ```protobuf message Resource { optional google.protobuf.Struct resource = 1; optional string ready = 2; map connectionDetails = 3; } ``` -------------------------------- ### Configure CLI Options Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/types.md Defines the `CLI` struct for configuring command-line interface options, including debug logging, network settings, address, TLS certificate directory, and insecure mode. ```go type CLI struct { Debug bool `help:"Emit debug logs in addition to info logs." short:"d" Network string `default:"tcp" help:"Network on which to listen for gRPC connections." Address string `default:":9443" help:"Address at which to listen for gRPC connections." TLSCertsDir string `env:"TLS_SERVER_CERTS_DIR" help:"Directory containing server certs (tls.key, tls.crt) and the CA used to verify client certificates (ca.crt)" Insecure bool `help:"Run without mTLS credentials. If you supply this flag --tls-server-certs-dir will be ignored." } ``` -------------------------------- ### Run CLI with mTLS Certificates Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/api-reference/CLI.md Configures the function-dummy CLI to use mTLS by specifying the directory containing server TLS certificates. ```bash # Run with mTLS certificates function-dummy --tls-server-certs-dir=/etc/tls/server ``` -------------------------------- ### Build Function Package Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/usage-examples.md Builds the Docker image for the function runtime and then creates an XPkg function package, embedding the runtime image. This package is suitable for distribution. ```bash # Navigate to project directory cd /workspace/home/function-dummy # Run code generation go generate ./... # Build the Docker image for the function runtime docker build . --tag=function-dummy-runtime:latest # Build the XPkg function package crossplane xpkg build -f package --embed-runtime-image=function-dummy-runtime:latest # Result: A .xpkg file suitable for distribution ``` -------------------------------- ### Run Function Server in Development (Insecure Mode) Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/usage-examples.md Use this command to run the function server locally without TLS for development purposes. The `--debug` flag enables verbose logging. ```bash cd /workspace/home/function-dummy go run . --insecure # Or with debug logging go run . --insecure --debug # Expected output: # 2024/06/26T10:00:00Z INFO Running Function tag= # (waits for requests on :9443) ``` -------------------------------- ### Create a Test XR Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/usage-examples.md Creates a simple TestXR custom resource instance that will be processed by the composition. ```yaml apiVersion: example.crossplane.io/v1beta1 kind: TestXR metadata: name: test-instance spec: {} ``` -------------------------------- ### Build Function Package Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/api-reference/Main.md Builds the Crossplane XPkg function package. First, build the runtime image, then build the package embedding the runtime image. ```bash # First, build the runtime image docker build . --tag=runtime # Then, build the XPkg function package crossplane xpkg build -f package --embed-runtime-image=runtime ``` -------------------------------- ### GitHub Actions Workflow for Testing Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/usage-examples.md A GitHub Actions workflow to automate testing, code generation, and Docker image building for the function-dummy project on every push or pull request. ```yaml name: Test on: [push, pull_request] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions/setup-go@v2 with: go-version: '1.24' - run: go test ./... - run: go generate ./... - run: docker build . --tag=test-image ``` -------------------------------- ### Default CLI Configuration Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/api-reference/CLI.md Shows the default configuration for the CLI struct, which enables TCP on port 9443 with mTLS. ```go &CLI{ Debug: false, Network: "tcp", Address: ":9443", Insecure: false, } ``` -------------------------------- ### Run Development Server (No TLS) Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/configuration.md Use this command for local development to run the server without TLS and with debug logging enabled. It defaults to port 9443. ```bash function-dummy --insecure --debug ``` -------------------------------- ### Define CLI Type Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/modules.md Defines the `CLI` type for holding server configuration. Instances are created by `kong.Parse()` during CLI parsing. ```go type CLI struct { Debug bool Network string Address string TLSCertsDir string Insecure bool } ``` -------------------------------- ### Run Composition Render Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/usage-examples.md Executes the Crossplane composition render command to process the TestXR against the Test Composition. ```bash crossplane beta render \ /tmp/test-xr.yaml \ /tmp/test-composition.yaml ``` -------------------------------- ### Run Function Server in Production (mTLS) Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/usage-examples.md Run the function server with mutual TLS (mTLS) enabled for secure communication. Ensure TLS certificates are placed in the specified directory. This can also be configured via an environment variable. ```bash # Prepare TLS certificates in /etc/tls/server/ # Required files: # - tls.key (server private key) # - tls.crt (server certificate) # - ca.crt (CA for client verification) go run . --network=tcp --address=:9443 --tls-server-certs-dir=/etc/tls/server # Or using environment variable export TLS_SERVER_CERTS_DIR=/etc/tls/server go run . ``` -------------------------------- ### Render Kubernetes Resources Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/README.md Uses the Crossplane CLI to render Kubernetes resources based on provided YAML definitions. This is part of the integration testing process. ```bash crossplane beta render xr.yaml composition.yaml functions.yaml ``` -------------------------------- ### Render Composition with Crossplane CLI Source: https://github.com/crossplane-contrib/function-dummy/blob/main/README.md Command to render a composition using the Crossplane CLI, useful for testing and local development. ```shell $ crossplane beta render xr.yaml composition.yaml functions.yaml ``` -------------------------------- ### CLI Configuration Struct Tags Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/api-reference/Main.md Magic values like default port and network are defined as struct tags in the CLI. ```go Address string `default:":9443"` Network string `default:"tcp"` ``` -------------------------------- ### Verify Output Source: https://github.com/crossplane-contrib/function-dummy/blob/main/_autodocs/usage-examples.md Checks the output of the composition render to confirm that the dummy function has updated the XR's status as expected. ```bash # Output should show the XR with the status added by the dummy function # apiVersion: example.crossplane.io/v1beta1 # kind: TestXR # metadata: # name: test-instance # spec: {} # status: # phase: Ready # message: "Successfully processed by dummy function" ```