畏难情绪和猎奇心理作祟,总是对那些奇奇怪怪的小功能感兴趣,对开源组件核心功能的源码阅读却拖拖拉拉
例如,presto-cli实际是一个command,这个command执行起来后才能支持SQL输入、查询执行、查询结果展示等,才形成了CLI(Command Line Interface
,命令行界面)
# 指定了option的command
./presto --server localhost:8080 --user sunrise --catalog hive
# command的运行逻辑由run()方法控制,运行起来后,允许用户与Presto服务进行查询交互
> select * from tpch.orders limit 10;
笔者的愚见: 如果一个command执行起来后,用户可以与之交互,则这个command就变成了CLI
令笔者感兴趣的是:presto-cli对应的名为presto
的command是如何实现的呢?
至于presto-cli是如何将用户输入的SQL传递给Presto集群,又如何执行进度、执行结果等,笔者并不感兴趣
在阅读presto-cli模块的源码时,发现presto-cli的入口类为Presto,其main()方法中启动了一个Console类
public final class Presto
{
private Presto() {}
public static void main(String[] args)
{
Console console = singleCommand(Console.class).parse(args);
if (console.helpOption.showHelpIfRequested() ||
console.versionOption.showVersionIfRequested()) {
return;
}
System.exit(console.run() ? 0 : 1);
}
}
Console类的定义如下,对应上面截图中的presto命令(一个single command)
@Command(name = "presto", description = "Presto interactive console")
public class Console
{
... // 省略static final字段,只展示与option有关的字段
@Inject
public HelpOption helpOption;
@Inject
public VersionOption versionOption = new VersionOption();
@Inject
public ClientOptions clientOptions = new ClientOptions();
... // 其他代码省略
}
仔细阅读相关代码后发现,presto命令的实现依赖了airlift的airline,还使用的是不再维护的0.8版本的airline
deprecated的Airline,对Airline的介绍如下:
Airline is a Java annotation-based framework for parsing Git like command line structures.
Airline是基于注解的Java框架,用于解析像git一样的命令
Airline的maven依赖如下:
<dependency>
<groupId>io.airliftgroupId>
<artifactId>airlineartifactId>
<version>0.9version>
dependency>
Airline 2的介绍则更加直白,就是一个构建CLI的Java库
Airline is an annotation-driven Java library for building Command Line Interfaces (CLIs), it supports simple commands all the way through to complex Git style CLIs with groups and user defined command aliases.
Airline是注解驱动的、用于构建CLI的Java库。从简单的command,到复杂的git风格(有group和用户自定义command别名)的CLI,Airline都支持
Airline 2的maven依赖如下:
<dependency>
<groupId>com.github.rvessegroupId>
<artifactId>airlineartifactId>
<version>2.9.0version>
dependency>
目标: 使用Airline实现一个简单的即席查询(ad-hoc query)的伪CLI,只打印启动CLI时的用户选项(client options)
整个项目需要使用到如下maven依赖
<dependencies>
<dependency>
<groupId>io.airliftgroupId>
<artifactId>airlineartifactId>
<version>0.9version>
dependency>
<dependency>
<groupId>com.google.guavagroupId>
<artifactId>guavaartifactId>
<version>31.1-jreversion>
dependency>
dependencies>
--help
、--version
这两个必备的option,还有--serevr
、--user
、--session
等与访问即席查询服务有关的client options--help
选项,可以直接使用Airline提供的HelpOption
类--version
选项和后续的client options都需要自定义,需要使用Airline的@Option
注解模拟presto-cli,VersionOption的代码实现如下:
public class VersionOption
{
// 可选的option,即command中可以不使用;默认值为false,即默认不展示cli的version信息
@Option(name = "--version", description = "Display version information and exit")
public Boolean version = false;
// 返回version,以决定是否运行cli;一般展示version和帮助信息,不需要开启cli
public boolean showVersionIfRequested()
{
if (version) {
// AdhocQuery就是cli的入口类,获取入口类的implementation version,可能为null
String clientVersion = AdhocQuery.class.getPackage().getImplementationVersion();
System.out.println("Ad-hoc Query CLI " + firstNonNull(clientVersion, "(version unknown)"));
}
return version;
}
}
@Option
中的不同元素,体验各个元素的作用public class ClientOptions
{
// 带默认值的optional option
@Option(name = "--server", title = "server", description = "ad-hoc query server location (default: localhost:8080)")
public String server = "localhost:8080";
// 带默认值的optional option
@Option(name = "--user", title = "user", description = "Username")
public String user = System.getProperty("user.name");
// optional option,默认值null(string的默认值)
@Option(name = "--password", title = "password", description = "Password")
public String password;
// optional option,要么不使用该选项,要么使用时指定两个session属性
@Option(name = "--session", title = "session",
description = "Session property (property can be at most two; format: --session key1=value1 key2=value2; " +
"use 'SHOW SESSION' to see available properties)",
arity = 2)
public final List<Property> sessionProperties = new ArrayList<>();
// required option,使用command时必须使用debug选项;由于debug选项为boolean类型,也就是debug选项的值必须为true
@Option(name = "--debug", title = "debug", description = "Enable debug information", required = true)
public boolean debug;
// --help显示帮助信息时,将隐藏该选项
@Option(name = "--advanced", title = "advanced-properties", hidden = true,
description = "Advanced property (property can be used multiple times; format: --advanced key1=value1 --advanced key2=value2 ...)")
public List<Property> advancedProperties = new ArrayList<>();
@Override
public String toString()
{
return toStringHelper(this)
.add("server", server)
.add("user", user)
.add("password", password)
.add("sessionProperties", sessionProperties)
.add("debug", debug)
.add("advancedProperties", advancedProperties)
.toString();
}
}
k1=v1
类型的键值对public class Property {
private static final Splitter NAME_VALUE_SPLITTER = Splitter.on('=').limit(2);
private static final CharMatcher PRINTABLE_ASCII = CharMatcher.inRange((char) 0x21, (char) 0x7E); // spaces are not allowed
private final String name;
private final String value;
public Property(String property) {
List<String> nameValue = NAME_VALUE_SPLITTER.splitToList(property);
checkArgument(nameValue.size() == 2, "Invalid property: %s", property);
name = nameValue.get(0);
value = nameValue.get(1);
verifyProperty(name, value);
System.out.printf("create property from property string (%s)\n", property);
}
private static void verifyProperty(String name, String value) {
checkArgument(!name.isEmpty(), "Session property name is empty");
checkArgument(name.indexOf('=') < 0, "Session property name must not contain '=': %s", name);
checkArgument(PRINTABLE_ASCII.matchesAllOf(name), "Session property name contains spaces or is not US_ASCII: %s", name);
checkArgument(PRINTABLE_ASCII.matchesAllOf(value), "Session property value contains spaces or is not US_ASCII: %s", value);
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return name + '=' + value;
}
@Override
public int hashCode() {
return Objects.hash(name, value);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Property other = (Property) obj;
return Objects.equals(this.name, other.name) &&
Objects.equals(this.value, other.value);
}
}
使用Airline提供的@Command
注解定义command:
@Inject
),传递给commandrun()
方法,里面包含命令的执行逻辑;为了简单起见,这里不支持用户交互,所以是一个伪CLI @Command(name = "adhoc-query", description = "Ad-hoc query interactive console")
public class Console
{
@Inject // javax.inject.Inject;
public HelpOption helpOption;
// 不知为何,VersionOption无法自动实现依赖注入,需要手动创建,且无法去除@Inject注解
@Inject
public VersionOption versionOption = new VersionOption();
@Inject
public ClientOptions clientOptions;
/**
* 简单打印client options的值
*/
public void run()
{
System.out.println(clientOptions);
}
}
AdhocQuery
:public class AdhocQuery
{
// 工具类,不支持对象的创建
private AdhocQuery() {}
public static void main(String[] args)
{
// 使用SingleCommand.singleCommand()创建一个parser,可以解析Console的命令行参数,如option、argument等
// 使用parse()方法解析来自args的命令行参数,得到对应的、已初始化的命令行
Console console = singleCommand(Console.class).parse(args);
// 如果使用--help选项,则打印command帮助信息后退出
// 如果使用--version选项,则打印command帮助信息后退出
if (console.helpOption.showHelpIfRequested() ||
console.versionOption.showVersionIfRequested()) {
return;
}
// 执行command,这里选择打印command的client options信息
console.run();
}
}
required=true
带来的影响
对照帮助信息,理解@Option
的多个元素
hidden = true
带来的影响
--advanced
选项--advanced
选项时,设置了hidden = true
,导致该选项的帮助信息被隐藏option的值
将args修改为--debug
,发现打印的client options信息如下:
null
--debug
定义为required的、boolean的option,导致在命令行中必须使用它ClientOptions{server=localhost:8080, user=11120066, password=null, sessionProperties=[], debug=true, advancedProperties=[]}
arity = 2
带来的影响
尝试使用--session
,添加访问即席查询的session property,args如下
--debug --session k1=v1
这是因为在定义--session
选项时,设置了arity = 2
,导致使用该选项时,必须且只能设置两个session property
按照之前使用maven创建一个可以通过java -jar
执行的jar包的经验,使用下面的plugin配置就可以实现该CLI的打包
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-shade-pluginartifactId>
<version>3.1.1version>
<executions>
<execution>
<phase>packagephase>
<goals>
<goal>shadegoal>
goals>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.sunrise.AdhocQuerymainClass>
transformer>
transformers>
configuration>
execution>
executions>
plugin>
生成的jar包改名、添加可执行权限,就可以像./presto --server localhost:8080 --user sunrise --catalog hive
一样去使用了
如果使用java -jar
并给出程序运行参数,也是能成功打印出帮助信息的
java -jar adhoc-query --debug --help
但是,笔者还是想跟presto-cli一样,提供一个能./adhoc-query --debug --help
这样执行的jar
查看presto-cli的打包方式,发现与当前使用的打包方式有差异
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-shade-pluginartifactId>
<version>3.1.1version>
<executions>
<execution>
<phase>packagephase>
<goals>
<goal>shadegoal>
goals>
<configuration>
<shadedArtifactAttached>trueshadedArtifactAttached>
<shadedClassifierName>executableshadedClassifierName>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<manifestEntries>
<Main-Class>com.sunrise.AdhocQueryMain-Class>
manifestEntries>
transformer>
transformers>
configuration>
execution>
executions>
plugin>
<plugin>
<groupId>org.skife.mavengroupId>
<artifactId>really-executable-jar-maven-pluginartifactId>
<version>1.0.5version>
<configuration>
<flags>-Xmx1Gflags>
<classifier>executableclassifier>
configuration>
<executions>
<execution>
<phase>packagephase>
<goals>
<goal>really-executable-jargoal>
goals>
execution>
executions>
plugin>
重新打包后,在target目录下发现有两个jar,一个是带executable后缀的、具有可执行权限的jar,这跟presto-cli原始的jar名一致
重命名airline-study-1.0-SNAPSHOT-executable.jar
,再次执行./adhoc-query --debug --help
,成功打印出帮助信息