2014年11月30日日曜日

RethinkDBとgroovyでデータベースを一覧表示する

RethinkDBとgroovyでデータベースを一覧表示するには、以下のサンプルコードのようにdbListを使用します。

サンプルコード
@GrabConfig(systemClassLoader=true)
@Grab(group='com.rethinkdb', module='rethink-java-driver', version='0.3')
import com.rethinkdb.*

def hostname = "192.168.1.211" // replace this

RethinkDB r = RethinkDB.r
def conn = r.connect(hostname)
r.dbList().run(conn).each {
  println it
}
conn.close()

Apache Ambariとgroovyで、コンポーネントを列挙する

Apache Ambariとgroovyで、コンポーネントを列挙するには、以下のようなコードを実行します。

サンプルコード
@Grab(group='org.apache.httpcomponents', module='httpclient', version='4.3.5')
import org.apache.http.client.methods.*
import org.apache.http.impl.client.*
import org.apache.http.message.*
import org.apache.http.auth.*
import groovy.json.*

def host = "192.168.1.249" // replace this
def port = 8080
def user = "admin"
def password = "admin"
def cluster = "cluster1"
def service = "HDFS"

def httpclient = new DefaultHttpClient()
httpclient.withCloseable {
  def method = new HttpGet(
    "http://${user}:${password}@${host}:${port}/api/v1/clusters/${cluster}/services" +
    "/${service}/components?fields=ServiceComponentInfo/state"
  )
  def response = httpclient.execute(method)
  println response.getStatusLine().getStatusCode()

  def json = new JsonSlurper().parseText(response.getEntity().getContent().text)
  for(item in json.items){
    println "component name:${item.ServiceComponentInfo.component_name}"
    println "state:${item.ServiceComponentInfo.state}"
    println "href:${item.href}"
  }
}
動作環境
Apache Ambari 1.6.1, HDP2.1, groovy 2.3.2

2014年11月28日金曜日

groovyから気象情報APIを使用して、経度・緯度から気象情報を求める

groovyから気象情報APIを使用して、経度・緯度から気象情報を求めるには、以下のようなコードを実行します。

サンプルコード
@Grab(group='org.apache.httpcomponents', module='httpclient', version='4.3.5')
import org.apache.http.client.methods.*
import org.apache.http.impl.client.*
import org.apache.http.message.*
import groovy.json.*

def appid = "your-app-id"
// 緯度経度
def coordinates = "139.75363355,35.69400229"

def httpclient = new DefaultHttpClient()
def method = new HttpGet("http://weather.olp.yahooapis.jp/v1/place?appid=${appid}&output=json&coordinates=${coordinates}")
def response = httpclient.execute(method)
println response.getStatusLine().getStatusCode()

def json = new JsonSlurper().parseText(response.getEntity().getContent().text)
// タイプ、日時、降水強度(mm/h)
json.Feature.Property.WeatherList.Weather[0].each {
  println "${it.Type}:${it.Date}:${it.Rainfall}"
}
関連情報
YOLP(地図):気象情報API - Yahoo!デベロッパーネットワーク

2014年11月27日木曜日

groovyとDocker Remote APIでcontainerのIPアドレスを表示する

groovyとDocker Remote APIでcontainerのIPアドレスを表示するには、以下のようなコードを実行します。

サンプルコード
@Grab(group='org.apache.httpcomponents', module='httpclient', version='4.3.5')
import org.apache.http.client.methods.*
import org.apache.http.impl.client.*
import org.apache.http.message.*
import org.apache.http.auth.*
import groovy.json.*

def host = "192.168.1.215" // replace this
def port = 4243
def containerId = "your-container-id"

def httpclient = new DefaultHttpClient()
httpclient.withCloseable {

  def method = new HttpGet(
    "http://${host}:${port}/containers/${containerId}/json"
  )
  def response = httpclient.execute(method)
  println response.getStatusLine().getStatusCode()

  def json = new JsonSlurper().parseText(response.getEntity().getContent().text)
  println "IP Address:${json.NetworkSettings.IPAddress}"
  println "IP Prefix Length:${json.NetworkSettings.IPPrefixLen}"
  println "Gateway:${json.NetworkSettings.Gateway}"
}

Docker Remote APIを使用可能にする方法
ubuntuの場合、/etc/default/dockerに以下のように記述します。
DOCKER_OPTS="-H tcp://0.0.0.0:4243 -H unix:///var/run/docker.sock -d"
そのあと、dockerを再起動します。
sudo service docker restart

動作環境
Docker 1.2.0

2014年11月25日火曜日

groovyとApache Phoenixでテーブルを削除する

groovyとApache Phoenixでテーブルを削除するには、以下のようなコードを実行します。

サンプルコード
import groovy.sql.Sql
import java.sql.*

sql = Sql.newInstance(
  "jdbc:phoenix:localhost",
  "",
  "",
  "org.apache.phoenix.jdbc.PhoenixDriver")

stmt = """
DROP TABLE CUSTOMER
"""
sql.execute(stmt)
クライアント設定
phoenix-4.1.0-bin.tar.gzを解凍しphoenix-4.1.0-bin/hadoop2/phoenix-4.1.0-client-hadoop2.jarを~/.groovy/libなどにコピーします。

動作環境
groovy 2.3.6, JDK 7 Update 65, Hadoop 2.5.0, zookeeper 3.4.6, hbase 0.98.5, phoenix 4.1.0

2014年11月24日月曜日

groovyでGanymed SSH-2を使用する方法のまとめ

groovyでGanymed SSH-2を使用する方法のまとめ
○コマンド実行
○ファイルの列挙・アップロード・ダウンロード
○ディレクトリ操作
○その他のファイル操作

groovyとGanymed SSH-2で秘密鍵を使用してログインする

groovyとGanymed SSH-2で秘密鍵を使用してログインするには、以下のコードを実行します。

サンプルコード
@Grab(group='ch.ethz.ganymed', module='ganymed-ssh2', version='262')
import ch.ethz.ssh2.*

host = "your-linux-box"
username = "user"
// puttygenを使用している場合は、Conversions -> Export OpenSSH keyを選択する
privateKey = "openssh_private_key"  

// サーバに接続
conn = new Connection(host)
conn.connect()
if( !conn.authenticateWithPublicKey(username, new File(privateKey), null) ){
  throw new Exception("authentication failed.")
}

// コマンド実行
sess = conn.openSession()
sess.execCommand("""ls -alF""")
// 標準出力
stdout = new BufferedReader(new InputStreamReader(
  new StreamGobbler(sess.getStdout()), "UTF-8"))
stdout.withCloseable{
  it.eachLine { line ->
    println line
  }
}
// 標準エラー出力
stderr = new BufferedReader(new InputStreamReader(
  new StreamGobbler(sess.getStderr()), "UTF-8"))
stderr.withCloseable{
  it.eachLine { line ->
    println line
  }
}
sess.close()
conn.close()

○関連項目

groovyとGanymed SSH2でlinuxのディストリビューションとバージョンを取得する

groovyとGanymed SSH2でlinuxのディストリビューションとバージョンを取得するには、以下のコードを実行します。

サンプルコード
@Grab(group='ch.ethz.ganymed', module='ganymed-ssh2', version='262')
import ch.ethz.ssh2.*

host = "your-linux-box"
username = "user"
password = "password"

// サーバに接続
conn = new Connection(host)
conn.connect()
if( !conn.authenticateWithPassword(username, password) ){
  throw new Exception("authentication failed.")
}

sess = conn.openSession()
sess.execCommand("""lsb_release -ir""")
def result = [:]
// 標準出力
stdout = new BufferedReader(new InputStreamReader(
  new StreamGobbler(sess.getStdout()), "UTF-8"))
stdout.withCloseable{
  it.eachLine { line ->
    result.put( line.split(":")[0], line.split(":")[1].trim() )
  }
}
// 標準エラー出力
stderr = new BufferedReader(new InputStreamReader(
  new StreamGobbler(sess.getStderr()), "UTF-8"))
stderr.withCloseable{
  it.eachLine { line ->
    println line
  }
}
println result

sess.close()
conn.close()

○関連項目

2014年11月21日金曜日

groovyからYahoo!リバースジオコーダAPIを使用して、経度・緯度から住所を求める

groovyからYahoo!リバースジオコーダAPIを使用して、経度・緯度から住所を求めるには、以下のようなコードを実行します。

サンプルコード
@Grab(group='org.apache.httpcomponents', module='httpclient', version='4.3.5')
import org.apache.http.client.methods.*
import org.apache.http.impl.client.*
import org.apache.http.message.*
import groovy.json.*

def appid = "your-app-id"
def lon = 139.75363355
def lat = 35.69400229

def httpclient = new DefaultHttpClient()
def method = new HttpGet("http://reverse.search.olp.yahooapis.jp/OpenLocalPlatform/V1/reverseGeoCoder?appid=${appid}&output=json&lat=${lat}&lon=${lon}")
def response = httpclient.execute(method)
println response.getStatusLine().getStatusCode()

def json = new JsonSlurper().parseText(response.getEntity().getContent().text)
// 住所
println json.Feature.Property.Address[0]
関連情報
YOLP(地図):Yahoo!リバースジオコーダAPI - Yahoo!デベロッパーネットワーク

2014年11月20日木曜日

groovyとScoop REST APIでjobを開始する

groovyとScoop REST APIでjobを開始するには、以下のようなコードを実行します。

サンプルコード
@Grab(group='org.apache.httpcomponents', module='httpclient', version='4.3.5')
import org.apache.http.client.methods.*
import org.apache.http.impl.client.*
import org.apache.http.auth.*
import org.apache.http.entity.*
import groovy.json.*

def host = "localhost"
def port = 12000
def httpclient = new DefaultHttpClient()

def jobid = "1"
def method = new HttpPost(
  "http://${host}:${port}/sqoop/v1/submission/action/${jobid}"
)
response = httpclient.execute(method)

println response.getStatusLine().getStatusCode()
動作環境
groovy 2.3.6, JDK7 update67, Cloudera CDH 5.1.2

2014年11月18日火曜日

groovyとRabbitMQのHTTP APIを使用して、userを削除する

groovyとRabbitMQのHTTP APIを使用して、userを削除するには、以下のようなコードを実行します。

サンプルコード
@Grab(group='org.apache.httpcomponents', module='httpclient', version='4.3.5')
import org.apache.http.client.*
import org.apache.http.client.methods.*
import org.apache.http.client.protocol.*
import org.apache.http.impl.auth.*
import org.apache.http.impl.client.*
import org.apache.http.auth.*
import org.apache.http.entity.*
import org.apache.http.message.*
import org.apache.http.protocol.*
import org.apache.http.conn.*
import org.apache.http.*
import groovy.json.*

ConnectionKeepAliveStrategy ckas = new ConnectionKeepAliveStrategy() {
  public long getKeepAliveDuration(HttpResponse response, HttpContext context)
  {
    HeaderElementIterator it = new BasicHeaderElementIterator(
      response.headerIterator(HTTP.CONN_KEEP_ALIVE))
    while(it.hasNext()){
      HeaderElement he = it.nextElement()
      if( he.value != null && he.param.equalsIgnoreCase("timeout") ){
        try
        {
          return Long.parseLong(he.value) * 1000
        }
        catch(NumberFormatException nfex){}
      }
    }
    return 30 * 1000
  }
}
def host = "192.168.1.219"
def port = 15672
def user = "guest"
def pass = "guest"

CredentialsProvider credsProvider = new BasicCredentialsProvider()
credsProvider.setCredentials(
  new AuthScope(host, port),
  new UsernamePasswordCredentials(user, pass)
)
AuthCache authCache = new BasicAuthCache()
HttpHost targetHost = new HttpHost(host, port, "http")
BasicScheme basicAuth = new BasicScheme()
authCache.put(targetHost, basicAuth)
HttpClientContext context = HttpClientContext.create()
context.setCredentialsProvider(credsProvider)
context.setAuthCache(authCache)

CloseableHttpClient httpclient = HttpClients.custom()
  .setKeepAliveStrategy(ckas)
  .build()
httpclient.withCloseable {
  // ユーザの削除
  def newUser = "user1"
  def method = new HttpDelete("http://${host}:${port}/api/users/${newUser}")
  response = httpclient.execute(method, context)
  println response.getStatusLine().getStatusCode()
}
動作環境
groovy 2.3.6, JDK7 update 65, RabbitMQ 3.3.5

2014年11月16日日曜日

Apache Ambariとgroovyで、サービスを列挙する

Apache Ambariとgroovyで、サービスを列挙するには、以下のようなコードを実行します。

サンプルコード
@Grab(group='org.apache.httpcomponents', module='httpclient', version='4.3.5')
import org.apache.http.client.methods.*
import org.apache.http.impl.client.*
import org.apache.http.message.*
import org.apache.http.auth.*
import groovy.json.*

def host = "192.168.1.249" // replace this
def port = 8080
def user = "admin"
def password = "admin"
def cluster = "cluster1"

def httpclient = new DefaultHttpClient()
httpclient.withCloseable {
  def method = new HttpGet(
    "http://${user}:${password}@${host}:${port}/api/v1/clusters/${cluster}/services?fields=ServiceInfo/state"
  )
  def response = httpclient.execute(method)
  println response.getStatusLine().getStatusCode()

  def json = new JsonSlurper().parseText(response.getEntity().getContent().text)
  for(item in json.items){
    println "service name:${item.ServiceInfo.service_name}"
    println "state:${item.ServiceInfo.state}"
    println "href:${item.href}"
  }
}
動作環境
Apache Ambari 1.6.1, HDP2.1, groovy 2.3.2

2014年11月14日金曜日

groovyとZooKeeperで、Watcherを使用してznodeができるまで待機する

groovyとZooKeeperで、Watcherを使用してznodeができるまで待機するには、以下のようなコードを実行します。

サンプルコード
@Grab(group='org.apache.zookeeper', module='zookeeper', version='3.4.6')
import org.apache.zookeeper.*
import org.apache.zookeeper.data.*


def zk = new ZooKeeper("localhost:2181", 3000, null)
def path = "/lock"
def lock = new Object()
try
{
  while(true){
    def stat = zk.exists(path, new Watcher(){
      public void process(WatchedEvent event){
        synchronized(lock){
          lock.notifyAll()
        }
      }
    });
    if( stat == null ){
      synchronized(lock){
        lock.wait()
      }
    } else {
      break
    }
  }
}
catch(InterruptedException iex)
{
  throw iex
}
finally
{
  zk.close()
}
動作環境
groovy 2.3.6, JDK 7 Update 65, Hadoop 2.5.0, zookeeper 3.4.6

2014年11月13日木曜日

groovyとSqoop REST APIでconnectionを一覧表示する

groovyとSqoop REST APIでconnectionを一覧表示するには、以下のようなコードを実行します。

サンプルコード
@Grab(group='org.apache.httpcomponents', module='httpclient', version='4.3.5')
import org.apache.http.client.methods.*
import org.apache.http.impl.client.*
import org.apache.http.auth.*
import groovy.json.*

def host = "localhost"
def port = 12000
def httpclient = new DefaultHttpClient()

def method = new HttpGet("http://${host}:${port}/sqoop/v1/connection/all")
response = httpclient.execute(method)

println response.getStatusLine().getStatusCode()
def json = new JsonSlurper().parseText(response.getEntity().getContent().text)
//println json
for(conn in json.all){
  println "id:${conn.id}, name:${conn.name}, connector id:${conn."connector-id"}"
}
動作環境
groovy 2.3.6, JDK7 update67, Cloudera CDH 5.1.2

2014年11月11日火曜日

groovyとRabbitMQのHTTP APIを使用して、userを作成する

groovyとRabbitMQのHTTP APIを使用して、userを作成するには、以下のようなコードを実行します。

サンプルコード
@Grab(group='org.apache.httpcomponents', module='httpclient', version='4.3.5')
import org.apache.http.client.*
import org.apache.http.client.methods.*
import org.apache.http.client.protocol.*
import org.apache.http.impl.auth.*
import org.apache.http.impl.client.*
import org.apache.http.auth.*
import org.apache.http.entity.*
import org.apache.http.message.*
import org.apache.http.protocol.*
import org.apache.http.conn.*
import org.apache.http.*
import groovy.json.*

ConnectionKeepAliveStrategy ckas = new ConnectionKeepAliveStrategy() {
  public long getKeepAliveDuration(HttpResponse response, HttpContext context)
  {
    HeaderElementIterator it = new BasicHeaderElementIterator(
      response.headerIterator(HTTP.CONN_KEEP_ALIVE))
    while(it.hasNext()){
      HeaderElement he = it.nextElement()
      if( he.value != null && he.param.equalsIgnoreCase("timeout") ){
        try
        {
          return Long.parseLong(he.value) * 1000
        }
        catch(NumberFormatException nfex){}
      }
    }
    return 30 * 1000
  }
}
def host = "192.168.1.219"
def port = 15672
def user = "guest"
def pass = "guest"

CredentialsProvider credsProvider = new BasicCredentialsProvider()
credsProvider.setCredentials(
  new AuthScope(host, port),
  new UsernamePasswordCredentials(user, pass)
)
AuthCache authCache = new BasicAuthCache()
HttpHost targetHost = new HttpHost(host, port, "http")
BasicScheme basicAuth = new BasicScheme()
authCache.put(targetHost, basicAuth)
HttpClientContext context = HttpClientContext.create()
context.setCredentialsProvider(credsProvider)
context.setAuthCache(authCache)

CloseableHttpClient httpclient = HttpClients.custom()
  .setKeepAliveStrategy(ckas)
  .build()
httpclient.withCloseable {
  // ユーザの作成
  def newUser = "user1"
  def method = new HttpPut("http://${host}:${port}/api/users/${newUser}")
  def json = new JsonBuilder()
  json (
    password:"user1", tags:"administrator"
  )
  method.setHeader("Content-Type", "application/json; charset=utf-8")
  method.setEntity(new StringEntity(json.toString(), "UTF-8"))
  response = httpclient.execute(method, context)
  println response.getStatusLine().getStatusCode()

  // パーミッションの設定
  def method2 = new HttpPut("http://${host}:${port}/api/permissions/%2f/${newUser}")
  json (
    configure:".*", write:".*", read:".*"
  )
  method2.setHeader("Content-Type", "application/json; charset=utf-8")
  method2.setEntity(new StringEntity(json.toString(), "UTF-8"))
  response = httpclient.execute(method2, context)
  println response.getStatusLine().getStatusCode()
}
動作環境
groovy 2.3.6, JDK7 update 65, RabbitMQ 3.3.5

2014年11月8日土曜日

groovyとDocker Remote APIでDockerfileからイメージを作成する

groovyとDocker Remote APIでDockerfileからイメージを作成するには、以下のようなコードを実行します。

サンプルコード
@Grab(group='org.apache.httpcomponents', module='httpclient', version='4.3.5')
import org.apache.http.client.methods.*
import org.apache.http.impl.client.*
import org.apache.http.entity.*
import groovy.json.*

// Dockerfileはstageディレクトリに配置する
def ant = new AntBuilder()
ant.tar(destfile:"dockerfile.tar", basedir:"./stage")

def host = "192.168.159.128" // replace this
def port = 4243
// 作成するイメージの名前
def imageName = "apache2"

def httpclient = new DefaultHttpClient()
httpclient.withCloseable {
  def method = new HttpPost(
    "http://${host}:${port}/build?t=${imageName}&rm=1&nocache=1"
  )
  // 作成したtarをpost
  def bae = new ByteArrayEntity(new File("dockerfile.tar").bytes)
  method.setEntity(bae)

  def response = httpclient.execute(method)
  response.withCloseable {
    System.out.println(response.getStatusLine())
    def isr = new InputStreamReader(response.getEntity().getContent())
    isr.eachLine { line ->
      def json = new JsonSlurper().parseText(line)
      println json.stream
    }
  }
}

Docker Remote APIを使用可能にする方法
ubuntuの場合、/etc/default/dockerに以下のように記述します。
DOCKER_OPTS="-H tcp://0.0.0.0:4243 -H unix:///var/run/docker.sock -d"
そのあと、dockerを再起動します。
sudo service docker restart

動作環境
Docker 1.3.1