<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Xiang Shen on Medium]]></title>
        <description><![CDATA[Stories by Xiang Shen on Medium]]></description>
        <link>https://medium.com/@shenxiang_96447?source=rss-aaed0024dcd7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1xPRqqh2dKbDKgq4cahqcg.jpeg</url>
            <title>Stories by Xiang Shen on Medium</title>
            <link>https://medium.com/@shenxiang_96447?source=rss-aaed0024dcd7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 21:58:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shenxiang_96447/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Custom ADK Agent using OAuth on Google Agentspace: A ServiceNow Example]]></title>
            <link>https://medium.com/google-cloud/custom-adk-agent-using-oauth-on-google-agentspace-a-servicenow-example-ef1fc3fdc66c?source=rss-aaed0024dcd7------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef1fc3fdc66c</guid>
            <category><![CDATA[servicenow]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[google-agentspace]]></category>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[agentspace]]></category>
            <dc:creator><![CDATA[Xiang Shen]]></dc:creator>
            <pubDate>Mon, 06 Oct 2025 04:00:24 GMT</pubDate>
            <atom:updated>2026-02-12T02:51:39.099Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>This guide provides a technical overview for developers on how to integrate a Google ADK agent running on Agentspace with third-party tools using the OAuth 2.0 Authorization Code flow. While this document uses ServiceNow as a specific example, the principles and practices described herein are applicable to a wide range of third-party applications. This method ensures secure access to external APIs on a user’s behalf without directly handling their credentials. Instead, a Google Cloud Authorization resource manages the OAuth flow and token lifecycle, simplifying a key challenge in building such integrations.</p><p>Managing OAuth 2.0 authentication differs significantly between local development and production environments. Locally, with tools like <strong>adk web</strong>, the ADK framework can initiate the OAuth 2.0 flow, but developers are responsible for configuring client ID, client secret, and managing redirect URIs.</p><p>In a cloud environment, specifically on Agent Engine with Agentspace, the platform handles the entire OAuth 2.0 token lifecycle. A dedicated Google Cloud Authorization resource securely stores client credentials, abstracting this complexity. The Agent Engine then injects the access token into the agent’s <strong>tool_context</strong> at runtime, making it available for API calls to the third-party tool.</p><p><strong>Note:</strong> This document focuses on the OAuth integration pattern for custom ADK agents, using ServiceNow as a practical example. The Agentspace connectors and its specific actions are outside the scope of this guide. For a visual demonstration of the concepts in action, please view <a href="https://www.youtube.com/watch?v=oos0Jrto9N4">this screencast</a>. A complete code example illustrating the ServiceNow integration is available on the ‘oauth’ branch of<a href="https://github.com/xiangshen-dk/servicenow_agent/tree/oauth"> this repository</a>.</p><h3>Architecture and Core Concepts</h3><p>The high-level process involves several steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mpnxePbXgcLWYixWhV2i-w.png" /></figure><ol><li><strong>User Request</strong>: A user sends a prompt to the ADK agent requiring ServiceNow access.</li><li><strong>Tool Call</strong>: The ADK agent, running on Google Agent Engine, identifies the need to interact with ServiceNow via a tool.</li><li><strong>Authorization Check</strong>: The Agent Engine verifies the agent’s configuration in Agentspace, detecting the linked Authorization resource and the requirement for OAuth.</li><li><strong>OAuth Flow Initiation</strong>: If no valid access token exists, the Agent Engine initiates the OAuth 2.0 Authorization Code flow, redirecting the user to ServiceNow for login and permission granting.</li><li><strong>Authorization Code</strong>: Upon user consent, ServiceNow redirects the user back to <a href="https://vertexaisearch.cloud.google.com/oauth-redirect">https://vertexaisearch.cloud.google.com/oauth-redirect</a> with a short-lived authorization code.</li><li><strong>Token Exchange</strong>: The Authorization resource exchanges this code with ServiceNow’s token endpoint for an access token and a refresh token. The sensitive refresh token is securely managed by Google Cloud infrastructure.</li><li><strong>Token Injection</strong>: The Agent Engine receives the access token and injects it into the agent’s tool_context under a dynamically constructed key using the AUTH_ID.</li><li><strong>Authenticated API Call</strong>: The agent’s tool code retrieves the access token from the context using the AUTH_ID key, then uses it to make a secure, authenticated API call to ServiceNow.</li><li><strong>Response</strong>: ServiceNow processes the request and returns data to the agent, which then formulates the final response for the user.</li></ol><h3>Configuration and Deployment</h3><p>The entire process has the following three main steps: ServiceNow configuration, code change, and deployment.</p><h3>Step 1: ServiceNow OAuth Application Setup</h3><p>Before deployment, you must manually configure an OAuth application in ServiceNow to obtain a Client ID and Client Secret.</p><p>To enable OAuth 2.0 for inbound integrations, ensure the <strong>OAuth 2.0 plugin</strong> is active and the property is set to true.</p><p><strong>Check Plugin Activation Status:</strong></p><ul><li>Navigate to System Definition &gt; Plugins in your ServiceNow instance.</li><li>Search for “OAuth” and verify the status of “OAuth 2.0” or similar plugins; it should be “Active” or “In Product.”</li></ul><p><strong>Verify System Property:</strong></p><ul><li>Type <strong>sys_properties.list</strong> in the filter bar and hit return.</li><li>Search for <strong>com.snc.platform.security.oauth.is.active</strong> and ensure its value is true.</li></ul><p>Subsequently, create a new inbound integration for OAuth to generate the <strong>Client ID</strong> and <strong>Client Secret</strong>:</p><ol><li>Access your ServiceNow instance with administrator privileges.</li><li>Navigate to System OAuth and select <strong>Inbound Integrations</strong>.</li><li>Click <strong>New integration</strong> and choose <strong>OAuth — Authorization code grant</strong>.</li><li>Provide a unique and descriptive name.</li><li>Set the Redirect URL to <a href="https://vertexaisearch.cloud.google.com/oauth-redirect.">https://vertexaisearch.cloud.google.com/oauth-redirect.</a></li><li>(Optional) Add auth scopes. If added, your agent must provide them during authorization.</li><li>Submit the form; ServiceNow will automatically generate the Client ID and Client Secret.</li><li>Copy these credentials for agent application configuration.</li></ol><h3>Step 2: Update the Agent Code to Use the Token</h3><p>You need to update your agent code to retrieve the access token required to access ServiceNow. The <strong>AUTH_ID</strong> is the key identifier that facilitates this process.</p><p>As previously stated, the AUTH_ID is a user-defined identifier for an authorization resource within Agentspace. This identifier is crucial for integrating agents with services that require OAuth 2.0.</p><p>For example, in the authorization resource shown below (created within a Google Cloud project), the AUTH_ID is <strong>auth-servicenow-test1</strong>.</p><pre>{<br>  &quot;name&quot;: &quot;projects/xxxx/locations/global/authorizations/auth-servicenow-test1&quot;,<br>  &quot;serverSideOauth2&quot;: {<br>    &quot;clientId&quot;: &quot;17f5af8f6xxxxxxxf361a76451cf&quot;,<br>    &quot;clientSecret&quot;: &quot;GHxxxxxxxxxxx1&quot;,<br>    &quot;tokenUri&quot;: &quot;https://&lt;your-servicenow-instance&gt;.service-now.com/oauth_token.do&quot;,<br>    &quot;authorizationUri&quot;: &quot;https://&lt;your-servicenow-instance&gt;.service-now.com/oauth_auth.do?response_type=code&amp;access_type=offline&amp;prompt=consent&quot;<br>  }<br>}</pre><p>The AUTH_ID can be any arbitrary string; however, there are two important considerations. First, the value <strong>should be unique</strong> for each redeployment of the agent and its authorization resource to prevent cached values from causing unexpected behavior. Second, this identifier will be visible during authorization prompts (see example below), so it should be chosen carefully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L0NqnLI2Vnpw79WvXaMiBw.png" /></figure><p>When an agent is registered in Agentspace, the AUTH_ID links it to a specific Authorization resource. This resource securely stores the necessary OAuth credentials, such as the client ID and secret. The example below shows a registered agent in Agentspace that is linked to an authorization resource via an AUTH_ID.</p><pre>{<br>  &quot;name&quot;: &quot;projects/xxxx/locations/global/collections/default_collection/engines/servicenow-test1_1758871894285/assistants/default_assistant/agents/4295369533393746166&quot;,<br>  &quot;displayName&quot;: &quot;ServiceNow Agent OAuth&quot;,<br>  &quot;description&quot;: &quot;An AI agent for managing ServiceNow records through natural language&quot;,<br>  &quot;createTime&quot;: &quot;2025-09-27T03:55:40.574458390Z&quot;,<br>  &quot;adkAgentDefinition&quot;: {<br>    &quot;toolSettings&quot;: {<br>      &quot;toolDescription&quot;: &quot;A tool to perform Create, Read, Update, and Delete operations on ServiceNow records.&quot;<br>    },<br>    &quot;provisionedReasoningEngine&quot;: {<br>      &quot;reasoningEngine&quot;: &quot;projects/xxxx/locations/us-central1/reasoningEngines/535528133424578560&quot;<br>    },<br>    &quot;authorizations&quot;: [<br>      &quot;projects/xxxx/locations/global/authorizations/auth-servicenow-test1-09262005-2&quot;<br>    ]<br>  },<br>  &quot;state&quot;: &quot;ENABLED&quot;<br>}</pre><p>At runtime, when the agent needs to make an authenticated API call, the Agent Engine uses the AUTH_ID to retrieve the corresponding access token and injects it into the agent’s <strong>tool_context</strong>. The agent’s code can then access this token from the context to make secure, authorized requests to the external service.</p><p>In the following example, the <strong>auth_id</strong> variable holds a value such as auth-servicenow-test1–09262005–2.</p><pre>access_token = tool_context.state.get(auth_id)<br># Note: In old versions of ADK, you need to have &#39;temp:&#39; as the prefix<br># For example: tool_context.state[f&quot;temp:{auth_id}&quot;]</pre><p>For a complete example of how the access token is retrieved and used in an agent, refer to <a href="https://github.com/xiangshen-dk/servicenow_agent/blob/oauth/snow_agent/servicenow_tool.py">this file</a>.</p><h3>Step 3: Deployment</h3><p>The deployment process involves three key steps, as demonstrated in <a href="https://github.com/xiangshen-dk/servicenow_agent/tree/oauth">this repository</a>:</p><ol><li><strong>Deploy Agent to Agent Engine (deploy_to_agent_engine.py):</strong> This script packages and deploys the ADK agent to the Vertex AI Agent Engine, passing necessary environment variables, including the AUTH_ID. It outputs a unique Reasoning Engine URI.</li><li><strong>Create the Google CloudAuthorization resource (scripts/create_authorization.sh):</strong> This script uses the Google Cloud SDK and a REST API call to create an Authorization resource, securely storing <strong>SERVICENOW_CLIENT_ID</strong> and <strong>SERVICENOW_CLIENT_SECRET</strong> from the <strong>.env</strong> file.</li><li><strong>Link Agent in Agentspace (scripts/create_or_patch_agent.sh):</strong> This script creates or updates an agent definition in Agentspace, linking the Reasoning Engine URI and associating the agent with the Authorization resource using the project number and AUTH_ID. This informs the Agent Engine that tool calls from this agent require OAuth.</li></ol><h3>Runtime Execution Flow</h3><p>Once deployed, the agent can make authenticated calls to ServiceNow.</p><h3>1. Initiating a Tool Call</h3><p>When a user’s prompt triggers the ServiceNow tool, the Agent Engine intervenes. Due to the agent’s linkage to an Authorization resource in Agentspace, the runtime knows an access token is required.</p><h3>2. Token Injection</h3><p>The Agent Engine transparently handles the entire OAuth 2.0 flow. It uses a valid, cached access token if available; otherwise, it initiates the authorization flow. Upon successful authorization, the engine injects the short-lived <strong>access_token</strong> into the tool_context object.</p><pre># From snow_agent/servicenow_tool.py<br>async def servicenow_crud(<br>    # ... args<br>    tool_context: ToolContext,<br>    # ... other args<br>) -&gt; Dict[str, Any]:<br>    agent_settings = AgentSettings()<br>    access_token = tool_context.state.get(f&quot;temp:{agent_settings.auth_id}&quot;)<br>    if not access_token:<br>        # Handle error</pre><h3>3. Authenticated API Call</h3><p>The retrieved <strong>access_token</strong> is passed to a <strong>ServiceNowClient</strong>, which includes the token in the <strong>Authorization</strong> header of the HTTP request to the ServiceNow API, completing the secure call.</p><pre># From snow_agent/servicenow_client.py<br>def _get_auth_headers(self, access_token: str) -&gt; Dict[str, str]:<br>    &quot;&quot;&quot;Get headers for authentication.&quot;&quot;&quot;<br>    return {<br>        &quot;Authorization&quot;: f&quot;Bearer {access_token}&quot;,<br>        &quot;Accept&quot;: &quot;application/json&quot;,<br>        &quot;Content-Type&quot;: &quot;application/json&quot;,<br>    }</pre><h3>Token Management</h3><p>The Agent Engine runtime is solely responsible for managing the token lifecycle, including:</p><ul><li>Securely storing the <strong>refresh_token</strong>.</li><li>Using the <strong>refresh_token</strong> to obtain new <strong>access_tokens</strong> when old ones expire.</li><li>Caching tokens for optimized performance.</li></ul><p>The ADK agent code does not need to implement any token refresh logic; it is always provided with a valid <strong>access_token</strong> for each tool call.</p><h3>Conclusion</h3><p>While this approach requires initial setup and additional development effort, it offers significant security and operational advantages:</p><p><strong>Enhanced Secret Management:</strong> Critical credentials, like the ServiceNow Client ID and Secret, are stored securely within a dedicated Authorization resource, keeping them entirely separate from the agent’s code, configuration, and environment variables.</p><p><strong>Improved Token Isolation:</strong> The agent exclusively handles short-lived access tokens, delegating the management of the more sensitive refresh token to Google Cloud’s robust and secure infrastructure. This separation minimizes the agent’s exposure to long-term credentials.</p><p><strong>Adherence to the Principle of Least Privilege:</strong> Through the OAuth process and the use of scopes, access for third-party applications is better controlled and monitored, ensuring they only receive the permissions they absolutely need.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef1fc3fdc66c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/custom-adk-agent-using-oauth-on-google-agentspace-a-servicenow-example-ef1fc3fdc66c">Custom ADK Agent using OAuth on Google Agentspace: A ServiceNow Example</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serverless Application Authorization Using Google Cloud Load Balancer Service Extensions]]></title>
            <link>https://medium.com/google-cloud/serverless-application-authorization-using-google-cloud-load-balancer-service-extensions-39ca3d1ad84a?source=rss-aaed0024dcd7------2</link>
            <guid isPermaLink="false">https://medium.com/p/39ca3d1ad84a</guid>
            <category><![CDATA[load-balancing]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[google-cloud-run]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Xiang Shen]]></dc:creator>
            <pubDate>Mon, 31 Mar 2025 02:08:09 GMT</pubDate>
            <atom:updated>2025-06-30T19:03:51.771Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>A common method for securing Google Cloud serverless applications (<a href="https://cloud.google.com/run">Cloud Run</a>, <a href="https://cloud.google.com/appengine">App Engine</a>, or <a href="https://cloud.google.com/functions">Cloud Run functions</a>) involves using a load balancer with <a href="https://cloud.google.com/security/products/iap">Identity-Aware Proxy</a> (IAP). IAP is enabled on the load balancer’s backend service, which points to a <a href="https://cloud.google.com/load-balancing/docs/negs/serverless-neg-concepts">serverless NEG</a>. IAP then intercepts requests, authenticates users (typically via Google Accounts), and verifies the IAM role, controlling access before it reaches the application.</p><p>Google Cloud Load Balancer’s new <a href="https://cloud.google.com/service-extensions/docs/overview">service extension feature</a> supports additional authorization capabilities, running after IAP as shown in the following diagram.</p><figure><img alt="Global external Application Load Balancers support extensions in the application security and traffic management stages" src="https://cdn-images-1.medium.com/max/788/0*hWoFSAqtB7wR7P2g" /><figcaption><em>Global external Application Load Balancers support extensions in the application security and traffic management stages</em></figcaption></figure><p>This tutorial demonstrates how to build an authorization extension, deployed on Cloud Run, for authorizing access to other serverless services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/0*43bebFma5VfH4J2g" /></figure><p><strong>Note</strong>: Service extensions include plugins and callouts. As or 03/2025, only callout authorization extensions are supported on Application Load Balancers. Refer to the official documentation for <a href="https://cloud.google.com/service-extensions/docs/lb-extensions-overview#supported-lbs">supported Application Load Balancer service extensions</a> for details.</p><h3>Implementation</h3><h4>Prerequisites</h4><p><strong>GCP Project:</strong> You need an active Google Cloud project.</p><p><strong>gcloud SDK:</strong> The <strong>gcloud</strong> command-line tool must be installed and configured.</p><p><strong>Billing Enabled:</strong> Billing must be enabled for your project.</p><p><strong>APIs Enabled:</strong> Enable the following APIs:</p><ul><li>Compute Engine API</li><li>Cloud Run API</li><li>Artifact Registry API</li><li>Certificate Manager API</li><li>Network Services API</li><li>Network Security API</li></ul><p>In this tutorial, we run all the commands in <a href="https://cloud.google.com/shell/docs">Cloud Shell</a>.</p><pre># Set variables. Replace with your values<br>export PROJECT_ID=&quot;your GCP project id&quot;<br>export REGION=&quot;us-central1&quot;<br># Use your own domain and DNS zone<br># If you don&#39;t own a domain, consider use services such as sslip.io or nip.io<br>export DOMAIN=&quot;democloud.info&quot;<br>export DNS_ZONE=&quot;democloud&quot;<br>export DNS_NAME=&quot;cr-example.${DOMAIN}&quot;<br><br># Set the project<br>gcloud config set project $PROJECT_ID<br># Enable the needed APIs<br>gcloud services enable \<br> compute.googleapis.com \<br> run.googleapis.com \<br> artifactregistry.googleapis.com \<br> certificatemanager.googleapis.com \<br> networkservices.googleapis.com \<br> networksecurity.googleapis.com</pre><h4>Create the sample service</h4><p><strong>Deploy the sample service</strong></p><p>In this tutorial, we deploy the default <strong>HelloWorld</strong> container to Cloud Run as our sample service.</p><pre>gcloud run deploy helloworld \<br> --image=us-docker.pkg.dev/cloudrun/container/hello \<br> --region=${REGION} \<br> --allow-unauthenticated \<br> --ingress internal-and-cloud-load-balancing</pre><p><strong>Create the Load Balancer Components</strong></p><p>This involves several steps: creating a backend service, a URL map, a target HTTPS proxy, and a forwarding rule.</p><p><strong>1. Reserve a static external IP address for the load balancer</strong></p><pre>gcloud compute addresses create example-ip \<br> --network-tier=PREMIUM \<br> --ip-version=IPV4 \<br> --global</pre><p><strong>2. Create a DNS record</strong></p><p>Here we use Google <a href="https://cloud.google.com/dns">Cloud DNS</a> in the same project. If you have another DNS service, configure the DNS name there accordingly.</p><p>Get the IP address from the previous command:</p><pre>IP=$(gcloud compute addresses describe example-ip \<br> --format=&quot;get(address)&quot; \<br> --global)</pre><p>Create the DNS record in the DNS zone:</p><pre>gcloud dns --project=${PROJECT_ID} record-sets create ${DNS_NAME}. --zone=&quot;${DNS_ZONE}&quot; \<br>  --type=&quot;A&quot; --ttl=&quot;300&quot; --rrdatas=&quot;$IP&quot;</pre><p><strong>3. Create a Serverless NEG</strong></p><pre>gcloud compute network-endpoint-groups create helloworld-neg \<br> --network-endpoint-type=serverless \<br> --cloud-run-service=helloworld \<br> --region=${REGION}</pre><p><strong>4. Create a Backend Service</strong></p><pre>gcloud compute backend-services create helloworld-backend \<br> --global \<br> --load-balancing-scheme=EXTERNAL_MANAGED</pre><p><strong>5. Add the serverless NEG to the Backend Service</strong></p><pre>gcloud compute backend-services add-backend helloworld-backend \<br> --global \<br> --network-endpoint-group=helloworld-neg \<br> --network-endpoint-group-region=${REGION}</pre><p><strong>6. Create a URL Map:</strong></p><pre>gcloud compute url-maps create helloworld-url-map \<br> --default-service=helloworld-backend</pre><p><strong>7. Create a SSL certificate</strong></p><p>You’ll need an SSL certificate for HTTPS. You can either use a <a href="https://cloud.google.com/load-balancing/docs/ssl-certificates/google-managed-certs">Google-managed certificate</a> (recommended) or a self-managed certificate.</p><p>Here we use a Google-Managed Certificate:</p><pre>gcloud compute ssl-certificates create helloworld-cert \<br> --domains=${DNS_NAME} \<br> --global</pre><p>To check the certificate status, use the following command. Provisioning may take a while (up to 60 minutes), so you can continue with the next steps and check back later. Wait until the certificate is ready, or HTTPS connections will fail.</p><pre>gcloud compute ssl-certificates describe helloworld-cert \<br> --global \<br> --format=&quot;get(name,managed.status, managed.domainStatus)&quot;</pre><p><strong>8. Create a Target HTTPS Proxy</strong></p><pre>gcloud compute target-https-proxies create helloworld-proxy \<br> --url-map=helloworld-url-map \<br> --ssl-certificates=helloworld-cert \<br> --global</pre><p><strong>9. Create a Forwarding Rule:</strong></p><pre>gcloud compute forwarding-rules create helloworld-forwarding-rule \<br> --load-balancing-scheme=EXTERNAL_MANAGED \<br> --target-https-proxy=helloworld-proxy \<br> --global \<br> --ports=443 \<br> --address=$IP</pre><p>After you create the forwarding rule, you can optionally add health checks and configure IAP; however, these steps are skipped for simplicity in this tutorial.</p><p>Once the SSL and the forwarding rule are provisioned, you should be able to access the sample service as <a href="https://${dna_name}/">https://${DNA_NAME}</a> in your browser.</p><h3>Create the extension</h3><p>This example deploys the <a href="https://github.com/GoogleCloudPlatform/service-extensions/tree/main/callouts/python/extproc/example/jwt_auth">jwt_auth</a> callout authorization extension from the <a href="https://github.com/GoogleCloudPlatform/service-extensions/tree/main">service-extension Github repo</a> to Cloud Run. This extension allows users to authenticate a JWT token generated from their own certificates.</p><p>You can follow the following commands to create and deploy the extension.</p><pre><br># Clone the repository from GitHub<br>git clone https://github.com/GoogleCloudPlatform/service-extensions.git<br><br># Change to the extension directory<br>cd service-extensions/callouts/python<br><br># Follow the steps to build the necessary container images<br>docker build \<br>  -f ./extproc/example/Dockerfile \<br>  --target service-callout-common-python \<br>  -t service-callout-common-python .<br><br><br>docker build \<br>  -f ./extproc/example/jwt_auth/Dockerfile \<br>  -t service-callout-jwt-example-python .<br><br># Create the Artifact Registry repository<br>gcloud artifacts repositories create my-ext-repo \<br>    --repository-format=docker \<br>    --location=${REGION}<br><br># Tag the image we needed<br>docker tag service-callout-jwt-example-python \<br>  ${REGION}-docker.pkg.dev/${PROJECT_ID}/my-ext-repo/jwt-svc:v1<br><br># Authorize and push the image to the AR repo<br>gcloud auth configure-docker ${REGION}-docker.pkg.dev<br><br>docker push ${REGION}-docker.pkg.dev/${PROJECT_ID}/my-ext-repo/jwt-svc:v1<br><br># Deploy the container image to Cloud Run and named <br># the extension service jwt-svc<br>gcloud run deploy jwt-svc \<br>    --region=${REGION} \<br>    --allow-unauthenticated \<br>    --use-http2 \<br>--image=${REGION}-docker.pkg.dev/${PROJECT_ID}/my-ext-repo/jwt-svc:v1<br><br># Create the serverless network endpoint group for the jwt-svc<br>gcloud compute network-endpoint-groups create jwt-ext-neg \<br>    --network-endpoint-type=serverless \<br>    --cloud-run-service=jwt-svc \<br>    --region=${REGION}<br><br># Create the backend for the serverless NEG<br>gcloud compute backend-services create jwt-svc-backend \<br>    --global \<br>    --load-balancing-scheme=EXTERNAL_MANAGED \<br>    --protocol=HTTP2 --port-name=http<br><br># Add the backend to the load balancer<br>gcloud compute backend-services add-backend jwt-svc-backend \<br>    --global \<br>    --network-endpoint-group=jwt-ext-neg \<br>    --network-endpoint-group-region=${REGION}</pre><h3>Configure the extension</h3><p>Use the following steps to configure the extension. For more details, you can read the GCP doc <a href="https://cloud.google.com/service-extensions/docs/configure-authorization-extensions">Configure an authorization extension</a>.</p><p>Define the extension in a YAML file that associates it with the backend service, jwt-svc-backend.</p><pre>cat &gt;authz-extension.yaml &lt;&lt;EOF<br> name: my-authz-ext<br> authority: ${DOMAIN}<br> loadBalancingScheme: EXTERNAL_MANAGED<br> service: https://www.googleapis.com/compute/v1/projects/${PROJECT_ID}/global/backendServices/jwt-svc-backend<br> forwardHeaders:<br> - authorization<br> failOpen: false<br> timeout: &quot;0.1s&quot;<br>EOF</pre><p>Import the authorization extension.</p><pre>gcloud beta service-extensions authz-extensions import my-authz-ext \<br> --source=authz-extension.yaml \<br> --location=global</pre><p>Define an authorization policy that associates the extension, my-authz-ext with the forwarding rule, helloworld-forwarding-rule. The CUSTOM action indicates that an extension is being used.</p><pre>cat &gt;authz-policy.yaml &lt;&lt;EOF<br>    name: my-authz-policy<br>    target:<br>      loadBalancingScheme: EXTERNAL_MANAGED<br>      resources:<br>        - &quot;https://www.googleapis.com/compute/v1/projects/${PROJECT_ID}/global/forwardingRules/helloworld-forwarding-rule&quot;<br>    action: CUSTOM<br>    customProvider:<br>      authzExtension:<br>        resources:<br>          - &quot;projects/${PROJECT_ID}/locations/global/authzExtensions/my-authz-ext&quot;<br>EOF</pre><p>Import the authorization policy to the project.</p><pre>gcloud beta network-security authz-policies import my-authz-policy \<br> --source=authz-policy.yaml \<br> --location=global</pre><h3>Test the extension</h3><p><strong>Successful example with a valid token</strong></p><p>When a client sends a request to a serverless application protected by a token-based authorization mechanism and the request includes a valid token, the authorization process will be successful. For example, if you run the following command with a valid token, you should see the HTML page returned.</p><pre>curl -H &quot;Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImlhdCI6MTcxMjE3MzQ2MSwiZXhwIjoyMDc1NjU4MjYxfQ.Vv-Lwn1z8BbVBGm-T1EKxv6T3XKCeRlvRrRmdu8USFdZUoSBK_aThzwzM2T8hlpReYsX9YFdJ3hMfq6OZTfHvfPLXvAt7iSKa03ZoPQzU8bRGzYy8xrb0ZQfrejGfHS5iHukzA8vtI2UAJ_9wFQiY5_VGHOBv9116efslbg-_gItJ2avJb0A0yr5uUwmE336rYEwgm4DzzfnTqPt8kcJwkONUsjEH__mePrva1qDT4qtfTPQpGa35TW8n9yZqse3h1w3xyxUfJd3BlDmoz6pQp2CvZkhdQpkWA1bnwpdqSDC7bHk4tYX6K5Q19na-2ff7gkmHZHJr0G9e_vAhQiE5w&quot; https://${DNS_NAME}</pre><p><strong>Failure example with an invalid token</strong></p><p>In this case, the request will be rejected, and no data or content will be returned.</p><pre>curl -H &quot;Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImlhdCI6MTUxNjIzOTAyMn0.KMUFsIDTnFmyG3nMiGM6H9FNFUROf3wh7SmqJp-QV30&quot; https://${DNS_NAME}</pre><p><strong>Note</strong>: the JWT key is using <a href="https://github.com/GoogleCloudPlatform/service-extensions/blob/main/callouts/python/extproc/ssl_creds/privatekey.pem">the private certificate in the repo</a>.</p><h3>Conclusion</h3><p>This tutorial demonstrated how to implement a load balancer authorization extension for serverless applications on Google Cloud, using a callout extension deployed on Cloud Run. This approach provides custom authorization capabilities beyond IAP, enabling fine-grained access control, such as JWT-based authentication. Users can expand upon this foundation to incorporate additional mechanisms, such as authentication using a user database or a third-party IdP.</p><h3>Clean up</h3><p>You can run the following commands to remove the resources you created for this tutorial.</p><pre># Replace with your values<br>export PROJECT_ID=&quot;your project id&quot;<br>export REGION=&quot;us-central1&quot;<br>export DOMAIN=&quot;democloud.info&quot;<br>export DNS_ZONE=&quot;democloud&quot;<br>export DNS_NAME=&quot;cr-example.${DOMAIN}&quot;<br># Delete the network security policy<br>gcloud beta network-security authz-policies delete my-authz-policy \<br>  --location=global<br># Delete the service extension<br>gcloud beta service-extensions authz-extensions delete my-authz-ext \<br>  --location=global<br># Delete Forwarding Rule<br>gcloud compute forwarding-rules delete helloworld-forwarding-rule \<br> --location=global<br># Delete Target HTTPS Proxy<br>gcloud compute target-https-proxies delete helloworld-proxy \<br> --global \<br> --project=$PROJECT_ID \<br> --quiet<br># Delete URL Map<br>gcloud compute url-maps delete helloworld-url-map \<br> --project=$PROJECT_ID \<br> --quiet<br># Delete SSL Certificate<br>gcloud compute ssl-certificates delete helloworld-cert \<br> --global \<br> --project=$PROJECT_ID \<br> --quiet<br># Delete Backend Services<br>gcloud compute backend-services delete helloworld-backend \<br> --global \<br> --project=$PROJECT_ID \<br> --quiet<br>gcloud compute backend-services delete jwt-svc-backend \<br> --global \<br> --project=$PROJECT_ID \<br> --quiet<br># Delete Serverless NEGs<br>gcloud compute network-endpoint-groups delete helloworld-neg \<br> --region=$REGION \<br> --project=$PROJECT_ID \<br> --quiet<br>gcloud compute network-endpoint-groups delete jwt-ext-neg \<br> --region=$REGION \<br> --project=$PROJECT_ID \<br> --quiet<br># Delete Cloud Run Services<br>gcloud run services delete helloworld \<br> --region=$REGION \<br> --project=$PROJECT_ID \<br> --quiet<br>gcloud run services delete jwt-svc \<br> --region=$REGION \<br> --project=$PROJECT_ID \<br> --quiet<br># Delete the reserved IP<br>gcloud compute addresses delete example-ip<br># Optionally, delete the DNS record if you used Cloud DNS<br>gcloud dns record-sets delete ${DNS_NAME} --zone=&quot;${DNS_ZONE}&quot; --type=&quot;A&quot;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39ca3d1ad84a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/serverless-application-authorization-using-google-cloud-load-balancer-service-extensions-39ca3d1ad84a">Serverless Application Authorization Using Google Cloud Load Balancer Service Extensions</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gain Insights into AI Applications with Distributed Tracing on Google Cloud]]></title>
            <link>https://medium.com/google-cloud/gain-insights-into-ai-applications-with-distributed-tracing-on-google-cloud-80ffe844855a?source=rss-aaed0024dcd7------2</link>
            <guid isPermaLink="false">https://medium.com/p/80ffe844855a</guid>
            <category><![CDATA[trace]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[opentelemetry]]></category>
            <category><![CDATA[genai]]></category>
            <dc:creator><![CDATA[Xiang Shen]]></dc:creator>
            <pubDate>Wed, 04 Dec 2024 15:34:22 GMT</pubDate>
            <atom:updated>2024-12-05T15:40:09.242Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<h3>Overview</h3><p>This tutorial guides you through implementing distributed tracing in AI applications hosted on Google Kubernetes Engine(GKE). By combining <a href="https://opentelemetry.io/">OpenTelemetry</a> (OTel) and <a href="https://cloud.google.com/trace/docs">Cloud Trace</a>, you’ll unlock valuable insights into your application’s performance and behavior.</p><p>Throughout the tutorial, you’ll work with a chatbot built using <a href="https://www.langchain.com/">LangChain</a> and <a href="https://streamlit.io/">Streamlit</a>, integrating a vector database and a model hosted on <a href="https://cloud.google.com/vertex-ai">Vertex AI</a>. You’ll learn how to instrument your application code with OTel, configure the <a href="https://opentelemetry.io/docs/collector/">OTel Collector</a> to forward trace data to Cloud Trace, and view the collected traces to comprehend request flows and pinpoint potential bottlenecks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TqhkB8x7wrARpcQR" /><figcaption>The architecture of the sample application</figcaption></figure><h3>Prerequisite</h3><p>To demonstrate tracing an AI application deployed on GKE, we will use a <a href="https://cloud.google.com/use-cases/retrieval-augmented-generation">retrieval-augmented generation</a> (RAG) chatbot as an example. This chatbot also leverages a vector database. You can follow the tutorials linked in the next two sections to deploy the infrastructure and the application.</p><h4>1) Deploy a PostgreSQL vector database on GKE</h4><p>AI applications often require a vector database to implement RAG. There are many different vector database implementations. In <a href="https://cloud.google.com/kubernetes-engine/docs/tutorials/deploy-pgvector">this tutorial</a>, there are detailed steps you can follow to deploy a PostgreSQL vector database cluster on GKE.</p><p>PostgreSQL comes with a range of modules and extensions that extend the database’s functionality. In this tutorial, you will deploy PostgreSQL with the Pgvector extension enabled as the vector database implementation. This database will be deployed on GKE.</p><h4>2) Build a RAG chatbot with GKE and Cloud Storage</h4><p>A sample application from <a href="https://cloud.google.com/kubernetes-engine/docs/tutorials/build-rag-chatbot">this tutorial</a> is used to show you how to integrate a large language model (LLM) application based on RAG with PDF files that you upload to a Cloud Storage bucket.</p><p>This sample application uses a database as both a storage and a semantic search engine. The database holds the representations (embeddings) of the uploaded documents. You use the LangChain framework to interact with the embeddings, and you use the Gemini models through Vertex AI.</p><p>LangChain is a popular open-source Python framework that simplifies many machine learning tasks and has interfaces to integrate with different vector databases and AI services.</p><h3>OTel Collector</h3><p>The <a href="https://opentelemetry.io/docs/collector/">OpenTelemetry Collector</a> is a essential component that acts as an intermediary between your application and various observability systems. It simplifies your application by handling the complexities of exporting telemetry data to different backends, allowing your application to focus on its core functionality. Furthermore, it offers a vendor-agnostic solution, giving you the freedom to choose the best backend for your needs without being tied to a specific vendor. Additionally, the Collector provides advanced features like data processing, filtering, and enrichment, enabling you to gain deeper insights into your application’s performance.</p><p>Before configuring the OpenTelemetry Collector and redeploying the application, let’s reset any environment variables from the previous tutorials.</p><pre>export PROJECT_ID=&lt;Your-GCP-Project_Id&gt;<br>export PROJECT_NUM=$(gcloud projects describe $PROJECT_ID --format=&quot;value(projectNumber)&quot;)<br>export KUBERNETES_CLUSTER_PREFIX=postgres<br>export REGION=us-central1<br>export DB_NAMESPACE=pg-ns<br>export DOCKER_REPO=&quot;${REGION}-docker.pkg.dev/${PROJECT_ID}/${KUBERNETES_CLUSTER_PREFIX}-images&quot;</pre><p>Now, proceed with the following steps.</p><ol><li>Use a text editor to create a file named otel-config.yaml. This file will hold the configuration for the OpenTelemetry Collector.</li></ol><pre>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: otel-config<br>data:<br>  collector.yaml: |<br>    receivers:<br>     # Enable endpoints for receiving data<br>     # supplied in OTLP format.<br>     otlp:<br>       protocols:<br>         http:<br>           endpoint: ${env:MY_POD_IP}:4318<br>         grpc:<br>           endpoint: ${env:MY_POD_IP}:4317<br><br>    exporters:<br>     # Export traces using the standard googelcloud exporter<br>     googlecloud:<br>       user_agent: Google-Cloud-OTLP<br>    processors:<br>     # Batch telemetry together to more efficiently send to GCP<br>     batch:<br>       send_batch_max_size: 500<br>       send_batch_size: 500<br>       timeout: 1s<br>     # If running on GCP (e.g. on GKE), detect resource attributes from the environment.<br>     resourcedetection:<br>       detectors: [&quot;env&quot;, &quot;gcp&quot;]<br>    service:<br>     pipelines:<br>       traces:<br>         receivers: [&quot;otlp&quot;]<br>         processors: [&quot;batch&quot;, &quot;resourcedetection&quot;]<br>         exporters: [&quot;googlecloud&quot;]</pre><p>For this tutorial, we’ll focus solely on tracing and omit other configurations like logging and metrics. To learn more about these components, refer to the <a href="https://cloud.google.com/stackdriver/docs/managed-prometheus/setup-otel">Get started with the OpenTelemetry Collector</a> on Google Cloud documentation.</p><p>2. Use <strong>kubectl</strong> to to create the config map.</p><pre>kubectl apply -n $DB_NAMESPACE  -f ./otel-config.yaml</pre><p>3. Use a text editor to create a file named otel-collector.yaml. This file will contain the Kubernetes manifest to deploy the OpenTelemetry Collector.</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br> name: otel-collector<br>spec:<br> replicas: 1<br> selector:<br>   matchLabels:<br>     app: otel-collector<br> template:<br>   metadata:<br>     labels:<br>       app: otel-collector<br>   spec:<br>     containers:<br>     - name: otel-collector<br>       imagePullPolicy: Always<br>       image: otel/opentelemetry-collector-contrib:0.108.0<br>       args:<br>       - --config<br>       - /etc/otel/config.yaml<br>       env:<br>        - name: MY_POD_IP<br>          valueFrom:<br>            fieldRef:<br>              apiVersion: v1<br>              fieldPath: status.podIP<br>       volumeMounts:<br>       - mountPath: /etc/otel/<br>         name: otel-config<br>     volumes:<br>     - name: otel-config<br>       configMap:<br>         name: otel-config<br>         items:<br>         - key: collector.yaml<br>           path: config.yaml<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br> name: opentelemetry-collector<br> labels:<br>   app: opentelemetry-collector<br>spec:<br> type: ClusterIP<br> selector:<br>   app: otel-collector<br> internalTrafficPolicy: Cluster<br> ports:<br>   - name: otel-grpc<br>     protocol: TCP<br>     port: 4317<br>     targetPort: 4317<br>   - name: otlp-http<br>     port: 4318<br>     targetPort: 4318<br>     protocol: TCP</pre><p>In this deployment, we’re using version 0.108.0 of the OpenTelemetry Collector. You can update to a newer version by checking the <a href="https://github.com/open-telemetry/opentelemetry-collector-contrib/releases">collector releases</a>, modifying the otel-collector.yaml manifest file with the desired version, and redeploying.</p><p>4. To simplify our setup, we’ll use the default Kubernetes service account within this namespace. This service account needs permission to use Cloud Trace. We’ll grant this permission using workload identity federation.</p><pre>gcloud projects add-iam-policy-binding projects/${PROJECT_ID} \<br>    --role=roles/cloudtrace.agent \<br>    --member=principal://iam.googleapis.com/projects/${PROJECT_NUM}/locations/global/workloadIdentityPools/${PROJECT_ID}.svc.id.goog/subject/ns/${DB_NAMESPACE}/sa/default \<br>    --condition=None</pre><p>5. Use <strong>kubectl</strong> to deploy the collector.</p><pre>kubectl create -n $DB_NAMESPACE  -f ./otel-collector.yaml</pre><p>6. Verify the deployment.</p><p>After a moment, you can run the following command to check the status of the deployment.</p><pre>kubectl -n $DB_NAMESPACE get deployment otel-collector</pre><p>If the deployment is successful, you should see something like the following:</p><pre>NAME             READY   UP-TO-DATE   AVAILABLE   AGE<br>otel-collector   1/1     1            1           21s</pre><p>You can also go to the Cloud Logging explorer or use the following command to check the logs.</p><pre>kubectl -n $DB_NAMESPACE logs deployment/otel-collector</pre><p>Among the logs, you should have the log entries like the following:</p><pre>2024-12-04T14:18:29.172Z        info    otlpreceiver@v0.108.1/otlp.go:103       Starting GRPC server    {&quot;kind&quot;: &quot;receiver&quot;, &quot;name&quot;: &quot;otlp&quot;, &quot;data_type&quot;: &quot;traces&quot;, &quot;endpoint&quot;: &quot;10.48.1.13:4317&quot;}<br>2024-12-04T14:18:29.172Z        info    otlpreceiver@v0.108.1/otlp.go:153       Starting HTTP server    {&quot;kind&quot;: &quot;receiver&quot;, &quot;name&quot;: &quot;otlp&quot;, &quot;data_type&quot;: &quot;traces&quot;, &quot;endpoint&quot;: &quot;10.48.1.13:4318&quot;}<br>2024-12-04T14:18:29.173Z        info    service@v0.108.1/service.go:289 Everything is ready. Begin running and processing data.</pre><h3>Update and deploy the chatbot</h3><p>A few files in the chatbot application need to be updated to enable tracing.</p><h4>Update the Dockerfile</h4><p>Update the chatbot <a href="https://github.com/GoogleCloudPlatform/kubernetes-engine-samples/blob/main/databases/postgres-pgvector/docker/chatbot/Dockerfile">Dockerfile</a> to include the OTel dependencies.</p><pre>FROM python:3.12-slim-bookworm<br><br>ENV POSTGRES_HOST=gke-pg-cluster-rw.pg-ns<br>ENV DATABASE_NAME=app<br>ENV COLLECTION_NAME=training-docs<br>RUN apt update &amp;&amp; \<br>    apt install -y --no-install-recommends gcc libc6-dev &amp;&amp; \<br>    rm -rf /var/lib/apt/lists/*<br>WORKDIR /app<br>COPY requirements.txt requirements.txt<br>RUN pip install --no-cache-dir -r requirements.txt<br>RUN opentelemetry-bootstrap -a install<br>COPY . .<br><br>ENTRYPOINT [ &quot;opentelemetry-instrument&quot;, &quot;python&quot;, &quot;-m&quot;, &quot;streamlit&quot;, &quot;run&quot;, &quot;/app/chat.py&quot;]</pre><h4>Add additional dependencies</h4><p>Update the <a href="https://github.com/GoogleCloudPlatform/kubernetes-engine-samples/blob/main/databases/postgres-pgvector/docker/chatbot/requirements.txt">requirements.txt</a> file to include the OTel Python libraries.</p><pre>streamlit==1.38.0<br>google-cloud-aiplatform==1.65.0<br>langchain==0.2.16<br>langchain-community==0.2.16<br>langchain-google-vertexai==1.0.10<br>pgvector==0.3.2<br>psycopg2-binary==2.9.9<br>arxiv==2.1.3<br>pymupdf==1.24.10<br>opentelemetry-distro<br>opentelemetry-exporter-otlp<br>opentelemetry-exporter-otlp-proto-http<br>opentelemetry-instrumentation-langchain</pre><h4>Instrument the code</h4><p>Update the <a href="https://github.com/GoogleCloudPlatform/kubernetes-engine-samples/blob/main/databases/postgres-pgvector/docker/chatbot/chat.py">chat.py</a> file and add the OTel libraries. To simplify the initial setup, we’ll create a parent span that encompasses the entire request handling process. This means that all operations within the chatbot will be captured under this span. For more complex applications, you might want to create more granular spans for individual operations to gain more detailed insights.</p><pre>……<br>import os<br># Import opentelemetry files<br>from opentelemetry.instrumentation.langchain import LangchainInstrumentor<br><br>from opentelemetry.sdk.resources import SERVICE_INSTANCE_ID, SERVICE_NAME, Resource<br>from opentelemetry import trace<br>from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter<br>from opentelemetry.sdk.trace import TracerProvider<br>from opentelemetry.sdk.trace.export import BatchSpanProcessor<br><br><br># [START opentelemetry_instrumentation_setup_opentelemetry]<br>resource = Resource.create(attributes={<br>   # Use the PID as the service.instance.id to avoid duplicate timeseries<br>   # from different Gunicorn worker processes.<br>   SERVICE_INSTANCE_ID: f&quot;worker-{os.getpid()}&quot;,<br>})<br><br>trace_provider = TracerProvider(resource=resource)<br>processor = BatchSpanProcessor(OTLPSpanExporter())<br>trace_provider.add_span_processor(processor)<br>trace.set_tracer_provider(trace_provider)<br>tracer = trace.get_tracer(__name__)<br><br># Start the parent span. Pay attention to the indentation<br>with tracer.start_as_current_span(&quot;start-work&quot;) as span:<br>   # [START gke_databases_postgres_pgvector_docker_chat_model]<br>   vertexAI = ChatVertexAI(model_name=&quot;gemini-pro&quot;, streaming=True, convert_system_message_to_human=True)<br><br> …..<br><br></pre><h4>Rebuild the container image</h4><p>After updating the code, rebuild the container image using the following command:</p><pre>gcloud builds submit postgres-pgvector/docker/chatbot --region=${REGION} \<br>    --tag ${DOCKER_REPO}/chatbot:1.0</pre><p>You can use a different tag to version your image (e.g., chatbot:2.0). If you do this, remember to also update the chatbot.yaml file with the new tag.</p><h4>Update the manifest and deploy it</h4><p>Finally, let’s update the <a href="https://github.com/GoogleCloudPlatform/kubernetes-engine-samples/blob/main/databases/postgres-pgvector/manifests/03-rag/chatbot.yaml">postgres-pgvector/manifests/03-rag/chatbot.yaml</a> file. This file defines the Kubernetes deployment for your chatbot application. We need to add the following environment variables to configure the OpenTelemetry exporter:</p><pre>- name: OTEL_SERVICE_NAME<br>  value: &quot;opentelemetry-collector&quot;<br>- name: OTEL_EXPORTER_OTLP_ENDPOINT<br>  value: &quot;http://$(OTEL_SERVICE_NAME):4317&quot;<br>- name: OTEL_TRACES_EXPORTER<br>  value: &quot;console,otlp&quot;<br>- name: OTEL_RESOURCE_ATTRIBUTES<br>  value: &quot;service.name=chatbot,service.namespace=pg-ns&quot;</pre><p>These environment variables tell the OpenTelemetry SDK where to send the trace data (OTEL_EXPORTER_JAEGER_ENDPOINT) and provide additional attributes to identify the source of the traces (OTEL_RESOURCE_ATTRIBUTES). Make sure to add these variables within the spec.template.spec.containers section of your chatbot.yaml file.</p><p>After you add them, your chatbot.yaml should look like the following:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: chatbot<br>  labels: &amp;labels<br>    app: postgres-chatbot<br>spec:<br>  selector:<br>    matchLabels: *labels<br>  template:<br>    metadata: <br>      labels: *labels<br>    spec:<br>      serviceAccountName: embed-docs-sa<br>      containers:<br>      - name: chatbot<br>        image: &lt;DOCKER_REPO&gt;/chatbot:1.0<br>        imagePullPolicy: Always<br>        resources:<br>          requests:<br>            memory: &quot;1Gi&quot;<br>            cpu: &quot;500m&quot;<br>          limits:<br>            memory: &quot;1Gi&quot;<br>            cpu: &quot;1&quot;<br>        env:<br>        - name: OTEL_SERVICE_NAME<br>          value: &quot;opentelemetry-collector&quot;<br>        - name: OTEL_EXPORTER_OTLP_ENDPOINT<br>          value: &quot;http://$(OTEL_SERVICE_NAME):4317&quot;<br>        - name: OTEL_TRACES_EXPORTER<br>          value: &quot;console,otlp&quot;<br>        - name: OTEL_RESOURCE_ATTRIBUTES<br>          value: &quot;service.name=chatbot,service.namespace=pg-ns&quot;<br>        - name: PASSWORD<br>          valueFrom:<br>            secretKeyRef:<br>              name: gke-pg-cluster-app<br>              key: password<br>        - name: USERNAME<br>          valueFrom:<br>            secretKeyRef:<br>              name: gke-pg-cluster-app<br>              key: username<br>        - name: POSTGRES_HOST <br>          value: gke-pg-cluster-rw.pg-ns<br>        - name: STREAMLIT_SERVER_PORT<br>          value: &quot;80&quot;<br>        - name: DATABASE_NAME<br>          value: &quot;app&quot;<br>        - name: COLLECTIONS_NAME<br>          value: &quot;training-docs&quot;<br>        ports:<br>        - containerPort: 80<br>        resources:<br>          requests:<br>            cpu: 200m<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: chatbot<br>  labels: &amp;labels<br>    app: postgres-chatbot<br>spec:<br>  # type: ClusterIP<br>  type: LoadBalancer<br>  ports:<br>    - port: 80<br>  selector: *labels</pre><p>Run the following command to redeploy the chatbot app:</p><pre>sed &quot;s|&lt;DOCKER_REPO&gt;|$DOCKER_REPO|&quot; postgres-pgvector/manifests/03-rag/chatbot.yaml | kubectl -n pg-ns apply -f -</pre><h3>View the traces</h3><p>After you redeploy the application, open the chatbot endpoint in your browser. Then, type a question like the following:</p><pre>Hi, what are Google plans for the future?</pre><p>You should receive an answer from the chatbot. Now, go to the <a href="https://www.google.com/url?sa=E&amp;source=gmail&amp;q=https://console.cloud.google.com/traces">Cloud Trace explorer</a> in the Google Cloud Console. You should see a trace point representing the chatbot’s request handling. Click on this trace point to view the details. This page shows the duration of the request, the different spans within the trace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dv69RjCTFExhm62OZoOWcQ.png" /></figure><h3>What’s next</h3><ul><li>Review <a href="https://cloud.google.com/learn/what-is-opentelemetry">Google Cloud OpenTelementry documentation</a> in more detail.</li><li>For Vertext AI Langchain agent tracing, review <a href="https://cloud.google.com/vertex-ai/generative-ai/docs/reasoning-engine/manage#tracing-langchain-agent">Tracing for a </a><a href="https://cloud.google.com/vertex-ai/generative-ai/docs/reasoning-engine/manage#tracing-langchain-agent">LangchainAgent instance</a>.</li><li>Try out other Google Cloud features for yourself. Have a look at more <a href="https://cloud.google.com/docs/tutorials">tutorials</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80ffe844855a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/gain-insights-into-ai-applications-with-distributed-tracing-on-google-cloud-80ffe844855a">Gain Insights into AI Applications with Distributed Tracing on Google Cloud</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Self-managed GPU Monitoring Stack on Google Cloud with DCGM, Prometheus, and Grafana]]></title>
            <link>https://medium.com/google-cloud/self-managed-gpu-monitoring-stack-on-google-cloud-with-dcgm-prometheus-and-grafana-04c8355c5132?source=rss-aaed0024dcd7------2</link>
            <guid isPermaLink="false">https://medium.com/p/04c8355c5132</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[gpu-monitoring]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[cloud-monitoring]]></category>
            <category><![CDATA[prometheus]]></category>
            <dc:creator><![CDATA[Xiang Shen]]></dc:creator>
            <pubDate>Wed, 11 Sep 2024 05:12:45 GMT</pubDate>
            <atom:updated>2024-09-12T04:33:09.094Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<h3>Overview</h3><p>On Google Cloud, there are increasingly more Kubernetes workloads that require accelerators like GPUs. Monitoring GPU usage on GKE can be challenging and often necessitates the use of <a href="https://developer.nvidia.com/dcgm">NVIDIA Data Center GPU Manager</a> (DCGM). Google provides two approaches for using DCGM: a <a href="https://cloud.google.com/stackdriver/docs/managed-prometheus/exporters/nvidia-dcgm">self-managed approach</a> via the DCGM exporter and a <a href="https://cloud.google.com/kubernetes-engine/docs/how-to/dcgm-metrics">managed addon</a> to collect and view metrics.</p><p>However, users sometimes desire more flexibility and want to use DCGM with other open-source tools such as Prometheus and Grafana.</p><p>This tutorial outlines the setup of a self-managed, open-source GPU monitoring stack. The stack leverages Prometheus exporters, Google Cloud Managed Service for Prometheus (GMP), and Grafana. This solution empowers users to effectively monitor and address performance issues in GPU-accelerated workloads. By optimizing resource utilization and ensuring the health and availability of GPU systems, this stack enables users to maintain optimal performance and reliability.</p><p>Specifically, the monitoring stack comprises the following components:</p><ul><li><a href="https://docs.nvidia.com/datacenter/cloud-native/gpu-telemetry/latest/dcgm-exporter.html"><strong>DCGM Prometheus exporter</strong></a><strong>:</strong> This collects a wide range of metrics from GPU devices and systems, including utilization, temperature, power consumption, and memory usage.</li><li><a href="https://cloud.google.com/stackdriver/docs/managed-prometheus"><strong>Google Cloud Managed Service for Prometheus</strong></a><strong> (GMP):</strong> This platform provides a hosted Prometheus instance, simplifying the deployment and management of the monitoring stack without requiring extensive infrastructure setup.</li><li><a href="https://grafana.com/grafana/dashboards/"><strong>Visualization and alerting via Grafana</strong></a><strong>:</strong> These offer visual representations of collected metrics, empowering users to monitor GPU performance, identify trends, and detect anomalies.</li></ul><h3>Create a GKE cluster with a GPU node pool</h3><p>In this tutorial, a GKE cluster with a GPU node pool needs to be created. We also need to run some sample workloads. The following steps walk you through the process. For more details about the example, you can read <a href="https://cloud.google.com/kubernetes-engine/docs/quickstarts/train-model-gpus-standard">this doc</a>.</p><p>You need to run all the following commands in Cloud Shell.</p><p>First, let’s clone the sample repository:</p><pre>git clone https://github.com/GoogleCloudPlatform/ai-on-gke/ ai-on-gke<br>cd ai-on-gke/tutorials-and-examples/gpu-examples/training-single-gpu</pre><p>Configure the variables:</p><pre>export PROJECT_ID=[YOUR-PROJECT-ID]</pre><pre>export REGION=us-central1<br>export CLUSTER_NAME=gke-gpu-cluster<br>export NAMESPACE=gke-ai-namespace<br>export K8S_SA_NAME=gpu-k8s-sa<br>export BUCKET_NAME=${PROJECT_ID}-gke-gpu-bucket</pre><p>Configure the environment and enable the needed services:</p><pre>gcloud config set project “$PROJECT_ID”<br>gcloud config set compute/region “$REGION”</pre><pre>gcloud services enable compute.googleapis.com container.googleapis.com</pre><pre>PROJECT_NUMBER=$(gcloud projects describe $PROJECT_ID — format=’value(projectNumber)’)</pre><p>Create the GKE cluster:</p><pre>gcloud container clusters create ${CLUSTER_NAME} \<br> — addons GcsFuseCsiDriver \<br> — location=${REGION} \<br> — num-nodes=1 \<br> — workload-pool=${PROJECT_ID}.svc.id.goog</pre><p>Create the GKE node pool:</p><pre>gcloud container node-pools create gke-gpu-pool-1 \<br> — accelerator=type=nvidia-tesla-t4,count=1,gpu-driver-version=default \<br> — machine-type=n1-standard-16 — num-nodes=1 \<br> — location=us-central1 \<br> — cluster=gke-gpu-cluster</pre><p>Create a storage bucket:</p><pre>gcloud storage buckets create gs://${PROJECT_ID}-gke-gpu-bucket \<br> — uniform-bucket-level-access</pre><p>Create the namespace and service account in GKE:</p><pre>kubectl create namespace ${NAMESPACE}<br>kubectl create serviceaccount ${KSA} — namespace=${NAMESPACE}</pre><p>Use workload identity to allow access:</p><pre>gcloud storage buckets add-iam-policy-binding gs://${PROJECT_ID}-gke-gpu-bucket \<br> — member “principal://iam.googleapis.com/projects/${PROJECT_NUMBER}/locations/global/workloadIdentityPools/${PROJECT_ID}.svc.id.goog/subject/ns/${NAMESPACE}/sa/${K8S_SA_NAME}” \<br> — role “roles/storage.objectUser”</pre><p>Copy the data:</p><pre>gcloud storage cp src/tensorflow-mnist-example gs://${BUCKET_NAME}/ — recursive</pre><p>Start the training workload:</p><pre>envsubst &lt; src/gke-config/standard-tf-mnist-train.yaml | kubectl -n ${NAMESPACE} apply -f -</pre><p>You can either run the following command or view the logs from the console:</p><pre>kubectl logs -f jobs/mnist-training-job -c tensorflow -n ${NAMESPACE}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YLUOxHk2b0YWCG14" /></figure><h3>DCGM Prometheus exporter</h3><p>The NVIDIA <a href="https://docs.nvidia.com/datacenter/cloud-native/gpu-telemetry/latest/dcgm-exporter.html">DCGM exporter </a>is a specific type of Prometheus exporter designed to collect and expose metrics from NVIDIA GPUs (Graphics Processing Units) using the NVIDIA Data Center GPU Manager (DCGM).</p><h3>Install DCGM exporter</h3><p>There are multiple ways to install the DCGM exporter. In this tutorial, you can just run the following command:</p><pre>kubectl apply -f https://raw.githubusercontent.com/GoogleCloudPlatform/prometheus-engine/main/examples/nvidia-dcgm/exporter.yaml</pre><p>You can read <a href="https://cloud.google.com/stackdriver/docs/managed-prometheus/exporters/nvidia-dcgm#install-exporter">this doc </a>for more details regarding the installation of the DCGM exporter.</p><h3>Define a PodMonitoring resource</h3><p>In order to scrape metrics from Prometheus, you also need to Create a PodMonitor custom resource in GMP, specifying the namespace and labels to select the DCGM Exporter pod.</p><p>Run the following command to achieve that.</p><pre>kubectl apply -n gmp-public -f https://raw.githubusercontent.com/GoogleCloudPlatform/prometheus-engine/main/examples/nvidia-dcgm/pod-monitoring.yaml</pre><p>You can find more details about <a href="https://cloud.google.com/stackdriver/docs/managed-prometheus/exporters/nvidia-dcgm#exporter-podmonitoring">the example</a> here. Once the command runs successfully, you should see the following in the workloads page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cLdr0wAMqC_OyG9u" /></figure><h3>Google Cloud Managed Service for Prometheus (GMP)</h3><p>To Verify the configuration and metric collection is working fine. You can run the following PromQL query in <a href="https://console.cloud.google.com/monitoring/metrics-explorer">the Metrics explorer</a>. You can read <a href="https://cloud.google.com/stackdriver/docs/managed-prometheus/exporters/nvidia-dcgm#verify-config">this doc</a> for more details.</p><p>Alternatively, you can run the following command that uses curl to run a query.</p><pre>curl -s https://monitoring.googleapis.com/v1/projects/shenxiang-gcp-solution/location/global/prometheus/api/v1/query \<br> -d ‘query=DCGM_FI_DEV_GPU_UTIL{cluster=”gke-gpu-cluster”}’ \<br> -H “Authorization: Bearer $(gcloud auth print-access-token)”|jq</pre><p>You should see results like the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*V8My5fnYGdTIayNy" /></figure><h3>Grafana</h3><p>If you don’t have a Grafana instance, you need to install it or use the SaaS version. Grafana offers several installation methods, catering to different environments and preferences:</p><ol><li><strong>Grafana Cloud:</strong> The easiest way to get started is through Grafana Cloud, their managed service. This eliminates the need for manual installation and maintenance. Simply create a free account and start using Grafana immediately.</li><li><strong>Package Managers:</strong> Grafana provides packages for various operating systems, like Debian, Ubuntu, RPM-based distros, and Homebrew for macOS. These packages simplify the installation process, handling dependencies and configuration.</li><li><strong>Docker:</strong> If you prefer containerization, Grafana offers official Docker images. This allows for easy deployment and management within Docker environments.</li><li><strong>Binary Installation:</strong> You can also download the Grafana binary directly and run it. This method provides flexibility but requires manual configuration and setup.</li><li><strong>Kubernetes:</strong> For Kubernetes users, Grafana provides Helm charts to deploy and manage Grafana within Kubernetes clusters.</li></ol><p>Choose the method that best suits your needs and environment. Refer to the official Grafana documentation for detailed instructions on each installation method:</p><ul><li><strong>Grafana Installation Overview:</strong><a href="https://grafana.com/docs/grafana/latest/setup-grafana/installation/"> https://grafana.com/docs/grafana/latest/setup-grafana/installation</a></li><li><strong>Grafana Download:</strong><a href="https://grafana.com/grafana/download"> https://grafana.com/grafana/download</a></li></ul><h3>Configure Grafana</h3><p>Grafana can use GMP as a Prometheus data source directly, which means you can continue using any community-created or personal Grafana dashboards without any changes.</p><p><strong><em>Note</em></strong><em>: The community has created </em><a href="https://github.com/grafana/grafana/issues/70962"><em>a patch</em></a><em> that allows us to use the Cloud Monitoring data source to run PromQL. However, this is not recommended due to its limited functionality.</em></p><p>One challenge in configuring the Prometheus data source is setting up authentication. Using <a href="https://github.com/GoogleCloudPlatform/prometheus-engine/tree/main/cmd/datasource-syncer">data source syncer</a> is recommended, and you can follow the steps in <a href="https://cloud.google.com/stackdriver/docs/managed-prometheus/query#ui-grafana">this documentation</a> to configure the Prometheus data source in Grafana.</p><h3>Explore the DCGM metrics in Grafana</h3><ol><li>Click the menu icon and, in the sidebar, click Explore. A dropdown menu for the list of available data sources is on the upper-left side. The Prometheus data source will already be selected. If not, choose Prometheus.</li><li>Confirm that you’re in code mode by checking the Builder/Code toggle at the top right corner of the query panel.</li><li>In the query editor, where it says <em>Enter a PromQL query…</em>, enter <strong>sum(avg_over_time(DCGM_FI_DEV_GPU_TEMP[5m]))</strong> and then press <strong>Shift + Enter</strong>. A graph should appear.</li><li>In the top right corner, click the dropdown arrow on the Run Query button, and then select 5s. Grafana runs your query and updates the graph every 5 seconds.<br>You just made your first <em>PromQL</em> query! <a href="https://prometheus.io/docs/prometheus/latest/querying/basics/">PromQL</a> is a powerful query language that lets you select and aggregate time series data stored in Prometheus.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YXUvIZpFY32o98xQ" /></figure><h3>Grafana Dashboard</h3><p>You can choose to build your own dashboards or import an existing one. For example, to import the Grafana <a href="https://grafana.com/grafana/dashboards/12239-nvidia-dcgm-exporter-dashboard/">NVIDIA DCGM Exporter Dashboard</a>, you can click <strong>Import</strong> under Grafana’s dashboard menu, either use the dashboard id or copy/paste the JSON definition.</p><p>Due to the<a href="https://cloud.google.com/stackdriver/docs/managed-prometheus/query#http-api-details"> slight difference</a> of GMP, you may need to change some dashboard variables. For the DCGM exporter dashboard, you need to change the GPU variable query from label_values(gpu) to label_values(DCGM_FI_DEV_GPU_TEMP, gpu)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TaVNQ8UJbWXJbntI" /></figure><p>After update the variable, save the change and refresh the dashboard, you should see a dashboard similar to the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9NtvgTPJTOb3pBHu" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04c8355c5132" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/self-managed-gpu-monitoring-stack-on-google-cloud-with-dcgm-prometheus-and-grafana-04c8355c5132">Self-managed GPU Monitoring Stack on Google Cloud with DCGM, Prometheus, and Grafana</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Customizing Fluent Bit for Google Kubernetes Engine logs]]></title>
            <link>https://medium.com/google-cloud/customizing-fluent-bit-for-google-kubernetes-engine-logs-a484b5d80072?source=rss-aaed0024dcd7------2</link>
            <guid isPermaLink="false">https://medium.com/p/a484b5d80072</guid>
            <category><![CDATA[fluentbit]]></category>
            <category><![CDATA[gke]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Xiang Shen]]></dc:creator>
            <pubDate>Thu, 13 Jun 2024 20:01:13 GMT</pubDate>
            <atom:updated>2024-06-14T06:04:09.698Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*s6dLeTU4bdV_B4AvsbiWMw.png" /></figure><p>This tutorial describes how to customize <a href="https://fluentbit.io/">Fluent Bit</a> logging for a <a href="https://cloud.google.com/kubernetes-engine">Google Kubernetes Engine</a> cluster. In this tutorial, you learn how to host your own configurable Fluent Bit daemonset to send logs to <a href="https://cloud.google.com/logging">Cloud Logging</a> instead of selecting the Cloud Logging option when creating the Google Kubernetes Engine (GKE) cluster, which does not allow configuration of the Fluent Bit daemon.</p><p>This tutorial only applies to Linux nodes and assumes you’re familiar with <a href="https://kubernetes.io/docs/home/">Kubernetes</a>.</p><p>Unless otherwise noted, you enter all commands for this tutorial in <a href="https://cloud.google.com/shell">Cloud Shell</a>.</p><p><strong>Note</strong>: This tutorial was initially published in the <a href="https://github.com/GoogleCloudPlatform/community">Google Cloud Community repository</a>. Since the repo has been archived, I republished it here.</p><h3>Objectives</h3><ul><li>Deploy your own Fluent Bit daemonset on a Google Kubernetes Engine cluster, configured to log data to Cloud Logging.</li><li>Customize GKE logging to remove sensitive data from the Cloud Logging logs.</li></ul><h3>Costs</h3><p>This tutorial uses billable components of Google Cloud, including a three-node <a href="https://cloud.google.com/kubernetes-engine/pricing">Google Kubernetes Engine</a> cluster.</p><p>The <a href="https://cloud.google.com/products/calculator#id=38ec76f1-971f-41b5-8aec-a04e732129cc">pricing calculator</a> estimates the cost of this environment at around $1.14 for 8 hours.</p><h3>Before you begin</h3><ol><li>In the Cloud Console, on the <a href="https://console.cloud.google.com/projectselector2/home/dashboard">project selector page</a>, select or create a Cloud project. If you don’t plan to keep the resources you create in this procedure, create a project instead of selecting an existing one. After you finish this tutorial, you can delete the project, removing all resources associated with the project.</li><li>Make sure that billing is enabled for your Google Cloud project.</li><li><a href="https://cloud.google.com/billing/docs/how-to/modify-project">Learn how to confirm whether billing is enabled for your project.</a></li><li>Enable the Google Kubernetes Engine and Compute Engine APIs.</li><li><a href="https://console.cloud.google.com/flows/enableapi?apiid=container,compute.googleapis.com">Enable the APIs.</a></li></ol><h3>Initializing common variables</h3><p>In this section, you define variables that control where elements of the infrastructure are deployed.</p><ol><li><a href="https://console.cloud.google.com/?cloudshell=true">Open Cloud Shell</a>.</li><li>Set the variables used in this tutorial. This tutorial uses the region us-east-1. If you change the region, make sure that the zone values reference your region.</li></ol><pre>export region=us-east1<br>export zone=${region}-b<br>export project_id=[YOUR_PROJECT_ID]</pre><p>3. Set the default zone and project ID so that you don’t have to specify these values in every subsequent command:</p><pre>gcloud config set compute/zone ${zone}<br>gcloud config set project ${project_id}</pre><h3>Creating the GKE cluster</h3><ol><li>Clone the sample repository. The sample repository includes the Kubernetes manifests for the Fluent Bit daemonset and a test logging program that you deploy.</li></ol><pre>git clone https://github.com/xiangshen-dk/kubernetes-engine-customize-fluentbit.git</pre><p>2. Go to the directory for this tutorial in the cloned repository:</p><pre>cd kubernetes-engine-customize-fluentbit.git</pre><p>3. Create the GKE cluster with system-only logging turned on:</p><pre>gcloud container clusters create custom-fluentbit \<br>--zone $zone \<br>--logging=SYSTEM \<br>--tags=gke-cluster-with-customized-fluentbit \<br>--scopes=logging-write,storage-rw</pre><h3>Deploying the test logger application</h3><p>By default, the sample application that you deploy continuously emits random logging statements. The Docker container is built from the source code under the test-logger subdirectory.</p><ol><li>Build the test-logger container image:</li></ol><pre>docker build -t test-logger test-logger</pre><p>2. Tag the container before pushing to the registry:</p><pre>docker tag test-logger gcr.io/${project_id}/test-logger</pre><p>3. Push the container image:</p><pre>docker push gcr.io/${project_id}/test-logger</pre><p>4. Update the deployment file:</p><pre>envsubst &lt; kubernetes/test-logger.yaml &gt; kubernetes/test-logger-deploy.yaml</pre><p>5. Deploy the test-logger application to the GKE cluster:</p><pre>kubectl apply -f kubernetes/test-logger-deploy.yaml</pre><p>6. View the status of the test-logger pods:</p><pre>kubectl get pods</pre><p>7. Repeat this command until the output looks like the following, with all three test-logger pods running:</p><pre>NAME                           READY   STATUS    RESTARTS   AGE<br>test-logger-58f7bfdb89-4d2b5   1/1     Running   0          28s<br>test-logger-58f7bfdb89-qrlbl   1/1     Running   0          28s<br>test-logger-58f7bfdb89-xfrkx   1/1     Running   0          28s</pre><h3>Deploying the Fluent Bit daemonset to your cluster</h3><p>In this section, you configure and deploy your Fluent Bit daemonset.</p><p>Because you turned on system-only logging, a GKE-managed Fluent Bit daemonset is deployed that is responsible for system logging. The Kubernetes manifests for Fluent Bit that you deploy in this procedure are versions of the ones available from the Fluent Bit site for <a href="https://docs.fluentbit.io/manual/installation/kubernetes/">logging using Cloud Logging</a> and <a href="https://kubernetes.io/docs/concepts/cluster-administration/logging/">watching changes to Docker log files</a>.</p><ol><li>Create the service account and the cluster role in a new logging namespace:</li></ol><pre> kubectl apply -f ./kubernetes/fluentbit-rbac.yaml</pre><p>2. Deploy the Fluent Bit configuration:</p><pre>kubectl apply -f kubernetes/fluentbit-configmap.yaml</pre><p>3. Deploy the Fluent Bit daemonset:</p><pre>kubectl apply -f kubernetes/fluentbit-daemonset.yaml</pre><p>4. Check that the Fluent Bit pods have started:</p><pre>kubectl get pods --namespace=logging</pre><p>5. If they’re running, you see output like the following:</p><pre>NAME               READY   STATUS    RESTARTS   AGE<br>fluent-bit-246wz   1/1     Running   0          26s<br>fluent-bit-6h6ww   1/1     Running   0          26s<br>fluent-bit-zpp8q   1/1     Running   0          26s</pre><p>For details of configuring Fluent Bit for Kubernetes, see the <a href="https://docs.fluentbit.io/manual/installation/kubernetes">Fluent Bit manual</a>.</p><p>6. Verify that you’re seeing logs in Cloud Logging. In the console, on the left-hand side, select <strong>Logging</strong> &gt; <strong>Logs Explorer</strong>, and then select <strong>Kubernetes Container</strong> as a resource type in the <strong>Resource</strong> list.</p><p>7. Click <strong>Run Query</strong>.</p><p>8. In the <strong>Logs field explorer</strong>, select <strong>test-logger</strong> for <strong>CONTAINER_NAME</strong>. After you add the log field to the summary line, you should see logs similar to the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KLKzGa1lGE8figY3QU5edw.png" /></figure><h3>Filtering information from the log file</h3><p>In this section, you configure Fluent Bit to filter certain data so that it is not logged. For this tutorial, you filter out Social Security numbers, credit card numbers, and email addresses. To make this update, you change the daemonset to use a different ConfigMap that contains these filters. You use Kubernetes rolling updates feature and preserve the old version of the ConfigMap.</p><ol><li>Open the <a href="https://github.com/GoogleCloudPlatform/community/tree/master/tutorials/kubernetes-engine-customize-fluentbit/kubernetes/fluentbit-configmap.yaml">kubernetes/fluentbit-configmap.yaml</a> file in an editor.</li><li>Uncomment the lines after ### sample log scrubbing filters and before ### end sample log scrubbing filters.</li><li>Change the name of the ConfigMap from fluent-bit-config to fluent-bit-config-filtered by editing the metadata.name field.</li><li>Save and close the file.</li></ol><h3>Updating the Fluent Bit daemonset to use the new configuration</h3><p>In this section, you change kubernetes/fluentbit-daemonset.yaml to mount the fluent-bit-config-filtered ConfigMap instead of the fluent-bit-config ConfigMap.</p><ol><li>Open the <a href="https://github.com/GoogleCloudPlatform/community/tree/master/tutorials/kubernetes-engine-customize-fluentbit/kubernetes/fluentbit-daemonset.yaml">kubernetes/fluentbit-daemonset.yaml</a> file in an editor.</li><li>Change the name of the ConfigMap from fluent-bit-config to fluent-bit-config-filtered by editing the configMap.name field:</li></ol><pre>- name: fluent-bit-etc<br>configMap:<br>    name: fluent-bit-config</pre><p>3. Deploy the new version of the ConfigMap to your cluster:</p><pre>kubectl apply -f kubernetes/fluentbit-configmap.yaml</pre><p>4. Apply the new version of the daemonset:</p><pre>kubectl apply -f kubernetes/fluentbit-daemonset.yaml</pre><p>5. Roll out the update and wait for it to complete:</p><pre>kubectl rollout status ds/fluent-bit --namespace=logging</pre><p>When it completes, you should see the following message:</p><pre>daemon set &quot;fluent-bit&quot; successfully rolled out</pre><p>6. When the rollout is complete, refresh the Cloud Logging logs and make sure that the Social Security number, credit card number, and email address data has been filtered out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M2DRS_cArnqN-RxKHyzvoQ.png" /></figure><h3>Cleaning up: deleting the GKE cluster</h3><p>If you don’t want to delete the whole project, run the following command to delete the GKE cluster:</p><pre>gcloud container clusters delete custom-fluentbit --zone us-east1-b</pre><h3>What’s next</h3><ul><li>Review <a href="https://docs.fluentbit.io/manual/">Fluent Bit</a> documentation in more detail.</li><li>Review <a href="https://cloud.google.com/kubernetes-engine">Google Kubernetes Engine</a> documentation in more detail.</li><li>Try out other Google Cloud features for yourself. Have a look at our <a href="https://cloud.google.com/docs/tutorials">tutorials</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a484b5d80072" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/customizing-fluent-bit-for-google-kubernetes-engine-logs-a484b5d80072">Customizing Fluent Bit for Google Kubernetes Engine logs</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use Log Analytics for BigQuery Usage Analysis on Google Cloud]]></title>
            <link>https://medium.com/google-cloud/use-log-analytics-for-bigquery-usage-analysis-on-google-cloud-8f5454626c6c?source=rss-aaed0024dcd7------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f5454626c6c</guid>
            <category><![CDATA[log-analytics]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[logs]]></category>
            <dc:creator><![CDATA[Xiang Shen]]></dc:creator>
            <pubDate>Mon, 15 Apr 2024 21:15:54 GMT</pubDate>
            <atom:updated>2024-04-16T12:18:26.756Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<p>On Google Cloud you can use <a href="https://cloud.google.com/logging/docs/log-analytics#analytics">Log Analytics</a> to query and analyze your log data, and then you can view or <a href="https://cloud.google.com/logging/docs/analyze/charts">chart the query results</a>.</p><p><a href="https://cloud.google.com/bigquery">BigQuery</a> is Google Cloud’s fully managed enterprise data warehouse that helps you manage and analyze your data with built-in features like machine learning, geospatial analysis, and business intelligence.</p><p>While BigQuery offers built-in observability capabilities like the <a href="https://cloud.google.com/bigquery/docs/information-schema-intro">INFORMATION_SCHEMA</a> views, detailed logging remains crucial for in-depth usage analysis, auditing, and troubleshooting potential issues.</p><p>This article will walk you through how to analyze BigQuery logs using log analytics.</p><h3>Upgrade Log bucket</h3><p>First, if you haven’t, you need to configure Cloud Logging to upgrade all the existing log buckets with Log Analytics enabled.</p><p>To upgrade an existing bucket to use Log Analytics, do the following:</p><ol><li>In the navigation panel of the Google Cloud console, select <strong>Logging</strong>, and then select <strong>Logs Storage.</strong></li><li>Locate the bucket that you want to upgrade.</li><li>When the <strong>Log Analytics available</strong> column displays <strong>Upgrade</strong>, you can upgrade the log bucket to use Log Analytics. Click <strong>Upgrade</strong>.<br>A dialog opens. Click <strong>Confirm</strong>.</li></ol><h3>Perform BigQuery Activities</h3><p>Complete the following tasks to generate some BigQuery logs. In the tasks, the BigQuery command line tool <a href="https://cloud.google.com/bigquery/docs/reference/bq-cli-reference">bq</a> is used.</p><p><strong>Task 1. Create datasets</strong></p><p>Use the <strong>bq mk</strong> command to create new datasets named <strong>bq_logs</strong> and <strong>bq_logs_test </strong>in your project:</p><pre>bq mk bq_logs<br>bq mk bq_logs_testbq mk bq_logs_test</pre><p><strong>Task 2. List the datasets</strong></p><p>Use the <strong>bq ls</strong> command to list the datasets:</p><pre>bq ls</pre><p><strong>Task 3. Delete a dataset</strong></p><p>Use the <strong>bq rm</strong> command to delete the a dataset (select <strong>y</strong> when prompted):</p><pre>bq rm bq_logs_test</pre><p><strong>Task 4. Create a new table</strong></p><pre>bq mk \<br> --table \<br> --expiration 3600 \<br> --description &quot;This is a test table&quot; \<br> bq_logs.test_table \<br> id:STRING,name:STRING,address:STRING</pre><p>You should have a new empty table named <strong>test_table</strong> that has been created for your dataset.</p><p><strong>Task 5. Run some example queries</strong></p><p>You can run a simple query like the following to generates a log entry. Copy and paste the following query into the BigQuery Query editor:</p><pre>bq query — use_legacy_sql=false ‘SELECT current_date’</pre><p>The following query will leverage weather data from the <a href="https://cloud.google.com/blog/products/data-analytics/noaa-datasets-on-google-cloud-for-environmental-exploration">National Oceanic and Atmospheric Administration (NOAA)</a>. Copy the query into the BigQuery editor and click <strong>RUN</strong>.</p><pre>bq query --use_legacy_sql=false \<br>&#39;SELECT<br> gsod2021.date,<br> stations.usaf,<br> stations.wban,<br> stations.name,<br> stations.country,<br> stations.state,<br> stations.lat,<br> stations.lon,<br> stations.elev,<br> gsod2021.temp,<br> gsod2021.max,<br> gsod2021.min,<br> gsod2021.mxpsd,<br> gsod2021.gust,<br> gsod2021.fog,<br> gsod2021.hail<br>FROM<br> `bigquery-public-data.noaa_gsod.gsod2021` gsod2021<br>INNER JOIN<br> `bigquery-public-data.noaa_gsod.stations` stations<br>ON<br> gsod2021.stn = stations.usaf<br> AND gsod2021.wban = stations.wban<br>WHERE<br> stations.country = &quot;US&quot;<br> AND gsod2021.date = &quot;2021-12-15&quot;<br> AND stations.state IS NOT NULL<br> AND gsod2021.max != 9999.9<br>ORDER BY<br> gsod2021.min;&#39;</pre><h3>Perform log analysis</h3><p>Now there are some log entries for BigQuery. You can run some queries using Log Analytics.</p><p><strong>Task 1. Open Log Analytics</strong></p><p>On the left side, under <strong>Logging</strong> click <strong>Log Analytics</strong> to access the feature. You should see something like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6PrYdj0eZePE3wF8" /></figure><p>If your query field is empty or you forget which table you want to use, you can click the <strong>Query</strong> button to get the sample query back.</p><p>Now you can run your own queries in the query field. Remember to replace <strong>[Your Project Id]</strong> with the project id you are using.</p><p><strong>Task 2. To find the activities for BigQuery datasets</strong></p><p>You can query the activities that a dataset is created or deleted:</p><pre>SELECT<br> timestamp,<br> severity,<br> resource.type,<br> proto_payload.audit_log.authentication_info.principal_email,<br> proto_payload.audit_log.method_name,<br> proto_payload.audit_log.resource_name,<br>FROM<br> `[Your Project Id].global._Required._AllLogs`<br>WHERE<br> log_id = &#39;cloudaudit.googleapis.com/activity&#39;<br> AND proto_payload.audit_log.method_name LIKE &#39;datasetservice%&#39;<br>LIMIT<br> 100</pre><p>After run the query, you should see the output like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QgplyJgYAw8L93Rn" /></figure><p><strong>Task 3. To find the activities for BigQuery tables</strong></p><p>You can query the activities that a dataset is created or deleted:</p><pre>SELECT<br> timestamp,<br> severity,<br> resource.type,<br> proto_payload.audit_log.authentication_info.principal_email,<br> proto_payload.audit_log.method_name,<br> proto_payload.audit_log.resource_name,<br>FROM<br> `[Your Project Id].global._Required._AllLogs`<br>WHERE<br> log_id = &#39;cloudaudit.googleapis.com/activity&#39;<br> AND proto_payload.audit_log.method_name LIKE &#39;%TableService%&#39;<br>LIMIT<br> 100</pre><p>After run the query, you should see the output like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*REyZPbwK41Vfotxk" /></figure><p><strong>Task 4. To view the queries completed in BigQuery</strong></p><p>Run the following query:</p><pre>SELECT<br> timestamp,<br> resource.labels.project_id,<br> proto_payload.audit_log.authentication_info.principal_email,<br> JSON_VALUE(proto_payload.audit_log.service_data.jobCompletedEvent.job.jobConfiguration.query.query) AS query,<br> JSON_VALUE(proto_payload.audit_log.service_data.jobCompletedEvent.job.jobConfiguration.query.statementType) AS statementType,<br> JSON_VALUE(proto_payload.audit_log.service_data.jobCompletedEvent.job.jobStatus.error.message) AS message,<br> JSON_VALUE(proto_payload.audit_log.service_data.jobCompletedEvent.job.jobStatistics.startTime) AS startTime,<br> JSON_VALUE(proto_payload.audit_log.service_data.jobCompletedEvent.job.jobStatistics.endTime) AS endTime,<br> CAST(TIMESTAMP_DIFF( CAST(JSON_VALUE(proto_payload.audit_log.service_data.jobCompletedEvent.job.jobStatistics.endTime) AS TIMESTAMP), CAST(JSON_VALUE(proto_payload.audit_log.service_data.jobCompletedEvent.job.jobStatistics.startTime) AS TIMESTAMP), MILLISECOND)/1000 AS INT64) AS run_seconds,<br> CAST(JSON_VALUE(proto_payload.audit_log.service_data.jobCompletedEvent.job.jobStatistics.totalProcessedBytes) AS INT64) AS totalProcessedBytes,<br> CAST(JSON_VALUE(proto_payload.audit_log.service_data.jobCompletedEvent.job.jobStatistics.totalSlotMs) AS INT64) AS totalSlotMs,<br> JSON_VALUE(proto_payload.audit_log.service_data.jobCompletedEvent.job.jobStatistics.referencedTables) AS tables_ref,<br> CAST(JSON_VALUE(proto_payload.audit_log.service_data.jobCompletedEvent.job.jobStatistics.totalTablesProcessed) AS INT64) AS totalTablesProcessed,<br> CAST(JSON_VALUE(proto_payload.audit_log.service_data.jobCompletedEvent.job.jobStatistics.queryOutputRowCount) AS INT64) AS queryOutputRowCount,<br> severity<br>FROM<br> `[Your Project Id].global._Default._Default`<br>WHERE<br> log_id = &quot;cloudaudit.googleapis.com/data_access&quot;<br> AND proto_payload.audit_log.service_data.jobCompletedEvent IS NOT NULL<br>ORDER BY<br> startTime</pre><p>After the query completes, you should see the output like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yIhioPqh3mZwXguM" /></figure><p>Scroll through the results of the executed queries.</p><p><strong>Task 5. To chart the query result</strong></p><p>Instead of using a table to see the results, Log Analytics also supports creating charts for visualization. For example, to view a pie chart for the queries that have run, you can click the <strong>Chart</strong> button in the result view, select <strong>Pie chart</strong> as the chart type and <strong>query</strong> as the column. You should see a chart similar to the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HoiWqDgj6gqLAp58" /></figure><p>We’ve only scratched the surface of BigQuery log analysis; you can explore many other queries and charts to enhance your understanding of BigQuery. Feel free to contribute and create samples in <a href="https://github.com/GoogleCloudPlatform/observability-analytics-samples/tree/main/samples/logging">GCP’s sample GitHub repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f5454626c6c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/use-log-analytics-for-bigquery-usage-analysis-on-google-cloud-8f5454626c6c">Use Log Analytics for BigQuery Usage Analysis on Google Cloud</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrate Open Telemetry with Cloud Ops in a Linux Environment]]></title>
            <link>https://medium.com/google-cloud/integrate-open-telemetry-with-cloud-ops-in-a-linux-environment-5b03902911d3?source=rss-aaed0024dcd7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b03902911d3</guid>
            <category><![CDATA[gcp-security-operations]]></category>
            <category><![CDATA[opentelemetry]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Xiang Shen]]></dc:creator>
            <pubDate>Tue, 12 Mar 2024 02:03:35 GMT</pubDate>
            <atom:updated>2024-03-12T06:28:16.035Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<h3><strong>Integrate Open Telemetry with Google Cloud Ops in a Linux Environment</strong></h3><h3><strong>Overview</strong></h3><p>The OpenTelemetry documentation website outlines <a href="https://opentelemetry.io/docs/collector/deployment/">three basic patterns</a> users can employ to transmit telemetry data from their applications to a backend.</p><ul><li><strong>No Collector</strong></li></ul><p>The simplest pattern is to <a href="https://opentelemetry.io/docs/languages/">instrument</a> applications using an OpenTelemetry SDK that export telemetry signals (traces, metrics, logs) directly into a backend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/0*65xUYihm2MzP-CEU" /></figure><ul><li><strong>Use an agent</strong></li></ul><p>The agent collector deployment pattern consists of applications — <a href="https://opentelemetry.io/docs/languages/">instrumented</a> with an OpenTelemetry SDK using <a href="https://opentelemetry.io/docs/specs/otel/protocol/">OpenTelemetry protocol (OTLP)</a> — or other collectors (using the OTLP exporter) that send telemetry signals to a <a href="https://opentelemetry.io/docs/collector/">collector</a> instance running with the application or on the same host as the application (such as a sidecar or a daemonset).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*39G9LUXxVhSzCykf" /></figure><ul><li><strong>Use a gateway</strong></li></ul><p>The gateway collector deployment pattern consists of applications (or other collectors) sending telemetry signals to a single OTLP endpoint provided by one or more collector instances running as a standalone service (for example, a deployment in Kubernetes), typically per cluster, per data center or per region</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dx9kBQ-ZiaDEgeOT" /></figure><p>When possible, you should consider to use OpenTelemetry Collectors since they provide a vendor agnostic solution to receive, process, and export data in a wide range of existing telemetry formats and protocols. OpenTelemetry Collectors also allow you to export telemetry to one or multiple backends, including <a href="https://cloud.google.com/products/operations">Google Cloud Operation Suite</a> (Cloud Ops).</p><p>For highly reliable and scalable data ingestion, employing the gateway pattern is highly recommended.</p><h3><strong>Implementation</strong></h3><p>This tutorial will guide you through the steps of sending telemetry data from a Java Spring Boot application to Cloud Ops, using the open-source OpenTelemetry collector. Once completed, the architecture should resemble the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/0*H72W-vE_lu8-YkYB" /></figure><p>For simplicity, a Debian-based Linux distribution is used as an example. However, you should be able to adopt the pattern for other Linux distributions in any non-Google Cloud environments, such as in an on-premises VMWare environment, or in a different Cloud.</p><h4>Create the sample Spring Boot Application</h4><p>Perform the following steps on the Linux server (either the same or a different one) where you intend to run your application:</p><ol><li>To install the JDK and the required tools, execute the following commands, if they are not already installed:</li></ol><pre>sudo apt update &amp;&amp; sudo apt upgrade<br>sudo apt install openjdk-17-jdk unzip maven</pre><p>2. Create the Java Spring Boot sample Application and download it</p><pre>curl https://start.spring.io/starter.zip  \<br>   -d javaVersion=17 -d type=maven-project \<br>   -d language=java -d platformVersion=3.2.1 \<br>   -d packaging\=jar \<br>   -d groupId=com.example \<br>   -d artifactId=demo \<br>   -d name=demo \<br>   -d packageName=com.example.demo \<br>   -d dependencies=web \<br>   -o my-project.zip</pre><p>3. Unzip the content in the java-demo directory</p><pre>mkdir java-demo &amp;&amp; cd java-demo<br>unzip ../my-project.zip</pre><p>After run the commands, you should have the following files and directories in your current directory:</p><pre>HELP.md mvnw mvnw.cmd pom.xml src</pre><p>4. Create the <strong>RollController.java</strong> file</p><pre>cat &lt;&lt; EOF &gt; src/main/java/com/example/demo/RollController.java<br>package com.example.demo;<br><br>import java.util.Optional;<br>import java.util.concurrent.ThreadLocalRandom;<br>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.RequestParam;<br>import org.springframework.web.bind.annotation.RestController;<br><br>@RestController<br>public class RollController {<br>  private static final Logger logger = LoggerFactory.getLogger(RollController.class);<br><br>  @GetMapping(&quot;/rolldice&quot;)<br>  public String index(@RequestParam(&quot;player&quot;) Optional&lt;String&gt; player) {<br>    int result = this.getRandomNumber(1, 6);<br>    if (player.isPresent()) {<br>      logger.info(&quot;{} is rolling the dice: {}&quot;, player.get(), result);<br>    } else {<br>      logger.info(&quot;Anonymous player is rolling the dice: {}&quot;, result);<br>    }<br>    return Integer.toString(result);<br>  }<br><br>  public int getRandomNumber(int min, int max) {<br>    return ThreadLocalRandom.current().nextInt(min, max + 1);<br>  }<br>}<br>EOF</pre><p>5. Update the <strong>DemoApplication.java</strong> file</p><pre>cat &lt;&lt; EOF &gt; src/main/java/com/example/demo/DemoApplication.java<br>package com.example.demo;<br><br>import org.springframework.boot.Banner;<br>import org.springframework.boot.SpringApplication;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;<br><br>@SpringBootApplication<br>public class DemoApplication {<br><br>    public static void main(String[] args) {<br>        SpringApplication app = new SpringApplication(DemoApplication.class);<br>        app.setBannerMode(Banner.Mode.OFF);<br>        app.run(args);<br>    }<br>}<br>EOF</pre><p>6. Run the application using <strong>Maven</strong></p><pre>./mvnw spring-boot:run</pre><p>After finishing testing, you can press Control-c to stop the application.</p><p>7. Test the application</p><p>In a different terminal, send a request using <strong>curl</strong>:</p><pre>curl http://localhost:8080/rolldice</pre><p>In the Maven window, you should have output similar to the following:</p><pre>……<br>INFO 325243 - - [nio-8080-exec-5] [65adc697c76d7e3a51343a6fc20274d9–51343a6fc20274d9]<br>com.example.demo.RollController : Anonymous player is rolling the dice: 5</pre><h3>Install and configure collector</h3><p>When it comes to collectors, you can utilize the open-source <a href="https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/exporter/googlecloudexporter/README.md">Google Cloud Exporter</a>, and <a href="https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/exporter/googlemanagedprometheusexporter">Google Managed Service for Prometheus Exporter</a>. These exporters enable seamless data transmission from your application to the Cloud Ops backend.</p><p>To accomplish this, login to the linux server you want to install the collector and do the following.</p><ol><li>Check the <a href="https://github.com/open-telemetry/opentelemetry-collector-releases/releases">releases</a> of the collector and download it. For example, the following command will download the v0.92.0 collector to your current directory</li></ol><pre>curl -L -O https://github.com/open-telemetry/opentelemetry-collector-releases/releases/download/v0.92.0/otelcol-contrib_0.92.0_linux_amd64.deb</pre><p>2. Install the collector</p><pre>sudo apt install ./otelcol-contrib_0.92.0_linux_amd64.deb</pre><p>3. Check if the service is running</p><pre>systemctl status otelcol-contrib.service</pre><p>You should see output similar to the following:</p><pre>● otelcol-contrib.service — OpenTelemetry Collector Contrib<br>Loaded: loaded (/lib/systemd/system/otelcol-contrib.service; enabled; vendor preset: enabled)<br>Active: active (running) since Mon 2023–12–22 03:03:04 UTC; 6min ago<br>Main PID: 354900 (otelcol-contrib)<br>Tasks: 9 (limit: 19184)<br>Memory: 41.4M<br>CPU: 1.038s<br>CGroup: /system.slice/otelcol-contrib.service<br>└─354900 /usr/bin/otelcol-contrib - config=/etc/otelcol-contrib/config.yaml<br>……</pre><p>4. To update the configuration file, you can either use an editor or run the following command</p><pre>sudo bash -c &#39;cat &lt;&lt; EOF &gt; /etc/otelcol-contrib/config.yaml<br>receivers:<br>  otlp:<br>    protocols:<br>      grpc:<br>      http:<br>exporters:<br>  googlecloud:<br>  googlemanagedprometheus:<br>processors:<br>  # change the values as needed<br>  resource:<br>    attributes:<br>    - key: &quot;project_id&quot;<br>      value: &quot;YOUR-GOOGLE-CLOUD-PROJECT-ID&quot;<br>      action: upsert<br>    - key: &quot;location&quot;<br>      #it needs to be a GCP or AWS location such as us-east1 or aws:us-east-1<br>      value: &quot;us-central1&quot; <br>      action: upsert<br>    - key: &quot;cluster&quot;<br>      value: &quot;onprem&quot;<br>      action: upsert<br>    - key: &quot;namespace&quot;<br>      value: &quot;&quot;<br>      action: upsert<br>    - key: &quot;job&quot;<br>      value: &quot;metric_job&quot;<br>      action: upsert<br>    - key: &quot;instance&quot;<br>      value: &quot;test&quot;<br>      action: upsert<br>  transform:<br>    error_mode: ignore<br>    log_statements:<br>    - context: log<br>      statements:<br>      - set(attributes[&quot;gcp.log_name&quot;], resource.attributes[&quot;service.name&quot;]) where attributes[&quot;gcp.log_name&quot;] == nil  <br>  memory_limiter:<br>    check_interval: 1s<br>    limit_percentage: 65<br>    spike_limit_percentage: 20<br>  batch:<br>  resourcedetection:<br>    detectors: [env, system, gcp]<br>    timeout: 10s<br>service:<br>  pipelines:<br>    traces:<br>      receivers: [otlp]<br>      processors: [memory_limiter, batch]<br>      exporters: [googlecloud]<br>    metrics:<br>      receivers: [otlp]<br>      processors: [memory_limiter, batch, resourcedetection, resource]<br>      exporters: [googlemanagedprometheus]<br>    logs:<br>      receivers: [otlp]<br>      processors: [memory_limiter, transform, batch]<br>      exporters: [googlecloud]<br>EOF&#39;</pre><p>Depending on the platform the application is deployed to, you can use different detectors in the <strong>resourcedetection</strong> section. For example, you can use <strong>[env, ec2] </strong>for an application running on an AWS EC2 instance. For more information, you can read <a href="https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/processor/resourcedetectionprocessor/README.md">this doc</a>.</p><p>If you use an agent to collect data for the application and send it to a gateway, the processors , such as resource, detectors and transform, should be present in the agent rather than the gateway collector for high quality telemetry.</p><p>5. Create a service account for authentication</p><p>Ensure you have the proper permissions and perform the following steps in <a href="https://cloud.google.com/shell">Cloud Shell</a> opened from the Cloud console. If your platform supports <a href="https://cloud.google.com/iam/docs/workload-identity-federation">workload identity federation</a>, strongly consider using it instead of service accounts for enhanced security and simplified management.</p><p>a) Create the user-managed service account:</p><pre>export SA_NAME=otel-export-sa<br>export PROJECT_ID=[Your Project Id]<br>gcloud iam service-accounts create ${SA_NAME}</pre><p>Note:</p><ul><li><strong>SA_NAME</strong>: the name of the service account.</li><li><strong>PROJECT_ID</strong>: the Cloud Ops destination project ID.</li></ul><p>b) Grant the the following roles to the service account:</p><ul><li><a href="https://cloud.google.com/iam/docs/understanding-roles#monitoring-roles">Metrics</a>: roles/monitoring.metricWriter</li><li><a href="https://cloud.google.com/iam/docs/understanding-roles#cloud-trace-roles">Traces</a>: roles/cloudtrace.agent</li><li><a href="https://cloud.google.com/iam/docs/understanding-roles#logging-roles">Logs</a>: roles/logging.logWriter</li></ul><pre>gcloud projects add-iam-policy-binding ${PROJECT_ID} \<br> - member=serviceAccount:${SA_NAME}@${PROJECT_ID}.iam.gserviceaccount.com \<br> - role=roles/monitoring.metricWriter<br>gcloud projects add-iam-policy-binding ${PROJECT_ID} \<br> - member=serviceAccount:${SA_NAME}@${PROJECT_ID}.iam.gserviceaccount.com \<br> - role=roles/cloudtrace.agent<br>gcloud projects add-iam-policy-binding ${PROJECT_ID} \<br> - member=serviceAccount:${SA_NAME}@${PROJECT_ID}.iam.gserviceaccount.com \<br> - role=roles/logging.logWriter</pre><p>c) Download the service account key file</p><pre>gcloud iam service-accounts keys create otel-sa-key.json \<br> - iam-account=${SA_NAME}@${PROJECT_ID}.iam.gserviceaccount.com</pre><p><strong>Note</strong>: Keep the key file in a secure location and you may need it if you have to configure multiple collectors.</p><p>d) Copy the key file to the service directory</p><pre>sudo cp otel-sa-key.json /etc/otelcol-contrib/otel-sa-key.json<br>sudo chown otelcol-contrib:otelcol-contrib /etc/otelcol-contrib/otel-sa-key.json</pre><p>6. Update the environment for the service configuration file</p><p>The exporter will automatically look for the key file using the <strong>GOOGLE_APPLICATION_CREDENTIALS</strong> environment variable or, if that is unset, one of the <a href="https://cloud.google.com/docs/authentication/application-default-credentials">other known locations</a>. You can run the following command to add the environment variable to the configuration file.</p><pre>sudo bash -c &#39;cat &lt;&lt; EOF &gt;&gt; /etc/otelcol-contrib/otelcol-contrib.conf<br>GOOGLE_APPLICATION_CREDENTIALS=/etc/otelcol-contrib/otel-sa-key.json<br>EOF&#39;</pre><p>7. Restart the service</p><pre>sudo systemctl restart otelcol-contrib.service</pre><p>8. Check again to ensure the service is running</p><pre>systemctl status otelcol-contrib.service</pre><h3>Instrumentation</h3><p><a href="https://opentelemetry.io/docs/concepts/instrumentation/">Instrumentation</a> is the act of adding observability code to an app. There are <a href="https://opentelemetry.io/docs/languages/java/automatic/spring-boot/">different ways</a> to instrument a Spring Boot application. In this doc, you will use the <a href="https://opentelemetry.io/docs/languages/java/automatic/">OpenTelemetry Java agent</a> with byte code instrumentation.</p><ol><li>Download the <strong>opentelemetry-javaagent.jar</strong>.</li></ol><p>You can find all the available <a href="https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases">releases</a> in the GitHub <a href="https://github.com/open-telemetry/opentelemetry-java-instrumentation">opentelemetry-java-instrumentation repository.</a></p><pre>curl -L -O https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases/download/v1.32.0/opentelemetry-javaagent.jar</pre><p>2. Set and export variables that specify the Java agent JAR and the Google Cloud exporter. If you deploy the application and the collector on the same linux server, you can use 127.0.0.1 or localhost as the endpoint URL. You need to change the IP or the DNS name if they are on different servers.</p><pre>export JAVA_TOOL_OPTIONS=&quot;-javaagent:./opentelemetry-javaagent.jar -Dotel.exporter.otlp.protocol=grpc&quot; \<br>  OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4317 \<br>  OTEL_TRACES_EXPORTER=otlp \<br>  OTEL_METRICS_EXPORTER=otlp \<br>  OTEL_LOGS_EXPORTER=otlp \<br>  OTEL_SERVICE_NAME=my-springboot-demo</pre><p>3. Build and run the Spring Boot application</p><pre>mvn clean package<br>java -jar ./target/demo-0.0.1-SNAPSHOT.jar</pre><p>4. Verify the results. From another terminal, send a request using curl again:</p><pre>curl localhost:8080/rolldice</pre><p>You should see the application respond with a random dice number.</p><p>5. Verify the telemetry data in Cloud Ops</p><p>From Cloud Trace, you should see trace data like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*s6IzopnnFixN3Gzl" /></figure><p>From the Cloud Logging console, you should see application log entries like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WFW63lrhKQqR9ao8" /></figure><p>From Cloud Monitoring, you can query and visualize the available metrics, for example the following MQL query shows the total memory allocated to the Java virtual machine.</p><pre>fetch prometheus_target<br>| metric &#39;prometheus.googleapis.com/jvm_memory_committed_bytes/gauge&#39;<br>| group_by 1m,<br>   [value_jvm_memory_committed_bytes_mean:<br>      mean(value.jvm_memory_committed_bytes)]<br>| every 1m<br>| group_by [],<br>   [value_jvm_memory_committed_bytes_mean_aggregate:<br>      aggregate(value_jvm_memory_committed_bytes_mean)]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dKSDtkbeNCCyadmZ" /></figure><p>If you prefer PromQL, you can check the PromQL radio button for query language in the middle of the window. An equivalent PromQL query for the previous example is:</p><pre>sum(avg_over_time(jvm_memory_committed_bytes[${__interval}]))</pre><h3>Use a Gateway</h3><p>The <a href="https://opentelemetry.io/docs/collector/deployment/gateway/">gateway</a> collector pattern provides a single OTLP end-point and lets you scale your deployment with multiple backend collectors. The following example will show you a gateway deployment using NGINX as the load balancer to front the collectors. Although NGINX is used in this doc, alternative load balancer solutions can be employed, provided that they offer equivalent capabilities.</p><ol><li>To install NGINX, run the following command:</li></ol><pre>sudo apt install nginx</pre><ol><li>Configure the NGINX server by creating a <strong>otel.conf</strong> file under <strong>/etc/nginx/conf.d</strong>. You can use an editor or run the following command.</li></ol><pre>sudo bash -c &#39;cat &lt;&lt; EOF &gt; /etc/nginx/conf.d/otel.conf<br>server {<br>    listen 14317 http2;<br>    server_name _;<br><br>    location / {<br>            grpc_pass      grpc://collector4317;<br>            grpc_next_upstream     error timeout invalid_header http_500;<br>            grpc_connect_timeout   2;<br>            grpc_set_header        Host            \$host;<br>            grpc_set_header        X-Real-IP       \$remote_addr;<br>            grpc_set_header        X-Forwarded-For \$proxy_add_x_forwarded_for;<br>    }<br>}<br><br>server {<br>    listen 14318;<br>    server_name _;<br><br>    location / {<br>            proxy_pass      http://collector4318;<br>            proxy_redirect  off;<br>            proxy_next_upstream     error timeout invalid_header http_500;<br>            proxy_connect_timeout   2;<br>            proxy_set_header        Host            \$host;<br>            proxy_set_header        X-Real-IP       \$remote_addr;<br>            proxy_set_header        X-Forwarded-For \$proxy_add_x_forwarded_for;<br>    }<br>}<br><br>upstream collector4317 {<br>    server collector1:4317;<br>    # Additional collectors<br>    # server collector2:4317;<br>}<br><br>upstream collector4318 {<br>    server collector1:4318;<br>    # Additional collectors<br>    # server collector2:4318;<br>}<br>EOF&#39;</pre><p>In the configuration file, the listening ports are changed to 14317 and 14318 in case you run the NGINX server on the same linux box and have a port conflict. You can also add multiple collectors as you wish. If your collector server names are different, you need to replace them or use the IP addresses. For example, to use the IP for server collector1, you can do the following:</p><pre># Get the host IP address on the colletor1 host<br>hostname -i|cut -d&#39; &#39; -f2<br># Replace the IP on the NGINX host with the value you got<br>sudo sed -i -e &quot;s/collector1/IP/&quot; /etc/nginx/conf.d/otel.conf</pre><ol><li>Reload NGINX for the new configuration</li></ol><pre>sudo systemctl reload nginx</pre><ol><li>After the NGINX server reloads successfully, you can now use it in the <strong>OTEL_EXPORTER_OTLP_ENDPOINT</strong>:</li></ol><pre>export JAVA_TOOL_OPTIONS=&quot;-javaagent:./opentelemetry-javaagent.jar -Dotel.exporter.otlp.protocol=grpc&quot; \<br>  OTEL_EXPORTER_OTLP_ENDPOINT=http://[NGINX SERVER NAME or IP]:14317 \<br>  OTEL_TRACES_EXPORTER=otlp \<br>  OTEL_METRICS_EXPORTER=otlp \<br>  OTEL_LOGS_EXPORTER=otlp</pre><ol><li>Run the Spring Boot application again</li></ol><pre>java -jar ./target/demo-0.0.1-SNAPSHOT.jar</pre><p>After sending a few more requests using curl, you should see the corresponding trace, logging and metric data in Cloud Ops.</p><p>You can also use your favorite automation tool to install and configure all the elements. If you are interested, you can find an Ansible example <a href="https://github.com/GoogleCloudPlatform/observability-analytics-samples/tree/otel/samples/otel">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/0*FEDWX8sLW703pwd8" /></figure><p>In this example, a gateway pattern is used, and a collector has been configured as the local agent on the application servers. After the agents process the telemetry data, the data are sent to a gateway which has backend collectors configured to communicate with Google Cloud Operation Suite.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b03902911d3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/integrate-open-telemetry-with-cloud-ops-in-a-linux-environment-5b03902911d3">Integrate Open Telemetry with Cloud Ops in a Linux Environment</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>