### StartTask Golang Client Example Source: https://github.com/cloudfoundry/bbs/blob/main/docs/024-api-tasks-internal.md Use this to start a task. Ensure you have a logger and the task and cell GUIDs. ```go client := bbs.NewClient(url) shouldStart, err := client.StartTask(logger, "task-guid", "cell-1") if err != nil { log.Printf("failed to start task: " + err.Error()) } if shouldStart { log.Print("task should be started") } else { log.Print("task should NOT be started") } ``` -------------------------------- ### Example: Retrieve DesiredLRPSchedulingInfo by Process GUID Source: https://github.com/cloudfoundry/bbs/blob/main/docs/033-api-lrps.md Demonstrates usage of the DesiredLRPBySchedulingInfoProcessGuid client method. ```go client := bbs.NewClient(url) schedInfo, err := client.DesiredLRPBySchedulingInfoProcessGuid(logger, "some-processs-guid") if err != nil { log.Printf("failed to retrieve desired lrp scheduling info: " + err.Error()) } ``` -------------------------------- ### Example: Retrieve DesiredLRP by Process GUID Source: https://github.com/cloudfoundry/bbs/blob/main/docs/033-api-lrps.md Demonstrates usage of the DesiredLRPByProcessGuid client method. ```go client := bbs.NewClient(url) desiredLRP, err := client.DesiredLRPByProcessGuid(logger, "some-processs-guid") if err != nil { log.Printf("failed to retrieve desired lrp: " + err.Error()) } ``` -------------------------------- ### Fetch Domains Usage Example Source: https://github.com/cloudfoundry/bbs/blob/main/docs/050-domains.md Example of using the client to retrieve a list of all fresh domains. ```go client := bbs.NewClient(url) domains, err := client.Domains(logger) ``` -------------------------------- ### RejectTask Golang Client Example Source: https://github.com/cloudfoundry/bbs/blob/main/docs/024-api-tasks-internal.md Use this to reject a task. Provide the task GUID and the reason for rejection. ```go client := bbs.NewClient(url) err := client.RejectTask(logger, "task-guid", "not enough resources") if err != nil { log.Printf("could not reject task: " + err.Error()) } ``` -------------------------------- ### Upsert Domain Usage Example Source: https://github.com/cloudfoundry/bbs/blob/main/docs/050-domains.md Example of using the client to mark a domain as fresh for 60 seconds. ```go client := bbs.NewClient(url) err := client.UpsertDomain(logger, "my-domain", 60*time.Second) ``` -------------------------------- ### Start Actual LRP Instance Source: https://github.com/cloudfoundry/bbs/blob/main/docs/034-api-lrps-internal.md Use this to report to BBS that a cell has started an Actual LRP instance. Requires LRP key, instance key, network info, internal routes, and metric tags. ```go client := bbs.NewClient(url) err := client.StartActualLRP(logger, &models.ActualLRPKey{ ProcessGuid: "some-guid", Index: 0, Domain: "some-domain", }, &models.ActualLRPInstanceKey{ InstanceGuid: "some-instance-guid", CellId: "some-cellID", }, &models.ActualLRPNetInfo{ Address: "1.2.3.4", models.NewPortMapping(10,20), InstanceAddress: "2.2.2.2", }, []*models.ActualLRPInternalRoute{ {Hostname: "some-internal-route.apps.internal"}, }, map[string]string{"app_name": "some-app-name"}, ) if err != nil { log.Printf("failed to start actual lrp: " + err.Error()) } ``` -------------------------------- ### CompleteTask Golang Client Example Source: https://github.com/cloudfoundry/bbs/blob/main/docs/024-api-tasks-internal.md Use this to complete a task, specifying whether it failed, the failure reason if applicable, and the result if successful. Requires task GUID, cell ID, and status flags. ```go client := bbs.NewClient(url) err = client.CompleteTask(logger, "task-guid", "cell-1", false, "", "result") if err != nil { log.Printf("could not complete task: " + err.Error()) } ``` -------------------------------- ### POST /v1/tasks/start Source: https://github.com/cloudfoundry/bbs/blob/main/docs/024-api-tasks-internal.md Initiates the start process for a specific task. ```APIDOC ## POST /v1/tasks/start ### Description Starts a task by sending a StartTaskRequest to the BBS. ### Method POST ### Endpoint /v1/tasks/start ### Request Body - **taskGuid** (string) - Required - The GUID of the Task to start. - **cellID** (string) - Required - ID of the cell intending to start the Task. ### Response #### Success Response (200) - **shouldStart** (bool) - True if the Task should be started, false if not. ``` -------------------------------- ### Define a New Task Source: https://github.com/cloudfoundry/bbs/blob/main/docs/021-defining-tasks.md Use this to create a new task with a unique GUID, domain, and a detailed task definition. Ensure the GUID and domain are valid and non-empty. ```go client := bbs.NewClient(url) err := client.DesireTask( "task-guid", // 'guid' parameter "domain", // 'domain' parameter &models.TaskDefinition{ RootFs: "docker:///docker.com/docker", EnvironmentVariables: []*models.EnvironmentVariable{ { Name: "FOO", Value: "BAR", }, }, CachedDependencies: []*models.CachedDependency{ { Name: "app bits", From: "https://blobstore.com/bits/app-bits", To: "/usr/local/app", CacheKey: "cache-key", LogSource: "log-source", ChecksumAlgorithm: "md5", ChecksumValue: "the-checksum", }, }, ImageLayers: []*models.ImageLayer{ { Url: "https://blobstore.com/bits/other-bits", DestinationPath: "/usr/local/app/other", DigestValue: "some digest", DigestAlgorithm: models.DigestAlgorithmSha256, MediaType: models.MediaTypeTgz, LayerType: models.LayerTypeExclusive, }, }, Action: models.WrapAction(&models.RunAction{ User: "user", Path: "echo", Args: []string{"hello world"}, ResourceLimits: &models.ResourceLimits{}, }), MemoryMb: 256, DiskMb: 1024, MaxPids: 1024, CpuWeight: 42, Privileged: true, LogGuid: "123", LogSource: "APP", MetricsGuid: "456", CompletionCallbackUrl: "http://36.195.164.128:8080", ResultFile: "some-file.txt", EgressRules: []*models.SecurityGroupRule{ { Protocol: "tcp", Destinations: []string{"0.0.0.0/0"}, PortRange: &models.PortRange{ Start: 1, End: 1024, }, Log: true, }, { Protocol: "udp", Destinations: []string{"8.8.0.0/16"}, Ports: []uint32{53}, }, }, Annotation: "place any label/note/thing here", TrustedSystemCertificatesPath: "/etc/somepath", VolumeMounts: []*models.VolumeMount{ { Driver: "my-driver", ContainerPath: "/mnt/mypath", Mode: models.BindMountMode_RO, Shared: { VolumeId: "my-volume", }, }, } PlacementTags: []string{"tag-1", "tag-2"}, } ) ``` -------------------------------- ### Example: Retrieve DesiredLRPSchedulingInfos Source: https://github.com/cloudfoundry/bbs/blob/main/docs/033-api-lrps.md Demonstrates usage of the DesiredLRPSchedulingInfos client method with a domain filter. ```go client := bbs.NewClient(url) info, err := client.DesiredLRPSchedulingInfos(logger, &models.DesiredLRPFilter{ Domain: "cf-apps", }) if err != nil { log.Printf("failed to retrieve desired lrp scheduling info: " + err.Error()) } ``` -------------------------------- ### Retrieve Actual LRP Group by Process GUID and Index Source: https://github.com/cloudfoundry/bbs/blob/main/docs/033-api-lrps.md Use this method to fetch a specific ActualLRPGroup using its process GUID and instance index. Ensure you have a logger and the correct process details. ```go ActualLRPGroupByProcessGuidAndIndex(logger lager.Logger, processGuid string, index int) (*models.ActualLRPGroup, error) ``` ```go client := bbs.NewClient(url) actualLRPGroup, err := client.ActualLRPGroupByProcessGuidAndIndex(logger, "my-guid", 0) if err != nil { log.Printf("failed to retrieve actual lrps: " + err.Error()) } ``` -------------------------------- ### Retrieve ActualLRPs via Golang Client Source: https://github.com/cloudfoundry/bbs/blob/main/docs/033-api-lrps.md Defines the ActualLRPs method signature and provides a usage example for filtering ActualLRPs by domain, cell, process GUID, or index. ```go ActualLRPs(lager.Logger, models.ActualLRPFilter) ([]*models.ActualLRP, error) ``` ```go client := bbs.NewClient(url) actualLRPs, err := client.ActualLRPs(logger, &models.ActualLRPFilter{ Domain: "some-domain", CellId: "some-cell", ProcessGuid: "some-process-guid", Index: &someIndex, }) if err != nil { log.Printf("failed to retrieve actual lrps: " + err.Error()) } ``` -------------------------------- ### Retrieve DesiredLRPSchedulingInfo by Process GUID Source: https://github.com/cloudfoundry/bbs/blob/main/docs/033-api-lrps.md Defines the Golang client method signature for fetching scheduling information for a specific process GUID. ```go DesiredLRPSchedulingInfoByProcessGuid(ctx context.Context, logger lager.Logger, processGuid string) (*models.DesiredLRPSchedulingInfo, error) ``` -------------------------------- ### GET /bbs/v1/lrps / GET /bbs/v1/lrp/:process_guid Source: https://context7.com/cloudfoundry/bbs/llms.txt Retrieves DesiredLRP definitions with optional filtering. ```APIDOC ## GET /bbs/v1/lrps ### Description Retrieves a list of DesiredLRP definitions, with optional filtering by domain or process GUIDs. ### Method GET ### Endpoint /bbs/v1/lrps ### Query Parameters - **domain** (string) - Optional - Filters LRPs by the specified domain. - **process_guids** (array of strings) - Optional - Filters LRPs by the specified process GUIDs. ### Response #### Success Response (200) - **desired_lrps** (array of models.DesiredLRP) - A list of DesiredLRP objects matching the filter criteria. #### Response Example ```json [ { "process_guid": "my-web-app", "domain": "cf-apps", "root_fs": "preloaded:cflinuxfs3", "instances": 3, "memory_mb": 512, "disk_mb": 1024, "max_pids": 1024, "cpu_weight": 100, "environment_variables": [ {"name": "PORT", "value": "8080"}, {"name": "NODE_ENV", "value": "production"} ], "ports": [8080, 8443], "routes": { "cf-router": "[{\"hostnames\":[\"my-app.example.com\"],\"port\":8080}]" }, "action": { "run_action": { "user": "vcap", "path": "/app/start.sh", "resource_limits": {} } }, "start_timeout_ms": 60000, "check_definition": { "checks": [ { "http_check": { "port": 8080, "path": "/health", "request_timeout_ms": 1000, "interval_ms": 5000 } } ], "readiness_checks": [ { "http_check": { "port": 8080, "path": "/ready", "request_timeout_ms": 1000, "interval_ms": 2000 } } ] }, "log_guid": "my-web-app", "log_source": "APP", "metric_tags": { "source_id": {"static": "my-web-app"}, "instance_index": {"dynamic": "index"} }, "egress_rules": [ { "protocol": "tcp", "destinations": ["10.0.0.0/8"], "port_range": {"start": 443, "end": 443} } ] } ] ``` ## GET /bbs/v1/lrp/:process_guid ### Description Retrieves a specific DesiredLRP definition by its process GUID. ### Method GET ### Endpoint /bbs/v1/lrp/:process_guid ### Path Parameters - **process_guid** (string) - Required - The GUID of the DesiredLRP to retrieve. ### Response #### Success Response (200) - **desired_lrp** (models.DesiredLRP) - The DesiredLRP object matching the provided process GUID. #### Response Example ```json { "process_guid": "my-web-app", "domain": "cf-apps", "root_fs": "preloaded:cflinuxfs3", "instances": 3, "memory_mb": 512, "disk_mb": 1024, "max_pids": 1024, "cpu_weight": 100, "environment_variables": [ {"name": "PORT", "value": "8080"}, {"name": "NODE_ENV", "value": "production"} ], "ports": [8080, 8443], "routes": { "cf-router": "[{\"hostnames\":[\"my-app.example.com\"],\"port\":8080}]" }, "action": { "run_action": { "user": "vcap", "path": "/app/start.sh", "resource_limits": {} } }, "start_timeout_ms": 60000, "check_definition": { "checks": [ { "http_check": { "port": 8080, "path": "/health", "request_timeout_ms": 1000, "interval_ms": 5000 } } ], "readiness_checks": [ { "http_check": { "port": 8080, "path": "/ready", "request_timeout_ms": 1000, "interval_ms": 2000 } } ] }, "log_guid": "my-web-app", "log_source": "APP", "metric_tags": { "source_id": {"static": "my-web-app"}, "instance_index": {"dynamic": "index"} }, "egress_rules": [ { "protocol": "tcp", "destinations": ["10.0.0.0/8"], "port_range": {"start": 443, "end": 443} } ] } ``` ``` -------------------------------- ### POST /v1/desired_lrp_scheduling_infos/get_by_process_guid Source: https://github.com/cloudfoundry/bbs/blob/main/docs/033-api-lrps.md Retrieves the DesiredLRPSchedulingInfo for a given process GUID. ```APIDOC ## POST /v1/desired_lrp_scheduling_infos/get_by_process_guid ### Description Returns the DesiredLRPSchedulingInfo with the given process guid. ### Method POST ### Endpoint /v1/desired_lrp_scheduling_infos/get_by_process_guid ### Request Body - **process_guid** (string) - Required - The GUID of the DesiredLRPSchedulingInfo to retrieve. ### Request Example ```json { "process_guid": "some-process-guid" } ``` ### Response #### Success Response (200) - **desired_lrp_scheduling_info** (object) - The requested DesiredLRPSchedulingInfo. #### Response Example ```json { "desired_lrp_scheduling_info": { "process_guid": "some-process-guid", "domain": "some-domain", "type": "web", "index": 0, "host": "10.0.0.1", "ports": [8080], "placement_tags": ["tag1"] } } ``` ``` -------------------------------- ### StartActualLRP API Source: https://github.com/cloudfoundry/bbs/blob/main/docs/034-api-lrps-internal.md The cell calls `StartActualLRP` to report to the BBS that it has started an ActualLRP instance. This endpoint is used for reporting a started ActualLRP instance. ```APIDOC ## POST /v1/actual_lrps/start.r1 ### Description Reports to the BBS that an ActualLRP instance has started on a cell, providing its networking information and associated metadata. ### Method POST ### Endpoint /v1/actual_lrps/start.r1 ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **key** (object) - Required - The ActualLRPKey for the instance. - **processGuid** (string) - Required - The GUID of the corresponding DesiredLRP. - **index** (integer) - Required - Index of the ActualLRP. - **domain** (string) - Required - The domain of the LRP. - **instanceKey** (object) - Required - InstanceKey for the ActualLRP to start. - **instanceGuid** (string) - Required - The GUID of the instance to start. - **cellId** (string) - Required - ID of the Cell starting the ActualLRP. - **netInfo** (object) - Required - Networking information for the ActualLRP. - **address** (string) - The IP address of the instance. - **ports** (array) - An array of port mappings. - **container_port** (integer) - The port inside the container. - **host_port** (integer) - The port on the host. - **instanceAddress** (string) - The address accessible from within the cell. - **internalRoutes** (array) - An array of internal routes for the ActualLRP. - **hostname** (string) - The hostname for the internal route. - **metricTags** (object) - Key-value pairs for metric tags. ### Request Example ```json { "key": { "processGuid": "some-guid", "index": 0, "domain": "some-domain" }, "instanceKey": { "instanceGuid": "some-instance-guid", "cellId": "some-cellID" }, "netInfo": { "address": "1.2.3.4", "ports": [ { "container_port": 10, "host_port": 20 } ], "instanceAddress": "2.2.2.2" }, "internalRoutes": [ { "hostname": "some-internal-route.apps.internal" } ], "metricTags": { "app_name": "some-app-name" } } ``` ### Response #### Success Response (200) - **actualLrpGroup** (object) - Description of the ActualLRP group. - **desiredLrpDescriptor** (object) - Descriptor for the desired LRP. - **actualLrp** (object) - Details of the actual LRP. #### Response Example ```json { "actualLrpGroup": { "desiredLrpDescriptor": { "processGuid": "some-guid", "domain": "some-domain" }, "actualLrp": { "processGuid": "some-guid", "index": 0, "instanceKey": { "instanceGuid": "some-instance-guid", "cellId": "some-cellID" }, "state": "RUNNING", "netInfo": { "address": "1.2.3.4", "ports": [ { "container_port": 10, "host_port": 20 } ], "instanceAddress": "2.2.2.2" }, "logGuid": "some-log-guid", "hostKey": "some-host-key", "ports": [ { "container_port": 10, "host_port": 20 } ], "internalRoutes": [ { "hostname": "some-internal-route.apps.internal" } ], "metricTags": { "app_name": "some-app-name" } } } } ``` ``` -------------------------------- ### Egress Rule with All Protocol Source: https://github.com/cloudfoundry/bbs/blob/main/docs/054-common-models.md Example of an egress rule for the 'all' protocol. Set `Log` to true to log outgoing connections. Place rules with `Log: true` at the end of the rule list. ```go all := &SecurityGroupRule{ Protocol: "all", Destinations: []string{"1.2.3.4"}, Log: true, Annotations: []string{"sg-1234"}, } ``` -------------------------------- ### Egress Rule with UDP Protocol Source: https://github.com/cloudfoundry/bbs/blob/main/docs/054-common-models.md Example of an egress rule for the 'udp' protocol, using CIDR notation for destinations and a port range. Logging is not explicitly enabled. ```go udp := &SecurityGroupRule{ Protocol: "udp", Destinations: []string{"1.2.3.4/8"}, PortRange: { Start: 8000, End: 8085, }, } ``` -------------------------------- ### Retrieve Actual LRPs Source: https://context7.com/cloudfoundry/bbs/llms.txt Fetch information about running ActualLRP instances. Filter by process GUID, domain, cell ID, or specific instance index. ```go // Get all ActualLRPs for a specific process actualLRPs, err := client.ActualLRPs(logger, "trace-id", models.ActualLRPFilter{ ProcessGuid: "my-web-app", }) if err != nil { log.Printf("failed to retrieve actual lrps: %s", err.Error()) } for _, lrp := range actualLRPs { log.Printf("Instance %d: State=%s, Address=%s:%d, Routable=%v", lrp.Index, lrp.State, lrp.Address, lrp.Ports[0].HostPort, lrp.GetRoutable(), ) } ``` ```go // Filter by domain and cell cellLRPs, err := client.ActualLRPs(logger, "trace-id", models.ActualLRPFilter{ Domain: "cf-apps", CellID: "cell-z1-0", }) ``` ```go // Get specific instance by index index := int32(0) instanceLRPs, err := client.ActualLRPs(logger, "trace-id", models.ActualLRPFilter{ ProcessGuid: "my-web-app", Index: &index, }) ``` -------------------------------- ### Resolve Task with BBS Client Source: https://github.com/cloudfoundry/bbs/blob/main/docs/023-api-tasks.md Use this to resolve a task. Requires a logger and the task's GUID. ```go client := bbs.NewClient(url) err := client.ResolvingTask(logger, "the-task-guid") if err != nil { log.Printf("failed to resolving task: " + err.Error()) } ``` -------------------------------- ### Retrieve Tasks Source: https://context7.com/cloudfoundry/bbs/llms.txt Fetches task information from the BBS using various filters such as GUID, domain, or cell ID. ```go // List all tasks tasks, err := client.Tasks(logger, "trace-id") if err != nil { log.Printf("failed to retrieve tasks: %s", err.Error()) } for _, task := range tasks { log.Printf("Task: %s, State: %s", task.TaskGuid, task.State) } // Get a specific task by GUID task, err := client.TaskByGuid(logger, "trace-id", "my-task-guid") if err != nil { log.Printf("failed to retrieve task: %s", err.Error()) } log.Printf("Task state: %s, Result: %s", task.State, task.Result) // List tasks by domain domainTasks, err := client.TasksByDomain(logger, "trace-id", "my-domain") if err != nil { log.Printf("failed to retrieve tasks: %s", err.Error()) } // List tasks by cell ID cellTasks, err := client.TasksByCellID(logger, "trace-id", "cell-z1-0") if err != nil { log.Printf("failed to retrieve tasks: %s", err.Error()) } ``` -------------------------------- ### Egress Rule with TCP Protocol Source: https://github.com/cloudfoundry/bbs/blob/main/docs/054-common-models.md Example of an egress rule for the 'tcp' protocol, specifying destination IP range and ports. `Log` is enabled to track connections. ```go tcp := &SecurityGroupRule{ Protocol: "tcp", Destinations: []string{"1.2.3.4-2.3.4.5"}, Ports: []int{80, 443}, Log: true, } ``` -------------------------------- ### GET /actual_lrps Source: https://github.com/cloudfoundry/bbs/blob/main/docs/030-lrps.md Fetches ActualLRP instances from the Diego BBS. Supports filtering by domain, process_guid, or specific index. ```APIDOC ## GET /actual_lrps ### Description Fetches an array of ActualLRP instances. Can be filtered by domain, process_guid, or index. ### Method GET ### Endpoint /actual_lrps ### Query Parameters - **domain** (string) - Optional - Filter by domain - **process_guid** (string) - Optional - Filter by process_guid - **index** (integer) - Optional - Filter by index ### Response #### Success Response (200) - **process_guid** (string) - Identifier for the LRP - **instance_guid** (string) - Unique identifier for the instance - **cell_id** (string) - Identifier of the Diego Cell - **domain** (string) - Associated domain - **index** (integer) - Instance index - **state** (string) - Current state (UNCLAIMED, CLAIMED, RUNNING, CRASHED) - **address** (string) - Externally accessible IP - **ports** (array) - Mapping of container ports to host ports - **placement_error** (string) - Error message if placement failed - **since** (integer) - Last modified timestamp (nanoseconds) - **metric_tags** (object) - Metadata for logs and metrics - **OptionalRoutable** (object) - Contains routable status - **availability_zone** (string) - Availability zone of the cell #### Response Example [ { "process_guid": "some-process-guid", "instance_guid": "some-instance-guid", "cell_id": "some-cell-id", "domain": "some-domain", "index": 15, "state": "RUNNING", "address": "10.10.11.11", "ports": [ {"container_port": 8080, "host_port": 60001} ] } ] ``` -------------------------------- ### List Desired LRPs with Filter Source: https://github.com/cloudfoundry/bbs/blob/main/docs/033-api-lrps.md Retrieves a list of DesiredLRPs matching the provided filter. The filter can specify a domain and/or a list of process GUIDs. ```go DesiredLRPs(logger lager.Logger, filter models.DesiredLRPFilter) ([]*models.DesiredLRP, error) ``` ```go client := bbs.NewClient(url) desiredLRPS, err := client.DesiredLRPs(logger, &models.DesiredLRPFilter{ Domain: "cf-apps", }) if err != nil { log.Printf("failed to retrieve desired lrps: " + err.Error()) } ``` -------------------------------- ### Egress Rule with ICMP Protocol Source: https://github.com/cloudfoundry/bbs/blob/main/docs/054-common-models.md Example of an egress rule for the 'icmp' protocol, specifying multiple destinations and ICMP type/code information. Logging is not explicitly enabled. ```go icmp := &SecurityGroupRule{ Protocol: "icmp", Destinations: []string{"1.2.3.4", "2.3.4.5/6"}, IcmpInfo: { Type: 1, Code: 40, }, } ``` -------------------------------- ### GET /v1/cells/list.r1 Source: https://github.com/cloudfoundry/bbs/blob/main/docs/012-api-cells.md Deprecated endpoint to retrieve a list of cell presences via a GET request. ```APIDOC ## GET /v1/cells/list.r1 ### Description Deprecated endpoint to retrieve a list of cell presences. ### Method GET ### Endpoint /v1/cells/list.r1 ### Response #### Success Response (200) - **CellsResponse** (object) - A collection of cell presence information. ``` -------------------------------- ### Instantiate TryAction Source: https://github.com/cloudfoundry/bbs/blob/main/docs/053-actions.md Instantiate a TryAction, providing the action to wrap and an optional log source for tagging logs. ```go action := &model.TryAction{ Action: differentAction, LogSource: "some-log-source", } ``` -------------------------------- ### Initialize a BBS Client Source: https://context7.com/cloudfoundry/bbs/llms.txt Establishes a secure TLS connection to the BBS server and verifies connectivity using the Ping method. ```go import ( "code.cloudfoundry.org/bbs" "code.cloudfoundry.org/lager/v3" ) // Create a secure client with TLS certificates client, err := bbs.NewClient( "https://bbs.service.cf.internal:8889", "/var/vcap/jobs/bbs/config/certs/ca.crt", "/var/vcap/jobs/bbs/config/certs/client.crt", "/var/vcap/jobs/bbs/config/certs/client.key", 0, // clientSessionCacheSize 0, // maxIdleConnsPerHost ) if err != nil { log.Fatalf("failed to create bbs client: %s", err.Error()) } // Create a logger logger := lager.NewLogger("my-app") // Verify connectivity if client.Ping(logger, "trace-id") { log.Println("BBS server is reachable") } ``` -------------------------------- ### Desire a Task Source: https://github.com/cloudfoundry/bbs/blob/main/docs/022-task-examples.md Use this to create and schedule a new task. Ensure the TaskDefinition includes all necessary parameters like RootFs, DiskMb, MemoryMb, and the Action to be performed. ```go client := bbs.NewClient("http://10.244.16.2:8889") err = client.DesireTask( "some-guid", "some-domain", &models.TaskDefinition{ RootFs: "docker:///busybox", DiskMb: 1024, MemoryMb: 1024, MaxPids: 1024, CpuWeight: 42, Action: models.WrapAction(&models.RunAction{ User: "root", Path: "sh", Args: []string{"-c", "echo hello world > result-file.txt"}, ResourceLimits: &models.ResourceLimits{}, }), CompletionCallbackUrl: "http://10.244.16.6:7890", ResultFile: "result-file.txt", }, ) ``` -------------------------------- ### Retrieve Desired LRPs Source: https://context7.com/cloudfoundry/bbs/llms.txt Fetch DesiredLRP definitions using filtering options. You can list all LRPs in a domain, filter by specific process GUIDs, or retrieve a single LRP by its GUID. ```go // List all DesiredLRPs in a domain desiredLRPs, err := client.DesiredLRPs(logger, "trace-id", models.DesiredLRPFilter{ Domain: "cf-apps", }) if err != nil { log.Printf("failed to retrieve desired lrps: %s", err.Error()) } for _, lrp := range desiredLRPs { log.Printf("LRP: %s, Instances: %d", lrp.ProcessGuid, lrp.Instances) } ``` ```go // Filter by specific process GUIDs filteredLRPs, err := client.DesiredLRPs(logger, "trace-id", models.DesiredLRPFilter{ ProcessGuids: []string{"app-guid-1", "app-guid-2"}, }) ``` ```go // Get a specific DesiredLRP by process GUID desiredLRP, err := client.DesiredLRPByProcessGuid(logger, "trace-id", "my-web-app") if err != nil { log.Printf("failed to retrieve desired lrp: %s", err.Error()) } log.Printf("LRP %s has %d instances", desiredLRP.ProcessGuid, desiredLRP.Instances) ``` -------------------------------- ### Configure a DownloadAction Source: https://github.com/cloudfoundry/bbs/blob/main/docs/053-actions.md Use DownloadAction to fetch an archive from a URL and extract it into a container. Specify the source URL, destination path, user, and optional parameters like artifact name, cache key, log source, and checksums for validation. ```go action := &models.DownloadAction{ From: "http://some/endpoint", To: "/some/container/path", User: "username", Artifact: "download name", CacheKey: "some-cache-key", LogSource: "some-log-source", ChecksumAlgorithm: "md5", ChecksumValue: "some-checksum-value", } ``` -------------------------------- ### Implement Task Callback Handler Source: https://context7.com/cloudfoundry/bbs/llms.txt Set up an HTTP endpoint to receive and process task completion callbacks from the BBS. ```go import ( "encoding/json" "io/ioutil" "net/http" ) func taskCallbackHandler(w http.ResponseWriter, r *http.Request) { data, err := ioutil.ReadAll(r.Body) if err != nil { http.Error(w, "failed to read body", http.StatusBadRequest) return } var response models.TaskCallbackResponse if err := json.Unmarshal(data, &response); err != nil { http.Error(w, "invalid json", http.StatusBadRequest) return } log.Printf("Task %s completed", response.TaskGuid) log.Printf(" Failed: %v", response.Failed) log.Printf(" Failure Reason: %s", response.FailureReason) log.Printf(" Result: %s", response.Result) log.Printf(" Annotation: %s", response.Annotation) w.WriteHeader(http.StatusOK) } http.HandleFunc("/task-callback", taskCallbackHandler) http.ListenAndServe(":8080", nil) ``` -------------------------------- ### POST /v1/tasks/get_by_task_guid.r3 Source: https://github.com/cloudfoundry/bbs/blob/main/docs/023-api-tasks.md Retrieves a specific task by its GUID. ```APIDOC ## POST /v1/tasks/get_by_task_guid.r3 ### Description Retrieves a specific task by its GUID. ### Method POST ### Endpoint /v1/tasks/get_by_task_guid.r3 ### Parameters #### Request Body - **taskGuid** (string) - Required - The GUID of the task to retrieve. ### Request Example ```json { "taskGuid": "some-task-guid" } ``` ### Response #### Success Response (200) - **task** (object) - The task object. - **guid** (string) - The GUID of the task. - **name** (string) - The name of the task. - **state** (string) - The current state of the task. - **domain** (string) - The domain of the task. - **cell_id** (string) - The ID of the cell the task is running on. - **creation_time** (string) - The timestamp when the task was created. - **start_time** (string) - The timestamp when the task started. - **end_time** (string) - The timestamp when the task ended. - **result** (object) - The result of the task if completed or failed. #### Response Example ```json { "task": { "guid": "some-task-guid", "name": "my-task", "state": "COMPLETED", "domain": "production", "cell_id": "cell-abc", "creation_time": "2023-10-27T10:00:00Z", "start_time": "2023-10-27T10:05:00Z", "end_time": "2023-10-27T10:10:00Z", "result": { "failure_reason": null } } } ``` ``` -------------------------------- ### Define a New LRP Source: https://github.com/cloudfoundry/bbs/blob/main/docs/031-defining-lrps.md Use this to define a new LRP with various configuration options. Ensure all required fields are populated correctly. ```go client := bbs.NewClient(url) err := client.DesireLRP(logger, &models.DesiredLRP{ ProcessGuid: "some-guid", Domain: "some-domain", RootFs: "some-rootfs", Instances: 1, EnvironmentVariables: []*models.EnvironmentVariable{{Name: "FOO", Value: "bar"}}, CachedDependencies: []*models.CachedDependency{ { Name: "app bits", From: "blobstore.com/bits/app-bits", To: "/usr/local/app", CacheKey: "cache-key", LogSource: "log-source" }, { Name: "app bits with checksum", From: "blobstore.com/bits/app-bits-checksum", To: "/usr/local/app-checksum", CacheKey: "cache-key", LogSource: "log-source", ChecksumAlgorithm: "md5", ChecksumValue: "checksum-value" }, }, ImageLayers: []*models.ImageLayer{ { Url: "https://blobstore.com/bits/other-bits", DestinationPath: "/usr/local/app/other", DigestValue: "some digest", DigestAlgorithm: models.DigestAlgorithmSha256, MediaType: models.MediaTypeTgz, LayerType: models.LayerTypeExclusive, }, }, Setup: models.WrapAction(&models.RunAction{Path: "ls", User: "name"}), Action: models.WrapAction(&models.RunAction{Path: "ls", User: "name"}), StartTimeoutMs: 15000, Monitor: models.WrapAction(models.EmitProgressFor( models.Timeout( &models.RunAction{ Path: "ls", User: "name" }, 10*time.Second, ), "start-message", "success-message", "failure-message", )), DiskMb: 512, MaxPids: 1024, MemoryMb: 1024, Privileged: true, CpuWeight: 42, Ports: []uint32{8080, 9090}, Routes: &models.Routes{"my-router": json.RawMessage(`{"foo":"bar"}`)}, LogSource: "some-log-source", LogGuid: "some-log-guid", Annotation: "some-annotation", Network: &models.Network{ Properties: map[string]string{ "some-key": "some-value", "some-other-key": "some-other-value", }, }, EgressRules: []*models.SecurityGroupRule{{ Protocol: models.TCPProtocol, Destinations: []string{"1.1.1.1/32", "2.2.2.2/32"}, PortRange: &models.PortRange{Start: 10, End: 16000}, }}, ModificationTag: &models.NewModificationTag("epoch", 0), LegacyDownloadUser: "legacy-dan", TrustedSystemCertificatesPath: "/etc/somepath", VolumeMounts: []*models.VolumeMount{ { Driver: "my-driver", ContainerPath: "/mnt/mypath", Mode: models.BindMountMode_RO, Shared: { VolumeId: "my-volume", }, }, }, PlacementTags: []string{"example-tag", "example-tag-2"}, CheckDefinition: &models.CheckDefinition{ Checks: []*models.Check{ { TcpCheck: &models.TCPCheck{ Port: 54321, ConnectTimeoutMs: 100 RequestTimeoutMs: 100, IntervalMs: 500, }, }, }, LogSource: "health-check", ReadinessChecks: []*models.Check{ { HttpCheck: &models.HTTPCheck{ Port: 12345, Path: "/some/path", RequestTimeoutMs: 100, IntervalMs: 500, }, }, }, }, MetricTags: map[string]*models.MetricTagValue{ "source_id": &models.MetricTagValue{ Static: "some-source-id", }, "instance_index": &models.MetricTagValue{ Dynamic: models.MetricTagDynamicValueIndex, }, }, }) ``` -------------------------------- ### POST /v1/tasks/cancel Source: https://github.com/cloudfoundry/bbs/blob/main/docs/023-api-tasks.md Cancels the task with the given task GUID. ```APIDOC ## POST /v1/tasks/cancel ### Description Cancels the task with the given task GUID. ### Method POST ### Endpoint /v1/tasks/cancel ### Parameters #### Request Body - **taskGuid** (string) - Required - The GUID of the task to cancel. ### Request Example ```json { "taskGuid": "some-task-guid" } ``` ### Response #### Success Response (200) - No content is returned on successful cancellation. #### Response Example (No response body) ``` -------------------------------- ### Receive LRPCallbackResponse Source: https://github.com/cloudfoundry/bbs/blob/main/docs/032-lrp-examples.md Sets up an HTTP handler to process callback responses from Diego. ```go func taskCallbackHandler(w http.ResponseWriter, r *http.Request) { var taskResponse models.LRPCallbackResponse data, err := ioutil.ReadAll(r.Body) if err != nil { log.Printf("failed to read task response") panic(err) } err = json.Unmarshal(data, &taskResponse) if err != nil { log.Printf("failed to unmarshal json") panic(err) } log.Printf("here's the result from your LRPCallbackResponse:\n %s\n\n", taskResponse.Result) } http.HandleFunc("/", taskCallbackHandler) go http.ListenAndServe("7890", nil) ``` -------------------------------- ### Remove a DesiredLRP Source: https://github.com/cloudfoundry/bbs/blob/main/docs/032-lrp-examples.md Removes a DesiredLRP from the system by its process GUID. ```go client := bbs.NewClient(url) err := client.RemoveDesiredLRP(logger, "some-process-guid") if err != nil { log.Printf("failed to remove desired lrp: " + err.Error()) } ``` -------------------------------- ### Docker Image Root Filesystem Source: https://github.com/cloudfoundry/bbs/blob/main/docs/021-defining-tasks.md Define the root filesystem using a Docker image. Specify the image URI, optionally including a tag. For non-Docker Hub registries, include the registry host in the URI. ```go RootFs: "docker:///docker-org/docker-image#docker-tag" ``` ```go RootFs: "docker://index.myregistry.gov/docker-org/docker-image#docker-tag" ``` -------------------------------- ### Subscribe to ActualLRP Instance Events Source: https://context7.com/cloudfoundry/bbs/llms.txt Subscribes to real-time events for ActualLRP instance lifecycle changes. Handles creation, changes, removal, and crashes. ```go eventSource, err := client.SubscribeToInstanceEvents(logger) if err != nil { log.Printf("failed to subscribe to events: %s", err.Error()) } defer eventSource.Close() for { event, err := eventSource.Next() if err != nil { if err == events.ErrSourceClosed { log.Println("event source closed, resubscribing...") break } log.Printf("error getting event: %s", err.Error()) continue } switch event.EventType() { case models.EventTypeActualLRPInstanceCreated: created := event.(*models.ActualLRPInstanceCreatedEvent) log.Printf("LRP created: %s index %d", created.ActualLrp.ProcessGuid, created.ActualLrp.Index) case models.EventTypeActualLRPInstanceChanged: changed := event.(*models.ActualLRPInstanceChangedEvent) log.Printf("LRP changed: %s from %s to %s", changed.Before.ProcessGuid, changed.Before.State, changed.After.State) case models.EventTypeActualLRPInstanceRemoved: removed := event.(*models.ActualLRPInstanceRemovedEvent) log.Printf("LRP removed: %s index %d", removed.ActualLrp.ProcessGuid, removed.ActualLrp.Index) case models.EventTypeActualLRPCrashed: crashed := event.(*models.ActualLRPCrashedEvent) log.Printf("LRP crashed: %s reason: %s, crash count: %d", crashed.ActualLRPKey.ProcessGuid, crashed.CrashReason, crashed.CrashCount) } } ``` -------------------------------- ### Update a DesiredLRP Source: https://github.com/cloudfoundry/bbs/blob/main/docs/033-api-lrps.md Updates an existing DesiredLRP identified by its process GUID. ```go UpdateDesiredLRP(logger lager.Logger, processGuid string, update *models.DesiredLRPUpdate) error ``` ```go client := bbs.NewClient(url) instances := 4 annotation := "My annotation" err := client.UpdateDesiredLRP(logger, "some-process-guid", &models.DesiredLRPUpdate{ Instances: &instances, MetricTags: map[string]*models.MetricTagValue{"source_id": {Static: "some-guid"}}, Routes: &models.Routes{}, Annotation: &annotation, }) if err != nil { log.Printf("failed to update desired lrp: " + err.Error()) } ``` -------------------------------- ### Configure a RunAction Source: https://github.com/cloudfoundry/bbs/blob/main/docs/053-actions.md Use RunAction to execute a process within a container. Specify the executable path, arguments, working directory, user, environment variables, and resource limits. Logs are emitted to the logging system, including the exit status. ```go action := &models.RunAction{ Path: "/path/to/executable", Args: []string{"some", "args to", "pass in"}, Dir: "/path/to/working/directory", User: "username", EnvironmentVariables: []*models.EnvironmentVariable{ { Name: "ENVNAME", Value: "ENVVALUE", }, }, ResourceLimits: &models.ResourceLimits{ Nofile: 1000, }, LogSource: "some-log-source", SuppressLogOutput: false, } ``` -------------------------------- ### CancelTask Golang Client Method Source: https://github.com/cloudfoundry/bbs/blob/main/docs/023-api-tasks.md Cancels a task identified by its GUID. ```go func (c *client) CancelTask(logger lager.Logger, taskGuid string) error ```