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

2014年11月7日金曜日

groovyとZooKeeperで、sequential znodeを作成する

groovyとZooKeeperで、sequential znodeを作成するには、以下のようなコードを実行します。

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

def zk = new ZooKeeper("localhost:2181", 3000, null)
try
{
  zk.create("/test1", "sample1".getBytes("UTF-8"),
    ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL)
  for(child in zk.getChildren("/", false)){
    println child
  }
}
finally
{
  zk.close()
}
動作環境
groovy 2.3.6, JDK 7 Update 65, Hadoop 2.5.0, zookeeper 3.4.6

2014年11月6日木曜日

groovyとSqoop REST APIでsqoopのバージョンを取得する

groovyとSqoop REST APIでsqoopのバージョンを取得するには、以下のようなコードを実行します。

サンプルコード
@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/version")
response = httpclient.execute(method)

println response.getStatusLine().getStatusCode()
def json = new JsonSlurper().parseText(response.getEntity().getContent().text)
println json.version
動作環境
groovy 2.3.6, JDK7 update67, Cloudera CDH 5.1.2

2014年11月4日火曜日

groovyとRabbitMQのHTTP APIを使用して、userを一覧表示する

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.methods.*
import org.apache.http.impl.client.*
import org.apache.http.auth.*
import groovy.json.*

def host = "192.168.1.219"
def port = 15672
def user = "guest"
def pass = "guest"
def httpclient = new DefaultHttpClient()
httpclient.getCredentialsProvider().setCredentials(
  new AuthScope(host, port),
  new UsernamePasswordCredentials(user, pass)
)

def method = new HttpGet("http://${host}:${port}/api/users")
response = httpclient.execute(method)

println response.getStatusLine().getStatusCode()
def json = new JsonSlurper().parseText(response.getEntity().getContent().text)
println json
println "----"
for(ruser in json){
  println "[${ruser.name}]:tags=${ruser.tags}"
}
動作環境
groovy 2.3.6, JDK7 update 65, RabbitMQ 3.3.5

2014年11月2日日曜日

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}/hosts"
  )
  def response = httpclient.execute(method)
  println response.getStatusLine().getStatusCode()

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