Skip to content

Commit

Permalink
Merge remote-tracking branch 'migration/main' into java-tasks-migration
Browse files Browse the repository at this point in the history
  • Loading branch information
averikitsch committed Oct 27, 2022
2 parents f6055b4 + 8729b7d commit 93c91d8
Show file tree
Hide file tree
Showing 15 changed files with 1,195 additions and 0 deletions.
157 changes: 157 additions & 0 deletions tasks/native-image-sample/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
# Cloud Tasks Sample Application with Native Image

The Cloud Tasks sample application demonstrates some common operations with
[Google Cloud Tasks](https://cloud.google.com/tasks) and is compatible with
Native Image compilation.

This application will create a new queue called `graal-test-queue` if it does
not already exist.
It will then submit a new task to this queue.

## Setup Instructions

You will need to follow these prerequisite steps in order to run these samples:

1. If you have not already, [create a Google Cloud Platform Project](https://cloud.google.com/resource-manager/docs/creating-managing-projects#creating_a_project).

2. Install the [Google Cloud SDK](https://cloud.google.com/sdk/) which will allow you to run the sample with your project's credentials.

Once installed, log in with Application Default Credentials using the following command:

```
gcloud auth application-default login
```

**Note:** Authenticating with Application Default Credentials is convenient to use during development, but we recommend [alternate methods of authentication](https://cloud.google.com/docs/authentication/production) during production use.

3. Install the native image compiler.

You can follow the [official installation instructions](https://www.graalvm.org/docs/getting-started/#install-graalvm).
After following the instructions, ensure that you install the Native Image extension installed by running:

```
gu install native-image
```

Once you finish following the instructions, verify that the default version of Java is set to the correct version by running `java -version` in a terminal.

You will see something similar to the below output:

```
$ java -version
openjdk version "17.0.3" 2022-04-19
OpenJDK Runtime Environment GraalVM CE 22.1.0 (build 17.0.3+7-jvmci-22.1-b06)
OpenJDK 64-Bit Server VM GraalVM CE 22.1.0 (build 17.0.3+7-jvmci-22.1-b06, mixed mode, sharing)
```

4. [Enable the Cloud Tasks APIs](https://console.cloud.google.com/apis/api/cloudtasks.googleapis.com).

### Run with Native Image Compilation

Navigate to this directory in a new terminal.

1. The project uses an environment variable `LOCATION_ID` to run the test. Set the environment variable by calling:

```
export LOCATION_ID=us-east1
```

2. Compile the application using the native image Compiler. This step may take a few minutes.

```
$ mvn package -P native
```



3. Run the application:

```
$ ./target/native-image-sample
```

4. The application runs through some basic Cloud Tasks operations (create queue, create task) and then prints some results of the operations.

```
Test queue ready: name: "projects/xxxxxxxxxx/locations/us-central1/queues/graal-test-queue-4009"
rate_limits {
max_dispatches_per_second: 500.0
max_burst_size: 100
max_concurrent_dispatches: 1
}
retry_config {
max_attempts: 100
min_backoff {
nanos: 100000000
}
max_backoff {
seconds: 3600
}
max_doublings: 16
}
state: RUNNING
Created task: name: "projects/xxxxxxxxxx/locations/us-central1/queues/graal-test-queue-4009/tasks/5886258204485021611"
http_request {
url: "https://google.com/"
http_method: GET
headers {
key: "User-Agent"
value: "Google-Cloud-Tasks"
}
}
schedule_time {
seconds: 1613189391
nanos: 486293000
}
create_time {
seconds: 1613189391
}
dispatch_deadline {
seconds: 600
}
view: BASIC
Queue purged
Queue deleted
```

5. Run the test in the project in the native-image mode

```
$ export LOCATION_ID=us-east1 && mvn test -P native
...
[INFO] -------------------------------------------------------
[INFO] T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.example.tasks.ITNativeImageTasksSample
...
[INFO] --- native-maven-plugin:0.9.9:test (test-native) @ native-image-sample ---
[INFO] ====================
[INFO] Initializing project: native-image-sample
...
com.example.tasks.ITNativeImageTasksSample > testRunSampleApplication SUCCESSFUL
Test run finished after 1025 ms
[ 3 containers found ]
[ 0 containers skipped ]
[ 3 containers started ]
[ 0 containers aborted ]
[ 3 containers successful ]
[ 0 containers failed ]
[ 1 tests found ]
[ 0 tests skipped ]
[ 1 tests started ]
[ 0 tests aborted ]
[ 1 tests successful ]
[ 0 tests failed ]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 02:27 min
...
```
142 changes: 142 additions & 0 deletions tasks/native-image-sample/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example.tasks</groupId>
<artifactId>native-image-sample</artifactId>
<name>Native Image Sample</name>

<!--
The parent pom defines common style checks and testing strategies for our samples.
Removing or replacing it should not affect the execution of the samples in anyway.
-->
<parent>
<groupId>com.google.cloud.samples</groupId>
<artifactId>shared-configuration</artifactId>
<version>1.2.0</version>
</parent>

<properties>
<!-- Java 8 because the Kokoro Sample test uses that Java version -->
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>libraries-bom</artifactId>
<version>26.1.3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-core</artifactId>
</dependency>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-tasks</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.truth</groupId>
<artifactId>truth</artifactId>
<version>1.1.3</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<!-- These plugins enable building the application to a JAR *not* using Native Image -->
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>com.example.TasksSampleApplication</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>

<profiles>
<profile>
<id>native</id>
<dependencies>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>5.9.1</version>
</dependency>
<dependency>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>junit-platform-native</artifactId>
<version>0.9.14</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<!-- Must use older version of surefire plugin for native-image testing. -->
<version>2.22.2</version>
<configuration>
<includes>
<include>**/IT*</include>
</includes>
</configuration>
</plugin>
<plugin>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>native-maven-plugin</artifactId>
<version>0.9.14</version>
<extensions>true</extensions>
<configuration>
<mainClass>com.example.tasks.TasksSampleApplication</mainClass>
<buildArgs>
<buildArg>--no-fallback</buildArg>
<buildArg>--no-server</buildArg>
</buildArgs>
</configuration>
<executions>
<execution>
<id>build-native</id>
<goals>
<goal>build</goal>
<goal>test</goal>
</goals>
<phase>package</phase>
</execution>
<execution>
<id>test-native</id>
<goals>
<goal>test</goal>
</goals>
<phase>test</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.tasks;

import com.google.cloud.ServiceOptions;
import com.google.cloud.tasks.v2.CloudTasksClient;
import com.google.cloud.tasks.v2.CreateQueueRequest;
import com.google.cloud.tasks.v2.HttpMethod;
import com.google.cloud.tasks.v2.HttpRequest;
import com.google.cloud.tasks.v2.LocationName;
import com.google.cloud.tasks.v2.Queue;
import com.google.cloud.tasks.v2.QueueName;
import com.google.cloud.tasks.v2.RateLimits;
import com.google.cloud.tasks.v2.Task;
import java.io.IOException;
import java.util.UUID;

/** Sample application demonstrating Native Image compatibility with Google Cloud Tasks APIs. */
public class TasksSampleApplication {
/**
* Queue name randomness added to avoid FAILED_PRECONDITION: The queue cannot be created because a
* queue with this name existed too recently.
*/
private static final String GRAALVM_TEST_QUEUE_NAME = "graal-test-queue-";

private static final String LOCATION_ID = System.getenv("LOCATION_ID");

/** Runs the Cloud Tasks sample application. */
public static void main(String[] args) throws IOException {
String projectId = ServiceOptions.getDefaultProjectId();
LocationName parent = LocationName.of(projectId, LOCATION_ID);
QueueName queueName =
QueueName.of(
parent.getProject(),
parent.getLocation(),
GRAALVM_TEST_QUEUE_NAME + UUID.randomUUID().toString());

try (CloudTasksClient client = CloudTasksClient.create()) {
// Create queue
Queue queue =
Queue.newBuilder()
.setName(queueName.toString())
.setRateLimits(RateLimits.newBuilder().setMaxConcurrentDispatches(1).build())
.build();

CreateQueueRequest createQueueRequest =
CreateQueueRequest.newBuilder().setParent(parent.toString()).setQueue(queue).build();

Queue createdQueue = client.createQueue(createQueueRequest);
System.out.println("Test queue ready: " + createdQueue);

// Create task
HttpRequest taskTarget =
HttpRequest.newBuilder()
.setUrl("https://google.com")
.setHttpMethod(HttpMethod.GET)
.build();

Task taskRequest = Task.newBuilder().setHttpRequest(taskTarget).build();
Task task = client.createTask(queueName, taskRequest);
System.out.println("Created task: " + task);

// Cleanup
client.purgeQueue(queueName);
System.out.println("Queue purged");

client.deleteQueue(queueName);
System.out.println("Queue deleted");
}
}
}
Loading

0 comments on commit 93c91d8

Please sign in to comment.