• EnglishEspañol日本語한국어Português
  • Inicia sesiónComenzar ahora

Te ofrecemos esta traducción automática para facilitar la lectura.

In the event of any inconsistency between the English version and the translated version, the English versionwill take priority. Please visit this page for more information.

Crea una propuesta

Integración de monitoreo temporal

Nuestra integración temporal monitorea el rendimiento de sus datos temporales, ayudándolo a diagnosticar problemas en su aplicación de escritura distribuida, tolerante a fallas y escalable. Nuestra integración temporal le brinda un dashboard prediseñado con su aplicación Temporal SDK métrica más importante.

Después de configurar la integración con New Relic, vea sus datos en un panel como este, listo para usar.

Instalar el agente de infraestructura

El agente New Relic Infrastructure es la base para introducir sus datos temporales en New Relic. Si aún no lo ha hecho, instale el agente usando una de estas opciones:

Exponer Temporal métrica

Para obtener la Temporal métrica es necesario seguir algunos pasos de la siguiente manera:

Instale la docker y docker-compose en su host.

sudo apt-get update
sudo apt install docker
sudo apt install docker-compose

Los siguientes pasos ejecutarán una instancia local del servidor temporal utilizando el archivo de configuración predeterminado docker-compose.yml:

  1. Clona el repositorio.

    git clone https://github.com/temporalio/docker-compose.git
  2. Cambie el directorio a la raíz del proyecto y agregue el extremo y el puerto de Prometheus en el archivo docker-compose.yml .

    sudo nano docker-compose/docker-compose.yml
    • Debajo de container_name: temporal en la sección Medio ambiente, incluya el extremo Prometheus de la siguiente manera: - PROMETHEUS_ENDPOINT=0.0.0.0:8000.
    • De manera similar, dentro del mismo contenedor, debajo de la sección de puertos, especifique el puerto como: - 8000:8000.
    • A continuación se muestra un ejemplo de cómo exponer un extremo de Prometheus en su dockerlocal: componer la configuración del clúster temporal:
    Environment:
    - PROMETHEUS_ENDPOINT=0.0.0.0:8000
    ports:
    - 8000:8000
  3. Ejecute el comando docker-compose up .

    sudo docker-compose up

    Puede comprobar el servidor temporal ejecutándose en las siguientes URL:

  • El servidor temporal estará disponible el localhost:7233.
  • La UI de usuario web temporal estará disponible en http://<YOUR_DOMAIN>:8080
  • El servidor Temporal métrica estará disponible en el http://<YOUR_DOMAIN>:8000/metrics

Exponer Java SDK métrica

Puede configurar el registro de Prometheus y el reportero de estadísticas de Micrometer, establecer el alcance y exponer un extremo desde el cual Prometheus puede extraer la métrica del Cliente SDK de la siguiente manera.

  1. Para configurar métrica para el temporal del SDK de Java, cree un archivo MetricsWorker.java en el directorio raíz del proyecto.

    package <add_your_project_main_directory>; // please add your java application main directory name.
    import com.sun.net.httpserver.HttpServer;
    import com.uber.m3.tally.RootScopeBuilder;
    import com.uber.m3.tally.Scope;
    import com.uber.m3.tally.StatsReporter;
    import com.uber.m3.util.ImmutableMap;
    import io.micrometer.prometheus.PrometheusConfig;
    import io.micrometer.prometheus.PrometheusMeterRegistry;
    import io.temporal.client.WorkflowClient;
    import io.temporal.client.WorkflowClientOptions;
    import io.temporal.common.reporter.MicrometerClientStatsReporter;
    import io.temporal.serviceclient.WorkflowServiceStubs;
    import io.temporal.serviceclient.WorkflowServiceStubsOptions;
    import io.temporal.worker.Worker;
    import io.temporal.worker.WorkerFactory;
    public class MetricsWorker {
    static final String WORK_FLOW_TASK_QUEUE = "WORK_FLOW_TASK_QUEUE"; //This can be a work flow task name used to differentiate the metrics logs from other work flow
    public static void main(String[] args) {
    PrometheusMeterRegistry registry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);
    StatsReporter reporter = new MicrometerClientStatsReporter(registry);
    // set up a new scope, report every 10 seconds
    Scope scope = new RootScopeBuilder()
    .tags(ImmutableMap.of(
    "workerCustomTag1",
    "workerCustomTag1Value",
    "workerCustomTag2",
    "workerCustomTag2Value"))
    .reporter(reporter)
    .reportEvery(com.uber.m3.util.Duration.ofSeconds(10));
    // For Prometheus collection, expose the scrape endpoint at port 8077. See Micrometer documentation for details on starting the Prometheus scrape endpoint. For example,
    HttpServer scrapeEndpoint = MetricsUtils.startPrometheusScrapeEndpoint(registry, 8077); //note: MetricsUtils is a utility file with the scrape endpoint configuration. See Micrometer docs for details on this configuration.
    // Stopping the starter stops the HTTP server that exposes the scrape endpoint.
    //Runtime.getRuntime().addShutdownHook(new Thread(() -> scrapeEndpoint.stop(1)));
    //Create Workflow service stubs to connect to the Frontend Service.
    WorkflowServiceStubs service = WorkflowServiceStubs.newServiceStubs(
    WorkflowServiceStubsOptions.newBuilder()
    .setMetricsScope(scope) //set the metrics scope for the WorkflowServiceStubs
    .build());
    //Create a Workflow service client, which can be used to start, signal, and query Workflow Executions.
    WorkflowClient yourClient = WorkflowClient.newInstance(service,
    WorkflowClientOptions.newBuilder().build());

Runtime.getRuntime().addShutdownHook(new Thread(() -> scrapeEndpoint.stop(1))); // Add metrics scope to workflow service stub options WorkerFactory factory = WorkerFactory.newInstance(yourClient);

Worker worker = factory.newWorker(WORK_FLOW_TASK_QUEUE); worker.registerWorkflowImplementationTypes(SampleWorkflowImpl.class);//Design a workflow incorporating temporal elements and invoking activities within it. Determine where to capture metrics logs and register them with the worker worker.registerActivitiesImplementations(new SampleActivityImpl()); // Develop an Activity interface utilizing temporal annotations, proceed to its implementation, and establish a connection with the worker by mapping it to registerActivities

factory.start(); } }

2. Crear un archivo `MetricsUtils.java` en el directorio principal del proyecto, que contenga la configuración para el extremo de scraping.
```java
package <add_your_project_main_directory>; // please add your java application main directory name.
import com.sun.net.httpserver.HttpServer;
import io.micrometer.prometheus.PrometheusMeterRegistry;
import static java.nio.charset.StandardCharsets.UTF_8;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
public class MetricsUtils {
public static HttpServer startPrometheusScrapeEndpoint(
PrometheusMeterRegistry registry, int port) {
try {
HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
server.createContext(
"/metrics",
httpExchange -> {
String response = registry.scrape();
httpExchange.sendResponseHeaders(200, response.getBytes(UTF_8).length);
try (OutputStream os = httpExchange.getResponseBody()) {
os.write(response.getBytes(UTF_8));
}
});
server.start();
return server;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
  1. Agregue la dependencia en el archivo build.gradle debajo de dependency section.

    implementation "io.micrometer:micrometer-registry-prometheus"
  2. Copie el fragmento a continuación y modifique el mainClass con el directorio relevante para su proyecto en la tarea del archivo build.gradle para iniciar el trabajador.

    task startMetricsWorker(type: JavaExec) {
    mainClass = '<ProjectRoot.MetricsWorker>' // Add your MetricsWorker file directory.
    classpath = sourceSets.main.runtimeClasspath
    }
  3. Vaya al directorio de su proyecto y construya.

    ./gradlew build
  4. Iniciar al trabajador.

    ./gradlew startMetricsWorker
  5. Vea el trabajador métrica en el extremo Prometheus Scrape expuesto: http://<YOUR_DOMAIN>:8077/metrics.

Nota

Para más información sobre la configuración del SDK métrica, consulta la documentación oficial de Temporal.

Configurando NRI-Prometheus

Después de una instalación exitosa, el agente New Relic Infrastructure . Para crear un archivo de configuración de nri-prometheus, siga estos pasos:

1.Cree un archivo con el nombre nri-prometheus-temporal-config.yml en esta ruta:

cd /etc/newrelic-infra/integrations.d/

Después de crear el archivo nri-prometheus-temporal-config.yml , debe actualizar las URL con YOUR_HOST_IP:

URL: ["http://<YOUR_HOST_IP>:8000/metrics", "http://<YOUR_HOST_IP>:8077/metrics"]

integrations:
- name: nri-prometheus
config:
standalone: false
# Defaults to true. When standalone is set to `false`, `nri-prometheus` requires an infrastructure agent to send data.
emitters: infra-sdk
# When running with infrastructure agent emitters will have to include infra-sdk
cluster_name: Temporal_Server_Metrics
# Match the name of your cluster with the name seen in New Relic.
targets:
- description: Temporal_Server_Metrics
urls: ["http://<YOUR_DOMAIN>:8000/metrics", "http://<YOUR_DOMAIN>:8077/metrics"]
# tls_config:
# ca_file_path: "/etc/etcd/etcd-client-ca.crt"
# cert_file_path: "/etc/etcd/etcd-client.crt"
# key_file_path: "/etc/etcd/etcd-client.key"
verbose: false
# Defaults to false. This determines whether or not the integration should run in verbose mode.
audit: false
# Defaults to false and does not include verbose mode. Audit mode logs the uncompressed data sent to New Relic and can lead to a high log volume.
# scrape_timeout: "YOUR_TIMEOUT_DURATION"
# `scrape_timeout` is not a mandatory configuration and defaults to 30s. The HTTP client timeout when fetching data from endpoints.
scrape_duration: "5s"
# worker_threads: 4
# `worker_threads` is not a mandatory configuration and defaults to `4` for clusters with more than 400 endpoints. Slowly increase the worker thread until scrape time falls between the desired `scrape_duration`. Note: Increasing this value too much results in huge memory consumption if too many metrics are scraped at once.
insecure_skip_verify: false
# Defaults to false. Determins if the integration should skip TLS verification or not.
timeout: 10s

Configuración de registro temporal

Para configurar el registro temporal, siga los pasos que se describen a continuación.

  1. Ejecute el siguiente comando docker para verificar el estado de ejecución del contenedor.

    bash
    $
    sudo docker ps
  2. Copie el ID del contenedor para el contenedor temporal-ui y ejecute el comando proporcionado.

    bash
    $
    sudo docker logs -f <container_id> &> /tmp/temporal.log &

    Luego, verifique el archivo de registro ubicado en el directorio /tmp/ llamado temporal.log.

Reenviar registro temporal a New Relic

Puede utilizar nuestro reenvío de registros para reenviar el registro temporal a New Relic. En máquinas Linux, su archivo de registro llamado logging.yml debe estar presente en esta ruta:

bash
$
cd /etc/newrelic-infra/logging.d/

Una vez creado el archivo de registro, incluya el script siguiente en el archivo logging.yml :

logs:
- name: temporal_logs
file: /tmp/temporal.log
attributes:
logtype: temporal_logs

Reiniciar el agente de infraestructura

Antes de que pueda comenzar a leer sus datos, utilice las instrucciones de nuestros documentos del agente de infraestructura para reiniciar su agente de infraestructura.

bash
$
sudo systemctl restart newrelic-infra.service

En un par de minutos, tu Temporal enviará métrica a one.newrelic.com.

Encuentra tus datos

Puede elegir nuestra plantilla dashboard prediseñada llamada Temporal para monitor su métrica Temporal. Siga estos pasos para utilizar nuestra plantilla dashboard prediseñadas:

  1. Desde one.newrelic.com, vaya a la página + Add data .
  2. Haga clic en Dashboards.
  3. En la barra de búsqueda, escribe Temporal.
  4. Debería aparecer el dashboard temporal. Haga clic en él para instalarlo.

Su dashboard temporal se considera un panel personalizado y se puede encontrar en la UI del panel. Para obtener documentos sobre el uso y edición del panel, consulte nuestros documentos dashboard .

Aquí hay una consulta NRQL para verificar la suma de latencia de la solicitud temporal:

SELECT sum(temporal_request_latency_sum) FROM Metric
Copyright © 2024 New Relic Inc.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.