blob: 09b54bc22f03516b86d74ae5d7842a08d829b9ce [file]
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
#
"""Builds the Beam YAML pipeline that `beam pipe` runs.
`beam pipe --from SOURCE --to SINK` reads records from one set of files and
writes them to another, in the same or a different format. This module turns
those flags into a two-step Beam YAML pipeline: a read transform and a write
transform from Beam YAML's standard IO (`ReadFromCsv`, `WriteToJson`, ...).
The read and the write are chosen independently; Beam YAML's schemas connect
them.
It never builds or runs a pipeline, so it is tested on plain data, and
`beam pipe --dry-run` prints exactly what it returns.
"""
import os
import re
import shlex
from typing import NamedTuple
import yaml
class PipeSpecError(ValueError):
"""A problem with `beam pipe`'s flags, reported to the user as-is."""
class PipeSpec(NamedTuple):
"""The pipeline for one `beam pipe` command."""
spec: dict
# The sink path. Beam file sinks treat it as a prefix and write sharded
# files that start with it, so the command checks for and lists files
# matching it.
output_prefix: str
# Format name -> suffix of the Beam YAML transforms (ReadFrom<X>, WriteTo<X>).
_FORMATS = {'csv': 'Csv', 'json': 'Json', 'parquet': 'Parquet', 'avro': 'Avro'}
_EXTENSIONS = {
'.csv': 'csv',
'.json': 'json',
'.jsonl': 'json',
'.parquet': 'parquet',
'.avro': 'avro',
}
# Schemes handled by Beam filesystems. Anything else with '://' is rejected
# here with a clear message, rather than failing inside the pipeline.
_FILE_SCHEMES = ('gs', 's3', 'azfs', 'hdfs', 'file')
def build_pipe_spec(source, sink, from_format=None, to_format=None):
"""Returns the PipeSpec for `beam pipe --from source --to sink`.
Args:
source: The `--from` path or glob, on any Beam filesystem.
sink: The `--to` path prefix, on any Beam filesystem.
from_format: The source format; defaults to the file extension.
to_format: The sink format; defaults to the file extension.
Raises:
PipeSpecError: if a location or format is invalid. The message names the
flag that fixes it.
"""
read = _transform('ReadFrom', source, from_format, '--from-format')
write = _transform('WriteTo', sink, to_format, '--to-format')
spec = {'pipeline': {'type': 'chain', 'transforms': [read, write]}}
return PipeSpec(spec, sink)
# A trailing run of glob characters, dashes and Beam shard suffixes
# ("-00000-of-00001"), as in `out/users.json*` or `users.json-00000-of-00001`.
_SHARD_OR_GLOB_SUFFIX = re.compile(r'(-\d+-of-\d+|[-*?])+$')
def _extension(path):
"""The file extension of a path or glob, for example '.json'.
Beam file sinks write sharded files that start with the output path, so
reading one command's output in another uses a glob such as
`out/users.json*`. The extension is the one before that suffix.
"""
name = _SHARD_OR_GLOB_SUFFIX.sub(
'', os.path.basename(path.replace('\\', '/')))
return os.path.splitext(name)[1].lower()
def _transform(verb, path, fmt, flag):
if '://' in path and path.split('://', 1)[0].lower() not in _FILE_SCHEMES:
schemes = ', '.join(s + '://' for s in _FILE_SCHEMES)
raise PipeSpecError(
f'unsupported location {path!r}: use a local path or one of '
f'{schemes}')
# Never guess: without a flag the extension decides, and an unknown
# extension is an error that names the flag to add.
fmt = (fmt or _EXTENSIONS.get(_extension(path), '')).lower()
if not fmt:
raise PipeSpecError(
f'cannot tell the format of {path!r} (no known file extension)\n'
f' add {flag}, for example: {flag} json')
if fmt not in _FORMATS:
raise PipeSpecError(
f'unsupported format {fmt!r} for {path!r}; use one of: '
f'{", ".join(_FORMATS)}')
return {'type': verb + _FORMATS[fmt], 'config': {'path': path}}
def to_yaml(spec, argv):
"""Renders a pipeline as a Beam YAML file to save and run with `beam run`.
The file starts with a comment showing the command that generated it, so a
saved pipeline records where it came from.
"""
header = '# Generated by: beam pipe ' + shlex.join(argv)
return header + '\n' + yaml.safe_dump(spec, sort_keys=False)