|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one |
| 3 | + * or more contributor license agreements. See the NOTICE file |
| 4 | + * distributed with this work for additional information |
| 5 | + * regarding copyright ownership. The ASF licenses this file |
| 6 | + * to you under the Apache License, Version 2.0 (the |
| 7 | + * "License"); you may not use this file except in compliance |
| 8 | + * with the License. You may obtain a copy of the License at |
| 9 | + * |
| 10 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, software |
| 13 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | + * See the License for the specific language governing permissions and |
| 16 | + * limitations under the License. |
| 17 | + */ |
| 18 | +package org.apache.beam.sdk.io.gcp.spanner; |
| 19 | + |
| 20 | +import java.util.concurrent.TimeUnit; |
| 21 | +import org.apache.beam.sdk.extensions.gcp.util.GceMetadataUtil; |
| 22 | +import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Strings; |
| 23 | +import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Supplier; |
| 24 | +import org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Suppliers; |
| 25 | +import org.checkerframework.checker.nullness.qual.Nullable; |
| 26 | + |
| 27 | +/** Metadata class for SpannerIO. */ |
| 28 | +final class SpannerIOMetadata { |
| 29 | + |
| 30 | + private final @Nullable String beamJobId; |
| 31 | + |
| 32 | + static final Supplier<SpannerIOMetadata> INSTANCE = |
| 33 | + Suppliers.memoizeWithExpiration(() -> refreshInstance(), 5, TimeUnit.MINUTES); |
| 34 | + |
| 35 | + private SpannerIOMetadata(@Nullable String beamJobId) { |
| 36 | + this.beamJobId = beamJobId; |
| 37 | + } |
| 38 | + |
| 39 | + /** |
| 40 | + * Creates a SpannerIOMetadata. This will request metadata properly based on which runner is being |
| 41 | + * used. |
| 42 | + */ |
| 43 | + public static SpannerIOMetadata create() { |
| 44 | + return INSTANCE.get(); |
| 45 | + } |
| 46 | + |
| 47 | + private static SpannerIOMetadata refreshInstance() { |
| 48 | + String dataflowJobId = GceMetadataUtil.fetchDataflowJobId(); |
| 49 | + if (Strings.isNullOrEmpty(dataflowJobId)) { |
| 50 | + return new SpannerIOMetadata(null); |
| 51 | + } |
| 52 | + |
| 53 | + return new SpannerIOMetadata(dataflowJobId); |
| 54 | + } |
| 55 | + |
| 56 | + /* |
| 57 | + * Returns the beam job id. Can be null if it is not running on Dataflow. |
| 58 | + */ |
| 59 | + public @Nullable String getBeamJobId() { |
| 60 | + return this.beamJobId; |
| 61 | + } |
| 62 | +} |
0 commit comments