-
Notifications
You must be signed in to change notification settings - Fork 1
/
CloudStorageLoader.scala
147 lines (130 loc) · 5.29 KB
/
CloudStorageLoader.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
/*
* Copyright (c) 2018-2021 Snowplow Analytics Ltd. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at
* http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and
* limitations there under.
*/
package com.snowplowanalytics.storage.googlecloudstorage.loader
import io.circe.parser.parse
import com.spotify.scio._
import org.joda.time.Duration
import org.apache.beam.sdk.coders.StringUtf8Coder
import org.apache.beam.sdk.io.FileIO.Write.FileNaming
import org.apache.beam.sdk.io.{Compression, FileBasedSink, FileIO, TextIO}
import org.apache.beam.sdk.io.fs.ResourceId
import org.apache.beam.sdk.io.gcp.pubsub.PubsubIO
import org.apache.beam.sdk.options.{ValueProvider, PipelineOptionsFactory}
import org.apache.beam.sdk.options.ValueProvider.NestedValueProvider
import org.apache.beam.sdk.transforms.SerializableFunction
import org.apache.beam.sdk.transforms.windowing.{FixedWindows, Window}
import com.snowplowanalytics.iglu.core._
import com.snowplowanalytics.iglu.core.circe.implicits._
/** Dataflow job outputting the content from a Pubsub subscription to a Cloud Storage bucket. */
object CloudStorageLoader {
def main(args: Array[String]): Unit = {
PipelineOptionsFactory.register(classOf[Options])
val options = PipelineOptionsFactory
.fromArgs(args: _*)
.withValidation
.as(classOf[Options])
options.setStreaming(true)
run(options)
}
def run(options: Options): Unit = {
val sc = ScioContext(options)
val outputDirectory = options.getOutputDirectory
val outputFileNamePrefix = options.getOutputFilenamePrefix
val shardTemplate = options.getShardTemplate
val outputFilenameSuffix = options.getOutputFilenameSuffix
val dateFormat = options.getDateFormat
val partitionedOutputDirectory = options.getPartitionedOutputDirectory()
val inputIO = PubsubIO.readStrings().fromSubscription(options.getInputSubscription)
val input = sc
.customInput("input", inputIO)
.withName("window")
.applyTransform(
Window.into(FixedWindows.of(Duration.standardMinutes(options.getWindowDuration.toLong)))
)
if (partitionedOutputDirectory.isAccessible()) {
// Partition output according to row type
val outputDynamic = FileIO.writeDynamic[String, String]()
.by(getRowType(_, outputDirectory).prefix)
.via(TextIO.sink())
.to(partitionedOutputDirectory.get())
.withNumShards(options.getNumShards)
.withCompression(getCompression(options.getCompression))
.withDestinationCoder(StringUtf8Coder.of())
.withNaming(new SerializableFunction[String, FileNaming] {
// Create FileNaming for partition of window which
// partitioned according to row type
override def apply(rowType: String): FileNaming =
WindowedFilenamePolicy(
None,
outputFileNamePrefix,
shardTemplate,
outputFilenameSuffix,
dateFormat,
Some(rowType)
)
})
input.saveAsCustomOutput("output", outputDynamic)
} else {
// Output to same directory without partitioning
// according to row type
val outputIO = TextIO.write()
.withWindowedWrites
.withNumShards(options.getNumShards)
.withWritableByteChannelFactory(
FileBasedSink.CompressionType.fromCanonical(getCompression(options.getCompression)))
.withTempDirectory(NestedValueProvider.of(
outputDirectory,
new SerializableFunction[String, ResourceId] {
def apply(input: String): ResourceId =
FileBasedSink.convertToFileResourceIfPossible(input)
}
))
.to(WindowedFilenamePolicy(
Some(outputDirectory),
outputFileNamePrefix,
shardTemplate,
outputFilenameSuffix,
dateFormat,
None
))
input.saveAsCustomOutput("output", outputIO)
}
sc.run()
}
/**
* Find type of the row according to its schema key
* @param row string to find the type of it
* @return row type of given string
*/
private[loader] def getRowType(row: String, partitionErrorDir: ValueProvider[String]): RowType =
parse(row) match {
case Left(_) => RowType.Unpartitioned(partitionErrorDir.get)
case Right(json) => SchemaKey.extract(json).fold(
_ => RowType.Unpartitioned(partitionErrorDir.get),
k => RowType.SelfDescribing(k)
)
}
/**
* Tries to parse a string as a [[Compression]], falls back to uncompressed.
* @param compression string to parse
* @return the parsed compression
*/
private def getCompression(compression: String): Compression =
compression.trim.toLowerCase match {
case "bz2" => Compression.BZIP2
case "gzip" => Compression.GZIP
case _ => Compression.UNCOMPRESSED
}
}