You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@gearpump.apache.org by ma...@apache.org on 2016/05/10 02:42:11 UTC
[01/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Repository: incubator-gearpump
Updated Branches:
refs/heads/master 9bb9ca5d8 -> 83b36ef76
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/org/apache/gearpump/streaming/dsl/StreamAppSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/org/apache/gearpump/streaming/dsl/StreamAppSpec.scala b/streaming/src/test/scala/org/apache/gearpump/streaming/dsl/StreamAppSpec.scala
new file mode 100644
index 0000000..dd286de
--- /dev/null
+++ b/streaming/src/test/scala/org/apache/gearpump/streaming/dsl/StreamAppSpec.scala
@@ -0,0 +1,93 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.dsl
+
+import akka.actor.ActorSystem
+import org.apache.gearpump.cluster.TestUtil
+import org.apache.gearpump.cluster.client.ClientContext
+import org.apache.gearpump.streaming.dsl.plan.OpTranslator.SourceTask
+import org.mockito.Mockito.when
+import org.scalatest._
+import org.scalatest.mock.MockitoSugar
+
+import scala.concurrent.Await
+import scala.concurrent.duration.Duration
+class StreamAppSpec extends FlatSpec with Matchers with BeforeAndAfterAll with MockitoSugar {
+
+ implicit var system: ActorSystem = null
+
+ override def beforeAll(): Unit = {
+ system = ActorSystem("test", TestUtil.DEFAULT_CONFIG)
+ }
+
+ override def afterAll(): Unit = {
+ system.terminate()
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+
+ it should "be able to generate multiple new streams" in {
+ val context: ClientContext = mock[ClientContext]
+ when(context.system).thenReturn(system)
+
+ val app = StreamApp("dsl", context)
+ app.source(List("A"), 1, "")
+ app.source(List("B"), 1, "")
+
+ assert(app.graph.vertices.size == 2)
+ }
+
+ it should "plan the dsl to Processsor(TaskDescription) DAG" in {
+ val context: ClientContext = mock[ClientContext]
+ when(context.system).thenReturn(system)
+
+ val app = StreamApp("dsl", context)
+ val parallism = 3
+ app.source(List("A", "B", "C"), parallism, "").flatMap(Array(_)).reduce(_ + _)
+ val task = app.plan.dag.vertices.iterator.next()
+ assert(task.taskClass == classOf[SourceTask[_, _]].getName)
+ assert(task.parallelism == parallism)
+ }
+
+ it should "produce 3 messages" in {
+ val context: ClientContext = mock[ClientContext]
+ when(context.system).thenReturn(system)
+ val app = StreamApp("dsl", context)
+ val list = List[String](
+ "0",
+ "1",
+ "2"
+ )
+ val producer = app.source(list, 1, "producer").flatMap(Array(_)).reduce(_ + _)
+ val task = app.plan.dag.vertices.iterator.next()
+ /*
+ val task = app.plan.dag.vertices.iterator.map(desc => {
+ LOG.info(s"${desc.taskClass}")
+ })
+ val sum = producer.flatMap(msg => {
+ LOG.info("in flatMap")
+ assert(msg.msg.isInstanceOf[String])
+ val num = msg.msg.asInstanceOf[String].toInt
+ Array(num)
+ }).reduce(_+_)
+ val task = app.plan.dag.vertices.iterator.map(desc => {
+ LOG.info(s"${desc.taskClass}")
+ })
+ */
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/org/apache/gearpump/streaming/dsl/StreamSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/org/apache/gearpump/streaming/dsl/StreamSpec.scala b/streaming/src/test/scala/org/apache/gearpump/streaming/dsl/StreamSpec.scala
new file mode 100644
index 0000000..6bdd8aa
--- /dev/null
+++ b/streaming/src/test/scala/org/apache/gearpump/streaming/dsl/StreamSpec.scala
@@ -0,0 +1,125 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.dsl
+
+import akka.actor._
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.client.ClientContext
+import org.apache.gearpump.cluster.{TestUtil, UserConfig}
+import org.apache.gearpump.partitioner.{CoLocationPartitioner, HashPartitioner}
+import org.apache.gearpump.streaming.dsl.StreamSpec.Join
+import org.apache.gearpump.streaming.dsl.partitioner.GroupByPartitioner
+import org.apache.gearpump.streaming.dsl.plan.OpTranslator._
+import org.apache.gearpump.streaming.task.{StartTime, Task, TaskContext}
+import org.apache.gearpump.util.Graph
+import org.apache.gearpump.util.Graph._
+import org.mockito.Mockito.when
+import org.scalatest._
+import org.scalatest.mock.MockitoSugar
+
+import scala.concurrent.Await
+import scala.concurrent.duration.Duration
+import scala.util.{Either, Left, Right}
+
+class StreamSpec extends FlatSpec with Matchers with BeforeAndAfterAll with MockitoSugar {
+
+ implicit var system: ActorSystem = null
+
+ override def beforeAll(): Unit = {
+ system = ActorSystem("test", TestUtil.DEFAULT_CONFIG)
+ }
+
+ override def afterAll(): Unit = {
+ system.terminate()
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+
+ it should "translate the DSL to a DAG" in {
+ val context: ClientContext = mock[ClientContext]
+ when(context.system).thenReturn(system)
+
+ val app = StreamApp("dsl", context)
+
+ val data =
+ """
+ five four three two one
+ five four three two
+ five four three
+ five four
+ five
+ """
+ val stream = app.source(data.lines.toList, 1, "").
+ flatMap(line => line.split("[\\s]+")).filter(_.nonEmpty).
+ map(word => (word, 1)).
+ groupBy(_._1, parallelism = 2).
+ reduce((left, right) => (left._1, left._2 + right._2)).
+ map[Either[(String, Int), String]](Left(_))
+
+ val query = app.source(List("two"), 1, "").map[Either[(String, Int), String]](Right(_))
+ stream.merge(query).process[(String, Int)](classOf[Join], 1)
+
+ val appDescription = app.plan
+
+ val dagTopology = appDescription.dag.mapVertex(_.taskClass).mapEdge { (node1, edge, node2) =>
+ edge.partitionerFactory.partitioner.getClass.getName
+ }
+ val expectedDagTopology = getExpectedDagTopology
+
+ assert(dagTopology.vertices.toSet.equals(expectedDagTopology.vertices.toSet))
+ assert(dagTopology.edges.toSet.equals(expectedDagTopology.edges.toSet))
+ }
+
+ private def getExpectedDagTopology: Graph[String, String] = {
+ val source = classOf[SourceTask[_, _]].getName
+ val group = classOf[GroupByTask[_, _, _]].getName
+ val merge = classOf[TransformTask[_, _]].getName
+ val join = classOf[Join].getName
+
+ val hash = classOf[HashPartitioner].getName
+ val groupBy = classOf[GroupByPartitioner[_, _]].getName
+ val colocation = classOf[CoLocationPartitioner].getName
+
+ val expectedDagTopology = Graph(
+ source ~ groupBy ~> group ~ colocation ~> merge ~ hash ~> join,
+ source ~ hash ~> merge
+ )
+ expectedDagTopology
+ }
+}
+
+object StreamSpec {
+
+ class Join(taskContext: TaskContext, userConf: UserConfig) extends Task(taskContext, userConf) {
+
+ var query: String = null
+ override def onStart(startTime: StartTime): Unit = {}
+
+ override def onNext(msg: Message): Unit = {
+ msg.msg match {
+ case Left(wordCount: (String @unchecked, Int @unchecked)) =>
+ if (query != null && wordCount._1 == query) {
+ taskContext.output(new Message(wordCount))
+ }
+
+ case Right(query: String) =>
+ this.query = query
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/org/apache/gearpump/streaming/dsl/partitioner/GroupByPartitionerSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/org/apache/gearpump/streaming/dsl/partitioner/GroupByPartitionerSpec.scala b/streaming/src/test/scala/org/apache/gearpump/streaming/dsl/partitioner/GroupByPartitionerSpec.scala
new file mode 100644
index 0000000..fcc646d
--- /dev/null
+++ b/streaming/src/test/scala/org/apache/gearpump/streaming/dsl/partitioner/GroupByPartitionerSpec.scala
@@ -0,0 +1,44 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.dsl.partitioner
+
+import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.streaming.dsl.partitioner.GroupByPartitionerSpec.People
+
+class GroupByPartitionerSpec extends FlatSpec with Matchers with BeforeAndAfterAll {
+ it should "use the outpout of groupBy function to do partition" in {
+ val mark = People("Mark", "male")
+ val tom = People("Tom", "male")
+ val michelle = People("Michelle", "female")
+
+ val partitionNum = 10
+ val groupBy = new GroupByPartitioner[People, String](_.gender)
+ assert(groupBy.getPartition(Message(mark), partitionNum)
+ == groupBy.getPartition(Message(tom), partitionNum))
+
+ assert(groupBy.getPartition(Message(mark), partitionNum)
+ != groupBy.getPartition(Message(michelle), partitionNum))
+ }
+}
+
+object GroupByPartitionerSpec {
+ case class People(name: String, gender: String)
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/org/apache/gearpump/streaming/dsl/plan/OpTranslatorSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/org/apache/gearpump/streaming/dsl/plan/OpTranslatorSpec.scala b/streaming/src/test/scala/org/apache/gearpump/streaming/dsl/plan/OpTranslatorSpec.scala
new file mode 100644
index 0000000..ecc5352
--- /dev/null
+++ b/streaming/src/test/scala/org/apache/gearpump/streaming/dsl/plan/OpTranslatorSpec.scala
@@ -0,0 +1,143 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.dsl.plan
+
+import scala.concurrent.Await
+import scala.concurrent.duration.Duration
+
+import akka.actor.ActorSystem
+import org.mockito.ArgumentCaptor
+import org.mockito.Matchers._
+import org.mockito.Mockito._
+import org.scalatest._
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.{TestUtil, UserConfig}
+import org.apache.gearpump.streaming.Constants._
+import org.apache.gearpump.streaming.MockUtil
+import org.apache.gearpump.streaming.dsl.CollectionDataSource
+import org.apache.gearpump.streaming.dsl.plan.OpTranslator._
+import org.apache.gearpump.streaming.task.StartTime
+
+class OpTranslatorSpec extends FlatSpec with Matchers with BeforeAndAfterAll {
+
+ "andThen" should "chain multiple single input function" in {
+ val dummy = new DummyInputFunction[String]
+ val split = new FlatMapFunction[String, String](line => line.split("\\s"), "split")
+
+ val filter = new FlatMapFunction[String, String](word =>
+ if (word.isEmpty) None else Some(word), "filter")
+
+ val map = new FlatMapFunction[String, Int](word => Some(1), "map")
+
+ val sum = new ReduceFunction[Int]({ (left, right) => left + right }, "sum")
+
+ val all = dummy.andThen(split).andThen(filter).andThen(map).andThen(sum)
+
+ assert(all.description == "split.filter.map.sum")
+
+ val data =
+ """
+ five four three two one
+ five four three two
+ five four three
+ five four
+ five
+ """
+ val count = all.process(data).toList.last
+ assert(count == 15)
+ }
+
+ "Source" should "iterate over input source and apply attached operator" in {
+
+ val taskContext = MockUtil.mockTaskContext
+
+ val conf = UserConfig.empty
+ val data = "one two three".split("\\s")
+
+ // Source with no transformer
+ val source = new SourceTask[String, String](new CollectionDataSource[String](data), None,
+ taskContext, conf)
+ source.onStart(StartTime(0))
+ source.onNext(Message("next"))
+ verify(taskContext, times(1)).output(anyObject())
+
+ // Source with transformer
+ val anotherTaskContext = MockUtil.mockTaskContext
+ val double = new FlatMapFunction[String, String](word => List(word, word), "double")
+ val another = new SourceTask(new CollectionDataSource[String](data), Some(double),
+ anotherTaskContext, conf)
+ another.onStart(StartTime(0))
+ another.onNext(Message("next"))
+ verify(anotherTaskContext, times(2)).output(anyObject())
+ }
+
+ "GroupByTask" should "group input by groupBy Function and " +
+ "apply attached operator for each group" in {
+
+ val data = "1 2 2 3 3 3"
+
+ var map = Map.empty[String, Int]
+
+ val concat = new ReduceFunction[String]({ (left, right) =>
+ left + right
+ }, "concat")
+
+ implicit val system = ActorSystem("test", TestUtil.DEFAULT_CONFIG)
+ val config = UserConfig.empty.withValue[SingleInputFunction[String, String]](
+ GEARPUMP_STREAMING_OPERATOR, concat)
+
+ val taskContext = MockUtil.mockTaskContext
+
+ val task = new GroupByTask[String, String, String](input => input, taskContext, config)
+ task.onStart(StartTime(0))
+
+ val peopleCaptor = ArgumentCaptor.forClass(classOf[Message])
+
+ data.split("\\s+").foreach { word =>
+ task.onNext(Message(word))
+ }
+ verify(taskContext, times(6)).output(peopleCaptor.capture())
+
+ import scala.collection.JavaConverters._
+
+ val values = peopleCaptor.getAllValues().asScala.map(input => input.msg.asInstanceOf[String])
+ assert(values.mkString(",") == "1,2,22,3,33,333")
+ system.terminate()
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+
+ "MergeTask" should "accept two stream and apply the attached operator" in {
+
+ // Source with transformer
+ val taskContext = MockUtil.mockTaskContext
+ val conf = UserConfig.empty
+ val double = new FlatMapFunction[String, String](word => List(word, word), "double")
+ val task = new TransformTask[String, String](Some(double), taskContext, conf)
+ task.onStart(StartTime(0))
+
+ val data = "1 2 2 3 3 3".split("\\s+")
+
+ data.foreach { input =>
+ task.onNext(Message(input))
+ }
+
+ verify(taskContext, times(data.length * 2)).output(anyObject())
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/org/apache/gearpump/streaming/executor/ExecutorSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/org/apache/gearpump/streaming/executor/ExecutorSpec.scala b/streaming/src/test/scala/org/apache/gearpump/streaming/executor/ExecutorSpec.scala
new file mode 100644
index 0000000..4c4b37b
--- /dev/null
+++ b/streaming/src/test/scala/org/apache/gearpump/streaming/executor/ExecutorSpec.scala
@@ -0,0 +1,110 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.executor
+
+import scala.concurrent.Await
+import scala.concurrent.duration.Duration
+
+import akka.actor.{ActorSystem, Props}
+import akka.testkit.TestProbe
+import org.mockito.Matchers._
+import org.mockito.Mockito.{times, _}
+import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
+
+import org.apache.gearpump.cluster.appmaster.WorkerInfo
+import org.apache.gearpump.cluster.scheduler.Resource
+import org.apache.gearpump.cluster.worker.WorkerId
+import org.apache.gearpump.cluster.{ExecutorContext, TestUtil, UserConfig}
+import org.apache.gearpump.streaming.AppMasterToExecutor._
+import org.apache.gearpump.streaming.ExecutorToAppMaster.RegisterTask
+import org.apache.gearpump.streaming.appmaster.TaskRegistry.TaskLocations
+import org.apache.gearpump.streaming.executor.TaskLauncherSpec.MockTask
+import org.apache.gearpump.streaming.task.{Subscriber, TaskId}
+import org.apache.gearpump.streaming.{LifeTime, ProcessorDescription}
+import org.apache.gearpump.transport.HostPort
+
+class ExecutorSpec extends FlatSpec with Matchers with BeforeAndAfterAll {
+ val appId = 0
+ val executorId = 0
+ val workerId = WorkerId(0, 0L)
+ var appMaster: TestProbe = null
+ implicit var system: ActorSystem = null
+ val userConf = UserConfig.empty
+
+ override def beforeAll(): Unit = {
+ system = ActorSystem("TaskLauncherSpec", TestUtil.DEFAULT_CONFIG)
+ appMaster = TestProbe()
+ }
+
+ override def afterAll(): Unit = {
+ system.terminate()
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+
+ it should "call launcher to launch task" in {
+ val worker = TestProbe()
+ val workerInfo = WorkerInfo(workerId, worker.ref)
+ val executorContext = ExecutorContext(executorId, workerInfo, appId, "app",
+ appMaster.ref, Resource(2))
+ val taskLauncher = mock(classOf[ITaskLauncher])
+ val executor = system.actorOf(Props(new Executor(executorContext, userConf, taskLauncher)))
+ val processor = ProcessorDescription(id = 0, taskClass = classOf[MockTask].getName,
+ parallelism = 2)
+ val taskIds = List(TaskId(0, 0), TaskId(0, 1))
+ val launchTasks = LaunchTasks(taskIds, dagVersion = 0, processor, List.empty[Subscriber])
+
+ val task = TestProbe()
+ when(taskLauncher.launch(any(), any(), any(), any(), any()))
+ .thenReturn(taskIds.map((_, task.ref)).toMap)
+
+ val client = TestProbe()
+ client.send(executor, launchTasks)
+ client.expectMsg(TasksLaunched)
+
+ verify(taskLauncher, times(1)).launch(any(), any(), any(), any(), any())
+
+ executor ! RegisterTask(TaskId(0, 0), executorId, HostPort("localhost:80"))
+ executor ! RegisterTask(TaskId(0, 1), executorId, HostPort("localhost:80"))
+
+ executor ! TaskRegistered(TaskId(0, 0), 0, 0)
+
+ task.expectMsgType[TaskRegistered]
+
+ executor ! TaskRegistered(TaskId(0, 1), 0, 0)
+
+ task.expectMsgType[TaskRegistered]
+
+ executor ! TaskLocationsReady(TaskLocations(Map.empty), dagVersion = 0)
+ executor ! StartAllTasks(dagVersion = 0)
+
+ task.expectMsgType[StartTask]
+ task.expectMsgType[StartTask]
+
+ val changeTasks = ChangeTasks(taskIds, dagVersion = 1, life = LifeTime(0, Long.MaxValue),
+ List.empty[Subscriber])
+
+ client.send(executor, changeTasks)
+ client.expectMsgType[TasksChanged]
+
+ executor ! TaskLocationsReady(TaskLocations(Map.empty), 1)
+ executor ! StartAllTasks(dagVersion = 1)
+
+ task.expectMsgType[ChangeTask]
+ task.expectMsgType[ChangeTask]
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/org/apache/gearpump/streaming/executor/TaskArgumentStoreSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/org/apache/gearpump/streaming/executor/TaskArgumentStoreSpec.scala b/streaming/src/test/scala/org/apache/gearpump/streaming/executor/TaskArgumentStoreSpec.scala
new file mode 100644
index 0000000..bd45121
--- /dev/null
+++ b/streaming/src/test/scala/org/apache/gearpump/streaming/executor/TaskArgumentStoreSpec.scala
@@ -0,0 +1,45 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.executor
+
+import org.scalatest._
+
+import org.apache.gearpump.streaming.executor.Executor.TaskArgumentStore
+import org.apache.gearpump.streaming.executor.TaskLauncher.TaskArgument
+import org.apache.gearpump.streaming.task.TaskId
+
+class TaskArgumentStoreSpec extends FlatSpec with Matchers with BeforeAndAfterEach {
+ it should "retain all history of taskArgument" in {
+ val version0 = TaskArgument(0, null, null)
+ val version2 = version0.copy(dagVersion = 2)
+ val store = new TaskArgumentStore
+ val task = TaskId(0, 0)
+ store.add(task, version0)
+ store.add(task, version2)
+
+ // Should return a version which is same or older than expected version
+ assert(store.get(dagVersion = 1, task) == Some(version0))
+ assert(store.get(dagVersion = 0, task) == Some(version0))
+ assert(store.get(dagVersion = 2, task) == Some(version2))
+
+ store.removeObsoleteVersion()
+ assert(store.get(dagVersion = 1, task) == None)
+ assert(store.get(dagVersion = 0, task) == None)
+ assert(store.get(dagVersion = 2, task) == Some(version2))
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/org/apache/gearpump/streaming/executor/TaskLauncherSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/org/apache/gearpump/streaming/executor/TaskLauncherSpec.scala b/streaming/src/test/scala/org/apache/gearpump/streaming/executor/TaskLauncherSpec.scala
new file mode 100644
index 0000000..074866a
--- /dev/null
+++ b/streaming/src/test/scala/org/apache/gearpump/streaming/executor/TaskLauncherSpec.scala
@@ -0,0 +1,78 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.executor
+
+import scala.concurrent.Await
+import scala.concurrent.duration.Duration
+
+import akka.actor.{Actor, ActorSystem}
+import akka.testkit.TestProbe
+import org.scalatest._
+
+import org.apache.gearpump.cluster.{TestUtil, UserConfig}
+import org.apache.gearpump.serializer.SerializationFramework
+import org.apache.gearpump.streaming.ProcessorDescription
+import org.apache.gearpump.streaming.executor.TaskLauncher.TaskArgument
+import org.apache.gearpump.streaming.executor.TaskLauncherSpec.{MockTask, MockTaskActor}
+import org.apache.gearpump.streaming.task.{Task, TaskContext, TaskContextData, TaskId, TaskWrapper}
+
+class TaskLauncherSpec extends FlatSpec with Matchers with BeforeAndAfterAll {
+ val appId = 0
+ val executorId = 0
+ var appMaster: TestProbe = null
+ implicit var system: ActorSystem = null
+ val userConf = UserConfig.empty
+
+ override def beforeAll(): Unit = {
+ system = ActorSystem("TaskLauncherSpec", TestUtil.DEFAULT_CONFIG)
+ appMaster = TestProbe()
+ }
+
+ override def afterAll(): Unit = {
+ system.terminate()
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+
+ it should "able to launch tasks" in {
+ val launcher = new TaskLauncher(appId, "app", executorId, appMaster.ref,
+ userConf, classOf[MockTaskActor])
+ val taskIds = List(TaskId(0, 0), TaskId(0, 1))
+ val processor = ProcessorDescription(id = 0, taskClass = classOf[MockTask].getName,
+ parallelism = 2)
+ val argument = TaskArgument(0, processor, null)
+
+ val tasks = launcher.launch(taskIds, argument, system, null,
+ "gearpump.shared-thread-pool-dispatcher")
+ tasks.keys.toSet shouldBe taskIds.toSet
+ }
+}
+
+object TaskLauncherSpec {
+ class MockTaskActor(
+ val taskId: TaskId,
+ val taskContextData : TaskContextData,
+ userConf : UserConfig,
+ val task: TaskWrapper,
+ serializer: SerializationFramework) extends Actor {
+ def receive: Receive = null
+ }
+
+ class MockTask(taskContext: TaskContext, userConf: UserConfig)
+ extends Task(taskContext, userConf) {
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/org/apache/gearpump/streaming/metrics/ProcessorAggregatorSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/org/apache/gearpump/streaming/metrics/ProcessorAggregatorSpec.scala b/streaming/src/test/scala/org/apache/gearpump/streaming/metrics/ProcessorAggregatorSpec.scala
new file mode 100644
index 0000000..5804b00
--- /dev/null
+++ b/streaming/src/test/scala/org/apache/gearpump/streaming/metrics/ProcessorAggregatorSpec.scala
@@ -0,0 +1,261 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.metrics
+
+import scala.collection.JavaConverters._
+import scala.util.Random
+
+import org.scalatest.{FlatSpec, Matchers}
+
+import org.apache.gearpump.cluster.ClientToMaster.ReadOption
+import org.apache.gearpump.cluster.MasterToClient.HistoryMetricsItem
+import org.apache.gearpump.metrics.Metrics.{Gauge, Histogram, Meter}
+import org.apache.gearpump.streaming.metrics.ProcessorAggregator.{AggregatorFactory, HistogramAggregator, MeterAggregator, MultiLayerMap}
+import org.apache.gearpump.streaming.task.TaskId
+import org.apache.gearpump.util.HistoryMetricsService.HistoryMetricsConfig
+
+class ProcessorAggregatorSpec extends FlatSpec with Matchers {
+
+ "MultiLayerMap" should "maintain multiple layers HashMap" in {
+ val layers = 3
+ val map = new MultiLayerMap[String](layers)
+
+ assert(map.get(layer = 0, "key") == null)
+
+ // Illegal, handle safely
+ assert(map.get(layer = 10, "key") == null)
+
+ map.put(layer = 0, "key", "value")
+ assert(map.get(layer = 0, "key") == "value")
+
+ map.put(layer = 1, "key2", "value2")
+ map.put(layer = 2, "key3", "value3")
+ map.put(layer = 2, "key4", "value4")
+
+ // Illegal, should be ignored
+ map.put(layer = 4, "key5", "value5")
+
+ assert(map.size == 4)
+ assert(map.valueIterator.asScala.toSet == Set("value", "value2", "value3", "value4"))
+ }
+
+ "HistogramAggregator" should "aggregate by calculating average" in {
+ val aggregator = new HistogramAggregator("processor")
+
+ val a = Histogram("processor.task1", 1, 2, 3, 4, 5, 6)
+ val b = Histogram("processor.task2", 5, 6, 7, 8, 9, 10)
+ val expect = Histogram("processor.task2", 3, 4, 5, 6, 7, 8)
+
+ val olderTime = 100
+ val newerTime = 200
+
+ aggregator.aggregate(HistoryMetricsItem(time = newerTime, a))
+ aggregator.aggregate(HistoryMetricsItem(time = olderTime, b))
+
+ val result = aggregator.result
+
+ // Picks old time as aggregated time
+ assert(result.time == olderTime)
+
+ // Does average
+ val check = result.value.asInstanceOf[Histogram]
+
+ assert(check.mean - expect.mean < 0.01)
+ assert(check.stddev - expect.stddev < 0.01)
+ assert(check.median - expect.median < 0.01)
+ assert(check.p95 - expect.p95 < 0.01)
+ assert(check.p99 - expect.p99 < 0.01)
+ assert(check.p999 - expect.p999 < 0.01)
+ }
+
+ "MeterAggregator" should "aggregate by summing" in {
+ val aggregator = new MeterAggregator("processor")
+
+ val a = Meter("processor.task1", count = 1, 1, 3, "s")
+ val b = Meter("processor.task2", count = 2, 5, 7, "s")
+ val expect = Meter("processor.task2", count = 3, 6, 10, "s")
+
+ val olderTime = 100
+ val newerTime = 200
+
+ aggregator.aggregate(HistoryMetricsItem(time = newerTime, a))
+ aggregator.aggregate(HistoryMetricsItem(time = olderTime, b))
+
+ val result = aggregator.result
+
+ // Picks old time
+ assert(result.time == olderTime)
+
+ // Does summing
+ val check = result.value.asInstanceOf[Meter]
+
+ assert(check.count == expect.count)
+ assert(check.m1 - expect.m1 < 0.01)
+ assert(check.meanRate - expect.meanRate < 0.01)
+ assert(check.rateUnit == expect.rateUnit)
+ }
+
+ "AggregatorFactory" should "create aggregator" in {
+ val factory = new AggregatorFactory()
+
+ val a = Meter("processor.task1", count = 1, 1, 3, "s")
+ val b = Histogram("processor.task1", 1, 2, 3, 4, 5, 6)
+
+ val aggegator1 = factory.create(HistoryMetricsItem(time = 0, a), "name1")
+ assert(aggegator1.isInstanceOf[MeterAggregator])
+
+ val aggegator2 = factory.create(HistoryMetricsItem(time = 0, b), "name2")
+ assert(aggegator2.isInstanceOf[HistogramAggregator])
+ }
+
+ "ProcessorAggregator" should "aggregate on different read options" in {
+ val hours = 2 // Maintains 2 hours history
+ val seconds = 2 // Maintains 2 seconds recent data
+ val taskCount = 5 // For each processor
+ val metricCount = 100 // For each task, have metricCount metrics
+ val range = new HistoryMetricsConfig(hours, hours / 2 * 3600 * 1000,
+ seconds, seconds / 2 * 1000)
+
+ val aggregator = new ProcessorAggregator(range)
+
+ def count(value: Int): Int = value
+
+ def inputs(timeRange: Long): List[HistoryMetricsItem] = {
+ (0 until taskCount).map(TaskId(processorId = 0, _))
+ .flatMap(histogram(_, "receiveLatency", timeRange, metricCount)).toList ++
+ (0 until taskCount).map(TaskId(processorId = 0, _))
+ .flatMap(histogram(_, "processTime", timeRange, metricCount)).toList ++
+ (0 until taskCount).map(TaskId(processorId = 1, _))
+ .flatMap(histogram(_, "receiveLatency", timeRange, metricCount)).toList ++
+ (0 until taskCount).map(TaskId(processorId = 1, _))
+ .flatMap(histogram(_, "processTime", timeRange, metricCount)).toList ++
+ (0 until taskCount).map(TaskId(processorId = 0, _))
+ .flatMap(meter(_, "sendThroughput", timeRange, metricCount)).toList ++
+ (0 until taskCount).map(TaskId(processorId = 0, _))
+ .flatMap(meter(_, "receiveThroughput", timeRange, metricCount)).toList ++
+ (0 until taskCount).map(TaskId(processorId = 1, _))
+ .flatMap(meter(_, "sendThroughput", timeRange, metricCount)).toList ++
+ (0 until taskCount).map(TaskId(processorId = 1, _))
+ .flatMap(meter(_, "receiveThroughput", timeRange, metricCount)).toList
+ }
+
+ def check(list: List[HistoryMetricsItem], countMap: Map[String, Int]): Boolean = {
+ val nameCount = list.map(_.value.name).groupBy(key => key).mapValues(_.size).toList.toMap
+ nameCount sameElements countMap
+ }
+
+ // Aggregates on processor and meterNames,
+ val input = inputs(Long.MaxValue)
+ val readLatest = aggregator.aggregate(ReadOption.ReadLatest,
+ input.iterator, now = Long.MaxValue)
+ assert(readLatest.size == 8) // 2 processor * 4 metrics type
+ assert(check(readLatest, Map(
+ "app0.processor0:receiveLatency" -> count(1),
+ "app0.processor0:processTime" -> count(1),
+ "app0.processor0:sendThroughput" -> count(1),
+ "app0.processor0:receiveThroughput" -> count(1),
+ "app0.processor1:receiveLatency" -> count(1),
+ "app0.processor1:processTime" -> count(1),
+ "app0.processor1:sendThroughput" -> count(1),
+ "app0.processor1:receiveThroughput" -> count(1)
+ )))
+
+ // Aggregates on processor and meterNames and time range,
+ val readRecent = aggregator.aggregate(ReadOption.ReadRecent,
+ inputs(seconds * 1000).iterator, now = seconds * 1000)
+ assert(readRecent.size == 16) // 2 processor * 4 metrics type * 2 time range
+ assert(check(readRecent, Map(
+ "app0.processor0:receiveLatency" -> count(2),
+ "app0.processor0:processTime" -> count(2),
+ "app0.processor0:sendThroughput" -> count(2),
+ "app0.processor0:receiveThroughput" -> count(2),
+ "app0.processor1:receiveLatency" -> count(2),
+ "app0.processor1:processTime" -> count(2),
+ "app0.processor1:sendThroughput" -> count(2),
+ "app0.processor1:receiveThroughput" -> count(2)
+ )))
+
+ // Aggregates on processor and meterNames and time range,
+ val readHistory = aggregator.aggregate(ReadOption.ReadHistory,
+ inputs(hours * 3600 * 1000).iterator, now = hours * 3600 * 1000)
+ assert(readHistory.size == 16) // 2 processor * 4 metrics type * 2 time ranges
+ assert(check(readHistory, Map(
+ "app0.processor0:receiveLatency" -> count(2),
+ "app0.processor0:processTime" -> count(2),
+ "app0.processor0:sendThroughput" -> count(2),
+ "app0.processor0:receiveThroughput" -> count(2),
+ "app0.processor1:receiveLatency" -> count(2),
+ "app0.processor1:processTime" -> count(2),
+ "app0.processor1:sendThroughput" -> count(2),
+ "app0.processor1:receiveThroughput" -> count(2)
+ )))
+ }
+
+ private def histogram(
+ taskId: TaskId, metricName: String = "latency", timeRange: Long = Long.MaxValue,
+ repeat: Int = 1): List[HistoryMetricsItem] = {
+ val random = new Random()
+ (0 until repeat).map { _ =>
+ new HistoryMetricsItem(Math.abs(random.nextLong() % timeRange),
+ new Histogram(s"app0.processor${taskId.processorId}.task${taskId.index}:$metricName",
+ Math.abs(random.nextDouble()),
+ Math.abs(random.nextDouble()),
+ Math.abs(random.nextDouble()),
+ Math.abs(random.nextDouble()),
+ Math.abs(random.nextDouble()),
+ Math.abs(random.nextDouble())
+ ))
+ }.toList
+ }
+
+ private def meter(taskId: TaskId, metricName: String, timeRange: Long, repeat: Int)
+ : List[HistoryMetricsItem] = {
+ val random = new Random()
+ (0 until repeat).map { _ =>
+ new HistoryMetricsItem(Math.abs(random.nextLong() % timeRange),
+ new Meter(s"app0.processor${taskId.processorId}.task${taskId.index}:$metricName",
+ Math.abs(random.nextInt()),
+ Math.abs(random.nextDouble()),
+ Math.abs(random.nextDouble()),
+ "event/s")
+ )
+ }.toList
+ }
+
+ "ProcessorAggregator" should "handle smoothly for unsupported metric type and " +
+ "error formatted metric name" in {
+ val invalid = List(
+ // Unsupported metric type
+ HistoryMetricsItem(0, new Gauge("app0.processor0.task0:gauge", 100)),
+
+ // Wrong format: should be app0.processor0.task0:throughput
+ HistoryMetricsItem(0, new Meter("app0.processor0.task0/throughput", 100, 0, 0, ""))
+ )
+
+ val valid = histogram(TaskId(0, 0), repeat = 10)
+
+ val aggregator = new ProcessorAggregator(new HistoryMetricsConfig(0, 0, 0, 0))
+ val result = aggregator.aggregate(ReadOption.ReadLatest, (valid ++ invalid).toIterator,
+ now = Long.MaxValue)
+
+ // For one taskId, will only use one data point.
+ assert(result.size == 1)
+ assert(result.head.value.name == "app0.processor0:latency")
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/org/apache/gearpump/streaming/metrics/TaskFilterAggregatorSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/org/apache/gearpump/streaming/metrics/TaskFilterAggregatorSpec.scala b/streaming/src/test/scala/org/apache/gearpump/streaming/metrics/TaskFilterAggregatorSpec.scala
new file mode 100644
index 0000000..ee9402b
--- /dev/null
+++ b/streaming/src/test/scala/org/apache/gearpump/streaming/metrics/TaskFilterAggregatorSpec.scala
@@ -0,0 +1,80 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.metrics
+
+import scala.util.Random
+
+import org.scalatest.{FlatSpec, Matchers}
+
+import org.apache.gearpump.cluster.MasterToClient.HistoryMetricsItem
+import org.apache.gearpump.metrics.Metrics.{Histogram, Meter}
+import org.apache.gearpump.streaming.metrics.TaskFilterAggregator.Options
+import org.apache.gearpump.streaming.task.TaskId
+
+class TaskFilterAggregatorSpec extends FlatSpec with Matchers {
+
+ def metric(taskId: TaskId): HistoryMetricsItem = {
+ val random = new Random()
+ new HistoryMetricsItem(Math.abs(random.nextLong()),
+ new Histogram(s"app0.processor${taskId.processorId}.task${taskId.index}:latency",
+ 0, 0, 0, 0, 0, 0))
+ }
+
+ it should "filter data on processor range, task range combination" in {
+ val inputs = (0 until 10).flatMap { processor =>
+ (0 until 10).map { task =>
+ metric(TaskId(processor, task))
+ }
+ }.toList
+
+ val globalLimit = 10
+ val aggregator = new TaskFilterAggregator(globalLimit)
+
+ // Limit not met, return all matches in this matrix
+ var options = new Options(limit = 20, startTask = 3, endTask = 6,
+ startProcessor = 3, endProcessor = 6)
+ assert(aggregator.aggregate(options, inputs.iterator).size == 9)
+
+ // User limit reached
+ options = new Options(limit = 3, startTask = 3, endTask = 5,
+ startProcessor = 3, endProcessor = 5)
+ assert(aggregator.aggregate(options, inputs.iterator).size == 3)
+
+ // Global limit reached
+ options = new Options(limit = 20, startTask = 3, endTask = 8,
+ startProcessor = 3, endProcessor = 8)
+ assert(aggregator.aggregate(options, inputs.iterator).size == globalLimit)
+ }
+
+ it should "reject wrong format options" in {
+ val options = Map(TaskFilterAggregator.StartTask -> "not a number")
+ assert(Options.parse(options) == null)
+ }
+
+ it should "skip wrong format metrics" in {
+ val invalid = List {
+ // Wrong format: should be app0.processor0.task0:throughput
+ HistoryMetricsItem(0, new Meter("app0.processor0.task0/throughput", 100, 0, 0, ""))
+ }
+ val options = Options.acceptAll
+
+ val aggregator = new TaskFilterAggregator(Int.MaxValue)
+ assert(aggregator.aggregate(options, invalid.iterator).size == 0)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/org/apache/gearpump/streaming/source/DefaultTimeStampFilterSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/org/apache/gearpump/streaming/source/DefaultTimeStampFilterSpec.scala b/streaming/src/test/scala/org/apache/gearpump/streaming/source/DefaultTimeStampFilterSpec.scala
new file mode 100644
index 0000000..d6fa443
--- /dev/null
+++ b/streaming/src/test/scala/org/apache/gearpump/streaming/source/DefaultTimeStampFilterSpec.scala
@@ -0,0 +1,48 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.source
+
+import org.scalacheck.Gen
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{Matchers, PropSpec}
+
+import org.apache.gearpump.{Message, TimeStamp}
+
+class DefaultTimeStampFilterSpec extends PropSpec with PropertyChecks with Matchers {
+ property("DefaultTimeStampFilter should filter message against give timestamp") {
+ val timestampGen = Gen.chooseNum[Long](0L, 1000L)
+ val messageGen = for {
+ msg <- Gen.alphaStr
+ time <- timestampGen
+ } yield Message(msg, time)
+
+ val filter = new DefaultTimeStampFilter()
+
+ forAll(timestampGen, messageGen) {
+ (predicate: TimeStamp, message: Message) =>
+ if (message.timestamp >= predicate) {
+ filter.filter(message, predicate) shouldBe Some(message)
+ } else {
+ filter.filter(message, predicate) shouldBe None
+ }
+
+ filter.filter(null, predicate) shouldBe None
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/org/apache/gearpump/streaming/state/impl/CheckpointManagerSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/org/apache/gearpump/streaming/state/impl/CheckpointManagerSpec.scala b/streaming/src/test/scala/org/apache/gearpump/streaming/state/impl/CheckpointManagerSpec.scala
new file mode 100644
index 0000000..9e42e85
--- /dev/null
+++ b/streaming/src/test/scala/org/apache/gearpump/streaming/state/impl/CheckpointManagerSpec.scala
@@ -0,0 +1,89 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.state.impl
+
+import org.mockito.Mockito._
+import org.mockito.{Matchers => MockitoMatchers}
+import org.scalacheck.Gen
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{Matchers, PropSpec}
+
+import org.apache.gearpump.TimeStamp
+import org.apache.gearpump.streaming.transaction.api.CheckpointStore
+
+class CheckpointManagerSpec extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
+
+ val timestampGen = Gen.chooseNum[Long](0L, 1000L)
+ val checkpointIntervalGen = Gen.chooseNum[Long](100L, 10000L)
+ property("CheckpointManager should recover from CheckpointStore") {
+ forAll(timestampGen, checkpointIntervalGen) {
+ (timestamp: TimeStamp, checkpointInterval: Long) =>
+ val checkpointStore = mock[CheckpointStore]
+ val checkpointManager =
+ new CheckpointManager(checkpointInterval, checkpointStore)
+ checkpointManager.recover(timestamp)
+
+ verify(checkpointStore).recover(timestamp)
+ }
+ }
+
+ property("CheckpointManager should write checkpoint to CheckpointStore") {
+ val checkpointGen = Gen.alphaStr.map(_.getBytes("UTF-8"))
+ forAll(timestampGen, checkpointIntervalGen, checkpointGen) {
+ (timestamp: TimeStamp, checkpointInterval: Long, checkpoint: Array[Byte]) =>
+ val checkpointStore = mock[CheckpointStore]
+ val checkpointManager =
+ new CheckpointManager(checkpointInterval, checkpointStore)
+ checkpointManager.checkpoint(timestamp, checkpoint)
+
+ verify(checkpointStore).persist(timestamp, checkpoint)
+ }
+ }
+
+ property("CheckpointManager should close CheckpointStore") {
+ forAll(checkpointIntervalGen) {
+ (checkpointInterval: Long) =>
+ val checkpointStore = mock[CheckpointStore]
+ val checkpointManager =
+ new CheckpointManager(checkpointInterval, checkpointStore)
+ checkpointManager.close()
+ verify(checkpointStore).close()
+ }
+ }
+
+ property("CheckpointManager should update checkpoint time according to max message timestamp") {
+ forAll(timestampGen, checkpointIntervalGen) {
+ (timestamp: TimeStamp, checkpointInterval: Long) =>
+ val checkpointStore = mock[CheckpointStore]
+ val checkpointManager =
+ new CheckpointManager(checkpointInterval, checkpointStore)
+ checkpointManager.update(timestamp)
+ checkpointManager.getMaxMessageTime shouldBe timestamp
+
+ val checkpointTime = checkpointManager.getCheckpointTime.get
+ timestamp should (be < checkpointTime and be >= (checkpointTime - checkpointInterval))
+
+ checkpointManager.checkpoint(checkpointTime, Array.empty[Byte])
+ verify(checkpointStore).persist(MockitoMatchers.eq(checkpointTime),
+ MockitoMatchers.anyObject[Array[Byte]]())
+ checkpointManager.getCheckpointTime shouldBe empty
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/org/apache/gearpump/streaming/state/impl/InMemoryCheckpointStoreSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/org/apache/gearpump/streaming/state/impl/InMemoryCheckpointStoreSpec.scala b/streaming/src/test/scala/org/apache/gearpump/streaming/state/impl/InMemoryCheckpointStoreSpec.scala
new file mode 100644
index 0000000..8d2f515
--- /dev/null
+++ b/streaming/src/test/scala/org/apache/gearpump/streaming/state/impl/InMemoryCheckpointStoreSpec.scala
@@ -0,0 +1,37 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.state.impl
+
+import org.scalacheck.Gen
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{Matchers, PropSpec}
+
+class InMemoryCheckpointStoreSpec extends PropSpec with PropertyChecks with Matchers {
+
+ property("InMemoryCheckpointStore should provide read / write checkpoint") {
+ val timestampGen = Gen.chooseNum[Long](1, 1000)
+ val checkpointGen = Gen.alphaStr.map(_.getBytes("UTF-8"))
+ forAll(timestampGen, checkpointGen) { (timestamp: Long, checkpoint: Array[Byte]) =>
+ val store = new InMemoryCheckpointStore
+ store.recover(timestamp) shouldBe None
+ store.persist(timestamp, checkpoint)
+ store.recover(timestamp) shouldBe Some(checkpoint)
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/org/apache/gearpump/streaming/state/impl/NonWindowStateSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/org/apache/gearpump/streaming/state/impl/NonWindowStateSpec.scala b/streaming/src/test/scala/org/apache/gearpump/streaming/state/impl/NonWindowStateSpec.scala
new file mode 100644
index 0000000..4cdff95
--- /dev/null
+++ b/streaming/src/test/scala/org/apache/gearpump/streaming/state/impl/NonWindowStateSpec.scala
@@ -0,0 +1,132 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.state.impl
+
+import scala.util.Success
+
+import org.mockito.Mockito._
+import org.scalacheck.Gen
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{Matchers, PropSpec}
+
+import org.apache.gearpump.TimeStamp
+import org.apache.gearpump.streaming.state.api.{Monoid, Serializer}
+
+class NonWindowStateSpec extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
+
+ val longGen = Gen.chooseNum[Long](100L, System.currentTimeMillis())
+
+ property("NonWindowState should recover checkpointed state at given timestamp") {
+ forAll(longGen) {
+ (timestamp: TimeStamp) =>
+ val monoid = mock[Monoid[AnyRef]]
+ val serializer = mock[Serializer[AnyRef]]
+ val bytes = Array.empty[Byte]
+ val checkpoint = mock[AnyRef]
+ val zero = mock[AnyRef]
+ when(monoid.zero).thenReturn(zero, zero)
+ when(monoid.plus(zero, zero)).thenReturn(zero, Nil: _*)
+ when(monoid.plus(checkpoint, zero)).thenReturn(checkpoint, Nil: _*)
+
+ val state = new NonWindowState[AnyRef](monoid, serializer)
+ state.left shouldBe zero
+ state.right shouldBe zero
+ state.get shouldBe Some(zero)
+
+ when(serializer.deserialize(bytes)).thenReturn(Success(checkpoint))
+ state.recover(timestamp, bytes)
+
+ state.left shouldBe checkpoint
+ state.right shouldBe zero
+ state.get shouldBe Some(checkpoint)
+ }
+ }
+
+ property("NonWindowState checkpoints state") {
+ forAll(longGen) {
+ (checkpointTime: TimeStamp) =>
+ val monoid = mock[Monoid[AnyRef]]
+ val serializer = mock[Serializer[AnyRef]]
+
+ val left = mock[AnyRef]
+ val right = mock[AnyRef]
+ val zero = mock[AnyRef]
+ val plus = mock[AnyRef]
+
+ when(monoid.zero).thenReturn(zero, zero)
+ when(monoid.plus(zero, zero)).thenReturn(zero, Nil: _*)
+
+ val state = new NonWindowState[AnyRef](monoid, serializer)
+ state.left shouldBe zero
+ state.right shouldBe zero
+ state.get shouldBe Some(zero)
+
+ state.left = left
+ state.right = right
+
+ when(monoid.zero).thenReturn(zero, Nil: _*)
+ when(monoid.plus(left, right)).thenReturn(plus, Nil: _*)
+ when(monoid.plus(plus, zero)).thenReturn(plus, Nil: _*)
+ state.checkpoint()
+
+ verify(serializer).serialize(left)
+ state.left shouldBe plus
+ state.right shouldBe zero
+ state.get shouldBe Some(plus)
+ }
+ }
+
+ property("NonWindowState updates state") {
+ forAll(longGen) {
+ (checkpointTime: TimeStamp) =>
+ val monoid = mock[Monoid[AnyRef]]
+ val serializer = mock[Serializer[AnyRef]]
+
+ val left = mock[AnyRef]
+ val right = mock[AnyRef]
+ val zero = mock[AnyRef]
+ val plus = mock[AnyRef]
+
+ when(monoid.zero).thenReturn(zero, zero)
+ when(monoid.plus(zero, zero)).thenReturn(zero, Nil: _*)
+
+ val state = new NonWindowState[AnyRef](monoid, serializer)
+ state.left shouldBe zero
+ state.right shouldBe zero
+ state.get shouldBe Some(zero)
+
+ when(monoid.plus(zero, left)).thenReturn(left, Nil: _*)
+ when(monoid.plus(left, zero)).thenReturn(left, Nil: _*)
+ state.setNextCheckpointTime(checkpointTime)
+ state.update(checkpointTime - 1, left)
+ state.left shouldBe left
+ state.right shouldBe zero
+ state.get shouldBe Some(left)
+
+ when(monoid.plus(zero, right)).thenReturn(right, Nil: _*)
+ when(monoid.plus(left, right)).thenReturn(plus, Nil: _*)
+ state.setNextCheckpointTime(checkpointTime)
+ state.update(checkpointTime + 1, right)
+ state.left shouldBe left
+ state.right shouldBe right
+ state.get shouldBe Some(plus)
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/org/apache/gearpump/streaming/state/impl/WindowSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/org/apache/gearpump/streaming/state/impl/WindowSpec.scala b/streaming/src/test/scala/org/apache/gearpump/streaming/state/impl/WindowSpec.scala
new file mode 100644
index 0000000..d9282ae
--- /dev/null
+++ b/streaming/src/test/scala/org/apache/gearpump/streaming/state/impl/WindowSpec.scala
@@ -0,0 +1,61 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.state.impl
+
+import org.scalacheck.Gen
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{Matchers, PropSpec}
+
+import org.apache.gearpump.TimeStamp
+
+class WindowSpec extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
+
+ val windowSizeGen = Gen.chooseNum[Long](1L, 1000L)
+ val windowStepGen = Gen.chooseNum[Long](1L, 1000L)
+ val timestampGen = Gen.chooseNum[Long](0L, 1000L)
+ property("Window should only slide when time passes window end") {
+ forAll(timestampGen, windowSizeGen, windowStepGen) {
+ (timestamp: TimeStamp, windowSize: Long, windowStep: Long) =>
+ val window = new Window(windowSize, windowStep)
+ window.shouldSlide shouldBe false
+ window.update(timestamp)
+ window.shouldSlide shouldBe timestamp >= windowSize
+ }
+ }
+
+ property("Window should slide by one or to given timestamp") {
+ forAll(timestampGen, windowSizeGen, windowStepGen) {
+ (timestamp: TimeStamp, windowSize: Long, windowStep: Long) =>
+ val window = new Window(windowSize, windowStep)
+ window.range shouldBe(0L, windowSize)
+
+ window.slideOneStep()
+ window.range shouldBe(windowStep, windowSize + windowStep)
+
+ window.slideTo(timestamp)
+ val (startTime, endTime) = window.range
+ if (windowStep > windowSize) {
+ timestamp should (be >= startTime and be < (startTime + windowStep))
+ } else {
+ timestamp should (be >= startTime and be < endTime)
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/org/apache/gearpump/streaming/state/impl/WindowStateSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/org/apache/gearpump/streaming/state/impl/WindowStateSpec.scala b/streaming/src/test/scala/org/apache/gearpump/streaming/state/impl/WindowStateSpec.scala
new file mode 100644
index 0000000..299a626
--- /dev/null
+++ b/streaming/src/test/scala/org/apache/gearpump/streaming/state/impl/WindowStateSpec.scala
@@ -0,0 +1,239 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.state.impl
+
+import scala.collection.immutable.TreeMap
+import scala.util.Success
+
+import org.mockito.Mockito._
+import org.scalacheck.Gen
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{Matchers, PropSpec}
+
+import org.apache.gearpump._
+import org.apache.gearpump.streaming.MockUtil
+import org.apache.gearpump.streaming.state.api.{Group, Serializer}
+
+class WindowStateSpec extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
+
+ val longGen = Gen.chooseNum[Long](100L, 10000L)
+
+ val intervalGen = for {
+ st <- longGen
+ et <- Gen.chooseNum[Long](st + 1, 100000L)
+ } yield Interval(st, et)
+
+ property("WindowState init should recover checkpointed state") {
+ forAll(intervalGen) {
+ (interval: Interval) =>
+ val window = mock[Window]
+ val taskContext = MockUtil.mockTaskContext
+ val group = mock[Group[AnyRef]]
+ val serializer = mock[Serializer[TreeMap[Interval, AnyRef]]]
+
+ val timestamp = interval.startTime
+ val zero = mock[AnyRef]
+ val bytes = Array.empty[Byte]
+ val data = mock[AnyRef]
+ val checkpoint = TreeMap(interval -> data)
+ when(group.zero).thenReturn(zero, zero)
+ when(group.plus(zero, data)).thenReturn(data, Nil: _*)
+ when(group.plus(data, zero)).thenReturn(data, Nil: _*)
+ when(group.plus(zero, zero)).thenReturn(zero, Nil: _*)
+ when(serializer.deserialize(bytes)).thenReturn(Success(checkpoint))
+
+ val state = new WindowState[AnyRef](group, serializer, taskContext, window)
+ state.left shouldBe zero
+ state.right shouldBe zero
+ state.get shouldBe Some(zero)
+
+ state.recover(timestamp, bytes)
+
+ state.left shouldBe data
+ state.right shouldBe zero
+ state.get shouldBe Some(data)
+ state.getIntervalStates(interval.startTime, interval.endTime) shouldBe checkpoint
+ }
+ }
+
+ property("WindowState checkpoints") {
+ forAll(longGen) { (checkpointTime: TimeStamp) =>
+ val window = mock[Window]
+ val taskContext = MockUtil.mockTaskContext
+ val group = mock[Group[AnyRef]]
+ val serializer = mock[Serializer[TreeMap[Interval, AnyRef]]]
+
+ val zero = mock[AnyRef]
+ val left = mock[AnyRef]
+ val right = mock[AnyRef]
+ val plus = mock[AnyRef]
+
+ when(group.zero).thenReturn(zero, zero)
+ when(group.plus(zero, zero)).thenReturn(zero, Nil: _*)
+ val state = new WindowState[AnyRef](group, serializer, taskContext, window)
+ state.left shouldBe zero
+ state.right shouldBe zero
+ state.get shouldBe Some(zero)
+
+ val start = checkpointTime - 1
+ val end = checkpointTime + 1
+ val size = end - start
+ val step = 1L
+
+ when(window.range).thenReturn((start, end))
+ when(window.windowSize).thenReturn(size)
+ when(window.windowStep).thenReturn(step)
+ when(group.zero).thenReturn(zero, zero)
+ when(group.plus(zero, left)).thenReturn(left, Nil: _*)
+ when(group.plus(zero, right)).thenReturn(right, Nil: _*)
+ when(group.plus(left, right)).thenReturn(plus, Nil: _*)
+
+ state.left = left
+ state.updateIntervalStates(start, left, checkpointTime)
+ state.right = right
+ state.updateIntervalStates(checkpointTime, right, checkpointTime)
+
+ state.setNextCheckpointTime(checkpointTime)
+ state.checkpoint()
+
+ state.left shouldBe plus
+ state.right shouldBe zero
+ verify(serializer).serialize(TreeMap(Interval(start, checkpointTime) -> left))
+ }
+ }
+
+ property("WindowState updates state") {
+ forAll(longGen) { (checkpointTime: TimeStamp) =>
+ val window = mock[Window]
+ val taskContext = MockUtil.mockTaskContext
+ val group = mock[Group[AnyRef]]
+ val serializer = mock[Serializer[TreeMap[Interval, AnyRef]]]
+
+ val zero = mock[AnyRef]
+ val left = mock[AnyRef]
+ val right = mock[AnyRef]
+ val plus = mock[AnyRef]
+
+ when(group.zero).thenReturn(zero, zero)
+ val state = new WindowState[AnyRef](group, serializer, taskContext, window)
+
+ val start = checkpointTime - 1
+ val end = checkpointTime + 1
+ val size = end - start
+ val step = 1L
+
+ when(window.range).thenReturn((start, end))
+ when(window.windowSize).thenReturn(size)
+ when(window.windowStep).thenReturn(step)
+ when(window.shouldSlide).thenReturn(false)
+ when(group.plus(zero, left)).thenReturn(left, left)
+ when(group.plus(left, zero)).thenReturn(left, Nil: _*)
+ when(taskContext.upstreamMinClock).thenReturn(0L)
+
+ // Time < checkpointTime
+ // Update left in current window
+ state.setNextCheckpointTime(checkpointTime)
+ state.update(start, left)
+
+ verify(window).update(0L)
+ state.left shouldBe left
+ state.right shouldBe zero
+ state.get shouldBe Some(left)
+ state.getIntervalStates(start, end) shouldBe TreeMap(Interval(start, checkpointTime) -> left)
+
+ when(window.range).thenReturn((start, end))
+ when(window.windowSize).thenReturn(size)
+ when(window.windowStep).thenReturn(step)
+ when(window.shouldSlide).thenReturn(false)
+ when(group.plus(zero, right)).thenReturn(right, right)
+ when(group.plus(left, right)).thenReturn(plus, Nil: _*)
+ when(taskContext.upstreamMinClock).thenReturn(0L)
+
+ // Time >= checkpointTime
+ // Update right in current window
+ state.setNextCheckpointTime(checkpointTime)
+ state.update(checkpointTime, right)
+
+ verify(window, times(2)).update(0L)
+ state.left shouldBe left
+ state.right shouldBe right
+ state.get shouldBe Some(plus)
+ state.getIntervalStates(start, end) shouldBe
+ TreeMap(Interval(start, start + step) -> left, Interval(start + step, end) -> right)
+
+ // Slides window forward
+ when(window.range).thenReturn((start, end), (start + step, end + step))
+ when(window.shouldSlide).thenReturn(true)
+ when(taskContext.upstreamMinClock).thenReturn(checkpointTime)
+ when(group.minus(left, left)).thenReturn(zero, Nil: _*)
+ when(group.plus(zero, right)).thenReturn(right, Nil: _*)
+ when(group.plus(right, right)).thenReturn(plus, Nil: _*)
+ when(group.plus(zero, plus)).thenReturn(plus, Nil: _*)
+
+ state.setNextCheckpointTime(checkpointTime)
+ state.update(end, right)
+
+ verify(window).slideOneStep()
+ verify(window).update(checkpointTime)
+ state.left shouldBe zero
+ state.right shouldBe plus
+ state.get shouldBe Some(plus)
+ state.getIntervalStates(start, end + step) shouldBe
+ TreeMap(
+ Interval(start, start + step) -> left,
+ Interval(start + step, end) -> right,
+ Interval(end, end + step) -> right)
+ }
+ }
+
+ property("WindowState gets interval for timestamp") {
+ forAll(longGen, longGen, longGen, longGen) {
+ (timestamp: TimeStamp, checkpointTime: TimeStamp, windowSize: Long, windowStep: Long) =>
+ val windowManager = new Window(windowSize, windowStep)
+ val taskContext = MockUtil.mockTaskContext
+ val group = mock[Group[AnyRef]]
+ val serializer = mock[Serializer[TreeMap[Interval, AnyRef]]]
+
+ val zero = mock[AnyRef]
+ when(group.zero).thenReturn(zero, zero)
+ val state = new WindowState[AnyRef](group, serializer, taskContext, windowManager)
+
+ val interval = state.getInterval(timestamp, checkpointTime)
+ intervalSpec(interval, timestamp, checkpointTime, windowSize, windowStep)
+
+ val nextTimeStamp = interval.endTime
+ val nextInterval = state.getInterval(nextTimeStamp, checkpointTime)
+ intervalSpec(nextInterval, nextTimeStamp, checkpointTime, windowSize, windowStep)
+
+ interval.endTime shouldBe nextInterval.startTime
+ }
+
+ def intervalSpec(interval: Interval, timestamp: TimeStamp,
+ checkpointTime: TimeStamp, windowSize: Long, windowStep: Long): Unit = {
+ interval.startTime should be <= interval.endTime
+ timestamp / windowStep * windowStep should (be <= interval.startTime)
+ (timestamp - windowSize) / windowStep * windowStep should (be <= interval.startTime)
+ (timestamp / windowStep + 1) * windowStep should (be >= interval.endTime)
+ ((timestamp - windowSize) / windowStep + 1) * windowStep + windowSize should
+ (be >= interval.endTime)
+ checkpointTime should (be <= interval.startTime or be >= interval.endTime)
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/org/apache/gearpump/streaming/storage/InMemoryAppStoreOnMasterSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/org/apache/gearpump/streaming/storage/InMemoryAppStoreOnMasterSpec.scala b/streaming/src/test/scala/org/apache/gearpump/streaming/storage/InMemoryAppStoreOnMasterSpec.scala
new file mode 100644
index 0000000..71901a4
--- /dev/null
+++ b/streaming/src/test/scala/org/apache/gearpump/streaming/storage/InMemoryAppStoreOnMasterSpec.scala
@@ -0,0 +1,62 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.storage
+
+import scala.concurrent.Await
+import scala.concurrent.duration._
+
+import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpec}
+
+import org.apache.gearpump.cluster.{MasterHarness, MiniCluster}
+import org.apache.gearpump.streaming.StreamingTestUtil
+import org.apache.gearpump.util.Constants
+
+class InMemoryAppStoreOnMasterSpec extends WordSpec with Matchers with BeforeAndAfterAll {
+ implicit val timeout = Constants.FUTURE_TIMEOUT
+ implicit val dispatcher = MasterHarness.cachedPool
+
+ "InMemoryAppStoreOnMaster" should {
+ "save and return the data properly" in {
+ val appId = 0
+ val miniCluster = new MiniCluster
+ val master = miniCluster.mockMaster
+ StreamingTestUtil.startAppMaster(miniCluster, appId)
+ val store = new InMemoryAppStoreOnMaster(appId, master)
+
+ Thread.sleep(500)
+
+ store.put("String_type", "this is a string")
+ store.put("Int_type", 1024)
+ store.put("Tuple2_type", ("element1", 1024))
+
+ val future1 = store.get("String_type").map { value =>
+ value.asInstanceOf[String] should be("this is a string")
+ }
+ val future2 = store.get("Int_type").map { value => value.asInstanceOf[Int] should be(1024) }
+ val future3 = store.get("Tuple2_type").map { value =>
+ value.asInstanceOf[(String, Int)] should be(("element1", 1024))
+ }
+ val future4 = store.get("key").map { value => value.asInstanceOf[Object] should be(null) }
+ Await.result(future1, 15.seconds)
+ Await.result(future2, 15.seconds)
+ Await.result(future3, 15.seconds)
+ Await.result(future4, 15.seconds)
+ miniCluster.shutDown
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/org/apache/gearpump/streaming/task/SubscriberSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/org/apache/gearpump/streaming/task/SubscriberSpec.scala b/streaming/src/test/scala/org/apache/gearpump/streaming/task/SubscriberSpec.scala
new file mode 100644
index 0000000..cfe47eb
--- /dev/null
+++ b/streaming/src/test/scala/org/apache/gearpump/streaming/task/SubscriberSpec.scala
@@ -0,0 +1,51 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.task
+
+import org.scalatest.{FlatSpec, Matchers}
+
+import org.apache.gearpump.partitioner.{HashPartitioner, Partitioner}
+import org.apache.gearpump.streaming.task.SubscriberSpec.TestTask
+import org.apache.gearpump.streaming.{DAG, ProcessorDescription}
+import org.apache.gearpump.util.Graph
+import org.apache.gearpump.util.Graph._
+
+class SubscriberSpec extends FlatSpec with Matchers {
+ "Subscriber.of" should "return all subscriber for a processor" in {
+
+ val sourceProcessorId = 0
+ val task1 = ProcessorDescription(id = sourceProcessorId, taskClass =
+ classOf[TestTask].getName, parallelism = 1)
+ val task2 = ProcessorDescription(id = 1, taskClass = classOf[TestTask].getName, parallelism = 1)
+ val task3 = ProcessorDescription(id = 2, taskClass = classOf[TestTask].getName, parallelism = 1)
+ val partitioner = Partitioner[HashPartitioner]
+ val dag = DAG(Graph(task1 ~ partitioner ~> task2, task1 ~ partitioner ~> task3,
+ task2 ~ partitioner ~> task3))
+
+ val subscribers = Subscriber.of(sourceProcessorId, dag)
+ assert(subscribers.size == 2)
+
+ assert(subscribers.toSet ==
+ Set(Subscriber(1, partitioner, task2.parallelism, task2.life), Subscriber(2, partitioner,
+ task3.parallelism, task3.life)))
+ }
+}
+
+object SubscriberSpec {
+ class TestTask
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/org/apache/gearpump/streaming/task/SubscriptionSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/org/apache/gearpump/streaming/task/SubscriptionSpec.scala b/streaming/src/test/scala/org/apache/gearpump/streaming/task/SubscriptionSpec.scala
new file mode 100644
index 0000000..4afee8b
--- /dev/null
+++ b/streaming/src/test/scala/org/apache/gearpump/streaming/task/SubscriptionSpec.scala
@@ -0,0 +1,142 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.task
+
+import java.util.Random
+
+import org.mockito.Mockito._
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.{FlatSpec, Matchers}
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.partitioner.{HashPartitioner, Partitioner}
+import org.apache.gearpump.streaming.task.SubscriptionSpec.NextTask
+import org.apache.gearpump.streaming.{LifeTime, ProcessorDescription}
+
+class SubscriptionSpec extends FlatSpec with Matchers with MockitoSugar {
+ val appId = 0
+ val executorId = 0
+ val taskId = TaskId(0, 0)
+ val session = new Random().nextInt()
+
+ val downstreamProcessorId = 1
+ val partitioner = Partitioner[HashPartitioner]
+
+ val parallism = 2
+ val downstreamProcessor = ProcessorDescription(downstreamProcessorId, classOf[NextTask].getName,
+ parallism)
+ val subscriber = Subscriber(downstreamProcessorId, partitioner, downstreamProcessor.parallelism,
+ downstreamProcessor.life)
+
+ private def prepare: (Subscription, ExpressTransport) = {
+ val transport = mock[ExpressTransport]
+ val subscription = new Subscription(appId, executorId, taskId, subscriber, session, transport)
+ subscription.start()
+
+ val expectedAckRequest = InitialAckRequest(taskId, session)
+ verify(transport, times(1)).transport(expectedAckRequest, TaskId(1, 0), TaskId(1, 1))
+
+ (subscription, transport)
+ }
+
+ it should "not send any more message when its life ends" in {
+ val (subscription, transport) = prepare
+ subscription.changeLife(LifeTime(0, 0))
+ val count = subscription.sendMessage(Message("some"))
+ assert(count == 0)
+ }
+
+ it should "send message and handle ack correctly" in {
+ val (subscription, transport) = prepare
+ val msg1 = new Message("1", timestamp = 70)
+ subscription.sendMessage(msg1)
+
+ verify(transport, times(1)).transport(msg1, TaskId(1, 1))
+ assert(subscription.minClock == 70)
+
+ val msg2 = new Message("0", timestamp = 50)
+ subscription.sendMessage(msg2)
+ verify(transport, times(1)).transport(msg2, TaskId(1, 0))
+
+ // minClock has been set to smaller one
+ assert(subscription.minClock == 50)
+
+ val initialMinClock = subscription.minClock
+
+ // Acks initial AckRequest(0)
+ subscription.receiveAck(Ack(TaskId(1, 1), 0, 0, session))
+ subscription.receiveAck(Ack(TaskId(1, 0), 0, 0, session))
+
+ // Sends 100 messages
+ 100 until 200 foreach { clock =>
+ subscription.sendMessage(Message("1", clock))
+ subscription.sendMessage(Message("2", clock))
+ }
+
+ // Ack not received, minClock no change
+ assert(subscription.minClock == initialMinClock)
+
+ subscription.receiveAck(Ack(TaskId(1, 1), 100, 100, session))
+ subscription.receiveAck(Ack(TaskId(1, 0), 100, 100, session))
+
+ // Ack received, minClock changed
+ assert(subscription.minClock > initialMinClock)
+
+ // Expects to receive two ackRequest for two downstream tasks
+ val ackRequestForTask0 = AckRequest(taskId, 200, session)
+ verify(transport, times(1)).transport(ackRequestForTask0, TaskId(1, 0))
+
+ val ackRequestForTask1 = AckRequest(taskId, 200, session)
+ verify(transport, times(1)).transport(ackRequestForTask1, TaskId(1, 1))
+ }
+
+ it should "disallow more message sending if there is no ack back" in {
+ val (subscription, transport) = prepare
+ // send 100 messages
+ 0 until (Subscription.MAX_PENDING_MESSAGE_COUNT * 2 + 1) foreach { clock =>
+ subscription.sendMessage(Message(randomMessage, clock))
+ }
+
+ assert(subscription.allowSendingMoreMessages() == false)
+ }
+
+ it should "report minClock as Long.MaxValue when there is no pending message" in {
+ val (subscription, transport) = prepare
+ val msg1 = new Message("1", timestamp = 70)
+ subscription.sendMessage(msg1)
+ assert(subscription.minClock == 70)
+ subscription.receiveAck(Ack(TaskId(1, 1), 1, 1, session))
+ assert(subscription.minClock == Long.MaxValue)
+ }
+
+ private def randomMessage: String = new Random().nextInt.toString
+}
+
+object SubscriptionSpec {
+
+ class NextTask(taskContext: TaskContext, conf: UserConfig) extends Task(taskContext, conf) {
+
+ override def onStart(startTime: StartTime): Unit = {
+ }
+
+ override def onNext(msg: Message): Unit = {
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/org/apache/gearpump/streaming/task/TaskActorSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/org/apache/gearpump/streaming/task/TaskActorSpec.scala b/streaming/src/test/scala/org/apache/gearpump/streaming/task/TaskActorSpec.scala
new file mode 100644
index 0000000..48901d2
--- /dev/null
+++ b/streaming/src/test/scala/org/apache/gearpump/streaming/task/TaskActorSpec.scala
@@ -0,0 +1,123 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.task
+
+import akka.actor.{ExtendedActorSystem, Props}
+import akka.testkit._
+import com.typesafe.config.{Config, ConfigFactory}
+import org.mockito.Mockito.{mock, times, verify, when}
+import org.scalatest.{BeforeAndAfterEach, Matchers, WordSpec}
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.{MasterHarness, TestUtil, UserConfig}
+import org.apache.gearpump.partitioner.{HashPartitioner, Partitioner}
+import org.apache.gearpump.serializer.{FastKryoSerializer, SerializationFramework}
+import org.apache.gearpump.streaming.AppMasterToExecutor.{ChangeTask, MsgLostException, StartTask, TaskChanged, TaskRegistered}
+import org.apache.gearpump.streaming.task.TaskActorSpec.TestTask
+import org.apache.gearpump.streaming.{DAG, LifeTime, ProcessorDescription}
+import org.apache.gearpump.util.Graph._
+import org.apache.gearpump.util.{Graph, Util}
+
+class TaskActorSpec extends WordSpec with Matchers with BeforeAndAfterEach with MasterHarness {
+ protected override def config: Config = {
+ ConfigFactory.parseString(
+ """ akka.loggers = ["akka.testkit.TestEventListener"]
+ | akka.test.filter-leeway = 20000
+ """.stripMargin).
+ withFallback(TestUtil.DEFAULT_CONFIG)
+ }
+
+ val appId = 0
+ val task1 = ProcessorDescription(id = 0, taskClass = classOf[TestTask].getName, parallelism = 1)
+ val task2 = ProcessorDescription(id = 1, taskClass = classOf[TestTask].getName, parallelism = 1)
+ val dag: DAG = DAG(Graph(task1 ~ Partitioner[HashPartitioner] ~> task2))
+ val taskId1 = TaskId(0, 0)
+ val taskId2 = TaskId(1, 0)
+ val executorId1 = 1
+ val executorId2 = 2
+
+ var mockMaster: TestProbe = null
+ var taskContext1: TaskContextData = null
+
+ var mockSerializerPool: SerializationFramework = null
+
+ override def beforeEach(): Unit = {
+ startActorSystem()
+ mockMaster = TestProbe()(getActorSystem)
+
+ mockSerializerPool = mock(classOf[SerializationFramework])
+ val serializer = new FastKryoSerializer(getActorSystem.asInstanceOf[ExtendedActorSystem])
+ when(mockSerializerPool.get()).thenReturn(serializer)
+
+ taskContext1 = TaskContextData(executorId1, appId,
+ "appName", mockMaster.ref, 1,
+ LifeTime.Immortal,
+ Subscriber.of(processorId = 0, dag))
+ }
+
+ "TaskActor" should {
+ "register itself to AppMaster when started" in {
+ val mockTask = mock(classOf[TaskWrapper])
+ val testActor = TestActorRef[TaskActor](Props(
+ new TaskActor(taskId1, taskContext1, UserConfig.empty,
+ mockTask, mockSerializerPool)))(getActorSystem)
+ testActor ! TaskRegistered(taskId1, 0, Util.randInt())
+ testActor ! StartTask(taskId1)
+
+ implicit val system = getActorSystem
+ val ack = Ack(taskId2, 100, 99, testActor.underlyingActor.sessionId)
+ EventFilter[MsgLostException](occurrences = 1) intercept {
+ testActor ! ack
+ }
+ }
+
+ "respond to ChangeTask" in {
+ val mockTask = mock(classOf[TaskWrapper])
+ val testActor = TestActorRef[TaskActor](Props(new TaskActor(taskId1, taskContext1,
+ UserConfig.empty, mockTask, mockSerializerPool)))(getActorSystem)
+ testActor ! TaskRegistered(taskId1, 0, Util.randInt())
+ testActor ! StartTask(taskId1)
+ mockMaster.expectMsgType[GetUpstreamMinClock]
+
+ mockMaster.send(testActor, ChangeTask(taskId1, 1, LifeTime.Immortal, List.empty[Subscriber]))
+ mockMaster.expectMsgType[TaskChanged]
+ }
+
+ "handle received message correctly" in {
+ val mockTask = mock(classOf[TaskWrapper])
+ val msg = Message("test")
+
+ val testActor = TestActorRef[TaskActor](Props(new TaskActor(taskId1, taskContext1,
+ UserConfig.empty, mockTask, mockSerializerPool)))(getActorSystem)
+ testActor.tell(TaskRegistered(taskId1, 0, Util.randInt()), mockMaster.ref)
+ testActor.tell(StartTask(taskId1), mockMaster.ref)
+
+ testActor.tell(msg, testActor)
+
+ verify(mockTask, times(1)).onNext(msg)
+ }
+ }
+
+ override def afterEach(): Unit = {
+ shutdownActorSystem()
+ }
+}
+
+object TaskActorSpec {
+ class TestTask
+}
\ No newline at end of file
[04/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/transaction/api/OffsetManager.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/transaction/api/OffsetManager.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/transaction/api/OffsetManager.scala
new file mode 100644
index 0000000..616894a
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/transaction/api/OffsetManager.scala
@@ -0,0 +1,44 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.transaction.api
+
+import org.apache.gearpump.{Message, TimeStamp}
+
+import scala.util.Try
+
+/**
+ * Filters offsets and store the mapping from timestamp to offset
+ */
+trait MessageFilter {
+ def filter(messageAndOffset: (Message, Long)): Option[Message]
+}
+
+/**
+ * Resolves timestamp to offset by look up the underlying storage
+ */
+trait OffsetTimeStampResolver {
+ def resolveOffset(time: TimeStamp): Try[Long]
+}
+
+/**
+ * Manages message's offset on TimeReplayableSource and timestamp
+ */
+trait OffsetManager extends MessageFilter with OffsetTimeStampResolver {
+ def close(): Unit
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/transaction/api/OffsetStorage.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/transaction/api/OffsetStorage.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/transaction/api/OffsetStorage.scala
new file mode 100644
index 0000000..40fc088
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/transaction/api/OffsetStorage.scala
@@ -0,0 +1,66 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.transaction.api
+
+import org.apache.gearpump.TimeStamp
+
+import scala.util.Try
+
+object OffsetStorage {
+
+ /**
+ * StorageEmpty means no data has been stored
+ */
+ case object StorageEmpty extends Throwable
+
+ /**
+ * Overflow means the looked up time is
+ * larger than the maximum stored TimeStamp
+ */
+ case class Overflow(maxTimestamp: Array[Byte]) extends Throwable
+
+ /**
+ * Underflow means the looked up time is
+ * smaller than the minimum stored TimeStamp
+ */
+ case class Underflow(minTimestamp: Array[Byte]) extends Throwable
+}
+
+/**
+ * OffsetStorage stores the mapping from TimeStamp to Offset
+ */
+trait OffsetStorage {
+ /**
+ * Tries to look up the time in the OffsetStorage return the corresponding Offset if the time is
+ * in the range of stored TimeStamps or one of the failure info (StorageEmpty, Overflow,
+ * Underflow)
+ *
+ * @param time the time to look for
+ * @return the corresponding offset if the time is in the range, otherwise failure
+ */
+ def lookUp(time: TimeStamp): Try[Array[Byte]]
+
+ def append(time: TimeStamp, offset: Array[Byte]): Unit
+
+ def close(): Unit
+}
+
+trait OffsetStorageFactory extends java.io.Serializable {
+ def getOffsetStorage(dir: String): OffsetStorage
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/transaction/api/TimeReplayableSource.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/transaction/api/TimeReplayableSource.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/transaction/api/TimeReplayableSource.scala
new file mode 100644
index 0000000..16f98d5
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/transaction/api/TimeReplayableSource.scala
@@ -0,0 +1,30 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.transaction.api
+
+import org.apache.gearpump.streaming.source.DataSource
+
+/**
+ * AT-LEAST-ONCE API. Represents a data source which allow replaying.
+ *
+ * Subclass should be able to replay messages on recovery from the time
+ * when an application crashed.
+ */
+trait TimeReplayableSource extends DataSource
+
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/transaction/api/TimeStampFilter.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/transaction/api/TimeStampFilter.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/transaction/api/TimeStampFilter.scala
new file mode 100644
index 0000000..2ddca3a
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/transaction/api/TimeStampFilter.scala
@@ -0,0 +1,29 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.transaction.api
+
+import org.apache.gearpump.{Message, TimeStamp}
+
+/**
+ * TimeStampFilter filters out messages that are obsolete.
+ */
+trait TimeStampFilter extends java.io.Serializable {
+ def filter(msg: Message, predicate: TimeStamp): Option[Message]
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/util/ActorPathUtil.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/util/ActorPathUtil.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/util/ActorPathUtil.scala
new file mode 100644
index 0000000..97c9385
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/util/ActorPathUtil.scala
@@ -0,0 +1,41 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.util
+
+import akka.actor.{ActorPath, ActorRef}
+
+import org.apache.gearpump.streaming.task.TaskId
+
+object ActorPathUtil {
+
+ def executorActorName(executorId: Int): String = executorId.toString
+
+ def taskActorName(taskId: TaskId): String = {
+ s"processor_${taskId.processorId}_task_${taskId.index}"
+ }
+
+ def taskActorPath(appMaster: ActorRef, executorId: Int, taskId: TaskId): ActorPath = {
+ val executorManager = appMaster.path.child(executorManagerActorName)
+ val executor = executorManager.child(executorActorName(executorId))
+ val task = executor.child(taskActorName(taskId))
+ task
+ }
+
+ def executorManagerActorName: String = "executors"
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/io/gearpump/streaming/DAGSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/io/gearpump/streaming/DAGSpec.scala b/streaming/src/test/scala/io/gearpump/streaming/DAGSpec.scala
deleted file mode 100644
index 13b8e34..0000000
--- a/streaming/src/test/scala/io/gearpump/streaming/DAGSpec.scala
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming
-
-import org.scalacheck.Gen
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{Matchers, PropSpec}
-
-import io.gearpump.partitioner.PartitionerDescription
-import io.gearpump.streaming.task.TaskId
-import io.gearpump.util.Graph
-import io.gearpump.util.Graph.Node
-
-class DAGSpec extends PropSpec with PropertyChecks with Matchers {
-
- val parallelismGen = Gen.chooseNum[Int](1, 100)
-
- property("DAG should be built correctly for a single task") {
- forAll(parallelismGen) { (parallelism: Int) =>
- val task = ProcessorDescription(id = 0, taskClass = "task", parallelism = parallelism)
- val graph = Graph[ProcessorDescription, PartitionerDescription](task)
- val dag = DAG(graph)
- dag.processors.size shouldBe 1
- assert(dag.taskCount == parallelism)
- dag.tasks.sortBy(_.index) shouldBe (0 until parallelism).map(index => TaskId(0, index))
- dag.graph.edges shouldBe empty
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/io/gearpump/streaming/MessageSerializerSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/io/gearpump/streaming/MessageSerializerSpec.scala b/streaming/src/test/scala/io/gearpump/streaming/MessageSerializerSpec.scala
deleted file mode 100644
index 7938415..0000000
--- a/streaming/src/test/scala/io/gearpump/streaming/MessageSerializerSpec.scala
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming
-
-import org.jboss.netty.buffer.{ChannelBufferOutputStream, ChannelBuffers}
-import org.scalatest.{Matchers, WordSpec}
-
-import io.gearpump.streaming.task._
-import io.gearpump.transport.netty.WrappedChannelBuffer
-
-class MessageSerializerSpec extends WordSpec with Matchers {
-
- def testSerializer[T](obj: T, taskMessageSerializer: TaskMessageSerializer[T]): T = {
- val length = taskMessageSerializer.getLength(obj)
- val bout = new ChannelBufferOutputStream(ChannelBuffers.buffer(length))
- taskMessageSerializer.write(bout, obj)
- val input = new WrappedChannelBuffer(ChannelBuffers.wrappedBuffer(bout.buffer().array()))
- taskMessageSerializer.read(input)
- }
-
- "SerializedMessageSerializer" should {
- "serialize and deserialize SerializedMessage properly" in {
- val serializer = new SerializedMessageSerializer
- val data = new Array[Byte](256)
- new java.util.Random().nextBytes(data)
- val msg = SerializedMessage(1024, data)
- val result = testSerializer(msg, serializer)
- assert(result.timeStamp == msg.timeStamp && result.bytes.sameElements(msg.bytes))
- }
- }
-
- "TaskIdSerializer" should {
- "serialize and deserialize TaskId properly" in {
- val taskIdSerializer = new TaskIdSerializer
- val taskId = TaskId(1, 3)
- assert(testSerializer(taskId, taskIdSerializer).equals(taskId))
- }
- }
-
- "AckRequestSerializer" should {
- "serialize and deserialize AckRequest properly" in {
- val serializer = new AckRequestSerializer
- val ackRequest = AckRequest(TaskId(1, 2), 1000, 1024)
- assert(testSerializer(ackRequest, serializer).equals(ackRequest))
- }
- }
-
- "InitialAckRequestSerializer" should {
- "serialize and deserialize AckRequest properly" in {
- val serializer = new InitialAckRequestSerializer
- val ackRequest = InitialAckRequest(TaskId(1, 2), 1024)
- assert(testSerializer(ackRequest, serializer).equals(ackRequest))
- }
- }
-
- "AckSerializer" should {
- "serialize and deserialize Ack properly" in {
- val serializer = new AckSerializer
- val ack = Ack(TaskId(1, 2), 1024, 1023, 1799)
- assert(testSerializer(ack, serializer).equals(ack))
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/io/gearpump/streaming/MockUtil.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/io/gearpump/streaming/MockUtil.scala b/streaming/src/test/scala/io/gearpump/streaming/MockUtil.scala
deleted file mode 100644
index 40310f7..0000000
--- a/streaming/src/test/scala/io/gearpump/streaming/MockUtil.scala
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming
-
-import akka.actor.{Actor, ActorSystem}
-import akka.testkit.TestActorRef
-import org.mockito.{ArgumentMatcher, Matchers, Mockito}
-
-import io.gearpump.cluster.TestUtil
-import io.gearpump.streaming.task.{TaskContext, TaskId}
-
-object MockUtil {
-
- lazy val system: ActorSystem = ActorSystem("mockUtil", TestUtil.DEFAULT_CONFIG)
-
- def mockTaskContext: TaskContext = {
- val context = Mockito.mock(classOf[TaskContext])
- Mockito.when(context.self).thenReturn(Mockito.mock(classOf[TestActorRef[Actor]]))
- Mockito.when(context.system).thenReturn(system)
- Mockito.when(context.parallelism).thenReturn(1)
- Mockito.when(context.taskId).thenReturn(TaskId(0, 0))
- context
- }
-
- def argMatch[T](func: T => Boolean): T = {
- Matchers.argThat(new ArgumentMatcher[T] {
- override def matches(param: Any): Boolean = {
- val mesage = param.asInstanceOf[T]
- func(mesage)
- }
- })
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/io/gearpump/streaming/StreamingTestUtil.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/io/gearpump/streaming/StreamingTestUtil.scala b/streaming/src/test/scala/io/gearpump/streaming/StreamingTestUtil.scala
deleted file mode 100644
index 2ea8b84..0000000
--- a/streaming/src/test/scala/io/gearpump/streaming/StreamingTestUtil.scala
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming
-
-import akka.actor._
-import akka.testkit.TestActorRef
-
-import io.gearpump.cluster.AppMasterToMaster.RegisterAppMaster
-import io.gearpump.cluster.appmaster.AppMasterRuntimeInfo
-import io.gearpump.cluster.scheduler.Resource
-import io.gearpump.cluster.{AppDescription, AppMasterContext, MiniCluster, UserConfig}
-import io.gearpump.streaming.appmaster.AppMaster
-import io.gearpump.util.Graph
-
-object StreamingTestUtil {
- private var executorId = 0
- val testUserName = "testuser"
-
- def startAppMaster(miniCluster: MiniCluster, appId: Int): TestActorRef[AppMaster] = {
-
- implicit val actorSystem = miniCluster.system
- val masterConf = AppMasterContext(appId, testUserName, Resource(1), null,
- None, miniCluster.mockMaster, AppMasterRuntimeInfo(appId, appName = appId.toString))
-
- val app = StreamApplication("test", Graph.empty, UserConfig.empty)
- val appDescription = AppDescription(app.name, app.appMaster.getName, app.userConfig)
- val props = Props(new AppMaster(masterConf, appDescription))
- val appMaster = miniCluster.launchActor(props).asInstanceOf[TestActorRef[AppMaster]]
- val registerAppMaster = RegisterAppMaster(appMaster, masterConf.registerData)
- miniCluster.mockMaster.tell(registerAppMaster, appMaster)
-
- appMaster
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/io/gearpump/streaming/appmaster/AppMasterSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/io/gearpump/streaming/appmaster/AppMasterSpec.scala b/streaming/src/test/scala/io/gearpump/streaming/appmaster/AppMasterSpec.scala
deleted file mode 100644
index 90fb8ab..0000000
--- a/streaming/src/test/scala/io/gearpump/streaming/appmaster/AppMasterSpec.scala
+++ /dev/null
@@ -1,238 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.appmaster
-
-import scala.concurrent.duration._
-
-import akka.actor.{ActorRef, Props}
-import akka.testkit.{TestActorRef, TestProbe}
-import org.scalatest._
-
-import io.gearpump.Message
-import io.gearpump.cluster.AppMasterToMaster._
-import io.gearpump.cluster.AppMasterToWorker.LaunchExecutor
-import io.gearpump.cluster.ClientToMaster.ShutdownApplication
-import io.gearpump.cluster.MasterToAppMaster.{AppMasterRegistered, ResourceAllocated}
-import io.gearpump.cluster.WorkerToAppMaster.ExecutorLaunchRejected
-import io.gearpump.cluster._
-import io.gearpump.cluster.appmaster.{AppMasterRuntimeEnvironment, AppMasterRuntimeInfo}
-import io.gearpump.cluster.master.MasterProxy
-import io.gearpump.cluster.scheduler.{Resource, ResourceAllocation, ResourceRequest}
-import io.gearpump.cluster.worker.WorkerId
-import io.gearpump.jarstore.FilePath
-import io.gearpump.partitioner.HashPartitioner
-import io.gearpump.streaming.task.{StartTime, TaskContext, _}
-import io.gearpump.streaming.{Processor, StreamApplication}
-import io.gearpump.util.Graph
-import io.gearpump.util.Graph._
-
-class AppMasterSpec extends WordSpec with Matchers with BeforeAndAfterEach with MasterHarness {
- protected override def config = TestUtil.DEFAULT_CONFIG
-
- var appMaster: ActorRef = null
-
- val appId = 0
- val workerId = WorkerId(1, 0L)
- val resource = Resource(1)
- val taskDescription1 = Processor[TaskA](2)
- val taskDescription2 = Processor[TaskB](2)
- val partitioner = new HashPartitioner
- var conf: UserConfig = null
-
- var mockTask: TestProbe = null
-
- var mockMaster: TestProbe = null
- var mockMasterProxy: ActorRef = null
-
- var mockWorker: TestProbe = null
- var appDescription: AppDescription = null
- var appMasterContext: AppMasterContext = null
- var appMasterRuntimeInfo: AppMasterRuntimeInfo = null
-
- override def beforeEach(): Unit = {
- startActorSystem()
-
- mockTask = TestProbe()(getActorSystem)
-
- mockMaster = TestProbe()(getActorSystem)
- mockWorker = TestProbe()(getActorSystem)
- mockMaster.ignoreMsg(ignoreSaveAppData)
- appMasterRuntimeInfo = AppMasterRuntimeInfo(appId, appName = appId.toString)
-
- implicit val system = getActorSystem
- conf = UserConfig.empty.withValue(AppMasterSpec.MASTER, mockMaster.ref)
- val mockJar = AppJar("for_test", FilePath("path"))
- appMasterContext = AppMasterContext(appId, "test", resource, null, Some(mockJar),
- mockMaster.ref, appMasterRuntimeInfo)
- val graph = Graph(taskDescription1 ~ partitioner ~> taskDescription2)
- val streamApp = StreamApplication("test", graph, conf)
- appDescription = Application.ApplicationToAppDescription(streamApp)
- import scala.concurrent.duration._
- mockMasterProxy = getActorSystem.actorOf(Props(new MasterProxy(List(mockMaster.ref.path),
- 30.seconds)), AppMasterSpec.MOCK_MASTER_PROXY)
- TestActorRef[AppMaster](
- AppMasterRuntimeEnvironment.props(List(mockMasterProxy.path), appDescription,
- appMasterContext))(getActorSystem)
-
- val registerAppMaster = mockMaster.receiveOne(15.seconds)
- assert(registerAppMaster.isInstanceOf[RegisterAppMaster])
- appMaster = registerAppMaster.asInstanceOf[RegisterAppMaster].appMaster
-
- mockMaster.reply(AppMasterRegistered(appId))
- mockMaster.expectMsg(15.seconds, GetAppData(appId, "DAG"))
- mockMaster.reply(GetAppDataResult("DAG", null))
- mockMaster.expectMsg(15.seconds, GetAppData(appId, "startClock"))
-
- mockMaster.reply(GetAppDataResult("startClock", 0L))
-
- mockMaster.expectMsg(15.seconds, RequestResource(appId, ResourceRequest(Resource(4),
- workerId = WorkerId.unspecified)))
- }
-
- override def afterEach(): Unit = {
- shutdownActorSystem()
- }
-
- "AppMaster" should {
- "kill it self when allocate resource time out" in {
- mockMaster.reply(ResourceAllocated(Array(ResourceAllocation(Resource(2),
- mockWorker.ref, workerId))))
- mockMaster.expectMsg(60.seconds, ShutdownApplication(appId))
- }
-
- "reschedule the resource when the worker reject to start executor" in {
- val resource = Resource(4)
- mockMaster.reply(ResourceAllocated(Array(ResourceAllocation(resource,
- mockWorker.ref, workerId))))
- mockWorker.expectMsgClass(classOf[LaunchExecutor])
- mockWorker.reply(ExecutorLaunchRejected(""))
- mockMaster.expectMsg(RequestResource(appId, ResourceRequest(resource, WorkerId.unspecified)))
- }
-
- "find a new master when lost connection with master" in {
-
- val watcher = TestProbe()(getActorSystem)
- watcher.watch(mockMasterProxy)
- getActorSystem.stop(mockMasterProxy)
- watcher.expectTerminated(mockMasterProxy)
- // Make sure the parent of mockMasterProxy has received the Terminated message.
- // Issus address: https://github.com/gearpump/gearpump/issues/1919
- Thread.sleep(2000)
-
- import scala.concurrent.duration._
- mockMasterProxy = getActorSystem.actorOf(Props(new MasterProxy(List(mockMaster.ref.path),
- 30.seconds)), AppMasterSpec.MOCK_MASTER_PROXY)
- mockMaster.expectMsgClass(15.seconds, classOf[RegisterAppMaster])
- }
-
- // // TODO: This test is failing on Travis randomly
- // // We have not identifed the root cause.
- // // Check: https://travis-ci.org/intel-hadoop/gearpump/builds/56826843
- // // Issue tracker: https://github.com/intel-hadoop/gearpump/issues/733
- //
- // "launch executor and task properly" in {
- // mockMaster.reply(ResourceAllocated(Array(ResourceAllocation(Resource(4), mockWorker.ref,
- // workerId))))
- // mockWorker.expectMsgClass(classOf[LaunchExecutor])
- //
- // val workerSystem = ActorSystem("worker", TestUtil.DEFAULT_CONFIG)
- // mockWorker.reply(RegisterActorSystem(ActorUtil.getSystemAddress(workerSystem).toString))
- // for (i <- 1 to 4) {
- // mockMaster.expectMsg(10 seconds, AppMasterSpec.TaskStarted)
- // }
- //
- // // clock status: task(0,0) -> 1, task(0,1)->0, task(1, 0)->0, task(1,1)->0
- // appMaster.tell(UpdateClock(TaskId(0, 0), 1), mockTask.ref)
- //
- // // there is no further upstream, so the upstreamMinClock is Long.MaxValue
- // mockTask.expectMsg(UpstreamMinClock(Long.MaxValue))
- //
- // // check min clock
- // appMaster.tell(GetLatestMinClock, mockTask.ref)
- // mockTask.expectMsg(LatestMinClock(0))
- //
- //
- // // clock status: task(0,0) -> 1, task(0,1)->1, task(1, 0)->0, task(1,1)->0
- // appMaster.tell(UpdateClock(TaskId(0, 1), 1), mockTask.ref)
- //
- // // there is no further upstream, so the upstreamMinClock is Long.MaxValue
- // mockTask.expectMsg(UpstreamMinClock(Long.MaxValue))
- //
- // // check min clock
- // appMaster.tell(GetLatestMinClock, mockTask.ref)
- // mockTask.expectMsg(LatestMinClock(0))
- //
- // // Clock status: task(0,0) -> 1, task(0,1)->1, task(1, 1)->0, task(1,1)->0
- // appMaster.tell(UpdateClock(TaskId(1, 0), 1), mockTask.ref)
- //
- // // Min clock of processor 0 (Task(0, 0) and Task(0, 1))
- // mockTask.expectMsg(UpstreamMinClock(1))
- //
- // // check min clock
- // appMaster.tell(GetLatestMinClock, mockTask.ref)
- // mockTask.expectMsg(LatestMinClock(0))
- //
- // // clock status: task(0,0) -> 1, task(0,1)->1, task(1, 1)->0, task(1,1)->1
- // appMaster.tell(UpdateClock(TaskId(1, 1), 1), mockTask.ref)
- //
- // // min clock of processor 0 (Task(0, 0) and Task(0, 1))
- // mockTask.expectMsg(UpstreamMinClock(1))
- //
- // // check min clock
- // appMaster.tell(GetLatestMinClock, mockTask.ref)
- // mockTask.expectMsg(LatestMinClock(1))
- //
- // // shutdown worker and all executor on this work, expect appmaster to ask
- // // for new resources
- // workerSystem.shutdown()
- // mockMaster.expectMsg(RequestResource(appId, ResourceRequest(Resource(4), relaxation =
- // Relaxation.ONEWORKER)))
- // }
- }
-
- def ignoreSaveAppData: PartialFunction[Any, Boolean] = {
- case msg: SaveAppData => true
- }
-}
-
-object AppMasterSpec {
- val MASTER = "master"
- case object TaskStarted
-
- val MOCK_MASTER_PROXY = "mockMasterProxy"
-}
-
-class TaskA(taskContext: TaskContext, userConf: UserConfig) extends Task(taskContext, userConf) {
-
- val master = userConf.getValue[ActorRef](AppMasterSpec.MASTER).get
- override def onStart(startTime: StartTime): Unit = {
- master ! AppMasterSpec.TaskStarted
- }
-
- override def onNext(msg: Message): Unit = {}
-}
-
-class TaskB(taskContext: TaskContext, userConf: UserConfig) extends Task(taskContext, userConf) {
-
- val master = userConf.getValue[ActorRef](AppMasterSpec.MASTER).get
- override def onStart(startTime: StartTime): Unit = {
- master ! AppMasterSpec.TaskStarted
- }
-
- override def onNext(msg: Message): Unit = {}
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/io/gearpump/streaming/appmaster/ClockServiceSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/io/gearpump/streaming/appmaster/ClockServiceSpec.scala b/streaming/src/test/scala/io/gearpump/streaming/appmaster/ClockServiceSpec.scala
deleted file mode 100644
index 01744a3..0000000
--- a/streaming/src/test/scala/io/gearpump/streaming/appmaster/ClockServiceSpec.scala
+++ /dev/null
@@ -1,241 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.appmaster
-
-import scala.concurrent.{Future, Promise}
-
-import akka.actor.{ActorSystem, Props}
-import akka.testkit.{ImplicitSender, TestKit, TestProbe}
-import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}
-
-import io.gearpump.cluster.{TestUtil, UserConfig}
-import io.gearpump.partitioner.{HashPartitioner, Partitioner, PartitionerDescription}
-import io.gearpump.streaming.appmaster.ClockService.{ChangeToNewDAG, ChangeToNewDAGSuccess, HealthChecker, ProcessorClock}
-import io.gearpump.streaming.appmaster.ClockServiceSpec.Store
-import io.gearpump.streaming.storage.AppDataStore
-import io.gearpump.streaming.task.{GetLatestMinClock, GetStartClock, UpstreamMinClock, _}
-import io.gearpump.streaming.{DAG, LifeTime, ProcessorDescription}
-import io.gearpump.util.Graph
-import io.gearpump.util.Graph._
-
-class ClockServiceSpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
- with WordSpecLike with Matchers with BeforeAndAfterAll {
-
- def this() = this(ActorSystem("ClockServiceSpec", TestUtil.DEFAULT_CONFIG))
-
- val hash = Partitioner[HashPartitioner]
- val task1 = ProcessorDescription(id = 0, taskClass = classOf[TaskActor].getName, parallelism = 1)
- val task2 = ProcessorDescription(id = 1, taskClass = classOf[TaskActor].getName, parallelism = 1)
- val dag = DAG(Graph(task1 ~ hash ~> task2))
-
- override def afterAll {
- TestKit.shutdownActorSystem(system)
- }
-
- "The ClockService" should {
- "maintain a global view of message timestamp in the application" in {
- val store = new Store()
- val startClock = 100L
- store.put(ClockService.START_CLOCK, startClock)
- val clockService = system.actorOf(Props(new ClockService(dag, store)))
- clockService ! GetLatestMinClock
- expectMsg(LatestMinClock(startClock))
-
- // task(0,0): clock(101); task(1,0): clock(100)
- clockService ! UpdateClock(TaskId(0, 0), 101)
-
- // There is no upstream, so pick Long.MaxValue
- expectMsg(UpstreamMinClock(Long.MaxValue))
-
- // Min clock is updated
- clockService ! GetLatestMinClock
- expectMsg(LatestMinClock(100))
-
- // task(0,0): clock(101); task(1,0): clock(101)
- clockService ! UpdateClock(TaskId(1, 0), 101)
-
- // Upstream is Task(0, 0), 101
- expectMsg(UpstreamMinClock(101))
-
- // Min clock is updated
- clockService ! GetLatestMinClock
- expectMsg(LatestMinClock(101))
- }
-
- "act on ChangeToNewDAG and make sure downstream clock smaller than upstreams" in {
- val store = new Store()
- val startClock = 100L
- store.put(ClockService.START_CLOCK, startClock)
- val clockService = system.actorOf(Props(new ClockService(dag, store)))
- val task = TestProbe()
- clockService.tell(UpdateClock(TaskId(0, 0), 200), task.ref)
- task.expectMsgType[UpstreamMinClock]
-
- val task3 = ProcessorDescription(id = 3, taskClass = classOf[TaskActor].getName,
- parallelism = 1)
- val task4 = ProcessorDescription(id = 4, taskClass = classOf[TaskActor].getName,
- parallelism = 1)
- val task5 = ProcessorDescription(id = 5, taskClass = classOf[TaskActor].getName,
- parallelism = 1)
- val dagAddMiddleNode = DAG(Graph(
- task1 ~ hash ~> task2,
- task1 ~ hash ~> task3,
- task3 ~ hash ~> task2,
- task2 ~ hash ~> task4,
- task5 ~ hash ~> task1
- ))
- val user = TestProbe()
- clockService.tell(ChangeToNewDAG(dagAddMiddleNode), user.ref)
-
- val clocks = user.expectMsgPF() {
- case ChangeToNewDAGSuccess(clocks) =>
- clocks
- }
-
- // For intermediate task, pick its upstream as initial clock
- assert(clocks(task3.id) == clocks(task1.id))
-
- // For sink task, pick its upstream as initial clock
- assert(clocks(task4.id) == clocks(task2.id))
-
- // For source task, set the initial clock as startClock
- assert(clocks(task5.id) == startClock)
- }
-
- "maintain global checkpoint time" in {
- val store = new Store()
- val startClock = 100L
- store.put(ClockService.START_CLOCK, startClock)
- val clockService = system.actorOf(Props(new ClockService(dag, store)))
- clockService ! UpdateClock(TaskId(0, 0), 200L)
- expectMsgType[UpstreamMinClock]
- clockService ! UpdateClock(TaskId(1, 0), 200L)
- expectMsgType[UpstreamMinClock]
-
- clockService ! GetStartClock
- expectMsg(StartClock(200L))
-
- val conf = UserConfig.empty.withBoolean("state.checkpoint.enable", true)
- val task3 = ProcessorDescription(id = 3, taskClass = classOf[TaskActor].getName,
- parallelism = 1, taskConf = conf)
- val task4 = ProcessorDescription(id = 4, taskClass = classOf[TaskActor].getName,
- parallelism = 1, taskConf = conf)
- val dagWithStateTasks = DAG(Graph(
- task1 ~ hash ~> task2,
- task1 ~ hash ~> task3,
- task3 ~ hash ~> task2,
- task2 ~ hash ~> task4
- ), version = 1)
-
- val taskId3 = TaskId(3, 0)
- val taskId4 = TaskId(4, 0)
-
- clockService ! ChangeToNewDAG(dagWithStateTasks)
- expectMsgType[ChangeToNewDAGSuccess]
-
- clockService ! ReportCheckpointClock(taskId3, startClock)
- clockService ! ReportCheckpointClock(taskId4, startClock)
- clockService ! GetStartClock
- expectMsg(StartClock(startClock))
-
- clockService ! ReportCheckpointClock(taskId3, 200L)
- clockService ! ReportCheckpointClock(taskId4, 300L)
- clockService ! GetStartClock
- expectMsg(StartClock(startClock))
-
- clockService ! ReportCheckpointClock(taskId3, 300L)
- clockService ! GetStartClock
- expectMsg(StartClock(300L))
- }
- }
-
- "ProcessorClock" should {
- "maintain the min clock of current processor" in {
- val processorId = 0
- val parallism = 3
- val clock = new ProcessorClock(processorId, LifeTime.Immortal, parallism)
- clock.init(100L)
- clock.updateMinClock(0, 101)
- assert(clock.min == 100L)
-
- clock.updateMinClock(1, 102)
- assert(clock.min == 100L)
-
- clock.updateMinClock(2, 103)
- assert(clock.min == 101L)
- }
- }
-
- "HealthChecker" should {
- "report stalling if the clock is not advancing" in {
- val healthChecker = new HealthChecker(stallingThresholdSeconds = 1)
- val source = ProcessorDescription(id = 0, taskClass = null, parallelism = 1)
- val sourceClock = new ProcessorClock(0, LifeTime.Immortal, 1)
- sourceClock.init(0L)
- val sink = ProcessorDescription(id = 1, taskClass = null, parallelism = 1)
- val sinkClock = new ProcessorClock(1, LifeTime.Immortal, 1)
- sinkClock.init(0L)
- val graph = Graph.empty[ProcessorDescription, PartitionerDescription]
- graph.addVertex(source)
- graph.addVertex(sink)
- graph.addEdge(source, PartitionerDescription(null), sink)
- val dag = DAG(graph)
- val clocks = Map(
- 0 -> sourceClock,
- 1 -> sinkClock
- )
-
- sourceClock.updateMinClock(0, 100L)
- sinkClock.updateMinClock(0, 100L)
-
- // Clock advances from 0 to 100, there is no stalling.
- healthChecker.check(currentMinClock = 100, clocks, dag, 200)
- healthChecker.getReport.stallingTasks shouldBe List.empty[TaskId]
-
- // Clock not advancing.
- // Pasted time exceed the stalling threshold, report stalling
- healthChecker.check(currentMinClock = 100, clocks, dag, 1300)
-
- // The source task is stalling the clock
- healthChecker.getReport.stallingTasks shouldBe List(TaskId(0, 0))
-
- // Advance the source clock
- sourceClock.updateMinClock(0, 101L)
- healthChecker.check(currentMinClock = 100, clocks, dag, 1300)
- // The sink task is stalling the clock
- healthChecker.getReport.stallingTasks shouldBe List(TaskId(1, 0))
- }
- }
-}
-
-object ClockServiceSpec {
-
- class Store extends AppDataStore {
-
- private var map = Map.empty[String, Any]
-
- def put(key: String, value: Any): Future[Any] = {
- map = map + (key -> value)
- Promise.successful(value).future
- }
-
- def get(key: String): Future[Any] = {
- Promise.successful(map.get(key).getOrElse(null)).future
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/io/gearpump/streaming/appmaster/DagManagerSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/io/gearpump/streaming/appmaster/DagManagerSpec.scala b/streaming/src/test/scala/io/gearpump/streaming/appmaster/DagManagerSpec.scala
deleted file mode 100644
index fb633f9..0000000
--- a/streaming/src/test/scala/io/gearpump/streaming/appmaster/DagManagerSpec.scala
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.appmaster
-
-import scala.concurrent.Await
-import scala.concurrent.duration.Duration
-
-import akka.actor.{ActorSystem, Props}
-import akka.testkit.TestProbe
-import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}
-
-import io.gearpump.cluster.{TestUtil, UserConfig}
-import io.gearpump.partitioner.{HashPartitioner, Partitioner}
-import io.gearpump.streaming.appmaster.DagManager.{DAGOperationFailed, DAGOperationSuccess, GetLatestDAG, GetTaskLaunchData, LatestDAG, NewDAGDeployed, ReplaceProcessor, TaskLaunchData, WatchChange}
-import io.gearpump.streaming.task.{Subscriber, TaskActor}
-import io.gearpump.streaming.{DAG, LifeTime, ProcessorDescription, StreamApplication}
-import io.gearpump.util.Graph
-import io.gearpump.util.Graph._
-
-class DagManagerSpec extends WordSpecLike with Matchers with BeforeAndAfterAll {
-
- val hash = Partitioner[HashPartitioner]
- val task1 = ProcessorDescription(id = 1, taskClass = classOf[TaskActor].getName, parallelism = 1)
- val task2 = ProcessorDescription(id = 2, taskClass = classOf[TaskActor].getName, parallelism = 1)
- val graph = Graph(task1 ~ hash ~> task2)
- val dag = DAG(graph)
- implicit var system: ActorSystem = null
- val appId = 0
- lazy val userConfig = UserConfig.empty.withValue(StreamApplication.DAG, graph)
-
- "DagManager" should {
- import io.gearpump.streaming.appmaster.ClockServiceSpec.Store
- "maintain the dags properly" in {
- val store = new Store
-
- val dagManager = system.actorOf(Props(new DagManager(appId, userConfig, store, Some(dag))))
- val client = TestProbe()
- client.send(dagManager, GetLatestDAG)
- client.expectMsg(LatestDAG(dag))
-
- client.send(dagManager, GetTaskLaunchData(dag.version, task1.id, null))
- val task1LaunchData = TaskLaunchData(task1, Subscriber.of(task1.id, dag))
- client.expectMsg(task1LaunchData)
-
- val task2LaunchData = TaskLaunchData(task2, Subscriber.of(task2.id, dag))
- client.send(dagManager, GetTaskLaunchData(dag.version, task2.id, null))
- client.expectMsg(task2LaunchData)
-
- val watcher = TestProbe()
- client.send(dagManager, WatchChange(watcher.ref))
- val task3 = task2.copy(id = 3, life = LifeTime(100, Long.MaxValue))
-
- client.send(dagManager, ReplaceProcessor(task2.id, task3))
- client.expectMsg(DAGOperationSuccess)
-
- client.send(dagManager, GetLatestDAG)
- val newDag = client.expectMsgPF() {
- case LatestDAG(dag) => dag
- }
- assert(newDag.processors.contains(task3.id))
- watcher.expectMsgType[LatestDAG]
-
- val task4 = task3.copy(id = 4)
- client.send(dagManager, ReplaceProcessor(task3.id, task4))
- client.expectMsgType[DAGOperationFailed]
-
- client.send(dagManager, NewDAGDeployed(newDag.version))
- client.send(dagManager, ReplaceProcessor(task3.id, task4))
- client.expectMsg(DAGOperationSuccess)
- }
-
- "retrieve last stored dag properly" in {
- val store = new Store
- val newGraph = Graph(task1 ~ hash ~> task2 ~> task2)
- val newDag = DAG(newGraph)
- store.put(StreamApplication.DAG, newDag)
- val dagManager = system.actorOf(Props(new DagManager(appId, userConfig, store, Some(dag))))
- val client = TestProbe()
- client.send(dagManager, GetLatestDAG)
- client.expectMsg(LatestDAG(newDag))
- }
- }
-
- override def afterAll {
- system.terminate()
- Await.result(system.whenTerminated, Duration.Inf)
- }
-
- override def beforeAll {
- this.system = ActorSystem("DagManagerSpec", TestUtil.DEFAULT_CONFIG)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/io/gearpump/streaming/appmaster/ExecutorManagerSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/io/gearpump/streaming/appmaster/ExecutorManagerSpec.scala b/streaming/src/test/scala/io/gearpump/streaming/appmaster/ExecutorManagerSpec.scala
deleted file mode 100644
index a57a1ae..0000000
--- a/streaming/src/test/scala/io/gearpump/streaming/appmaster/ExecutorManagerSpec.scala
+++ /dev/null
@@ -1,151 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.appmaster
-
-import scala.concurrent.Await
-import scala.concurrent.duration.Duration
-
-import akka.actor._
-import akka.testkit.TestProbe
-import com.typesafe.config.ConfigFactory
-import org.scalatest._
-
-import io.gearpump.TestProbeUtil
-import io.gearpump.cluster.AppMasterToWorker.ChangeExecutorResource
-import io.gearpump.cluster._
-import io.gearpump.cluster.appmaster.ExecutorSystemScheduler.{ExecutorSystemStarted, StartExecutorSystemTimeout, StartExecutorSystems}
-import io.gearpump.cluster.appmaster.{ExecutorSystem, WorkerInfo}
-import io.gearpump.cluster.scheduler.{Resource, ResourceRequest}
-import io.gearpump.cluster.worker.WorkerId
-import io.gearpump.jarstore.FilePath
-import io.gearpump.streaming.ExecutorId
-import io.gearpump.streaming.ExecutorToAppMaster.RegisterExecutor
-import io.gearpump.streaming.appmaster.ExecutorManager.{ExecutorStarted, _}
-import io.gearpump.streaming.appmaster.ExecutorManagerSpec.StartExecutorActorPlease
-import io.gearpump.util.ActorSystemBooter.BindLifeCycle
-import io.gearpump.util.LogUtil
-
-class ExecutorManagerSpec extends FlatSpec with Matchers with BeforeAndAfterAll {
- implicit var system: ActorSystem = null
-
- private val LOG = LogUtil.getLogger(getClass)
- private val appId = 0
- private val resource = Resource(10)
-
- override def beforeAll(): Unit = {
- system = ActorSystem("test", TestUtil.DEFAULT_CONFIG)
- }
-
- override def afterAll(): Unit = {
- system.terminate()
- Await.result(system.whenTerminated, Duration.Inf)
- }
-
- private def startExecutorSystems = {
- val master = TestProbe()
- val taskManager = TestProbe()
- val executor = TestProbe()
- val userConfig = UserConfig.empty
-
- val username = "user"
- val appName = "app"
- val appJar = Some(AppJar("for_test", FilePath("path")))
-
- val appMasterContext = AppMasterContext(appId, username, null, null, appJar, master.ref, null)
-
- val executorFactory = (_: ExecutorContext, _: UserConfig, _: Address, _: ExecutorId) => {
- executor.ref ! StartExecutorActorPlease
- TestProbeUtil.toProps(executor)
- }
- val executorManager = system.actorOf(Props(new ExecutorManager(userConfig, appMasterContext,
- executorFactory, ConfigFactory.empty, appName)))
-
- taskManager.send(executorManager, SetTaskManager(taskManager.ref))
- val resourceRequest = Array(ResourceRequest(resource, WorkerId.unspecified))
-
- // Starts executors
- taskManager.send(executorManager, StartExecutors(resourceRequest, appJar.get))
-
- // Asks master to start executor systems
- import scala.concurrent.duration._
- val startExecutorSystem = master.receiveOne(5.seconds).asInstanceOf[StartExecutorSystems]
- assert(startExecutorSystem.resources == resourceRequest)
- import startExecutorSystem.executorSystemConfig.{classPath, executorAkkaConfig, jar, jvmArguments, username => returnedUserName}
- assert(startExecutorSystem.resources == resourceRequest)
-
- assert(classPath.length == 0)
- assert(jvmArguments.length == 0)
- assert(jar == appJar)
- assert(returnedUserName == username)
- assert(executorAkkaConfig.isEmpty)
-
- (master, executor, taskManager, executorManager)
- }
-
- it should "report timeout to taskManager" in {
- import io.gearpump.streaming.appmaster.ExecutorManager._
- val (master, executor, taskManager, executorManager) = startExecutorSystems
- master.reply(StartExecutorSystemTimeout)
- taskManager.expectMsg(StartExecutorsTimeOut)
- }
-
- it should "start executor actor correctly" in {
- val (master, executor, taskManager, executorManager) = startExecutorSystems
- val executorSystemDaemon = TestProbe()
- val worker = TestProbe()
- val workerId = WorkerId(0, 0L)
- val workerInfo = WorkerInfo(workerId, worker.ref)
- val executorSystem = ExecutorSystem(0, null, executorSystemDaemon.ref,
- resource, workerInfo)
- master.reply(ExecutorSystemStarted(executorSystem, None))
- import scala.concurrent.duration._
- val bindLifeWith = executorSystemDaemon.receiveOne(3.seconds).asInstanceOf[BindLifeCycle]
- val proxyExecutor = bindLifeWith.actor
- executor.expectMsg(StartExecutorActorPlease)
-
- val executorId = 0
-
- // Registers executor
- executor.send(executorManager, RegisterExecutor(proxyExecutor, executorId,
- resource, workerInfo))
- taskManager.expectMsgType[ExecutorStarted]
-
- // Broadcasts message to childs
- taskManager.send(executorManager, BroadCast("broadcast"))
- executor.expectMsg("broadcast")
-
- // Unicast
- taskManager.send(executorManager, UniCast(executorId, "unicast"))
- executor.expectMsg("unicast")
-
- // Updates executor resource status
- val usedResource = Resource(5)
- executorManager ! ExecutorResourceUsageSummary(Map(executorId -> usedResource))
- worker.expectMsg(ChangeExecutorResource(appId, executorId, resource - usedResource))
-
- // Watches for executor termination
- system.stop(executor.ref)
- LOG.info("Shutting down executor, and wait taskManager to get notified")
- taskManager.expectMsg(ExecutorStopped(executorId))
- }
-}
-
-object ExecutorManagerSpec {
- case object StartExecutorActorPlease
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/io/gearpump/streaming/appmaster/ExecutorRestartPolicySpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/io/gearpump/streaming/appmaster/ExecutorRestartPolicySpec.scala b/streaming/src/test/scala/io/gearpump/streaming/appmaster/ExecutorRestartPolicySpec.scala
deleted file mode 100644
index 9d4432a..0000000
--- a/streaming/src/test/scala/io/gearpump/streaming/appmaster/ExecutorRestartPolicySpec.scala
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.appmaster
-
-import scala.concurrent.duration._
-
-import org.scalatest.{Matchers, WordSpec}
-
-import io.gearpump.streaming.executor.ExecutorRestartPolicy
-import io.gearpump.streaming.task.TaskId
-
-class ExecutorRestartPolicySpec extends WordSpec with Matchers {
-
- "ExecutorRestartPolicy" should {
- "decide whether to restart the executor" in {
- val executorId1 = 1
- val executorId2 = 2
- val taskId = TaskId(0, 0)
- val executorSupervisor = new ExecutorRestartPolicy(
- maxNrOfRetries = 3, withinTimeRange = 1.seconds)
- executorSupervisor.addTaskToExecutor(executorId1, taskId)
- assert(executorSupervisor.allowRestartExecutor(executorId1))
- assert(executorSupervisor.allowRestartExecutor(executorId1))
- executorSupervisor.addTaskToExecutor(executorId2, taskId)
- assert(executorSupervisor.allowRestartExecutor(executorId2))
- assert(!executorSupervisor.allowRestartExecutor(executorId2))
- Thread.sleep(1000)
- assert(executorSupervisor.allowRestartExecutor(executorId2))
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/io/gearpump/streaming/appmaster/HistoryMetricsServiceSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/io/gearpump/streaming/appmaster/HistoryMetricsServiceSpec.scala b/streaming/src/test/scala/io/gearpump/streaming/appmaster/HistoryMetricsServiceSpec.scala
deleted file mode 100644
index 6cd70d9..0000000
--- a/streaming/src/test/scala/io/gearpump/streaming/appmaster/HistoryMetricsServiceSpec.scala
+++ /dev/null
@@ -1,197 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.appmaster
-
-import scala.concurrent.Await
-
-import akka.actor.{ActorSystem, Props}
-import akka.testkit.TestProbe
-import org.scalatest.{BeforeAndAfterEach, FlatSpec, Matchers}
-
-import io.gearpump.cluster.ClientToMaster.QueryHistoryMetrics
-import io.gearpump.cluster.MasterToClient.HistoryMetrics
-import io.gearpump.cluster.TestUtil
-import io.gearpump.metrics.Metrics.{Counter, Histogram, Meter}
-import io.gearpump.util.HistoryMetricsService
-import io.gearpump.util.HistoryMetricsService._
-
-class HistoryMetricsServiceSpec extends FlatSpec with Matchers with BeforeAndAfterEach {
-
- val count = 2
- val intervalMs = 10
-
- val config = HistoryMetricsConfig(
- retainHistoryDataHours = 72,
- retainHistoryDataIntervalMs = 3600 * 1000,
- retainRecentDataSeconds = 300,
- retainRecentDataIntervalMs = 15 * 1000)
-
- "SingleValueMetricsStore" should "retain metrics and expire old value" in {
-
- val store = new SingleValueMetricsStore(count, intervalMs)
-
- var now = 0L
- // Only 1 data point will be kept in @intervalMs
- store.add(Counter("count", 1), now)
- store.add(Counter("count", 2), now)
-
- now = now + intervalMs + 1
-
- // Only 1 data point will be kept in @intervalMs
- store.add(Counter("count", 3), now)
- store.add(Counter("count", 4), now)
-
- now = now + intervalMs + 1
-
- // Only 1 data point will be kept in @intervalMs
- // expire oldest data point, because we only keep @count records
- store.add(Counter("count", 5), now)
- store.add(Counter("count", 6), now)
-
- val result = store.read
- assert(result.size == count)
-
- // The oldest value is expired
- assert(result.head.value.asInstanceOf[Counter].value == 3L)
-
- // The newest value is inserted
- assert(result.last.value.asInstanceOf[Counter].value == 5L)
- }
-
- val meterTemplate = Meter("meter", 0, 0, 0, "s")
-
- "HistogramMetricsStore" should "retain corse-grain history and fine-grain recent data" in {
- val store = new HistogramMetricsStore(config)
- val a = Histogram(null, 100, 0, 0, 0, 0, 0)
- val b = Histogram(null, 200, 0, 0, 0, 0, 0)
- val c = Histogram(null, 50, 0, 0, 0, 0, 0)
-
- store.add(a)
- store.add(b)
- store.add(c)
-
- assert(store.readLatest.map(_.value) == List(c))
- assert(store.readRecent.map(_.value) == List(a))
- assert(store.readHistory.map(_.value) == List(a))
- }
-
- "MeterMetricsStore" should "retain corse-grain history and fine-grain recent data" in {
- val store = new MeterMetricsStore(config)
-
- val a = Meter(null, 1, 100, 0, null)
- val b = Meter(null, 1, 200, 0, null)
- val c = Meter(null, 1, 50, 0, null)
-
- store.add(a)
- store.add(b)
- store.add(c)
-
- assert(store.readLatest.map(_.value) == List(c))
- assert(store.readRecent.map(_.value) == List(a))
- assert(store.readHistory.map(_.value) == List(a))
- }
-
- "CounterMetricsStore" should "retain corse-grain history and fine-grain recent data" in {
- val store = new CounterMetricsStore(config)
- val a = Counter(null, 50)
- val b = Counter(null, 100)
- val c = Counter(null, 150)
-
- store.add(a)
- store.add(b)
- store.add(c)
-
- assert(store.readLatest.map(_.value) == List(c))
- assert(store.readRecent.map(_.value) == List(a))
- assert(store.readHistory.map(_.value) == List(a))
- }
-
- "HistoryMetricsService" should
- "retain lastest metrics data and allow user to query metrics by path" in {
- implicit val system = ActorSystem("test", TestUtil.DEFAULT_CONFIG)
- val appId = 0
- val service = system.actorOf(Props(new HistoryMetricsService("app0", config)))
- service ! Counter("metric.counter", 0)
- service ! Meter("metric.meter", 0, 0, 0, null)
- service ! Histogram("metric.histogram", 0, 0, 0, 0, 0, 0)
-
- val client = TestProbe()
-
- // Filters metrics with path "metric.counter"
- client.send(service, QueryHistoryMetrics("metric.counter"))
- import scala.concurrent.duration._
- client.expectMsgPF(3.seconds) {
- case history: HistoryMetrics =>
- assert(history.path == "metric.counter")
- val metricList = history.metrics
- metricList.foreach(metricItem =>
- assert(metricItem.value.isInstanceOf[Counter])
- )
- }
-
- // Filters metrics with path "metric.meter"
- client.send(service, QueryHistoryMetrics("metric.meter"))
- client.expectMsgPF(3.seconds) {
- case history: HistoryMetrics =>
- assert(history.path == "metric.meter")
- val metricList = history.metrics
- metricList.foreach(metricItem =>
- assert(metricItem.value.isInstanceOf[Meter])
- )
- }
-
- // Filters metrics with path "metric.histogram"
- client.send(service, QueryHistoryMetrics("metric.histogram"))
- client.expectMsgPF(3.seconds) {
- case history: HistoryMetrics =>
- assert(history.path == "metric.histogram")
- val metricList = history.metrics
- metricList.foreach(metricItem =>
- assert(metricItem.value.isInstanceOf[Histogram])
- )
- }
-
- // Filters metrics with path prefix "metric", all metrics which can
- // match the path prefix will be retained.
- client.send(service, QueryHistoryMetrics("metric"))
- client.expectMsgPF(3.seconds) {
- case history: HistoryMetrics =>
- val metricList = history.metrics
-
- var counterFound = false
- var meterFound = false
- var histogramFound = false
-
- metricList.foreach(metricItem =>
- metricItem.value match {
- case v: Counter => counterFound = true
- case v: Meter => meterFound = true
- case v: Histogram => histogramFound = true
- case _ => // Skip
- }
- )
-
- // All kinds of metric type are reserved.
- assert(counterFound && meterFound && histogramFound)
- }
-
- system.terminate()
- Await.result(system.whenTerminated, Duration.Inf)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/io/gearpump/streaming/appmaster/JarSchedulerSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/io/gearpump/streaming/appmaster/JarSchedulerSpec.scala b/streaming/src/test/scala/io/gearpump/streaming/appmaster/JarSchedulerSpec.scala
deleted file mode 100644
index b391196..0000000
--- a/streaming/src/test/scala/io/gearpump/streaming/appmaster/JarSchedulerSpec.scala
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.appmaster
-
-import scala.concurrent.{Await, Future}
-
-import akka.actor.ActorSystem
-import org.scalatest.{Matchers, WordSpec}
-
-import io.gearpump.cluster.scheduler.{Resource, ResourceRequest}
-import io.gearpump.cluster.worker.WorkerId
-import io.gearpump.cluster.{AppJar, TestUtil}
-import io.gearpump.jarstore.FilePath
-import io.gearpump.partitioner.{HashPartitioner, Partitioner}
-import io.gearpump.streaming.appmaster.TaskSchedulerSpec.{TestTask1, TestTask2}
-import io.gearpump.streaming.task.TaskId
-import io.gearpump.streaming.{DAG, ProcessorDescription, _}
-import io.gearpump.util.Graph
-import io.gearpump.util.Graph._
-
-class JarSchedulerSpec extends WordSpec with Matchers {
- val mockJar1 = AppJar("jar1", FilePath("path"))
- val mockJar2 = AppJar("jar2", FilePath("path"))
- val task1 = ProcessorDescription(id = 0, taskClass = classOf[TestTask1].getName, parallelism = 1,
- jar = mockJar1)
- val task2 = ProcessorDescription(id = 1, taskClass = classOf[TestTask2].getName, parallelism = 1,
- jar = mockJar1)
- val task3 = ProcessorDescription(id = 2, taskClass = classOf[TestTask2].getName, parallelism = 2,
- jar = mockJar2)
- val dag = DAG(Graph(task1 ~ Partitioner[HashPartitioner] ~> task2))
-
- import scala.concurrent.duration._
-
- "JarScheduler" should {
- "schedule tasks depends on app jar" in {
- val system = ActorSystem("JarSchedulerSpec")
- implicit val dispatcher = system.dispatcher
- val manager = new JarScheduler(0, "APP", TestUtil.DEFAULT_CONFIG, system)
- manager.setDag(dag, Future {
- 0L
- })
- val requests = Array(ResourceRequest(Resource(2), WorkerId.unspecified))
- val result = Await.result(manager.getResourceRequestDetails(), 15.seconds)
- assert(result.length == 1)
- assert(result.head.jar == mockJar1)
- assert(result.head.requests.deep == requests.deep)
-
- val tasks = Await.result(manager.scheduleTask(mockJar1, WorkerId(0, 0L), 0,
- Resource(2)), 15.seconds)
- assert(tasks.contains(TaskId(0, 0)))
- assert(tasks.contains(TaskId(1, 0)))
-
- val newDag = replaceDAG(dag, 1, task3, 1)
-
- manager.setDag(newDag, Future {
- 0
- })
- val requestDetails = Await.result(manager.getResourceRequestDetails().
- map(_.sortBy(_.jar.name)), 15.seconds)
- assert(requestDetails.length == 2)
- assert(requestDetails.last.jar == mockJar2)
- assert(requestDetails.last.requests.deep == requests.deep)
-
- system.terminate()
- Await.result(system.whenTerminated, Duration.Inf)
- }
- }
-
- def replaceDAG(
- dag: DAG, oldProcessorId: ProcessorId, newProcessor: ProcessorDescription, newVersion: Int)
- : DAG = {
- val oldProcessorLife = LifeTime(dag.processors(oldProcessorId).life.birth,
- newProcessor.life.birth)
- val newProcessorMap = dag.processors ++
- Map(oldProcessorId -> dag.processors(oldProcessorId).copy(life = oldProcessorLife),
- newProcessor.id -> newProcessor)
- val newGraph = dag.graph.subGraph(oldProcessorId).
- replaceVertex(oldProcessorId, newProcessor.id).addGraph(dag.graph)
- new DAG(newVersion, newProcessorMap, newGraph)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/io/gearpump/streaming/appmaster/TaskLocatorSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/io/gearpump/streaming/appmaster/TaskLocatorSpec.scala b/streaming/src/test/scala/io/gearpump/streaming/appmaster/TaskLocatorSpec.scala
deleted file mode 100644
index 2e07def..0000000
--- a/streaming/src/test/scala/io/gearpump/streaming/appmaster/TaskLocatorSpec.scala
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.appmaster
-
-import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
-
-import io.gearpump.cluster.worker.WorkerId
-import io.gearpump.streaming.appmaster.TaskLocator.Localities
-import io.gearpump.streaming.task.TaskId
-
-class TaskLocatorSpec extends FlatSpec with Matchers with BeforeAndAfterAll {
- it should "serialize/deserialize correctly" in {
- val localities = new Localities(Map(WorkerId(0, 0L) -> Array(TaskId(0, 1), TaskId(1, 2))))
- Localities.toJson(localities)
-
- localities.localities.mapValues(_.toList) shouldBe
- Localities.fromJson(Localities.toJson(localities)).localities.mapValues(_.toList)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/io/gearpump/streaming/appmaster/TaskManagerSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/io/gearpump/streaming/appmaster/TaskManagerSpec.scala b/streaming/src/test/scala/io/gearpump/streaming/appmaster/TaskManagerSpec.scala
deleted file mode 100644
index 8153fce..0000000
--- a/streaming/src/test/scala/io/gearpump/streaming/appmaster/TaskManagerSpec.scala
+++ /dev/null
@@ -1,276 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.appmaster
-
-import scala.concurrent.duration.Duration
-import scala.concurrent.{Await, Future}
-
-import akka.actor.{ActorRef, ActorSystem, Props}
-import akka.testkit.TestProbe
-import org.mockito.Mockito._
-import org.scalatest.{BeforeAndAfterEach, FlatSpec, Matchers}
-
-import io.gearpump.cluster.MasterToAppMaster.ReplayFromTimestampWindowTrailingEdge
-import io.gearpump.cluster.scheduler.{Resource, ResourceRequest}
-import io.gearpump.cluster.worker.WorkerId
-import io.gearpump.cluster.{AppJar, TestUtil, UserConfig}
-import io.gearpump.jarstore.FilePath
-import io.gearpump.partitioner.{HashPartitioner, Partitioner, PartitionerDescription}
-import io.gearpump.streaming.AppMasterToExecutor.{LaunchTasks, StartAllTasks, StartDynamicDag, TaskLocationsReady, TaskLocationsReceived, TaskRegistered}
-import io.gearpump.streaming.ExecutorToAppMaster.RegisterTask
-import io.gearpump.streaming.appmaster.AppMaster.AllocateResourceTimeOut
-import io.gearpump.streaming.appmaster.ClockService.{ChangeToNewDAG, ChangeToNewDAGSuccess}
-import io.gearpump.streaming.appmaster.DagManager.{GetLatestDAG, GetTaskLaunchData, LatestDAG, NewDAGDeployed, TaskLaunchData, WatchChange}
-import io.gearpump.streaming.appmaster.ExecutorManager.{ExecutorResourceUsageSummary, SetTaskManager, StartExecutors, _}
-import io.gearpump.streaming.appmaster.JarScheduler.ResourceRequestDetail
-import io.gearpump.streaming.appmaster.TaskManagerSpec.{Env, Task1, Task2}
-import io.gearpump.streaming.executor.Executor.RestartTasks
-import io.gearpump.streaming.task.{StartTime, TaskContext, _}
-import io.gearpump.streaming.{DAG, LifeTime, ProcessorDescription, ProcessorId}
-import io.gearpump.transport.HostPort
-import io.gearpump.util.Graph
-import io.gearpump.util.Graph._
-import io.gearpump.{Message, TimeStamp}
-
-class TaskManagerSpec extends FlatSpec with Matchers with BeforeAndAfterEach {
-
- implicit var system: ActorSystem = null
-
- val task1Class = classOf[Task1].getName
- val task2Class = classOf[Task2].getName
-
- val mockJar = AppJar("jar_for_test", FilePath("path"))
- val task1 = ProcessorDescription(id = 0, taskClass = task1Class, parallelism = 1, jar = mockJar)
- val task2 = ProcessorDescription(id = 1, taskClass = task2Class, parallelism = 1, jar = mockJar)
-
- val dag: DAG = DAG(Graph(task1 ~ Partitioner[HashPartitioner] ~> task2))
- val dagVersion = 0
-
- val task1LaunchData = TaskLaunchData(task1, Subscriber.of(processorId = 0, dag))
- val task2LaunchData = TaskLaunchData(task2, Subscriber.of(processorId = 1, dag))
-
- val appId = 0
-
- val resource = Resource(2)
- val workerId = WorkerId(0, 0L)
- val executorId = 0
-
- override def beforeEach(): Unit = {
- system = ActorSystem("test", TestUtil.DEFAULT_CONFIG)
- }
-
- override def afterEach(): Unit = {
- system.terminate()
- Await.result(system.whenTerminated, Duration.Inf)
- }
-
- it should "recover by requesting new executors when executor stopped unexpectedly" in {
- val env = bootUp
- import env._
- implicit val dispatcher = system.dispatcher
-
- val resourceRequest = Array(ResourceRequest(resource, workerId))
- when(scheduler.executorFailed(executorId)).thenReturn(Future {
- Some(ResourceRequestDetail(mockJar,
- resourceRequest))
- })
-
- taskManager ! ExecutorStopped(executorId)
-
- // When one executor stop, it will also trigger the recovery by restart
- // existing executors
- executorManager.expectMsg(BroadCast(RestartTasks(dagVersion)))
-
- // Asks for new executors
- val returned = executorManager.receiveN(1).head.asInstanceOf[StartExecutors]
- assert(returned.resources.deep == resourceRequest.deep)
- executorManager.reply(StartExecutorsTimeOut)
-
- // TaskManager cannot handle the TimeOut error itself, escalate to appmaster.
- appMaster.expectMsg(AllocateResourceTimeOut)
- }
-
- it should "recover by restarting existing executors when message loss happen" in {
- val env = bootUp
- import env._
-
- taskManager ! ReplayFromTimestampWindowTrailingEdge(appId)
-
- // Restart the executors so that we can replay from minClock
- executorManager.expectMsg(BroadCast(RestartTasks(dagVersion)))
- }
-
- import io.gearpump.streaming.appmaster.TaskManager.TaskChangeRegistry
- "TaskChangeRegistry" should "track all modified task registration" in {
- val tasks = List(TaskId(0, 0), TaskId(0, 1))
- val registry = new TaskChangeRegistry(tasks)
- registry.taskChanged(TaskId(0, 0))
- registry.taskChanged(TaskId(0, 1))
- assert(registry.allTaskChanged)
- }
-
- "DAGDiff" should "track all the DAG migration impact" in {
- val defaultEdge = PartitionerDescription(null)
- val a = ProcessorDescription(id = 1, taskClass = null, parallelism = 1)
- val b = ProcessorDescription(id = 2, taskClass = null, parallelism = 1)
- val c = ProcessorDescription(id = 3, taskClass = null, parallelism = 1)
- val left = Graph(a ~ defaultEdge ~> b, a ~ defaultEdge ~> c)
-
- val d = ProcessorDescription(id = 4, taskClass = null, parallelism = 1)
- val right = left.copy
- right.addVertex(d)
- right.addEdge(c, defaultEdge, d)
- val e = a.copy(life = LifeTime(0, 0))
- right.replaceVertex(a, e)
-
- val diff = TaskManager.migrate(DAG(left), DAG(right, version = 1))
- diff.addedProcessors shouldBe List(d.id)
-
- diff.modifiedProcessors shouldBe List(a.id)
-
- diff.impactedUpstream shouldBe List(c.id)
- }
-
- private def bootUp: Env = {
-
- implicit val dispatcher = system.dispatcher
-
- val executorManager = TestProbe()
- val clockService = TestProbe()
- val appMaster = TestProbe()
- val executor = TestProbe()
-
- val scheduler = mock(classOf[JarScheduler])
-
- val dagManager = TestProbe()
-
- val taskManager = system.actorOf(
- Props(new TaskManager(appId, dagManager.ref, scheduler, executorManager.ref, clockService.ref,
- appMaster.ref, "appName")))
-
- dagManager.expectMsgType[WatchChange]
- executorManager.expectMsgType[SetTaskManager]
-
- // Step1: first transition from Unitialized to ApplicationReady
- executorManager.expectMsgType[ExecutorResourceUsageSummary]
- dagManager.expectMsgType[NewDAGDeployed]
-
- // Step2: Get Additional Resource Request
- when(scheduler.getResourceRequestDetails())
- .thenReturn(Future {
- Array(ResourceRequestDetail(mockJar, Array(ResourceRequest(resource,
- WorkerId.unspecified))))
- })
-
- // Step3: DAG changed. Start transit from ApplicationReady -> DynamicDAG
- dagManager.expectMsg(GetLatestDAG)
- dagManager.reply(LatestDAG(dag))
-
- // Step4: Start remote Executors.
- // received Broadcast
- executorManager.expectMsg(BroadCast(StartDynamicDag(dag.version)))
- executorManager.expectMsgType[StartExecutors]
-
- when(scheduler.scheduleTask(mockJar, workerId, executorId, resource))
- .thenReturn(Future(List(TaskId(0, 0), TaskId(1, 0))))
-
- // Step5: Executor is started.
- executorManager.reply(ExecutorStarted(executorId, resource, workerId, Some(mockJar)))
-
- // Step6: Prepare to start Task. First GetTaskLaunchData.
- val taskLaunchData: PartialFunction[Any, TaskLaunchData] = {
- case GetTaskLaunchData(_, 0, executorStarted) =>
- task1LaunchData.copy(context = executorStarted)
- case GetTaskLaunchData(_, 1, executorStarted) =>
- task2LaunchData.copy(context = executorStarted)
- }
-
- val launchData1 = dagManager.expectMsgPF()(taskLaunchData)
- dagManager.reply(launchData1)
-
- val launchData2 = dagManager.expectMsgPF()(taskLaunchData)
- dagManager.reply(launchData2)
-
- // Step7: Launch Task
- val launchTaskMatch: PartialFunction[Any, RegisterTask] = {
- case UniCast(executorId, launch: LaunchTasks) =>
- RegisterTask(launch.taskId.head, executorId, HostPort("127.0.0.1:3000"))
- }
-
- // Taskmanager should return the latest start clock to task(0,0)
- clockService.expectMsg(GetStartClock)
- clockService.reply(StartClock(0))
-
- // Step8: Task is started. registerTask.
- val registerTask1 = executorManager.expectMsgPF()(launchTaskMatch)
- taskManager.tell(registerTask1, executor.ref)
- executor.expectMsgType[TaskRegistered]
-
- val registerTask2 = executorManager.expectMsgPF()(launchTaskMatch)
- taskManager.tell(registerTask2, executor.ref)
- executor.expectMsgType[TaskRegistered]
-
- // Step9: start broadcasting TaskLocations.
- import scala.concurrent.duration._
- assert(executorManager.expectMsgPF(5.seconds) {
- case BroadCast(startAllTasks) => startAllTasks.isInstanceOf[TaskLocationsReady]
- })
-
- // Step10: Executor confirm it has received TaskLocationsReceived(version, executorId)
- taskManager.tell(TaskLocationsReceived(dag.version, executorId), executor.ref)
-
- // Step11: Tell ClockService to update DAG.
- clockService.expectMsgType[ChangeToNewDAG]
- clockService.reply(ChangeToNewDAGSuccess(Map.empty[ProcessorId, TimeStamp]))
-
- // Step12: start all tasks
- import scala.concurrent.duration._
- assert(executorManager.expectMsgPF(5.seconds) {
- case BroadCast(startAllTasks) => startAllTasks.isInstanceOf[StartAllTasks]
- })
-
- // Step13, Tell executor Manager the updated usage status of executors.
- executorManager.expectMsgType[ExecutorResourceUsageSummary]
-
- // Step14: transition from DynamicDAG to ApplicationReady
- Env(executorManager, clockService, appMaster, executor, taskManager, scheduler)
- }
-}
-
-object TaskManagerSpec {
- case class Env(
- executorManager: TestProbe,
- clockService: TestProbe,
- appMaster: TestProbe,
- executor: TestProbe,
- taskManager: ActorRef,
- scheduler: JarScheduler)
-
- class Task1(taskContext: TaskContext, userConf: UserConfig)
- extends Task(taskContext, userConf) {
- override def onStart(startTime: StartTime): Unit = {}
- override def onNext(msg: Message): Unit = {}
- }
-
- class Task2(taskContext: TaskContext, userConf: UserConfig)
- extends Task(taskContext, userConf) {
- override def onStart(startTime: StartTime): Unit = {}
- override def onNext(msg: Message): Unit = {}
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/io/gearpump/streaming/appmaster/TaskRegistrySpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/io/gearpump/streaming/appmaster/TaskRegistrySpec.scala b/streaming/src/test/scala/io/gearpump/streaming/appmaster/TaskRegistrySpec.scala
deleted file mode 100644
index e8417ea..0000000
--- a/streaming/src/test/scala/io/gearpump/streaming/appmaster/TaskRegistrySpec.scala
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.appmaster
-
-import org.scalatest.{BeforeAndAfterEach, FlatSpec, Matchers}
-
-import io.gearpump.cluster.scheduler.Resource
-import io.gearpump.streaming.appmaster.TaskRegistry.{Accept, Reject, TaskLocation, TaskLocations}
-import io.gearpump.streaming.task.TaskId
-import io.gearpump.transport.HostPort
-class TaskRegistrySpec extends FlatSpec with Matchers with BeforeAndAfterEach {
-
- it should "maintain registered tasks" in {
- val task0 = TaskId(0, 0)
- val task1 = TaskId(0, 1)
- val task2 = TaskId(0, 2)
-
- val register = new TaskRegistry(expectedTasks = List(task0, task1, task2))
- val host1 = HostPort("127.0.0.1:3000")
- val host2 = HostPort("127.0.0.1:3001")
-
- val executorId = 0
- assert(Accept == register.registerTask(task0, TaskLocation(executorId, host1)))
- assert(Accept == register.registerTask(task1, TaskLocation(executorId, host1)))
- assert(Accept == register.registerTask(task2, TaskLocation(executorId, host2)))
-
- assert(Reject == register.registerTask(TaskId(100, 0), TaskLocation(executorId, host2)))
-
- assert(register.isAllTasksRegistered)
- val TaskLocations(taskLocations) = register.getTaskLocations
- val tasksOnHost1 = taskLocations.get(host1).get
- val tasksOnHost2 = taskLocations.get(host2).get
- assert(tasksOnHost1.contains(task0))
- assert(tasksOnHost1.contains(task1))
- assert(tasksOnHost2.contains(task2))
-
- assert(register.getExecutorId(task0) == Some(executorId))
- assert(register.isTaskRegisteredForExecutor(executorId))
-
- register.processorExecutors(0) shouldBe Map(
- executorId -> List(task0, task1, task2)
- )
-
- register.usedResource.resources shouldBe Map(
- executorId -> Resource(3)
- )
- }
-}
[11/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/appmaster/ClockService.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/appmaster/ClockService.scala b/streaming/src/main/scala/io/gearpump/streaming/appmaster/ClockService.scala
deleted file mode 100644
index bd18bdc..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/appmaster/ClockService.scala
+++ /dev/null
@@ -1,447 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.appmaster
-
-import java.util
-import java.util.Date
-import java.util.concurrent.TimeUnit
-import scala.concurrent.Future
-import scala.concurrent.duration.FiniteDuration
-import scala.language.implicitConversions
-
-import akka.actor.{Actor, Cancellable, Stash}
-import org.slf4j.Logger
-
-import io.gearpump.TimeStamp
-import io.gearpump.cluster.ClientToMaster.GetStallingTasks
-import io.gearpump.google.common.primitives.Longs
-import io.gearpump.streaming.AppMasterToMaster.StallingTasks
-import io.gearpump.streaming._
-import io.gearpump.streaming.appmaster.ClockService.HealthChecker.ClockValue
-import io.gearpump.streaming.appmaster.ClockService._
-import io.gearpump.streaming.storage.AppDataStore
-import io.gearpump.streaming.task._
-import io.gearpump.util.LogUtil
-
-/**
- * Maintains a global view of message timestamp in the application
- */
-class ClockService(private var dag: DAG, store: AppDataStore) extends Actor with Stash {
- private val LOG: Logger = LogUtil.getLogger(getClass)
-
- import context.dispatcher
-
- private val healthChecker = new HealthChecker(stallingThresholdSeconds = 60)
- private var healthCheckScheduler: Cancellable = null
- private var snapshotScheduler: Cancellable = null
-
- override def receive: Receive = null
-
- override def preStart(): Unit = {
- LOG.info("Initializing Clock service, get snapshotted StartClock ....")
- store.get(START_CLOCK).asInstanceOf[Future[TimeStamp]].map { clock =>
- val startClock = Option(clock).getOrElse(0L)
-
- minCheckpointClock = Some(startClock)
-
- // Recover the application by restarting from last persisted startClock.
- // Only messge after startClock will be replayed.
- self ! StoredStartClock(startClock)
- LOG.info(s"Start Clock Retrieved, starting ClockService, startClock: $startClock")
- }
-
- context.become(waitForStartClock)
- }
-
- override def postStop(): Unit = {
- Option(healthCheckScheduler).map(_.cancel)
- Option(snapshotScheduler).map(_.cancel)
- }
-
- // Keep track of clock value of all processors.
- private var clocks = Map.empty[ProcessorId, ProcessorClock]
-
- // Each process can have multiple upstream processors. This keep track of the upstream clocks.
- private var upstreamClocks = Map.empty[ProcessorId, Array[ProcessorClock]]
-
- // We use Array instead of List for Performance consideration
- private var processorClocks = Array.empty[ProcessorClock]
-
- private var checkpointClocks: Map[TaskId, Vector[TimeStamp]] = null
-
- private var minCheckpointClock: Option[TimeStamp] = None
-
- private def checkpointEnabled(processor: ProcessorDescription): Boolean = {
- val taskConf = processor.taskConf
- taskConf != null && taskConf.getBoolean("state.checkpoint.enable") == Some(true)
- }
-
- private def resetCheckpointClocks(dag: DAG, startClock: TimeStamp): Unit = {
- this.checkpointClocks = dag.processors.filter(startClock < _._2.life.death)
- .filter { case (_, processor) =>
- checkpointEnabled(processor)
- }.flatMap { case (id, processor) =>
- (0 until processor.parallelism).map(TaskId(id, _) -> Vector.empty[TimeStamp])
- }
- if (this.checkpointClocks.isEmpty) {
- minCheckpointClock = None
- }
- }
-
- private def initDag(startClock: TimeStamp): Unit = {
- recoverDag(this.dag, startClock)
- }
-
- private def recoverDag(dag: DAG, startClock: TimeStamp): Unit = {
- this.clocks = dag.processors.filter(startClock < _._2.life.death).
- map { pair =>
- val (processorId, processor) = pair
- val parallelism = processor.parallelism
- val clock = new ProcessorClock(processorId, processor.life, parallelism)
- clock.init(startClock)
- (processorId, clock)
- }
-
- this.upstreamClocks = clocks.map { pair =>
- val (processorId, processor) = pair
-
- val upstreams = dag.graph.incomingEdgesOf(processorId).map(_._1)
- val upstreamClocks = upstreams.flatMap(clocks.get(_))
- (processorId, upstreamClocks.toArray)
- }
-
- this.processorClocks = clocks.toArray.map(_._2)
-
- resetCheckpointClocks(dag, startClock)
- }
-
- private def dynamicDAG(dag: DAG, startClock: TimeStamp): Unit = {
- val newClocks = dag.processors.filter(startClock < _._2.life.death).
- map { pair =>
- val (processorId, processor) = pair
- val parallelism = processor.parallelism
-
- val clock = if (clocks.contains(processor.id)) {
- clocks(processorId).copy(life = processor.life)
- } else {
- new ProcessorClock(processorId, processor.life, parallelism)
- }
- (processorId, clock)
- }
-
- this.clocks = newClocks
-
- this.upstreamClocks = newClocks.map { pair =>
- val (processorId, processor) = pair
-
- val upstreams = dag.graph.incomingEdgesOf(processorId).map(_._1)
- val upstreamClocks = upstreams.flatMap(newClocks.get(_))
- (processorId, upstreamClocks.toArray)
- }
-
- // Inits the clock of all processors.
- newClocks.map { pair =>
- val (processorId, processorClock) = pair
- val upstreamClock = getUpStreamMinClock(processorId)
- val birth = processorClock.life.birth
-
- if (dag.graph.inDegreeOf(processorId) == 0) {
- processorClock.init(Longs.max(birth, startClock))
- } else {
- processorClock.init(upstreamClock)
- }
- }
-
- this.processorClocks = clocks.toArray.map(_._2)
-
- resetCheckpointClocks(dag, startClock)
- }
-
- def waitForStartClock: Receive = {
- case StoredStartClock(startClock) =>
- initDag(startClock)
-
- import context.dispatcher
-
- // Period report current clock
- healthCheckScheduler = context.system.scheduler.schedule(
- new FiniteDuration(5, TimeUnit.SECONDS),
- new FiniteDuration(60, TimeUnit.SECONDS), self, HealthCheck)
-
- // Period snpashot latest min startclock to external storage
- snapshotScheduler = context.system.scheduler.schedule(new FiniteDuration(5, TimeUnit.SECONDS),
- new FiniteDuration(5, TimeUnit.SECONDS), self, SnapshotStartClock)
-
- unstashAll()
- context.become(clockService)
-
- case _ =>
- stash()
- }
-
- private def getUpStreamMinClock(processorId: ProcessorId): TimeStamp = {
- val clocks = upstreamClocks.get(processorId)
- if (clocks.isDefined) {
- if (clocks.get == null || clocks.get.length == 0) {
- Long.MaxValue
- } else {
- ProcessorClocks.minClock(clocks.get)
- }
- } else {
- Long.MaxValue
- }
- }
-
- def clockService: Receive = {
- case GetUpstreamMinClock(task) =>
- sender ! UpstreamMinClock(getUpStreamMinClock(task.processorId))
-
- case update@UpdateClock(task, clock) =>
- val upstreamMinClock = getUpStreamMinClock(task.processorId)
-
- val processorClock = clocks.get(task.processorId)
- if (processorClock.isDefined) {
- processorClock.get.updateMinClock(task.index, clock)
- } else {
- LOG.error(s"Cannot updateClock for task $task")
- }
- sender ! UpstreamMinClock(upstreamMinClock)
-
- case GetLatestMinClock =>
- sender ! LatestMinClock(minClock)
-
- case GetStartClock =>
- sender ! StartClock(getStartClock)
-
- case deathCheck: CheckProcessorDeath =>
- val processorId = deathCheck.processorId
- val processorClock = clocks.get(processorId)
- if (processorClock.isDefined) {
- val life = processorClock.get.life
- if (processorClock.get.min >= life.death) {
-
- LOG.info(s"Removing $processorId from clock service...")
- removeProcessor(processorId)
- } else {
- LOG.info(s"Unsuccessfully in removing $processorId from clock service...," +
- s" min: ${processorClock.get.min}, life: $life")
- }
- }
- case HealthCheck =>
- selfCheck()
-
- case SnapshotStartClock =>
- snapshotStartClock()
-
- case ReportCheckpointClock(task, time) =>
- updateCheckpointClocks(task, time)
-
- case GetCheckpointClock =>
- sender ! CheckpointClock(minCheckpointClock)
-
- case getStalling: GetStallingTasks =>
- sender ! StallingTasks(healthChecker.getReport.stallingTasks)
-
- case ChangeToNewDAG(dag) =>
- if (dag.version > this.dag.version) {
- // Transits to a new dag version
- this.dag = dag
- dynamicDAG(dag, getStartClock)
- } else {
- // Restarts current dag.
- recoverDag(dag, getStartClock)
- }
- LOG.info(s"Change to new DAG(dag = ${dag.version}), send back ChangeToNewDAGSuccess")
- sender ! ChangeToNewDAGSuccess(clocks.map { pair =>
- val (id, clock) = pair
- (id, clock.min)
- })
- }
-
- private def removeProcessor(processorId: ProcessorId): Unit = {
- clocks = clocks - processorId
- processorClocks = processorClocks.filter(_.processorId != processorId)
-
- upstreamClocks = upstreamClocks.map { pair =>
- val (id, upstreams) = pair
- val updatedUpstream = upstreams.filter(_.processorId != processorId)
- (id, updatedUpstream)
- }
-
- upstreamClocks = upstreamClocks - processorId
-
- // Removes dead processor from checkpoints.
- checkpointClocks = checkpointClocks.filter { kv =>
- val (taskId, processor) = kv
- taskId.processorId != processorId
- }
- }
-
- private def minClock: TimeStamp = {
- ProcessorClocks.minClock(processorClocks)
- }
-
- def selfCheck(): Unit = {
- val minTimestamp = minClock
-
- if (Long.MaxValue == minTimestamp) {
- processorClocks.foreach { clock =>
- LOG.info(s"Processor ${clock.processorId} Clock: min: ${clock.min}, " +
- s"taskClocks: " + clock.taskClocks.mkString(","))
- }
- }
-
- healthChecker.check(minTimestamp, clocks, dag, System.currentTimeMillis())
- }
-
- private def getStartClock: TimeStamp = {
- minCheckpointClock.getOrElse(minClock)
- }
-
- private def snapshotStartClock(): Unit = {
- store.put(START_CLOCK, getStartClock)
- }
-
- private def updateCheckpointClocks(task: TaskId, time: TimeStamp): Unit = {
- val clocks = checkpointClocks(task) :+ time
- checkpointClocks += task -> clocks
-
- if (checkpointClocks.forall(_._2.contains(time))) {
- minCheckpointClock = Some(time)
- LOG.info(s"minCheckpointTime $minCheckpointClock")
-
- checkpointClocks = checkpointClocks.mapValues(_.dropWhile(_ <= time))
- }
- }
-}
-
-object ClockService {
- val START_CLOCK = "startClock"
-
- case object HealthCheck
-
- class ProcessorClock(val processorId: ProcessorId, val life: LifeTime, val parallism: Int,
- private var _min: TimeStamp = 0L, private var _taskClocks: Array[TimeStamp] = null) {
-
- def copy(life: LifeTime): ProcessorClock = {
- new ProcessorClock(processorId, life, parallism, _min, _taskClocks)
- }
-
- def min: TimeStamp = _min
- def taskClocks: Array[TimeStamp] = _taskClocks
-
- def init(startClock: TimeStamp): Unit = {
- if (taskClocks == null) {
- this._min = startClock
- this._taskClocks = new Array(parallism)
- util.Arrays.fill(taskClocks, startClock)
- }
- }
-
- def updateMinClock(taskIndex: Int, clock: TimeStamp): Unit = {
- taskClocks(taskIndex) = clock
- _min = Longs.min(taskClocks: _*)
- }
- }
-
- case object SnapshotStartClock
-
- case class Report(stallingTasks: List[TaskId])
-
- /**
- * Check whether the clock is advancing normally
- */
- class HealthChecker(stallingThresholdSeconds: Int) {
- private val LOG: Logger = LogUtil.getLogger(getClass)
-
- private var minClock: ClockValue = null
- private val stallingThresholdMilliseconds = stallingThresholdSeconds * 1000
- // 60 seconds
- private var stallingTasks = Array.empty[TaskId]
-
- /** Check for stalling tasks */
- def check(
- currentMinClock: TimeStamp, processorClocks: Map[ProcessorId, ProcessorClock],
- dag: DAG, now: TimeStamp): Unit = {
- var isClockStalling = false
- if (null == minClock || currentMinClock > minClock.appClock) {
- minClock = ClockValue(systemClock = now, appClock = currentMinClock)
- } else {
- // Clock not advancing
- if (now > minClock.systemClock + stallingThresholdMilliseconds) {
- LOG.warn(s"Clock has not advanced for ${(now - minClock.systemClock) / 1000} seconds " +
- s"since ${minClock.prettyPrint}...")
- isClockStalling = true
- }
- }
-
- if (isClockStalling) {
- val processorId = dag.graph.topologicalOrderWithCirclesIterator.toList.find { processorId =>
- val clock = processorClocks.get(processorId)
- if (clock.isDefined) {
- clock.get.min == minClock.appClock
- } else {
- false
- }
- }
-
- processorId.foreach { processorId =>
- val processorClock = processorClocks(processorId)
- val taskClocks = processorClock.taskClocks
- stallingTasks = taskClocks.zipWithIndex.filter(_._1 == minClock.appClock).
- map(pair => TaskId(processorId, pair._2))
- }
- LOG.info(s"Stalling Tasks: ${stallingTasks.mkString(",")}")
- } else {
- stallingTasks = Array.empty[TaskId]
- }
- }
-
- def getReport: Report = {
- Report(stallingTasks.toList)
- }
- }
-
- object HealthChecker {
- case class ClockValue(systemClock: TimeStamp, appClock: TimeStamp) {
- def prettyPrint: String = {
- "(system clock: " + new Date(systemClock).toString + ", app clock: " + appClock + ")"
- }
- }
- }
-
- object ProcessorClocks {
-
- // Get the Min clock of all processors
- def minClock(clock: Array[ProcessorClock]): TimeStamp = {
- var i = 0
- var min = if (clock.length == 0) 0L else clock(0).min
- while (i < clock.length) {
- min = Math.min(min, clock(i).min)
- i += 1
- }
- min
- }
- }
-
- case class ChangeToNewDAG(dag: DAG)
- case class ChangeToNewDAGSuccess(clocks: Map[ProcessorId, TimeStamp])
-
- case class StoredStartClock(clock: TimeStamp)
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/appmaster/DagManager.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/appmaster/DagManager.scala b/streaming/src/main/scala/io/gearpump/streaming/appmaster/DagManager.scala
deleted file mode 100644
index f18b387..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/appmaster/DagManager.scala
+++ /dev/null
@@ -1,182 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.appmaster
-
-import scala.concurrent.Future
-
-import akka.actor.{Actor, ActorRef, Stash}
-import org.slf4j.Logger
-
-import io.gearpump.cluster.UserConfig
-import io.gearpump.partitioner.PartitionerDescription
-import io.gearpump.streaming._
-import io.gearpump.streaming.appmaster.DagManager._
-import io.gearpump.streaming.storage.AppDataStore
-import io.gearpump.streaming.task.Subscriber
-import io.gearpump.util.{Graph, LogUtil}
-
-/**
- * Handles dag modification and other stuff related with DAG
- *
- * DagManager maintains multiple version of DAGs. For each version, the DAG is immutable.
- * For operations like modifying a processor, it will create a new version of DAG.
- */
-class DagManager(appId: Int, userConfig: UserConfig, store: AppDataStore, dag: Option[DAG])
- extends Actor with Stash {
-
- import context.dispatcher
- private val LOG: Logger = LogUtil.getLogger(getClass, app = appId)
- private val NOT_INITIALIZED = -1
-
- private var dags = List.empty[DAG]
- private var maxProcessorId = -1
- private implicit val system = context.system
-
- private var watchers = List.empty[ActorRef]
-
- override def receive: Receive = null
-
- override def preStart(): Unit = {
- LOG.info("Initializing Dag Service, get stored Dag ....")
- store.get(StreamApplication.DAG).asInstanceOf[Future[DAG]].map { storedDag =>
- if (storedDag != null) {
- dags :+= storedDag
- } else {
- dags :+= dag.getOrElse(DAG(userConfig.getValue[Graph[ProcessorDescription,
- PartitionerDescription]](StreamApplication.DAG).get))
- }
- maxProcessorId = {
- val keys = dags.head.processors.keys
- if (keys.size == 0) {
- 0
- } else {
- keys.max
- }
- }
- self ! DagInitiated
- }
- context.become(waitForDagInitiate)
- }
-
- def waitForDagInitiate: Receive = {
- case DagInitiated =>
- unstashAll()
- context.become(dagService)
- case _ =>
- stash()
- }
-
- private def nextProcessorId: ProcessorId = {
- maxProcessorId += 1
- maxProcessorId
- }
-
- private def taskLaunchData(dag: DAG, processorId: Int, context: AnyRef): TaskLaunchData = {
- val processorDescription = dag.processors(processorId)
- val subscribers = Subscriber.of(processorId, dag)
- TaskLaunchData(processorDescription, subscribers, context)
- }
-
- def dagService: Receive = {
- case GetLatestDAG =>
- // Get the latest version of DAG.
- sender ! LatestDAG(dags.last)
- case GetTaskLaunchData(version, processorId, context) =>
- // Task information like Processor class, downstream subscriber processors and etc.
- dags.find(_.version == version).foreach { dag =>
- LOG.info(s"Get task launcher data for processor: $processorId, dagVersion: $version")
- sender ! taskLaunchData(dag, processorId, context)
- }
- case ReplaceProcessor(oldProcessorId, inputNewProcessor) =>
- // Replace a processor with new implementation. The upstream processors and downstream
- // processors are NOT changed.
- var newProcessor = inputNewProcessor.copy(id = nextProcessorId)
- if (inputNewProcessor.jar == null) {
- val oldJar = dags.last.processors.get(oldProcessorId).get
- newProcessor = newProcessor.copy(jar = oldJar.jar)
- }
- if (dags.length > 1) {
- sender ! DAGOperationFailed(
- "We are in the process of handling previous dynamic dag change")
- } else {
- val oldDAG = dags.last
- val newVersion = oldDAG.version + 1
- val newDAG = replaceDAG(oldDAG, oldProcessorId, newProcessor, newVersion)
- dags :+= newDAG
-
- LOG.info(s"ReplaceProcessor old: $oldProcessorId, new: $newProcessor")
- LOG.info(s"new DAG: $newDAG")
- watchers.foreach(_ ! LatestDAG(newDAG))
- sender ! DAGOperationSuccess
- }
-
- case WatchChange(watcher) =>
- // Checks whether there are modifications for this DAG.
- if (!this.watchers.contains(watcher)) {
- this.watchers :+= watcher
- }
-
- case NewDAGDeployed(dagVersion) =>
- // Means dynamic Dag transition completed, and the new DAG version has been successfully
- // deployed. The obsolete dag versions will be removed.
- if (dagVersion != NOT_INITIALIZED) {
- dags = dags.filter(_.version == dagVersion)
- store.put(StreamApplication.DAG, dags.last)
- }
- }
-
- private def replaceDAG(
- dag: DAG, oldProcessorId: ProcessorId, newProcessor: ProcessorDescription, newVersion: Int)
- : DAG = {
- val oldProcessorLife = LifeTime(dag.processors(oldProcessorId).life.birth,
- newProcessor.life.birth)
-
- val newProcessorMap = dag.processors ++
- Map(oldProcessorId -> dag.processors(oldProcessorId).copy(life = oldProcessorLife),
- newProcessor.id -> newProcessor)
-
- val newGraph = dag.graph.subGraph(oldProcessorId).
- replaceVertex(oldProcessorId, newProcessor.id).addGraph(dag.graph)
- new DAG(newVersion, newProcessorMap, newGraph)
- }
-}
-
-object DagManager {
- case object DagInitiated
-
- case class WatchChange(watcher: ActorRef)
-
- case object GetLatestDAG
- case class LatestDAG(dag: DAG)
-
- case class GetTaskLaunchData(dagVersion: Int, processorId: Int, context: AnyRef = null)
- case class TaskLaunchData(processorDescription : ProcessorDescription,
- subscribers: List[Subscriber], context: AnyRef = null)
-
- sealed trait DAGOperation
-
- case class ReplaceProcessor(oldProcessorId: ProcessorId,
- newProcessorDescription: ProcessorDescription) extends DAGOperation
-
- sealed trait DAGOperationResult
- case object DAGOperationSuccess extends DAGOperationResult
- case class DAGOperationFailed(reason: String) extends DAGOperationResult
-
- case class NewDAGDeployed(dagVersion: Int)
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/appmaster/ExecutorManager.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/appmaster/ExecutorManager.scala b/streaming/src/main/scala/io/gearpump/streaming/appmaster/ExecutorManager.scala
deleted file mode 100644
index ab99af5..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/appmaster/ExecutorManager.scala
+++ /dev/null
@@ -1,209 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.appmaster
-
-import scala.concurrent.duration._
-import scala.util.{Failure, Try}
-
-import akka.actor.SupervisorStrategy.Stop
-import akka.actor._
-import akka.remote.RemoteScope
-import com.typesafe.config.Config
-import org.apache.commons.lang.exception.ExceptionUtils
-
-import io.gearpump.cluster.AppMasterToWorker.ChangeExecutorResource
-import io.gearpump.cluster.appmaster.ExecutorSystemScheduler.{ExecutorSystemJvmConfig, ExecutorSystemStarted, StartExecutorSystemTimeout, StartExecutorSystems}
-import io.gearpump.cluster.appmaster.WorkerInfo
-import io.gearpump.cluster.scheduler.{Resource, ResourceRequest}
-import io.gearpump.cluster.worker.WorkerId
-import io.gearpump.cluster.{AppJar, AppMasterContext, ExecutorContext, UserConfig}
-import io.gearpump.streaming.ExecutorId
-import io.gearpump.streaming.ExecutorToAppMaster.RegisterExecutor
-import io.gearpump.streaming.appmaster.ExecutorManager._
-import io.gearpump.streaming.executor.Executor
-import io.gearpump.util.{LogUtil, Util}
-
-/**
- * ExecutorManager manage the start and stop of all executors.
- *
- * ExecutorManager will launch Executor when asked. It hide the details like starting
- * a new ExecutorSystem from user. Please use ExecutorManager.props() to construct this actor
- */
-private[appmaster] class ExecutorManager(
- userConfig: UserConfig,
- appContext: AppMasterContext,
- executorFactory: (ExecutorContext, UserConfig, Address, ExecutorId) => Props,
- clusterConfig: Config,
- appName: String)
- extends Actor {
-
- private val LOG = LogUtil.getLogger(getClass)
-
- import appContext.{appId, masterProxy, username}
-
- private var taskManager: ActorRef = null
-
- private implicit val actorSystem = context.system
- private val systemConfig = context.system.settings.config
-
- private var executors = Map.empty[Int, ExecutorInfo]
-
- def receive: Receive = waitForTaskManager
-
- def waitForTaskManager: Receive = {
- case SetTaskManager(taskManager) =>
- this.taskManager = taskManager
- context.become(service orElse terminationWatch)
- }
-
- // If something wrong on executor, ExecutorManager will stop the current executor,
- // and wait for AppMaster to start a new executor.
- override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 10,
- withinTimeRange = 1.minute) {
- case ex: Throwable =>
- val executorId = Try(sender.path.name.toInt)
- executorId match {
- case scala.util.Success(id) => {
- executors -= id
- LOG.error(s"Executor $id throws exception, stop it...\n" +
- ExceptionUtils.getStackTrace(ex))
- }
- case Failure(ex) => {
- LOG.error(s"Sender ${sender.path} is dead, but seems it is not an executor...")
- }
- }
- Stop
- }
-
- // Responds to outside queries
- def service: Receive = {
- case StartExecutors(resources, jar) =>
- masterProxy ! StartExecutorSystems(resources, getExecutorJvmConfig(Some(jar)))
- case ExecutorSystemStarted(executorSystem, boundedJar) =>
- import executorSystem.{address, executorSystemId, resource => executorResource, worker}
-
- val executorId = executorSystemId
- val executorContext = ExecutorContext(executorId, worker, appId, appName,
- appMaster = context.parent, executorResource)
- executors += executorId -> ExecutorInfo(executorId, null, worker, boundedJar)
-
- // Starts executor
- val executor = context.actorOf(executorFactory(executorContext, userConfig,
- address, executorId), executorId.toString)
- executorSystem.bindLifeCycleWith(executor)
- case StartExecutorSystemTimeout =>
- taskManager ! StartExecutorsTimeOut
-
- case RegisterExecutor(executor, executorId, resource, worker) =>
- LOG.info(s"executor $executorId has been launched")
- // Watches for executor termination
- context.watch(executor)
- val executorInfo = executors.get(executorId).get
- executors += executorId -> executorInfo.copy(executor = executor)
- taskManager ! ExecutorStarted(executorId, resource, worker.workerId, executorInfo.boundedJar)
-
- // Broadcasts message to all executors
- case BroadCast(msg) =>
- LOG.info(s"Broadcast ${msg.getClass.getSimpleName} to all executors")
- context.children.foreach(_ forward msg)
-
- // Unicasts message to single executor
- case UniCast(executorId, msg) =>
- LOG.info(s"Unicast ${msg.getClass.getSimpleName} to executor $executorId")
- val executor = executors.get(executorId)
- executor.foreach(_.executor forward msg)
-
- case GetExecutorInfo =>
- sender ! executors
-
- // Tells Executor manager resources that are occupied. The Executor Manager can use this
- // information to tell worker to reclaim un-used resources
- case ExecutorResourceUsageSummary(resources) =>
- executors.foreach { pair =>
- val (executorId, executor) = pair
- val resource = resources.get(executorId)
- val worker = executor.worker.ref
- // Notifies the worker the actual resource used by this application.
- resource match {
- case Some(resource) =>
- worker ! ChangeExecutorResource(appId, executorId, resource)
- case None =>
- worker ! ChangeExecutorResource(appId, executorId, Resource(0))
- }
- }
- }
-
- def terminationWatch: Receive = {
- case Terminated(actor) =>
- val executorId = Try(actor.path.name.toInt)
- executorId match {
- case scala.util.Success(id) => {
- executors -= id
- LOG.error(s"Executor $id is down")
- taskManager ! ExecutorStopped(id)
- }
- case scala.util.Failure(ex) =>
- LOG.error(s"failed to get the executor Id from path string ${actor.path}", ex)
- }
- }
-
- private def getExecutorJvmConfig(jar: Option[AppJar]): ExecutorSystemJvmConfig = {
- val executorAkkaConfig = clusterConfig
- val jvmSetting = Util.resolveJvmSetting(executorAkkaConfig.withFallback(systemConfig)).executor
-
- ExecutorSystemJvmConfig(jvmSetting.classPath, jvmSetting.vmargs, jar,
- username, executorAkkaConfig)
- }
-}
-
-private[appmaster] object ExecutorManager {
- case class StartExecutors(resources: Array[ResourceRequest], jar: AppJar)
- case class BroadCast(msg: Any)
-
- case class UniCast(executorId: Int, msg: Any)
-
- case object GetExecutorInfo
-
- case class ExecutorStarted(
- executorId: Int, resource: Resource, workerId: WorkerId, boundedJar: Option[AppJar])
- case class ExecutorStopped(executorId: Int)
-
- case class SetTaskManager(taskManager: ActorRef)
-
- case object StartExecutorsTimeOut
-
- def props(
- userConfig: UserConfig, appContext: AppMasterContext, clusterConfig: Config, appName: String)
- : Props = {
- val executorFactory =
- (executorContext: ExecutorContext,
- userConfig: UserConfig,
- address: Address,
- executorId: ExecutorId) =>
- Props(classOf[Executor], executorContext, userConfig)
- .withDeploy(Deploy(scope = RemoteScope(address)))
-
- Props(new ExecutorManager(userConfig, appContext, executorFactory, clusterConfig, appName))
- }
-
- case class ExecutorResourceUsageSummary(resources: Map[ExecutorId, Resource])
-
- case class ExecutorInfo(
- executorId: ExecutorId, executor: ActorRef, worker: WorkerInfo, boundedJar: Option[AppJar])
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/appmaster/JarScheduler.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/appmaster/JarScheduler.scala b/streaming/src/main/scala/io/gearpump/streaming/appmaster/JarScheduler.scala
deleted file mode 100644
index a2a9c74..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/appmaster/JarScheduler.scala
+++ /dev/null
@@ -1,176 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.appmaster
-
-import scala.concurrent.Future
-
-import akka.actor._
-import akka.pattern.ask
-import com.typesafe.config.Config
-
-import io.gearpump.TimeStamp
-import io.gearpump.cluster.AppJar
-import io.gearpump.cluster.scheduler.{Resource, ResourceRequest}
-import io.gearpump.cluster.worker.WorkerId
-import io.gearpump.partitioner.PartitionerDescription
-import io.gearpump.streaming.appmaster.JarScheduler._
-import io.gearpump.streaming.task.TaskId
-import io.gearpump.streaming.{DAG, ProcessorDescription}
-import io.gearpump.util.{Constants, Graph, LogUtil}
-
-/**
- * Different processors of the stream application can use different jars. JarScheduler is the
- * scheduler for different jars.
- *
- * For a DAG of multiple processors, each processor can have its own jar. Tasks of same jar
- * is scheduled by TaskScheduler, and TaskSchedulers are scheduled by JarScheduler.
- *
- * In runtime, the implementation is delegated to actor JarSchedulerImpl
- */
-class JarScheduler(appId: Int, appName: String, config: Config, factory: ActorRefFactory) {
- private val actor: ActorRef = factory.actorOf(Props(new JarSchedulerImpl(appId, appName, config)))
- private implicit val dispatcher = factory.dispatcher
- private implicit val timeout = Constants.FUTURE_TIMEOUT
-
- /** Set the current DAG version active */
- def setDag(dag: DAG, startClock: Future[TimeStamp]): Unit = {
- actor ! TransitToNewDag
- startClock.map { start =>
- actor ! NewDag(dag, start)
- }
- }
-
- /** AppMaster ask JarScheduler about how many resource it wants */
- def getResourceRequestDetails(): Future[Array[ResourceRequestDetail]] = {
- (actor ? GetResourceRequestDetails).asInstanceOf[Future[Array[ResourceRequestDetail]]]
- }
-
- /**
- * AppMaster has resource allocated, and ask the jar scheduler to schedule tasks
- * for this executor.
- */
- def scheduleTask(appJar: AppJar, workerId: WorkerId, executorId: Int, resource: Resource)
- : Future[List[TaskId]] = {
- (actor ? ScheduleTask(appJar, workerId, executorId, resource))
- .asInstanceOf[Future[List[TaskId]]]
- }
-
- /**
- * Some executor JVM process is dead. AppMaster asks jar scheduler to re-schedule the impacted
- * tasks.
- */
- def executorFailed(executorId: Int): Future[Option[ResourceRequestDetail]] = {
- (actor ? ExecutorFailed(executorId)).asInstanceOf[Future[Option[ResourceRequestDetail]]]
- }
-}
-
-object JarScheduler {
-
- case class ResourceRequestDetail(jar: AppJar, requests: Array[ResourceRequest])
-
- case class NewDag(dag: DAG, startTime: TimeStamp)
-
- case object TransitToNewDag
-
- case object GetResourceRequestDetails
-
- /**
- * Schedule tasks for one appJar.
- *
- * @param appJar Application jar.
- * @param workerId Worker machine Id.
- * @param executorId Executor Id.
- * @param resource Slots that are available.
- */
- case class ScheduleTask(appJar: AppJar, workerId: WorkerId, executorId: Int, resource: Resource)
-
- /** Some executor JVM is dead, try to recover tasks that are located on failed executor */
- case class ExecutorFailed(executorId: Int)
-
- class JarSchedulerImpl(appId: Int, appName: String, config: Config) extends Actor with Stash {
-
- // Each TaskScheduler maps to a jar.
- private var taskSchedulers = Map.empty[AppJar, TaskScheduler]
-
- private val LOG = LogUtil.getLogger(getClass)
-
- def receive: Receive = waitForNewDag
-
- def waitForNewDag: Receive = {
- case TransitToNewDag => // Continue current state
- case NewDag(dag, startTime) =>
-
- LOG.info(s"Init JarScheduler, dag version: ${dag.version}, startTime: $startTime")
-
- val processors = dag.processors.values.groupBy(_.jar)
-
- taskSchedulers = processors.map { jarAndProcessors =>
- val (jar, processors) = jarAndProcessors
- // Construct the sub DAG, each sub DAG maps to a separate jar.
- val subGraph = Graph.empty[ProcessorDescription, PartitionerDescription]
- processors.foreach { processor =>
- if (startTime < processor.life.death) {
- subGraph.addVertex(processor)
- }
- }
- val subDagForSingleJar = DAG(subGraph)
-
- val taskScheduler = taskSchedulers
- .getOrElse(jar, new TaskSchedulerImpl(appId, appName, config))
-
- LOG.info(s"Set DAG for TaskScheduler, count: " + subDagForSingleJar.processors.size)
- taskScheduler.setDAG(subDagForSingleJar)
- jar -> taskScheduler
- }
- unstashAll()
- context.become(ready)
- case other =>
- stash()
- }
-
- def ready: Receive = {
- // Notifies there is a new DAG coming.
- case TransitToNewDag =>
- context.become(waitForNewDag)
-
- case GetResourceRequestDetails =>
-
- // Asks each TaskScheduler (Each for one jar) the resource requests.
- val result: Array[ResourceRequestDetail] = taskSchedulers.map { jarAndScheduler =>
- val (jar, scheduler) = jarAndScheduler
- ResourceRequestDetail(jar, scheduler.getResourceRequests())
- }.toArray
- LOG.info(s"GetRequestDetails " + result.mkString(";"))
- sender ! result
-
- case ScheduleTask(appJar, workerId, executorId, resource) =>
- val result: List[TaskId] = taskSchedulers.get(appJar).map { scheduler =>
- scheduler.schedule(workerId, executorId, resource)
- }.getOrElse(List.empty)
- LOG.info(s"ScheduleTask " + result.mkString(";"))
- sender ! result
- case ExecutorFailed(executorId) =>
- val result: Option[ResourceRequestDetail] = taskSchedulers.
- find(_._2.scheduledTasks(executorId).nonEmpty).map { jarAndScheduler =>
- ResourceRequestDetail(jarAndScheduler._1, jarAndScheduler._2.executorFailed(executorId))
- }
- LOG.info(s"ExecutorFailed " + result.mkString(";"))
- sender ! result
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/appmaster/StreamAppMasterSummary.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/appmaster/StreamAppMasterSummary.scala b/streaming/src/main/scala/io/gearpump/streaming/appmaster/StreamAppMasterSummary.scala
deleted file mode 100644
index 3b2c8bf..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/appmaster/StreamAppMasterSummary.scala
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.appmaster
-
-import io.gearpump._
-import io.gearpump.cluster.AppMasterToMaster.AppMasterSummary
-import io.gearpump.cluster.MasterToAppMaster.AppMasterStatus
-import io.gearpump.cluster.{MasterToAppMaster, UserConfig}
-import io.gearpump.streaming.appmaster.AppMaster.ExecutorBrief
-import io.gearpump.streaming.{ExecutorId, LifeTime, ProcessorId}
-import io.gearpump.util.Graph
-import io.gearpump.util.HistoryMetricsService.HistoryMetricsConfig
-
-/** Stream application summary, used for REST API */
-case class StreamAppMasterSummary(
- appType: String = "streaming",
- appId: Int,
- appName: String = null,
- actorPath: String = null,
- clock: TimeStamp = 0L,
- status: AppMasterStatus = MasterToAppMaster.AppMasterActive,
- startTime: TimeStamp = 0L,
- uptime: TimeStamp = 0L,
- user: String = null,
- homeDirectory: String = "",
- logFile: String = "",
- dag: Graph[ProcessorId, String] = null,
- executors: List[ExecutorBrief] = null,
- processors: Map[ProcessorId, ProcessorSummary] = Map.empty[ProcessorId, ProcessorSummary],
- // Hiearachy level for each processor
- processorLevels: Map[ProcessorId, Int] = Map.empty[ProcessorId, Int],
- historyMetricsConfig: HistoryMetricsConfig = null)
- extends AppMasterSummary
-
-case class TaskCount(count: Int)
-
-case class ProcessorSummary(
- id: ProcessorId,
- taskClass: String,
- parallelism: Int,
- description: String,
- taskConf: UserConfig,
- life: LifeTime,
- executors: List[ExecutorId],
- taskCount: Map[ExecutorId, TaskCount])
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/appmaster/TaskLocator.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/appmaster/TaskLocator.scala b/streaming/src/main/scala/io/gearpump/streaming/appmaster/TaskLocator.scala
deleted file mode 100644
index 6e7ebc6..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/appmaster/TaskLocator.scala
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.appmaster
-
-import scala.collection.JavaConverters._
-import scala.util.Try
-
-import com.typesafe.config.{Config, ConfigFactory, ConfigRenderOptions, ConfigValueFactory}
-
-import io.gearpump.cluster.worker.WorkerId
-import io.gearpump.streaming.Constants
-import io.gearpump.streaming.appmaster.TaskLocator.{Localities, Locality, NonLocality, WorkerLocality}
-import io.gearpump.streaming.task.TaskId
-
-/**
- * TaskLocator is used to decide which machine one task should run on.
- *
- * User can specify config [[io.gearpump.streaming.Constants#GEARPUMP_STREAMING_LOCALITIES]] to
- * decide to control which machine the task is running on.
- */
-class TaskLocator(appName: String, config: Config) {
- private val taskLocalities: Map[TaskId, Locality] = loadTaskLocalities(config)
-
- /** Finds where a task should belongs to */
- def locateTask(taskId: TaskId): Locality = {
- taskLocalities.getOrElse(taskId, NonLocality)
- }
-
- private def loadTaskLocalities(config: Config): Map[TaskId, Locality] = {
- import io.gearpump.streaming.Constants.GEARPUMP_STREAMING_LOCALITIES
- Try(config.getConfig(s"$GEARPUMP_STREAMING_LOCALITIES.$appName")).map { appConfig =>
- val json = appConfig.root().render(ConfigRenderOptions.concise)
- Localities.fromJson(json)
- }.map { localityConfig =>
- import localityConfig.localities
- localities.keySet.flatMap { workerId =>
- val tasks = localities(workerId)
- tasks.map((_, WorkerLocality(workerId)))
- }.toArray.toMap
- }.getOrElse(Map.empty[TaskId, Locality])
- }
-}
-
-object TaskLocator {
-
- trait Locality
-
- /** Means we require the resource from the specific worker */
- case class WorkerLocality(workerId: WorkerId) extends Locality
-
- /** Means no preference on worker */
- object NonLocality extends Locality
-
- /** Localities settings. Mapping from workerId to list of taskId */
- case class Localities(localities: Map[WorkerId, Array[TaskId]])
-
- object Localities {
- val pattern = "task_([0-9]+)_([0-9]+)".r
-
- // To avoid polluting the classpath, we do the JSON translation ourself instead of
- // introducing JSON library dependencies directly.
- def fromJson(json: String): Localities = {
- val localities = ConfigFactory.parseString(json).getAnyRef("localities")
- .asInstanceOf[java.util.Map[String, String]].asScala.map { pair =>
- val workerId: WorkerId = WorkerId.parse(pair._1)
- val tasks = pair._2.split(",").map { task =>
- val pattern(processorId, taskIndex) = task
- TaskId(processorId.toInt, taskIndex.toInt)
- }
- (workerId, tasks)
- }.toMap
- new Localities(localities)
- }
-
- def toJson(localities: Localities): String = {
- val map = localities.localities.toList.map { pair =>
- (WorkerId.render(pair._1), pair._2.map(task =>
- s"task_${task.processorId}_${task.index}").mkString(","))
- }.toMap.asJava
- ConfigFactory.empty().withValue("localities", ConfigValueFactory.fromAnyRef(map)).
- root.render(ConfigRenderOptions.concise())
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/appmaster/TaskManager.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/appmaster/TaskManager.scala b/streaming/src/main/scala/io/gearpump/streaming/appmaster/TaskManager.scala
deleted file mode 100644
index 51f2f9c..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/appmaster/TaskManager.scala
+++ /dev/null
@@ -1,497 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.appmaster
-
-import scala.concurrent.Future
-import scala.concurrent.duration._
-
-import akka.actor._
-import akka.pattern.ask
-import org.slf4j.Logger
-
-import io.gearpump.TimeStamp
-import io.gearpump.cluster.MasterToAppMaster.ReplayFromTimestampWindowTrailingEdge
-import io.gearpump.streaming.AppMasterToExecutor._
-import io.gearpump.streaming.ExecutorToAppMaster.{MessageLoss, RegisterTask, UnRegisterTask}
-import io.gearpump.streaming._
-import io.gearpump.streaming.appmaster.AppMaster.{AllocateResourceTimeOut, LookupTaskActorRef, TaskActorRef}
-import io.gearpump.streaming.appmaster.ClockService.{ChangeToNewDAG, ChangeToNewDAGSuccess}
-import io.gearpump.streaming.appmaster.DagManager.{GetLatestDAG, GetTaskLaunchData, LatestDAG, NewDAGDeployed, TaskLaunchData, WatchChange}
-import io.gearpump.streaming.appmaster.ExecutorManager.{ExecutorStarted, StartExecutorsTimeOut, _}
-import io.gearpump.streaming.appmaster.TaskManager._
-import io.gearpump.streaming.appmaster.TaskRegistry.{Accept, TaskLocation}
-import io.gearpump.streaming.executor.Executor.RestartTasks
-import io.gearpump.streaming.executor.ExecutorRestartPolicy
-import io.gearpump.streaming.task._
-import io.gearpump.streaming.util.ActorPathUtil
-import io.gearpump.util.{Constants, LogUtil}
-
-/**
- *
- * TaskManager track all tasks's status.
- *
- * It is state machine with three states:
- * 1. applicationReady
- * 2. recovery
- * 3. dynamicDag
- *
- * When in state applicationReady:
- * 1. When there is message-loss or JVM crash, transit to state recovery.
- * 2. When user modify the DAG, transit to dynamicDag.
- *
- * When in state recovery:
- * 1. When all tasks has been recovered, transit to applicationReady.
- *
- * When in state dynamicDag:
- * 1. When dynamic dag transition is complete, transit to applicationReady.
- * 2. When there is message loss or JVM crash, transit to state recovery.
- */
-private[appmaster] class TaskManager(
- appId: Int,
- dagManager: ActorRef,
- jarScheduler: JarScheduler,
- executorManager: ActorRef,
- clockService: ActorRef,
- appMaster: ActorRef,
- appName: String)
- extends Actor {
-
- private val LOG: Logger = LogUtil.getLogger(getClass, app = appId)
- private val systemConfig = context.system.settings.config
-
- private val ids = new SessionIdFactory()
-
- private val executorRestartPolicy = new ExecutorRestartPolicy(maxNrOfRetries = 5,
- withinTimeRange = 20.seconds)
-
- private implicit val timeout = Constants.FUTURE_TIMEOUT
- private implicit val actorSystem = context.system
-
- import context.dispatcher
-
- dagManager ! WatchChange(watcher = self)
- executorManager ! SetTaskManager(self)
-
- private def getStartClock: Future[TimeStamp] = {
- (clockService ? GetStartClock).asInstanceOf[Future[StartClock]].map(_.clock)
- }
-
- private var startClock: Future[TimeStamp] = getStartClock
-
- def receive: Receive = applicationReady(DagReadyState.empty)
-
- private def onClientQuery(taskRegistry: TaskRegistry): Receive = {
- case clock: ClockEvent =>
- clockService forward clock
- case GetTaskList =>
- sender ! TaskList(taskRegistry.getTaskExecutorMap)
- case LookupTaskActorRef(taskId) =>
- val executorId = taskRegistry.getExecutorId(taskId)
- val requestor = sender
- executorId.map { executorId =>
- val taskPath = ActorPathUtil.taskActorPath(appMaster, executorId, taskId)
- context.actorSelection(taskPath).resolveOne(3.seconds).map { taskActorRef =>
- requestor ! TaskActorRef(taskActorRef)
- }
- }
- }
-
- /**
- * State applicationReady
- */
- def applicationReady(state: DagReadyState): Receive = {
- executorManager ! state.taskRegistry.usedResource
- dagManager ! NewDAGDeployed(state.dag.version)
- dagManager ! GetLatestDAG
- LOG.info(s"goto state ApplicationReady(dag = ${state.dag.version})...")
-
- val recoverRegistry = new TaskRegistry(expectedTasks = state.dag.tasks,
- deadTasks = state.taskRegistry.deadTasks)
-
- val recoverState = new StartDagState(state.dag, recoverRegistry)
-
- val onError: Receive = {
- case executorStopped@ExecutorStopped(executorId) =>
- if (state.taskRegistry.isTaskRegisteredForExecutor(executorId)) {
- self ! executorStopped
- context.become(recovery(recoverState))
- }
- case MessageLoss(executorId, taskId, cause) =>
- if (state.taskRegistry.isTaskRegisteredForExecutor(executorId) &&
- executorRestartPolicy.allowRestartExecutor(executorId)) {
- context.become(recovery(recoverState))
- } else {
- val errorMsg = s"Task $taskId fails too many times to recover"
- appMaster ! FailedToRecover(errorMsg)
- }
- case replay: ReplayFromTimestampWindowTrailingEdge =>
- LOG.error(s"Received $replay")
- context.become(recovery(recoverState))
- }
-
- val onNewDag: Receive = {
- case LatestDAG(newDag) =>
-
- if (newDag.version > state.dag.version) {
-
- executorManager ! BroadCast(StartDynamicDag(newDag.version))
- LOG.info("Broadcasting StartDynamicDag")
-
- val dagDiff = migrate(state.dag, newDag)
- jarScheduler.setDag(newDag, startClock)
- val resourceRequestsDetails = jarScheduler.getResourceRequestDetails()
- resourceRequestsDetails.map { details =>
- details.foreach { detail =>
- if (detail.requests.length > 0 && detail.requests.exists(!_.resource.isEmpty)) {
- executorManager ! StartExecutors(detail.requests, detail.jar)
- }
- }
- }
-
- var modifiedTasks = List.empty[TaskId]
- for (processorId <- dagDiff.modifiedProcessors ++ dagDiff.impactedUpstream) {
- val executors = state.taskRegistry.processorExecutors(processorId)
- executors.foreach { pair =>
- val (executorId, tasks) = pair
- modifiedTasks ++= tasks
- dagManager ! GetTaskLaunchData(newDag.version, processorId,
- ChangeTasksOnExecutor(executorId, tasks))
- }
- }
-
- val taskChangeRegistry = new TaskChangeRegistry(modifiedTasks)
-
- val deadTasks = state.taskRegistry.deadTasks
- val registeredTasks = state.taskRegistry.registeredTasks
- val dynamicTaskRegistry = new TaskRegistry(newDag.tasks, registeredTasks, deadTasks)
-
- val nextState = new StartDagState(newDag, dynamicTaskRegistry, taskChangeRegistry)
- context.become(dynamicDag(nextState, recoverState))
- }
- }
-
- val onUnRegisterTask: Receive = {
- case unRegister: UnRegisterTask =>
-
- LOG.info(s"Received $unRegister, stop task ${unRegister.taskId}")
- sender ! StopTask(unRegister.taskId)
-
- val taskId = unRegister.taskId
- val registry = state.taskRegistry
- val deadTasks = registry.deadTasks
-
- val newRegistry = registry.copy(registeredTasks = registry.registeredTasks - taskId,
- deadTasks = deadTasks + taskId)
-
- val newState = new DagReadyState(state.dag, newRegistry)
- context.become(applicationReady(newState))
- }
-
- // Recovers to same version
- onClientQuery(state.taskRegistry) orElse onError orElse onNewDag orElse
- onUnRegisterTask orElse unHandled("applicationReady")
- }
-
- /**
- * State dynamicDag
- */
- def dynamicDag(state: StartDagState, recoverState: StartDagState): Receive = {
- LOG.info(s"DynamicDag transit to dag version: ${state.dag.version}...")
-
- val onMessageLoss: Receive = {
- case executorStopped@ExecutorStopped(executorId) =>
- context.become(recovery(recoverState))
- case MessageLoss(executorId, taskId, cause) =>
- if (state.taskRegistry.isTaskRegisteredForExecutor(executorId) &&
- executorRestartPolicy.allowRestartExecutor(executorId)) {
- context.become(recovery(recoverState))
- } else {
- val errorMsg = s"Task $taskId fails too many times to recover"
- appMaster ! FailedToRecover(errorMsg)
- }
- }
-
- onMessageLoss orElse onClientQuery(state.taskRegistry) orElse
- startDag(state, recoverState) orElse unHandled("dynamicDag")
- }
-
- private def startDag(state: StartDagState, recoverState: StartDagState): Receive = {
- case executor: ExecutorStarted =>
- import executor.{boundedJar, executorId, resource, workerId}
- val taskIdsFuture = jarScheduler.scheduleTask(boundedJar.get, workerId, executorId, resource)
- taskIdsFuture.foreach { taskIds =>
- LOG.info(s"Executor $executor has been started, " +
- s"start to schedule tasks: ${taskIds.mkString(",")}")
- taskIds.groupBy(_.processorId).foreach { pair =>
- val (processorId, tasks) = pair
- dagManager ! GetTaskLaunchData(state.dag.version, processorId,
- StartTasksOnExecutor(executor.executorId, tasks))
- }
- }
-
- case StartExecutorsTimeOut =>
- appMaster ! AllocateResourceTimeOut
- case TaskLaunchData(processorDescription, subscribers, command) =>
- command match {
- case StartTasksOnExecutor(executorId, tasks) =>
- LOG.info(s"Start tasks on Executor($executorId), tasks: " + tasks)
- val launchTasks = LaunchTasks(tasks, state.dag.version, processorDescription, subscribers)
- executorManager ! UniCast(executorId, launchTasks)
- tasks.foreach(executorRestartPolicy.addTaskToExecutor(executorId, _))
- case ChangeTasksOnExecutor(executorId, tasks) =>
- LOG.info("change Task on executor: " + executorId + ", tasks: " + tasks)
- val changeTasks = ChangeTasks(tasks, state.dag.version, processorDescription.life,
- subscribers)
- executorManager ! UniCast(executorId, changeTasks)
- case other =>
- LOG.error(s"severe error! we expect ExecutorStarted but get ${other.getClass.toString}")
- }
- case TasksLaunched =>
- // We will track all launched task by message RegisterTask
- case TasksChanged(tasks) =>
- tasks.foreach(task => state.taskChangeRegistry.taskChanged(task))
-
- if (allTasksReady(state)) {
- broadcastLocations(state)
- }
-
- case RegisterTask(taskId, executorId, host) =>
- val client = sender
- val register = state.taskRegistry
- val status = register.registerTask(taskId, TaskLocation(executorId, host))
- if (status == Accept) {
- LOG.info(s"RegisterTask($taskId) TaskLocation: $host, Executor: $executorId")
- val sessionId = ids.newSessionId
-
- startClock.foreach(clock => client ! TaskRegistered(taskId, sessionId, clock))
- if (allTasksReady(state)) {
- broadcastLocations(state)
- }
- } else {
- sender ! TaskRejected(taskId)
- }
-
- case TaskChanged(taskId, dagVersion) =>
- state.taskChangeRegistry.taskChanged(taskId)
- if (allTasksReady(state)) {
- broadcastLocations(state)
- }
- case locationReceived: TaskLocationsReceived =>
- state.executorReadyRegistry.registerExecutor(locationReceived.executorId)
- if (allTasksReady(state) &&
- state.executorReadyRegistry.allRegistered(state.taskRegistry.executors)) {
- LOG.info("All executors are ready to start...")
- clockService ! ChangeToNewDAG(state.dag)
- }
- case locationRejected: TaskLocationsRejected =>
- LOG.error(s"received $locationRejected, start to recover")
- context.become(recovery(recoverState))
-
- case ChangeToNewDAGSuccess(_) =>
- if (allTasksReady(state) &&
- state.executorReadyRegistry.allRegistered(state.taskRegistry.executors)) {
- executorManager ! BroadCast(StartAllTasks(state.dag.version))
- context.become(applicationReady(new DagReadyState(state.dag, state.taskRegistry)))
- }
- }
-
- def onExecutorError: Receive = {
- case ExecutorStopped(executorId) =>
- if (executorRestartPolicy.allowRestartExecutor(executorId)) {
- jarScheduler.executorFailed(executorId).foreach { resourceRequestDetail =>
- if (resourceRequestDetail.isDefined) {
- executorManager ! StartExecutors(resourceRequestDetail.get.requests,
- resourceRequestDetail.get.jar)
- }
- }
- } else {
- val errorMsg = s"Executor restarted too many times to recover"
- appMaster ! FailedToRecover(errorMsg)
- }
- }
-
- private def allTasksReady(state: StartDagState): Boolean = {
- import state.{taskChangeRegistry, taskRegistry}
- taskRegistry.isAllTasksRegistered && taskChangeRegistry.allTaskChanged
- }
-
- private def broadcastLocations(state: StartDagState): Unit = {
- LOG.info(s"All tasks have been launched; send Task locations to all executors")
- val taskLocations = state.taskRegistry.getTaskLocations
- executorManager ! BroadCast(TaskLocationsReady(taskLocations, state.dag.version))
- }
-
- /**
- * State recovery
- */
- def recovery(state: StartDagState): Receive = {
- val recoverDagVersion = state.dag.version
- executorManager ! BroadCast(RestartTasks(recoverDagVersion))
-
- // Use new Start Clock so that we recover at timepoint we fails.
- startClock = getStartClock
-
- jarScheduler.setDag(state.dag, startClock)
-
- LOG.info(s"goto state Recovery(recoverDag = $recoverDagVersion)...")
- val ignoreClock: Receive = {
- case clock: ClockEvent =>
- // Ignores clock events.
- }
-
- if (state.dag.isEmpty) {
- applicationReady(new DagReadyState(state.dag, state.taskRegistry))
- } else {
- val registry = new TaskRegistry(expectedTasks = state.dag.tasks,
- deadTasks = state.taskRegistry.deadTasks)
-
- val recoverState = new StartDagState(state.dag, registry)
- ignoreClock orElse startDag(state, recoverState) orElse onExecutorError orElse
- unHandled("recovery")
- }
- }
-
- private def unHandled(state: String): Receive = {
- case other =>
- LOG.info(s"Received unknown message $other in state $state")
- }
-}
-
-private[appmaster] object TaskManager {
-
- /**
- * When application is ready, then transit to DagReadyState
- */
- class DagReadyState(val dag: DAG, val taskRegistry: TaskRegistry)
-
- object DagReadyState {
- def empty: DagReadyState = {
- new DagReadyState(
- DAG.empty.copy(version = -1),
- new TaskRegistry(List.empty[TaskId]))
- }
- }
-
- /**
- * When application is booting up or doing recovery, it use StartDagState
- */
- class StartDagState(
- val dag: DAG,
- val taskRegistry: TaskRegistry,
- val taskChangeRegistry: TaskChangeRegistry = new TaskChangeRegistry(List.empty[TaskId]),
- val executorReadyRegistry: ExecutorRegistry = new ExecutorRegistry)
-
- case object GetTaskList
-
- case class TaskList(tasks: Map[TaskId, ExecutorId])
-
- case class FailedToRecover(errorMsg: String)
-
- /**
- * Starts new Tasks on Executor executorId
- */
- case class StartTasksOnExecutor(executorId: Int, tasks: List[TaskId])
-
- /**
- * Changes existing tasks on executor executorId
- */
- case class ChangeTasksOnExecutor(executorId: Int, tasks: List[TaskId])
-
- /**
- * Tracks the registration of all new started executors.
- */
- class ExecutorRegistry {
- private var registeredExecutors = Set.empty[ExecutorId]
-
- def registerExecutor(executorId: ExecutorId): Unit = {
- registeredExecutors += executorId
- }
-
- def allRegistered(all: List[ExecutorId]): Boolean = {
- all.forall(executor => registeredExecutors.contains(executor))
- }
- }
-
- /**
- * Tracks the registration of all changed tasks.
- */
- class TaskChangeRegistry(targetTasks: List[TaskId]) {
- private var registeredTasks = Set.empty[TaskId]
- def taskChanged(taskId: TaskId): Unit = {
- registeredTasks += taskId
- }
- def allTaskChanged: Boolean = {
- targetTasks.forall(taskId => registeredTasks.contains(taskId))
- }
- }
-
- object TaskChangeRegistry {
- def empty: TaskChangeRegistry = new TaskChangeRegistry(List.empty[TaskId])
- }
-
- /**
- * DAGDiff is used to track impacted processors when doing dynamic dag.
- */
- case class DAGDiff(
- addedProcessors: List[ProcessorId],
- modifiedProcessors: List[ProcessorId],
- impactedUpstream: List[ProcessorId])
-
- /**
- * Migrates from old DAG to new DAG, return DAGDiff
- */
- def migrate(leftDAG: DAG, rightDAG: DAG): DAGDiff = {
- val left = leftDAG.processors.keySet
- val right = rightDAG.processors.keySet
-
- val added = right -- left
- val join = right -- added
-
- val modified = join.filter { processorId =>
- leftDAG.processors(processorId) != rightDAG.processors(processorId)
- }
-
- val upstream = (list: Set[ProcessorId]) => {
- list.flatMap { processorId =>
- rightDAG.graph.incomingEdgesOf(processorId).map(_._1).toSet
- } -- list
- }
-
- val impactedUpstream = upstream(added ++ modified)
-
- // All upstream tasks are affected, and should be handled properly.
- DAGDiff(added.toList, modified.toList, impactedUpstream.toList)
- }
-
- /**
- * Each new task will be assigned with a unique session Id.
- */
- class SessionIdFactory {
- private var nextSessionId = 1
-
- /**
- * Returns a new session Id for new task
- */
- final def newSessionId: Int = {
- val sessionId = nextSessionId
- nextSessionId += 1
- sessionId
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/appmaster/TaskRegistry.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/appmaster/TaskRegistry.scala b/streaming/src/main/scala/io/gearpump/streaming/appmaster/TaskRegistry.scala
deleted file mode 100644
index adfdeba..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/appmaster/TaskRegistry.scala
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.appmaster
-
-import org.slf4j.Logger
-
-import io.gearpump.cluster.scheduler.Resource
-import io.gearpump.streaming.appmaster.ExecutorManager.ExecutorResourceUsageSummary
-import io.gearpump.streaming.appmaster.TaskRegistry._
-import io.gearpump.streaming.task.TaskId
-import io.gearpump.streaming.{ExecutorId, ProcessorId}
-import io.gearpump.transport.HostPort
-import io.gearpump.util.LogUtil
-
-/**
- * Tracks the registration of all tasks, when the application is booting up.
- */
-class TaskRegistry(val expectedTasks: List[TaskId],
- var registeredTasks: Map[TaskId, TaskLocation] = Map.empty[TaskId, TaskLocation],
- var deadTasks: Set[TaskId] = Set.empty[TaskId]) {
-
- private val LOG: Logger = LogUtil.getLogger(getClass)
-
- private val processors = expectedTasks.map(_.processorId).toSet
-
- /**
- * When a task is booted, it need to call registerTask to register itself.
- * If this task is valid, then accept it, otherwise reject it.
- *
- * @param taskId Task that register itself to TaskRegistry.
- * @param location The host and port where this task is running on. NOTE: The host and port
- * is NOT the same host and port of Akka remoting. Instead, it is host and port
- * of custom netty layer, see [[io.gearpump.transport.netty.Context]].
- */
- def registerTask(taskId: TaskId, location: TaskLocation): RegisterTaskStatus = {
- val processorId = taskId.processorId
-
- if (processors.contains(processorId)) {
- registeredTasks += taskId -> location
- Accept
- } else {
- LOG.error(s" the task is not accepted for registration, taskId: ${taskId}")
- Reject
- }
- }
-
- def copy(expectedTasks: List[TaskId] = this.expectedTasks,
- registeredTasks: Map[TaskId, TaskLocation] = this.registeredTasks,
- deadTasks: Set[TaskId] = this.deadTasks): TaskRegistry = {
- new TaskRegistry(expectedTasks, registeredTasks, deadTasks)
- }
-
- def getTaskLocations: TaskLocations = {
- val taskLocations = registeredTasks.toList.groupBy(_._2.host).map { pair =>
- val (k, v) = pair
- val taskIds = v.map(_._1)
- (k, taskIds.toSet)
- }
- TaskLocations(taskLocations)
- }
-
- def getTaskExecutorMap: Map[TaskId, ExecutorId] = {
- getTaskLocations.locations.flatMap { pair =>
- val (hostPort, taskSet) = pair
- taskSet.map { taskId =>
- (taskId, getExecutorId(taskId).getOrElse(-1))
- }
- }
- }
-
- /** Query the executor Id where the task is running on */
- def getExecutorId(taskId: TaskId): Option[Int] = {
- registeredTasks.get(taskId).map(_.executorId)
- }
-
- /** Gets list of allocated executor Ids */
- def executors: List[ExecutorId] = {
- registeredTasks.toList.map(_._2.executorId)
- }
-
- def isAllTasksRegistered: Boolean = {
- val aliveTasks = (expectedTasks.toSet -- deadTasks)
- aliveTasks.forall(task => registeredTasks.contains(task))
- }
-
- def isTaskRegisteredForExecutor(executorId: ExecutorId): Boolean = {
- registeredTasks.exists(_._2.executorId == executorId)
- }
-
- private def filterTasks(processorId: ProcessorId): List[TaskId] = {
- registeredTasks.keys.toList.filter(_.processorId == processorId)
- }
-
- /** List of executors that current processor taks are running on */
- def processorExecutors(processorId: ProcessorId): Map[ExecutorId, List[TaskId]] = {
- val taskToExecutor = filterTasks(processorId).flatMap { taskId =>
- getExecutorId(taskId).map { executorId =>
- (taskId, executorId)
- }
- }
-
- val executorToTasks = taskToExecutor.groupBy(_._2).map { kv =>
- val (k, v) = kv
- (k, v.map(_._1))
- }
- executorToTasks
- }
-
- /** Summary about how many resources are used for all running tasks */
- def usedResource: ExecutorResourceUsageSummary = {
- val resourceMap = registeredTasks.foldLeft(Map.empty[ExecutorId, Resource]) { (map, task) =>
- val resource = map.getOrElse(task._2.executorId, Resource(0)) + Resource(1)
- map + (task._2.executorId -> resource)
- }
- ExecutorResourceUsageSummary(resourceMap)
- }
-}
-
-object TaskRegistry {
- sealed trait RegisterTaskStatus
- case object Accept extends RegisterTaskStatus
- case object Reject extends RegisterTaskStatus
-
- case class TaskLocation(executorId: Int, host: HostPort)
-
- case class TaskLocations(locations: Map[HostPort, Set[TaskId]])
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/appmaster/TaskSchedulerImpl.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/appmaster/TaskSchedulerImpl.scala b/streaming/src/main/scala/io/gearpump/streaming/appmaster/TaskSchedulerImpl.scala
deleted file mode 100644
index 62dff6c..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/appmaster/TaskSchedulerImpl.scala
+++ /dev/null
@@ -1,178 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.appmaster
-
-import com.typesafe.config.Config
-
-import io.gearpump.cluster.scheduler.{Relaxation, Resource, ResourceRequest}
-import io.gearpump.cluster.worker.WorkerId
-import io.gearpump.streaming.DAG
-import io.gearpump.streaming.appmaster.TaskLocator.{Locality, WorkerLocality}
-import io.gearpump.streaming.appmaster.TaskScheduler.{Location, TaskStatus}
-import io.gearpump.streaming.task.TaskId
-import io.gearpump.util.Constants
-
-/**
- * Schedules tasks to run for new allocated resources. TaskScheduler only schedule tasks that
- * share the same jar. For scheduling for multiple jars, see
- * [[io.gearpump.streaming.appmaster.JarScheduler]].
- */
-trait TaskScheduler {
-
- /**
- * This notify the scheduler that the task DAG is created.
- * @param dag task dag
- */
- def setDAG(dag: DAG): Unit
-
- /**
- * Get the resource requirements for all unscheduled tasks.
- */
- def getResourceRequests(): Array[ResourceRequest]
-
- /**
- * This notifies the scheduler that a resource slot on {workerId} and {executorId} is allocated
- * , and expect a task to be scheduled in return.
- * Task locality should be considered when deciding whether to offer a task on target {worker}
- * and {executor}
- *
- * @param workerId which worker this resource is located.
- * @param executorId which executorId this resource belongs to.
- * @return a list of tasks
- */
- def schedule(workerId: WorkerId, executorId: Int, resource: Resource): List[TaskId]
-
- /**
- * This notifies the scheduler that {executorId} is failed, and expect a set of
- * ResourceRequest for all failed tasks on that executor.
- *
- * @param executorId executor that failed
- * @return resource requests of the failed executor
- */
- def executorFailed(executorId: Int): Array[ResourceRequest]
-
- /**
- * Queries the task list that already scheduled on the executor
- *
- * @param executorId executor to query
- * @return a list of tasks
- */
- def scheduledTasks(executorId: Int): List[TaskId]
-}
-
-object TaskScheduler {
- case class Location(workerId: WorkerId, executorId: Int)
-
- class TaskStatus(val taskId: TaskId, val preferLocality: Locality, var allocation: Location)
-}
-
-class TaskSchedulerImpl(appId: Int, appName: String, config: Config) extends TaskScheduler {
- private val executorNum = config.getInt(Constants.APPLICATION_EXECUTOR_NUMBER)
-
- private var tasks = List.empty[TaskStatus]
-
- // Finds the locality of the tasks
- private val taskLocator = new TaskLocator(appName, config)
-
- override def setDAG(dag: DAG): Unit = {
- val taskMap = tasks.map(_.taskId).zip(tasks).toMap
-
- tasks = dag.tasks.sortBy(_.index).map { taskId =>
- val locality = taskLocator.locateTask(taskId)
- taskMap.getOrElse(taskId, new TaskStatus(taskId, locality, allocation = null))
- }
- }
-
- def getResourceRequests(): Array[ResourceRequest] = {
- fetchResourceRequests(fromOneWorker = false)
- }
-
- import io.gearpump.cluster.scheduler.Relaxation._
- private def fetchResourceRequests(fromOneWorker: Boolean = false): Array[ResourceRequest] = {
- var workersResourceRequest = Map.empty[WorkerId, Resource]
-
- tasks.filter(_.allocation == null).foreach { task =>
- task.preferLocality match {
- case WorkerLocality(workerId) =>
- val current = workersResourceRequest.getOrElse(workerId, Resource.empty)
- workersResourceRequest += workerId -> (current + Resource(1))
- case _ =>
- val workerId = WorkerId.unspecified
- val current = workersResourceRequest.getOrElse(workerId, Resource.empty)
- workersResourceRequest += workerId -> (current + Resource(1))
- }
- }
-
- workersResourceRequest.map { workerIdAndResource =>
- val (workerId, resource) = workerIdAndResource
- if (workerId == WorkerId.unspecified) {
- ResourceRequest(resource, workerId = WorkerId.unspecified, executorNum = executorNum)
- } else {
- ResourceRequest(resource, workerId, relaxation = SPECIFICWORKER)
- }
- }.toArray
- }
-
- override def schedule(workerId: WorkerId, executorId: Int, resource: Resource): List[TaskId] = {
- var scheduledTasks = List.empty[TaskId]
- val location = Location(workerId, executorId)
- // Schedules tasks for specific worker
- scheduledTasks ++= scheduleTasksForLocality(resource, location,
- (locality) => locality == WorkerLocality(workerId))
-
- // Schedules tasks without specific location preference
- scheduledTasks ++= scheduleTasksForLocality(resource - Resource(scheduledTasks.length),
- location, (locality) => true)
- scheduledTasks
- }
-
- private def scheduleTasksForLocality(
- resource: Resource, resourceLocation: Location, matcher: (Locality) => Boolean)
- : List[TaskId] = {
- var scheduledTasks = List.empty[TaskId]
- var index = 0
- var remain = resource.slots
- while (index < tasks.length && remain > 0) {
- val taskStatus = tasks(index)
- if (taskStatus.allocation == null && matcher(taskStatus.preferLocality)) {
- taskStatus.allocation = resourceLocation
- scheduledTasks +:= taskStatus.taskId
- remain -= 1
- }
- index += 1
- }
- scheduledTasks
- }
-
- override def executorFailed(executorId: Int): Array[ResourceRequest] = {
- val failedTasks = tasks.filter { status =>
- status.allocation != null && status.allocation.executorId == executorId
- }
- // Cleans the location of failed tasks
- failedTasks.foreach(_.allocation = null)
-
- Array(ResourceRequest(Resource(failedTasks.length),
- workerId = WorkerId.unspecified, relaxation = ONEWORKER))
- }
-
- override def scheduledTasks(executorId: Int): List[TaskId] = {
- tasks.filter { status =>
- status.allocation != null && status.allocation.executorId == executorId
- }.map(_.taskId)
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/dsl/Stream.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/dsl/Stream.scala b/streaming/src/main/scala/io/gearpump/streaming/dsl/Stream.scala
deleted file mode 100644
index ddd2037..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/dsl/Stream.scala
+++ /dev/null
@@ -1,230 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.dsl
-
-import scala.language.implicitConversions
-
-import org.slf4j.{Logger, LoggerFactory}
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.dsl.op._
-import io.gearpump.streaming.sink.DataSink
-import io.gearpump.streaming.task.{Task, TaskContext}
-import io.gearpump.util.Graph
-
-class Stream[T](
- private val graph: Graph[Op, OpEdge], private val thisNode: Op,
- private val edge: Option[OpEdge] = None) {
-
- /**
- * converts a value[T] to a list of value[R]
- *
- * @param fun FlatMap function
- * @param description The description message for this operation
- * @return A new stream with type [R]
- */
- def flatMap[R](fun: T => TraversableOnce[R], description: String = null): Stream[R] = {
- val flatMapOp = FlatMapOp(fun, Option(description).getOrElse("flatmap"))
- graph.addVertex(flatMapOp)
- graph.addEdge(thisNode, edge.getOrElse(Direct), flatMapOp)
- new Stream[R](graph, flatMapOp)
- }
-
- /**
- * Maps message of type T message of type R
- *
- * @param fun Function
- * @return A new stream with type [R]
- */
- def map[R](fun: T => R, description: String = null): Stream[R] = {
- this.flatMap({ data =>
- Option(fun(data))
- }, Option(description).getOrElse("map"))
- }
-
- /**
- * Keeps records when fun(T) == true
- *
- * @param fun the filter
- * @return a new stream after filter
- */
- def filter(fun: T => Boolean, description: String = null): Stream[T] = {
- this.flatMap({ data =>
- if (fun(data)) Option(data) else None
- }, Option(description).getOrElse("filter"))
- }
-
- /**
- * Reduces operations.
- *
- * @param fun reduction function
- * @param description description message for this operator
- * @return a new stream after reduction
- */
- def reduce(fun: (T, T) => T, description: String = null): Stream[T] = {
- val reduceOp = ReduceOp(fun, Option(description).getOrElse("reduce"))
- graph.addVertex(reduceOp)
- graph.addEdge(thisNode, edge.getOrElse(Direct), reduceOp)
- new Stream(graph, reduceOp)
- }
-
- /**
- * Log to task log file
- */
- def log(): Unit = {
- this.map(msg => LoggerFactory.getLogger("dsl").info(msg.toString), "log")
- }
-
- /**
- * Merges data from two stream into one
- *
- * @param other the other stream
- * @return the merged stream
- */
- def merge(other: Stream[T], description: String = null): Stream[T] = {
- val mergeOp = MergeOp(Option(description).getOrElse("merge"))
- graph.addVertex(mergeOp)
- graph.addEdge(thisNode, edge.getOrElse(Direct), mergeOp)
- graph.addEdge(other.thisNode, other.edge.getOrElse(Shuffle), mergeOp)
- new Stream[T](graph, mergeOp)
- }
-
- /**
- * Group by function (T => Group)
- *
- * For example, we have T type, People(name: String, gender: String, age: Int)
- * groupBy[People](_.gender) will group the people by gender.
- *
- * You can append other combinators after groupBy
- *
- * For example,
- * {{{
- * Stream[People].groupBy(_.gender).flatmap(..).filter.(..).reduce(..)
- * }}}
- *
- * @param fun Group by function
- * @param parallelism Parallelism level
- * @param description The description
- * @return the grouped stream
- */
- def groupBy[Group](fun: T => Group, parallelism: Int = 1, description: String = null)
- : Stream[T] = {
- val groupOp = GroupByOp(fun, parallelism, Option(description).getOrElse("groupBy"))
- graph.addVertex(groupOp)
- graph.addEdge(thisNode, edge.getOrElse(Shuffle), groupOp)
- new Stream[T](graph, groupOp)
- }
-
- /**
- * Connects with a low level Processor(TaskDescription)
- *
- * @param processor a user defined processor
- * @param parallelism parallelism level
- * @return new stream after processing with type [R]
- */
- def process[R](
- processor: Class[_ <: Task], parallelism: Int, conf: UserConfig = UserConfig.empty,
- description: String = null): Stream[R] = {
- val processorOp = ProcessorOp(processor, parallelism, conf,
- Option(description).getOrElse("process"))
- graph.addVertex(processorOp)
- graph.addEdge(thisNode, edge.getOrElse(Shuffle), processorOp)
- new Stream[R](graph, processorOp, Some(Shuffle))
- }
-}
-
-class KVStream[K, V](stream: Stream[Tuple2[K, V]]) {
- /**
- * GroupBy key
- *
- * Applies to Stream[Tuple2[K,V]]
- *
- * @param parallelism the parallelism for this operation
- * @return the new KV stream
- */
- def groupByKey(parallelism: Int = 1): Stream[Tuple2[K, V]] = {
- stream.groupBy(Stream.getTupleKey[K, V], parallelism, "groupByKey")
- }
-
- /**
- * Sum the value of the tuples
- *
- * Apply to Stream[Tuple2[K,V]], V must be of type Number
- *
- * For input (key, value1), (key, value2), will generate (key, value1 + value2)
- * @param numeric the numeric operations
- * @return the sum stream
- */
- def sum(implicit numeric: Numeric[V]): Stream[(K, V)] = {
- stream.reduce(Stream.sumByValue[K, V](numeric), "sum")
- }
-}
-
-object Stream {
-
- def apply[T](graph: Graph[Op, OpEdge], node: Op, edge: Option[OpEdge]): Stream[T] = {
- new Stream[T](graph, node, edge)
- }
-
- def getTupleKey[K, V](tuple: Tuple2[K, V]): K = tuple._1
-
- def sumByValue[K, V](numeric: Numeric[V]): (Tuple2[K, V], Tuple2[K, V]) => Tuple2[K, V]
- = (tuple1, tuple2) => Tuple2(tuple1._1, numeric.plus(tuple1._2, tuple2._2))
-
- implicit def streamToKVStream[K, V](stream: Stream[Tuple2[K, V]]): KVStream[K, V] = {
- new KVStream(stream)
- }
-
- implicit class Sink[T](stream: Stream[T]) extends java.io.Serializable {
- def sink[T](dataSink: DataSink, parallism: Int, conf: UserConfig, description: String)
- : Stream[T] = {
- implicit val sink = DataSinkOp[T](dataSink, parallism, conf,
- Some(description).getOrElse("traversable"))
- stream.graph.addVertex(sink)
- stream.graph.addEdge(stream.thisNode, Shuffle, sink)
- new Stream[T](stream.graph, sink)
- }
-
- def sink[T](
- sink: Class[_ <: Task], parallism: Int, conf: UserConfig = UserConfig.empty,
- description: String = null): Stream[T] = {
- val sinkOp = ProcessorOp(sink, parallism, conf, Option(description).getOrElse("source"))
- stream.graph.addVertex(sinkOp)
- stream.graph.addEdge(stream.thisNode, Shuffle, sinkOp)
- new Stream[T](stream.graph, sinkOp)
- }
- }
-}
-
-class LoggerSink[T] extends DataSink {
- var logger: Logger = null
-
- private var context: TaskContext = null
-
- override def open(context: TaskContext): Unit = {
- this.logger = context.logger
- }
-
- override def write(message: Message): Unit = {
- logger.info("logging message " + message.msg)
- }
-
- override def close(): Unit = Unit
-}
\ No newline at end of file
[05/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/state/api/Serializer.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/state/api/Serializer.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/state/api/Serializer.scala
new file mode 100644
index 0000000..22aa897
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/state/api/Serializer.scala
@@ -0,0 +1,26 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.state.api
+
+import scala.util.Try
+
+trait Serializer[T] extends java.io.Serializable {
+ def serialize(t: T): Array[Byte]
+ def deserialize(bytes: Array[Byte]): Try[T]
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/state/impl/CheckpointManager.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/state/impl/CheckpointManager.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/state/impl/CheckpointManager.scala
new file mode 100644
index 0000000..82b7952
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/state/impl/CheckpointManager.scala
@@ -0,0 +1,64 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.state.impl
+
+import org.apache.gearpump.TimeStamp
+import org.apache.gearpump.streaming.transaction.api.CheckpointStore
+
+/** Manage physical checkpoints to persitent storage like HDFS */
+class CheckpointManager(checkpointInterval: Long,
+ checkpointStore: CheckpointStore) {
+
+ private var maxMessageTime: Long = 0L
+ private var checkpointTime: Option[Long] = None
+
+ def recover(timestamp: TimeStamp): Option[Array[Byte]] = {
+ checkpointStore.recover(timestamp)
+ }
+
+ def checkpoint(timestamp: TimeStamp, checkpoint: Array[Byte]): Option[TimeStamp] = {
+ checkpointStore.persist(timestamp, checkpoint)
+ checkpointTime = checkpointTime.collect { case time if maxMessageTime > time =>
+ time + (1 + (maxMessageTime - time) / checkpointInterval) * checkpointInterval
+ }
+
+ checkpointTime
+ }
+
+ def update(messageTime: TimeStamp): Option[TimeStamp] = {
+ maxMessageTime = Math.max(maxMessageTime, messageTime)
+ if (checkpointTime.isEmpty) {
+ checkpointTime = Some((1 + messageTime / checkpointInterval) * checkpointInterval)
+ }
+
+ checkpointTime
+ }
+
+ def shouldCheckpoint(upstreamMinClock: TimeStamp): Boolean = {
+ checkpointTime.exists(time => upstreamMinClock >= time)
+ }
+
+ def getCheckpointTime: Option[TimeStamp] = checkpointTime
+
+ def close(): Unit = {
+ checkpointStore.close()
+ }
+
+ private[impl] def getMaxMessageTime: TimeStamp = maxMessageTime
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/state/impl/InMemoryCheckpointStore.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/state/impl/InMemoryCheckpointStore.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/state/impl/InMemoryCheckpointStore.scala
new file mode 100644
index 0000000..753050e
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/state/impl/InMemoryCheckpointStore.scala
@@ -0,0 +1,50 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.state.impl
+
+import org.apache.gearpump.TimeStamp
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.task.TaskContext
+import org.apache.gearpump.streaming.transaction.api.{CheckpointStore, CheckpointStoreFactory}
+
+/**
+ * an in memory store provided for test
+ * should not be used in real cases
+ */
+class InMemoryCheckpointStore extends CheckpointStore {
+ private var checkpoints = Map.empty[TimeStamp, Array[Byte]]
+
+ override def persist(timestamp: TimeStamp, checkpoint: Array[Byte]): Unit = {
+ checkpoints += timestamp -> checkpoint
+ }
+
+ override def recover(timestamp: TimeStamp): Option[Array[Byte]] = {
+ checkpoints.get(timestamp)
+ }
+
+ override def close(): Unit = {
+ checkpoints = Map.empty[TimeStamp, Array[Byte]]
+ }
+}
+
+class InMemoryCheckpointStoreFactory extends CheckpointStoreFactory {
+ override def getCheckpointStore(conf: UserConfig, taskContext: TaskContext): CheckpointStore = {
+ new InMemoryCheckpointStore
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/state/impl/NonWindowState.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/state/impl/NonWindowState.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/state/impl/NonWindowState.scala
new file mode 100644
index 0000000..b161713
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/state/impl/NonWindowState.scala
@@ -0,0 +1,53 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.state.impl
+
+import org.slf4j.Logger
+
+import org.apache.gearpump.TimeStamp
+import org.apache.gearpump.streaming.state.api.{Monoid, MonoidState, Serializer}
+import org.apache.gearpump.streaming.state.impl.NonWindowState._
+import org.apache.gearpump.util.LogUtil
+
+object NonWindowState {
+ val LOG: Logger = LogUtil.getLogger(classOf[NonWindowState[_]])
+}
+
+/**
+ * a MonoidState storing non-window state
+ */
+class NonWindowState[T](monoid: Monoid[T], serializer: Serializer[T])
+ extends MonoidState[T](monoid) {
+
+ override def recover(timestamp: TimeStamp, bytes: Array[Byte]): Unit = {
+ serializer.deserialize(bytes).foreach(left = _)
+ }
+
+ override def update(timestamp: TimeStamp, t: T): Unit = {
+ updateState(timestamp, t)
+ }
+
+ override def checkpoint(): Array[Byte] = {
+ val serialized = serializer.serialize(left)
+ LOG.debug(s"checkpoint time: $checkpointTime; checkpoint value: ($checkpointTime, $left)")
+ left = monoid.plus(left, right)
+ right = monoid.zero
+ serialized
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/state/impl/PersistentStateConfig.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/state/impl/PersistentStateConfig.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/state/impl/PersistentStateConfig.scala
new file mode 100644
index 0000000..de2991f
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/state/impl/PersistentStateConfig.scala
@@ -0,0 +1,28 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.state.impl
+
+object PersistentStateConfig {
+
+ val STATE_CHECKPOINT_ENABLE = "state.checkpoint.enable"
+ val STATE_CHECKPOINT_INTERVAL_MS = "state.checkpoint.interval.ms"
+ val STATE_CHECKPOINT_STORE_FACTORY = "state.checkpoint.store.factory"
+ val STATE_WINDOW_SIZE = "state.window.size"
+ val STATE_WINDOW_STEP = "state.window.step"
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/state/impl/Window.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/state/impl/Window.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/state/impl/Window.scala
new file mode 100644
index 0000000..c1f647e
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/state/impl/Window.scala
@@ -0,0 +1,54 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.state.impl
+
+import org.apache.gearpump.TimeStamp
+
+/**
+ * Used in window applications
+ * it keeps the current window and slide ahead when the window expires
+ */
+class Window(val windowSize: Long, val windowStep: Long) {
+
+ def this(windowConfig: WindowConfig) = {
+ this(windowConfig.windowSize, windowConfig.windowStep)
+ }
+
+ private var clock: TimeStamp = 0L
+ private var startTime = 0L
+
+ def update(clock: TimeStamp): Unit = {
+ this.clock = clock
+ }
+
+ def slideOneStep(): Unit = {
+ startTime += windowStep
+ }
+
+ def slideTo(timestamp: TimeStamp): Unit = {
+ startTime = timestamp / windowStep * windowStep
+ }
+
+ def shouldSlide: Boolean = {
+ clock >= (startTime + windowSize)
+ }
+
+ def range: (TimeStamp, TimeStamp) = {
+ startTime -> (startTime + windowSize)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/state/impl/WindowConfig.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/state/impl/WindowConfig.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/state/impl/WindowConfig.scala
new file mode 100644
index 0000000..b053837
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/state/impl/WindowConfig.scala
@@ -0,0 +1,25 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.state.impl
+
+object WindowConfig {
+ val NAME = "window_config"
+}
+
+case class WindowConfig(windowSize: Long, windowStep: Long)
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/state/impl/WindowState.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/state/impl/WindowState.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/state/impl/WindowState.scala
new file mode 100644
index 0000000..348f09e
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/state/impl/WindowState.scala
@@ -0,0 +1,165 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.state.impl
+
+import scala.collection.immutable.TreeMap
+
+import org.slf4j.Logger
+
+import org.apache.gearpump.TimeStamp
+import org.apache.gearpump.streaming.state.api.{Group, MonoidState, Serializer}
+import org.apache.gearpump.streaming.state.impl.WindowState._
+import org.apache.gearpump.streaming.task.TaskContext
+import org.apache.gearpump.util.LogUtil
+
+/**
+ * an interval is a dynamic time range that is divided by window boundary and checkpoint time
+ */
+case class Interval(startTime: TimeStamp, endTime: TimeStamp) extends Ordered[Interval] {
+ override def compare(that: Interval): Int = {
+ if (startTime < that.startTime) -1
+ else if (startTime > that.startTime) 1
+ else 0
+ }
+}
+
+object WindowState {
+ val LOG: Logger = LogUtil.getLogger(classOf[WindowState[_]])
+}
+
+/**
+ * this is a list of states, each of which is bounded by a time window
+ * state of each window doesn't affect each other
+ *
+ * WindowState requires a Algebird Group to be passed in
+ * Group augments Monoid with a minus function which makes it
+ * possible to undo the update by messages that have left the window
+ */
+class WindowState[T](group: Group[T],
+ serializer: Serializer[TreeMap[Interval, T]],
+ taskContext: TaskContext,
+ window: Window) extends MonoidState[T](group) {
+ /**
+ * each interval has a state updated by message with timestamp in
+ * [interval.startTime, interval.endTime)
+ */
+ private var intervalStates = TreeMap.empty[Interval, T]
+
+ private var lastCheckpointTime = 0L
+
+ override def recover(timestamp: TimeStamp, bytes: Array[Byte]): Unit = {
+ window.slideTo(timestamp)
+ serializer.deserialize(bytes)
+ .foreach { states =>
+ intervalStates = states
+ left = states.foldLeft(left) { case (accum, iter) =>
+ group.plus(accum, iter._2)
+ }
+ }
+ }
+
+ override def update(timestamp: TimeStamp, t: T): Unit = {
+ val (startTime, endTime) = window.range
+ if (timestamp >= startTime && timestamp < endTime) {
+ updateState(timestamp, t)
+ }
+
+ updateIntervalStates(timestamp, t, checkpointTime)
+
+ val upstreamMinClock = taskContext.upstreamMinClock
+ window.update(upstreamMinClock)
+
+ if (window.shouldSlide) {
+ window.slideOneStep()
+
+ val (newStartTime, newEndTime) = window.range
+ getIntervalStates(startTime, newStartTime).foreach { case (_, st) =>
+ left = group.minus(left, st)
+ }
+ if (checkpointTime > endTime) {
+ getIntervalStates(endTime, checkpointTime).foreach { case (_, st) =>
+ left = group.plus(left, st)
+ }
+ } else {
+ getIntervalStates(endTime, newEndTime).foreach { case (_, st) =>
+ right = group.plus(right, st)
+ }
+ }
+ }
+ }
+
+ override def checkpoint(): Array[Byte] = {
+ left = group.plus(left, right)
+ right = group.zero
+
+ val states = getIntervalStates(window.range._1, checkpointTime)
+ lastCheckpointTime = checkpointTime
+ LOG.debug(s"checkpoint time: $checkpointTime; checkpoint value: ($checkpointTime, $states)")
+ serializer.serialize(states)
+ }
+
+ /**
+ * Each message will update state in corresponding Interval[StartTime, endTime),
+ *
+ * which is decided by the message's timestamp t where
+ * {{{
+ * startTime = Math.max(lowerBound1, lowerBound2, checkpointTime)
+ * endTime = Math.min(upperBound1, upperBound2, checkpointTime)
+ * lowerBound1 = step * Nmax1 <= t
+ * lowerBound2 = step * Nmax2 + size <= t
+ * upperBound1 = step * Nmin1 > t
+ * upperBound2 = step * Nmin2 + size > t
+ * }}}
+ */
+ private[impl] def getInterval(timestamp: TimeStamp, checkpointTime: TimeStamp): Interval = {
+ val windowSize = window.windowSize
+ val windowStep = window.windowStep
+ val lowerBound1 = timestamp / windowStep * windowStep
+ val lowerBound2 =
+ if (timestamp < windowSize) 0L
+ else (timestamp - windowSize) / windowStep * windowStep + windowSize
+ val upperBound1 = (timestamp / windowStep + 1) * windowStep
+ val upperBound2 =
+ if (timestamp < windowSize) windowSize
+ else ((timestamp - windowSize) / windowStep + 1) * windowStep + windowSize
+ val lowerBound = Math.max(lowerBound1, lowerBound2)
+ val upperBound = Math.min(upperBound1, upperBound2)
+ if (checkpointTime > timestamp) {
+ Interval(Math.max(lowerBound, lastCheckpointTime), Math.min(upperBound, checkpointTime))
+ } else {
+ Interval(Math.max(lowerBound, checkpointTime), upperBound)
+ }
+ }
+
+ private[impl] def updateIntervalStates(timestamp: TimeStamp, t: T, checkpointTime: TimeStamp)
+ : Unit = {
+ val interval = getInterval(timestamp, checkpointTime)
+ intervalStates.get(interval) match {
+ case Some(st) =>
+ intervalStates += interval -> group.plus(st, t)
+ case None =>
+ intervalStates += interval -> group.plus(group.zero, t)
+ }
+ }
+
+ private[impl] def getIntervalStates(startTime: TimeStamp, endTime: TimeStamp)
+ : TreeMap[Interval, T] = {
+ intervalStates.dropWhile(_._1.endTime <= startTime).takeWhile(_._1.endTime <= endTime)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/storage/AppDataStore.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/storage/AppDataStore.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/storage/AppDataStore.scala
new file mode 100644
index 0000000..1db9f6a
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/storage/AppDataStore.scala
@@ -0,0 +1,30 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.storage
+
+import scala.concurrent._
+
+/**
+ * Generic storage to store KV Data.
+ */
+trait AppDataStore {
+ def put(key: String, value: Any): Future[Any]
+
+ def get(key: String): Future[Any]
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/storage/InMemoryAppStoreOnMaster.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/storage/InMemoryAppStoreOnMaster.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/storage/InMemoryAppStoreOnMaster.scala
new file mode 100644
index 0000000..ce98216
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/storage/InMemoryAppStoreOnMaster.scala
@@ -0,0 +1,48 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.storage
+
+import scala.concurrent.Future
+
+import akka.actor.ActorRef
+import akka.pattern.ask
+
+import org.apache.gearpump.cluster.AppMasterToMaster.{GetAppData, GetAppDataResult, SaveAppData}
+import org.apache.gearpump.util.Constants
+
+/**
+ * In memory application storage located on master nodes
+ */
+class InMemoryAppStoreOnMaster(appId: Int, master: ActorRef) extends AppDataStore {
+ implicit val timeout = Constants.FUTURE_TIMEOUT
+ import scala.concurrent.ExecutionContext.Implicits.global
+
+ override def put(key: String, value: Any): Future[Any] = {
+ master.ask(SaveAppData(appId, key, value))
+ }
+
+ override def get(key: String): Future[Any] = {
+ master.ask(GetAppData(appId, key)).asInstanceOf[Future[GetAppDataResult]].map { result =>
+ if (result.key.equals(key)) {
+ result.value
+ } else {
+ null
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/task/ExpressTransport.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/task/ExpressTransport.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/task/ExpressTransport.scala
new file mode 100644
index 0000000..7629cf9
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/task/ExpressTransport.scala
@@ -0,0 +1,75 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.task
+
+import akka.actor.{ActorRef, ExtendedActorSystem}
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.transport.netty.TaskMessage
+import org.apache.gearpump.transport.{Express, HostPort}
+import org.apache.gearpump.util.AkkaHelper
+/**
+ * ExpressTransport wire the networking function from default akka
+ * networking to customized implementation [[org.apache.gearpump.transport.Express]].
+ *
+ * See [[org.apache.gearpump.transport.Express]] for more information.
+ */
+trait ExpressTransport {
+ this: TaskActor =>
+
+ final val express = Express(context.system)
+ implicit val system = context.system.asInstanceOf[ExtendedActorSystem]
+
+ final def local: HostPort = express.localHost
+ lazy val sourceId = TaskId.toLong(taskId)
+
+ lazy val sessionRef: ActorRef = {
+ AkkaHelper.actorFor(system, s"/session#$sessionId")
+ }
+
+ def transport(msg: AnyRef, remotes: TaskId*): Unit = {
+ var serializedMessage: AnyRef = null
+
+ remotes.foreach { remote =>
+ val transportId = TaskId.toLong(remote)
+ val localActor = express.lookupLocalActor(transportId)
+ if (localActor.isDefined) {
+ localActor.get.tell(msg, sessionRef)
+ } else {
+ if (null == serializedMessage) {
+ msg match {
+ case message: Message =>
+ val bytes = serializerPool.get().serialize(message.msg)
+ serializedMessage = SerializedMessage(message.timestamp, bytes)
+ case _ => serializedMessage = msg
+ }
+ }
+ val taskMessage = new TaskMessage(sessionId, transportId, sourceId, serializedMessage)
+
+ val remoteAddress = express.lookupRemoteAddress(transportId)
+ if (remoteAddress.isDefined) {
+ express.transport(taskMessage, remoteAddress.get)
+ } else {
+ LOG.error(
+ s"Can not find target task $remote, maybe the application is undergoing recovery")
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/task/SerializedMessage.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/task/SerializedMessage.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/task/SerializedMessage.scala
new file mode 100644
index 0000000..675d5cc
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/task/SerializedMessage.scala
@@ -0,0 +1,42 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.task
+
+import java.io.{DataInput, DataOutput}
+
+import org.apache.gearpump.TimeStamp
+
+case class SerializedMessage(timeStamp: TimeStamp, bytes: Array[Byte])
+
+class SerializedMessageSerializer extends TaskMessageSerializer[SerializedMessage] {
+ override def getLength(obj: SerializedMessage): Int = 12 + obj.bytes.length
+
+ override def write(dataOutput: DataOutput, obj: SerializedMessage): Unit = {
+ dataOutput.writeLong(obj.timeStamp)
+ dataOutput.writeInt(obj.bytes.length)
+ dataOutput.write(obj.bytes)
+ }
+
+ override def read(dataInput: DataInput): SerializedMessage = {
+ val timestamp = dataInput.readLong()
+ val length = dataInput.readInt()
+ val bytes = new Array[Byte](length)
+ dataInput.readFully(bytes)
+ SerializedMessage(timestamp, bytes)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/task/SerializerResolver.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/task/SerializerResolver.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/task/SerializerResolver.scala
new file mode 100644
index 0000000..4c7867b
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/task/SerializerResolver.scala
@@ -0,0 +1,47 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.task
+
+import io.gearpump.esotericsoftware.kryo.util.{IntMap, ObjectMap}
+import org.apache.gearpump.streaming.task.SerializerResolver.Registration
+
+private[task] class SerializerResolver {
+ private var classId = 0
+ private val idToRegistration = new IntMap[Registration]()
+ private val classToRegistration = new ObjectMap[Class[_], Registration]()
+
+ def register[T](clazz: Class[T], serializer: TaskMessageSerializer[T]): Unit = {
+ val registration = new Registration(classId, clazz, serializer)
+ idToRegistration.put(classId, registration)
+ classToRegistration.put(clazz, registration)
+ classId += 1
+ }
+
+ def getRegistration(clazz: Class[_]): Registration = {
+ classToRegistration.get(clazz)
+ }
+
+ def getRegistration(clazzId: Int): Registration = {
+ idToRegistration.get(clazzId)
+ }
+}
+
+object SerializerResolver {
+ class Registration(val id: Int, val clazz: Class[_], val serializer: TaskMessageSerializer[_])
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/task/StartTime.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/task/StartTime.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/task/StartTime.scala
new file mode 100644
index 0000000..fb097d3
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/task/StartTime.scala
@@ -0,0 +1,24 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.task
+
+import org.apache.gearpump.TimeStamp
+
+/** Start time of streaming application. All message older than start time will be dropped */
+case class StartTime(startTime: TimeStamp = 0)
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/task/StreamingTransportSerializer.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/task/StreamingTransportSerializer.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/task/StreamingTransportSerializer.scala
new file mode 100644
index 0000000..1bdc175
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/task/StreamingTransportSerializer.scala
@@ -0,0 +1,68 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.task
+
+import java.io.{DataInput, DataOutput}
+
+import org.slf4j.Logger
+
+import org.apache.gearpump.streaming.{AckRequestSerializer, AckSerializer, InitialAckRequestSerializer, LatencyProbeSerializer}
+import org.apache.gearpump.transport.netty.ITransportMessageSerializer
+import org.apache.gearpump.util.LogUtil
+
+class StreamingTransportSerializer extends ITransportMessageSerializer {
+ private val log: Logger = LogUtil.getLogger(getClass)
+ private val serializers = new SerializerResolver
+
+ serializers.register(classOf[Ack], new AckSerializer)
+ serializers.register(classOf[AckRequest], new AckRequestSerializer)
+ serializers.register(classOf[InitialAckRequest], new InitialAckRequestSerializer)
+ serializers.register(classOf[LatencyProbe], new LatencyProbeSerializer)
+ serializers.register(classOf[SerializedMessage], new SerializedMessageSerializer)
+
+ override def serialize(dataOutput: DataOutput, obj: Object): Unit = {
+ val registration = serializers.getRegistration(obj.getClass)
+ if (registration != null) {
+ dataOutput.writeInt(registration.id)
+ registration.serializer.asInstanceOf[TaskMessageSerializer[AnyRef]].write(dataOutput, obj)
+ } else {
+ log.error(s"Can not find serializer for class type ${obj.getClass}")
+ }
+ }
+
+ override def deserialize(dataInput: DataInput, length: Int): Object = {
+ val classID = dataInput.readInt()
+ val registration = serializers.getRegistration(classID)
+ if (registration != null) {
+ registration.serializer.asInstanceOf[TaskMessageSerializer[AnyRef]].read(dataInput)
+ } else {
+ log.error(s"Can not find serializer for class id $classID")
+ null
+ }
+ }
+
+ override def getLength(obj: Object): Int = {
+ val registration = serializers.getRegistration(obj.getClass)
+ if (registration != null) {
+ registration.serializer.asInstanceOf[TaskMessageSerializer[AnyRef]].getLength(obj) + 4
+ } else {
+ log.error(s"Can not find serializer for class type ${obj.getClass}")
+ 0
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/task/Subscriber.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/task/Subscriber.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/task/Subscriber.scala
new file mode 100644
index 0000000..692d7f9
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/task/Subscriber.scala
@@ -0,0 +1,58 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.task
+
+import org.apache.gearpump.partitioner.PartitionerDescription
+import org.apache.gearpump.streaming.{DAG, LifeTime}
+
+/**
+ * Each processor can have multiple downstream subscribers.
+ *
+ * For example: When processor A subscribe to processor B, then the output of B will be
+ * pushed to processor A.
+ *
+ * @param processorId subscriber processor Id
+ * @param partitionerDescription subscriber partitioner
+ */
+case class Subscriber(processorId: Int, partitionerDescription: PartitionerDescription,
+ parallelism: Int, lifeTime: LifeTime)
+
+object Subscriber {
+
+ /**
+ *
+ * List subscriptions of a processor.
+ * The topology information is retrieved from dag
+ *
+ * @param processorId the processor to list
+ * @param dag the DAG
+ * @return the subscribers of this processor
+ */
+ def of(processorId: Int, dag: DAG): List[Subscriber] = {
+ val edges = dag.graph.outgoingEdgesOf(processorId)
+
+ edges.foldLeft(List.empty[Subscriber]) { (list, nodeEdgeNode) =>
+ val (_, partitioner, downstreamProcessorId) = nodeEdgeNode
+ val downstreamProcessor = dag.processors(downstreamProcessorId)
+ list :+ Subscriber(downstreamProcessorId, partitioner,
+ downstreamProcessor.parallelism, downstreamProcessor.life)
+ }
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/task/Subscription.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/task/Subscription.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/task/Subscription.scala
new file mode 100644
index 0000000..9accae2
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/task/Subscription.scala
@@ -0,0 +1,235 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.task
+
+import org.slf4j.Logger
+
+import io.gearpump.google.common.primitives.Shorts
+import org.apache.gearpump.partitioner.{MulticastPartitioner, Partitioner, UnicastPartitioner}
+import org.apache.gearpump.streaming.AppMasterToExecutor.MsgLostException
+import org.apache.gearpump.streaming.LifeTime
+import org.apache.gearpump.streaming.task.Subscription._
+import org.apache.gearpump.util.LogUtil
+import org.apache.gearpump.{Message, TimeStamp}
+
+/**
+ * Manges the output and message clock for single downstream processor
+ *
+ * @param subscriber downstream processor
+ * @param maxPendingMessageCount trigger flow control. Should be bigger than
+ * maxPendingMessageCountPerAckRequest
+ * @param ackOnceEveryMessageCount send on AckRequest to the target
+ */
+class Subscription(
+ appId: Int,
+ executorId: Int,
+ taskId: TaskId,
+ subscriber: Subscriber, sessionId: Int,
+ transport: ExpressTransport,
+ maxPendingMessageCount: Int = MAX_PENDING_MESSAGE_COUNT,
+ ackOnceEveryMessageCount: Int = ONE_ACKREQUEST_EVERY_MESSAGE_COUNT) {
+
+ assert(maxPendingMessageCount >= ackOnceEveryMessageCount)
+ assert(maxPendingMessageCount < Short.MaxValue / 2)
+
+ private val LOG: Logger = LogUtil.getLogger(getClass, app = appId,
+ executor = executorId, task = taskId)
+
+ import subscriber.{parallelism, partitionerDescription, processorId}
+
+ // Don't worry if this store negative number. We will wrap the Short
+ private val messageCount: Array[Short] = new Array[Short](parallelism)
+ private val pendingMessageCount: Array[Short] = new Array[Short](parallelism)
+ private val candidateMinClockSince: Array[Short] = new Array[Short](parallelism)
+
+ private val minClockValue: Array[TimeStamp] = Array.fill(parallelism)(Long.MaxValue)
+ private val candidateMinClock: Array[TimeStamp] = Array.fill(parallelism)(Long.MaxValue)
+
+ private var maxPendingCount: Short = 0
+
+ private var life = subscriber.lifeTime
+
+ private val partitioner = partitionerDescription.partitionerFactory.partitioner
+ private val sendFn = partitioner match {
+ case up: UnicastPartitioner =>
+ (msg: Message) => {
+ val partition = up.getPartition(msg, parallelism, taskId.index)
+ sendMessage(msg, partition)
+ }
+ case mp: MulticastPartitioner =>
+ (msg: Message) => {
+ val partitions = mp.getPartitions(msg, parallelism, taskId.index)
+ partitions.map(partition => sendMessage(msg, partition)).sum
+ }
+ }
+
+ def changeLife(life: LifeTime): Unit = {
+ this.life = life
+ }
+
+ def start(): Unit = {
+ val ackRequest = InitialAckRequest(taskId, sessionId)
+ transport.transport(ackRequest, allTasks: _*)
+ }
+
+ def sendMessage(msg: Message): Int = {
+ sendFn(msg)
+ }
+
+ /**
+ * Returns how many message is actually sent by this subscription
+ *
+ * @param msg the message to send
+ * @param partition the target partition to send message to
+ * @return 1 if success
+ */
+ def sendMessage(msg: Message, partition: Int): Int = {
+
+ var count = 0
+ // Only sends message whose timestamp matches the lifeTime
+ if (partition != Partitioner.UNKNOWN_PARTITION_ID && life.contains(msg.timestamp)) {
+
+ val targetTask = TaskId(processorId, partition)
+ transport.transport(msg, targetTask)
+
+ this.minClockValue(partition) = Math.min(this.minClockValue(partition), msg.timestamp)
+ this.candidateMinClock(partition) = Math.min(this.candidateMinClock(partition), msg.timestamp)
+
+ incrementMessageCount(partition, 1)
+
+ if (messageCount(partition) % ackOnceEveryMessageCount == 0) {
+ sendAckRequest(partition)
+ }
+
+ if (messageCount(partition) / maxPendingMessageCount !=
+ (messageCount(partition) + ackOnceEveryMessageCount) / maxPendingMessageCount) {
+ sendLatencyProbe(partition)
+ }
+ count = 1
+ count
+ } else {
+ if (needFlush) {
+ flush()
+ }
+ count = 0
+ count
+ }
+ }
+
+ private var lastFlushTime: Long = 0L
+ private val FLUSH_INTERVAL = 5 * 1000 // ms
+ private def needFlush: Boolean = {
+ System.currentTimeMillis() - lastFlushTime > FLUSH_INTERVAL &&
+ Shorts.max(pendingMessageCount: _*) > 0
+ }
+
+ private def flush(): Unit = {
+ lastFlushTime = System.currentTimeMillis()
+ allTasks.foreach { targetTaskId =>
+ sendAckRequest(targetTaskId.index)
+ }
+ }
+
+ private def allTasks: scala.collection.Seq[TaskId] = {
+ (0 until parallelism).map { taskIndex =>
+ TaskId(processorId, taskIndex)
+ }
+ }
+
+ /**
+ * Handles acknowledge message. Throw MessageLossException if required.
+ *
+ * @param ack acknowledge message received
+ */
+ def receiveAck(ack: Ack): Unit = {
+
+ val index = ack.taskId.index
+
+ if (ack.sessionId == sessionId) {
+ if (ack.actualReceivedNum == ack.seq) {
+ if ((ack.seq - candidateMinClockSince(index)).toShort >= 0) {
+ if (ack.seq == messageCount(index)) {
+ // All messages have been acked.
+ minClockValue(index) = Long.MaxValue
+ } else {
+ minClockValue(index) = candidateMinClock(index)
+ }
+ candidateMinClock(index) = Long.MaxValue
+ candidateMinClockSince(index) = messageCount(index)
+ }
+
+ pendingMessageCount(ack.taskId.index) = (messageCount(ack.taskId.index) - ack.seq).toShort
+ updateMaxPendingCount()
+ } else {
+ LOG.error(s"Failed! received ack: $ack, received: ${ack.actualReceivedNum}, " +
+ s"sent: ${ack.seq}, try to replay...")
+ throw new MsgLostException
+ }
+ }
+ }
+
+ def minClock: TimeStamp = {
+ minClockValue.min
+ }
+
+ def allowSendingMoreMessages(): Boolean = {
+ maxPendingCount < maxPendingMessageCount
+ }
+
+ def sendAckRequestOnStallingTime(stallingTime: TimeStamp): Unit = {
+ minClockValue.indices.foreach { i =>
+ if (minClockValue(i) == stallingTime && pendingMessageCount(i) > 0
+ && allowSendingMoreMessages) {
+ sendAckRequest(i)
+ sendLatencyProbe(i)
+ }
+ }
+ }
+
+ private def sendAckRequest(partition: Int): Unit = {
+ // Increments more count for each AckRequest
+ // to throttle the number of unacked AckRequest
+ incrementMessageCount(partition, ackOnceEveryMessageCount)
+ val targetTask = TaskId(processorId, partition)
+ val ackRequest = AckRequest(taskId, messageCount(partition), sessionId)
+ transport.transport(ackRequest, targetTask)
+ }
+
+ private def incrementMessageCount(partition: Int, count: Int): Unit = {
+ messageCount(partition) = (messageCount(partition) + count).toShort
+ pendingMessageCount(partition) = (pendingMessageCount(partition) + count).toShort
+ updateMaxPendingCount()
+ }
+
+ private def updateMaxPendingCount(): Unit = {
+ maxPendingCount = Shorts.max(pendingMessageCount: _*)
+ }
+
+ private def sendLatencyProbe(partition: Int): Unit = {
+ val probeLatency = LatencyProbe(System.currentTimeMillis())
+ val targetTask = TaskId(processorId, partition)
+ transport.transport(probeLatency, targetTask)
+ }
+}
+
+object Subscription {
+ // Makes sure it is smaller than MAX_PENDING_MESSAGE_COUNT
+ final val ONE_ACKREQUEST_EVERY_MESSAGE_COUNT = 100
+ final val MAX_PENDING_MESSAGE_COUNT = 1000
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/task/Task.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/task/Task.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/task/Task.scala
new file mode 100644
index 0000000..9c76a40
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/task/Task.scala
@@ -0,0 +1,189 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.task
+
+import scala.concurrent.duration.FiniteDuration
+
+import akka.actor.Actor.Receive
+import akka.actor.{ActorRef, ActorSystem, Cancellable, Props}
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.util.LogUtil
+import org.apache.gearpump.{Message, TimeStamp}
+
+/**
+ * This provides context information for a task.
+ */
+trait TaskContext {
+
+ def taskId: TaskId
+
+ def executorId: Int
+
+ def appId: Int
+
+ def appName: String
+
+ /**
+ * The actorRef of AppMaster
+ * @return application master's actor reference
+ */
+ def appMaster: ActorRef
+
+ /**
+ * The task parallelism
+ *
+ * For example, we can create 3 source tasks, and 3 sink tasks,
+ * the task parallelism is 3 for each.
+ *
+ * This can be useful when reading from partitioned data source.
+ * For example, for kafka, there may be 10 partitions, if we have
+ * parallelism of 2 for this task, then each task will be responsible
+ * to read data from 5 partitions.
+ *
+ * @return the parallelism level
+ */
+ def parallelism: Int
+
+ /**
+ * Please don't use this if possible.
+ * @return self actor ref
+ */
+ // TODO: We should remove the self from TaskContext
+ def self: ActorRef
+
+ /**
+ * Please don't use this if possible
+ * @return the actor system
+ */
+ // TODO: we should remove this in future
+ def system: ActorSystem
+
+ /**
+ * This can be used to output messages to downstream tasks. The data shuffling rule
+ * can be decided by Partitioner.
+ *
+ * @param msg message to output
+ */
+ def output(msg: Message): Unit
+
+ def actorOf(props: Props): ActorRef
+
+ def actorOf(props: Props, name: String): ActorRef
+
+ def schedule(initialDelay: FiniteDuration, interval: FiniteDuration)(f: => Unit): Cancellable
+
+ /**
+ * akka.actor.ActorRefProvider.scheduleOnce
+ *
+ * @param initialDelay the initial delay
+ * @param f the function to execute after initial delay
+ * @return the executable
+ */
+ def scheduleOnce(initialDelay: FiniteDuration)(f: => Unit): Cancellable
+
+ /**
+ * For managed message(type of Message), the sender only serve as a unique Id,
+ * It's address is not something meaningful, you should not use this directly
+ *
+ * For unmanaged message, the sender represent the sender ActorRef
+ * @return sender
+ */
+ def sender: ActorRef
+
+ /**
+ * Retrieves upstream min clock from TaskActor
+ *
+ * @return the min clock
+ */
+ def upstreamMinClock: TimeStamp
+
+ /**
+ * Logger is environment dependant, it should be provided by
+ * containing environment.
+ */
+ def logger: Logger
+}
+
+/**
+ * Streaming Task interface
+ */
+trait TaskInterface {
+
+ /**
+ * Method called with the task is initialized.
+ * @param startTime startTime that can be used to decide from when a source producer task should
+ * replay the data source, or from when a processor task should recover its
+ * checkpoint data in to in-memory state.
+ */
+ def onStart(startTime: StartTime): Unit
+
+ /**
+ * Method called for each message received.
+ *
+ * @param msg Message send by upstream tasks
+ */
+ def onNext(msg: Message): Unit
+
+ /**
+ * Method called when task is under clean up.
+ *
+ * This can be used to cleanup resource when the application finished.
+ */
+ def onStop(): Unit
+
+ /**
+ * Handlers unmanaged messages
+ *
+ * @return the handler
+ */
+ def receiveUnManagedMessage: Receive = null
+}
+
+abstract class Task(taskContext: TaskContext, userConf: UserConfig) extends TaskInterface {
+
+ import taskContext.{appId, executorId, taskId}
+
+ val LOG: Logger = LogUtil.getLogger(getClass, app = appId, executor = executorId, task = taskId)
+
+ protected implicit val system = taskContext.system
+
+ implicit val self = taskContext.self
+
+ /**
+ * For managed message(type of Message), the sender mean nothing,
+ * you should not use this directory
+ *
+ * For unmanaged message, the sender represent the sender actor
+ * @return the sender
+ */
+ protected def sender: ActorRef = taskContext.sender
+
+ def onStart(startTime: StartTime): Unit = {}
+
+ def onNext(msg: Message): Unit = {}
+
+ def onStop(): Unit = {}
+
+ override def receiveUnManagedMessage: Receive = {
+ case msg =>
+ LOG.error("Failed! Received unknown message " + "taskId: " + taskId + ", " + msg.toString)
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/task/TaskActor.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/task/TaskActor.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/task/TaskActor.scala
new file mode 100644
index 0000000..14742d0
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/task/TaskActor.scala
@@ -0,0 +1,397 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.task
+
+import java.util
+import java.util.concurrent.TimeUnit
+
+import akka.actor._
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.UserConfig
+import io.gearpump.gs.collections.impl.map.mutable.primitive.IntShortHashMap
+import org.apache.gearpump.metrics.Metrics
+import org.apache.gearpump.serializer.SerializationFramework
+import org.apache.gearpump.streaming.AppMasterToExecutor._
+import org.apache.gearpump.streaming.ExecutorToAppMaster._
+import org.apache.gearpump.streaming.{Constants, ProcessorId}
+import org.apache.gearpump.util.{LogUtil, TimeOutScheduler}
+import org.apache.gearpump.{Message, TimeStamp}
+
+/**
+ *
+ * All tasks of Gearpump runs inside a Actor. TaskActor is the Actor container for a task.
+ */
+class TaskActor(
+ val taskId: TaskId,
+ val taskContextData: TaskContextData,
+ userConf: UserConfig,
+ val task: TaskWrapper,
+ inputSerializerPool: SerializationFramework)
+ extends Actor with ExpressTransport with TimeOutScheduler {
+ var upstreamMinClock: TimeStamp = 0L
+ private var _minClock: TimeStamp = 0L
+
+ def serializerPool: SerializationFramework = inputSerializerPool
+
+ import taskContextData._
+
+ import org.apache.gearpump.streaming.Constants._
+ import org.apache.gearpump.streaming.task.TaskActor._
+ val config = context.system.settings.config
+
+ val LOG: Logger = LogUtil.getLogger(getClass, app = appId, executor = executorId, task = taskId)
+
+ // Metrics
+ private val metricName = s"app${appId}.processor${taskId.processorId}.task${taskId.index}"
+ private val receiveLatency = Metrics(context.system).histogram(
+ s"$metricName:receiveLatency", sampleRate = 1)
+ private val processTime = Metrics(context.system).histogram(s"$metricName:processTime")
+ private val sendThroughput = Metrics(context.system).meter(s"$metricName:sendThroughput")
+ private val receiveThroughput = Metrics(context.system).meter(s"$metricName:receiveThroughput")
+
+ private val maxPendingMessageCount = config.getInt(GEARPUMP_STREAMING_MAX_PENDING_MESSAGE_COUNT)
+ private val ackOnceEveryMessageCount = config.getInt(
+ GEARPUMP_STREAMING_ACK_ONCE_EVERY_MESSAGE_COUNT)
+
+ private val executor = context.parent
+ private var life = taskContextData.life
+
+ // Latency probe
+ import scala.concurrent.duration._
+
+ import context.dispatcher
+ final val LATENCY_PROBE_INTERVAL = FiniteDuration(1, TimeUnit.SECONDS)
+
+ // Clock report interval
+ final val CLOCK_REPORT_INTERVAL = FiniteDuration(1, TimeUnit.SECONDS)
+
+ // Flush interval
+ final val FLUSH_INTERVAL = FiniteDuration(100, TimeUnit.MILLISECONDS)
+
+ private val queue = new util.LinkedList[AnyRef]()
+
+ private var subscriptions = List.empty[(Int, Subscription)]
+
+ // SecurityChecker will be responsible of dropping messages from
+ // unknown sources
+ private val securityChecker = new SecurityChecker(taskId, self)
+ private[task] var sessionId = NONE_SESSION
+
+ // Reports to appMaster with my address
+ express.registerLocalActor(TaskId.toLong(taskId), self)
+
+ final def receive: Receive = null
+
+ task.setTaskActor(this)
+
+ def onStart(startTime: StartTime): Unit = {
+ task.onStart(startTime)
+ }
+
+ def onNext(msg: Message): Unit = task.onNext(msg)
+
+ def onUnManagedMessage(msg: Any): Unit = task.receiveUnManagedMessage.apply(msg)
+
+ def onStop(): Unit = task.onStop()
+
+ /**
+ * output to a downstream by specifying a arrayIndex
+ * @param arrayIndex this is not same as ProcessorId
+ */
+ def output(arrayIndex: Int, msg: Message): Unit = {
+ var count = 0
+ count += this.subscriptions(arrayIndex)._2.sendMessage(msg)
+ sendThroughput.mark(count)
+ }
+
+ def output(msg: Message): Unit = {
+ var count = 0
+ this.subscriptions.foreach { subscription =>
+ count += subscription._2.sendMessage(msg)
+ }
+ sendThroughput.mark(count)
+ }
+
+ final override def postStop(): Unit = {
+ onStop()
+ }
+
+ final override def preStart(): Unit = {
+ val register = RegisterTask(taskId, executorId, local)
+ LOG.info(s"$register")
+ executor ! register
+ context.become(waitForTaskRegistered)
+ }
+
+ private def allowSendingMoreMessages(): Boolean = {
+ subscriptions.forall(_._2.allowSendingMoreMessages())
+ }
+
+ private def doHandleMessage(): Unit = {
+ var done = false
+
+ var count = 0
+ val start = System.currentTimeMillis()
+
+ while (allowSendingMoreMessages() && !done) {
+ val msg = queue.poll()
+ if (msg != null) {
+ msg match {
+ case SendAck(ack, targetTask) =>
+ transport(ack, targetTask)
+ case m: Message =>
+ count += 1
+ onNext(m)
+ case other =>
+ // un-managed message
+ onUnManagedMessage(other)
+ }
+ } else {
+ done = true
+ }
+ }
+
+ receiveThroughput.mark(count)
+ if (count > 0) {
+ processTime.update((System.currentTimeMillis() - start) / count)
+ }
+ }
+
+ private def onStartClock(): Unit = {
+ LOG.info(s"received start, clock: $upstreamMinClock, sessionId: $sessionId")
+ subscriptions = subscribers.map { subscriber =>
+ (subscriber.processorId,
+ new Subscription(appId, executorId, taskId, subscriber, sessionId, this,
+ maxPendingMessageCount, ackOnceEveryMessageCount))
+ }.sortBy(_._1)
+
+ subscriptions.foreach(_._2.start())
+
+ import scala.collection.JavaConverters._
+ stashQueue.asScala.foreach { item =>
+ handleMessages(item.sender).apply(item.msg)
+ }
+ stashQueue.clear()
+
+ // Put this as the last step so that the subscription is already initialized.
+ // Message sending in current Task before onStart will not be delivered to
+ // target
+ onStart(new StartTime(upstreamMinClock))
+
+ appMaster ! GetUpstreamMinClock(taskId)
+ context.become(handleMessages(sender))
+ }
+
+ def waitForTaskRegistered: Receive = {
+ case start@TaskRegistered(_, sessionId, startClock) =>
+ this.sessionId = sessionId
+ this.upstreamMinClock = startClock
+ context.become(waitForStartClock)
+ }
+
+ private val stashQueue = new util.LinkedList[MessageAndSender]()
+
+ def waitForStartClock: Receive = {
+ case start: StartTask =>
+ onStartClock()
+ case other: AnyRef =>
+ stashQueue.add(MessageAndSender(other, sender()))
+ }
+
+ def handleMessages(sender: => ActorRef): Receive = {
+ case ackRequest: InitialAckRequest =>
+ val ackResponse = securityChecker.handleInitialAckRequest(ackRequest)
+ if (null != ackResponse) {
+ queue.add(SendAck(ackResponse, ackRequest.taskId))
+ doHandleMessage()
+ }
+ case ackRequest: AckRequest =>
+ // Enqueue to handle the ackRequest and send back ack later
+ val ackResponse = securityChecker.generateAckResponse(ackRequest, sender,
+ ackOnceEveryMessageCount)
+ if (null != ackResponse) {
+ queue.add(SendAck(ackResponse, ackRequest.taskId))
+ doHandleMessage()
+ }
+ case ack: Ack =>
+ subscriptions.find(_._1 == ack.taskId.processorId).foreach(_._2.receiveAck(ack))
+ doHandleMessage()
+ case inputMessage: SerializedMessage =>
+ val message = Message(serializerPool.get().deserialize(inputMessage.bytes),
+ inputMessage.timeStamp)
+ receiveMessage(message, sender)
+ case inputMessage: Message =>
+ receiveMessage(inputMessage, sender)
+ case upstream@UpstreamMinClock(upstreamClock) =>
+ this.upstreamMinClock = upstreamClock
+
+ val subMinClock = subscriptions.foldLeft(Long.MaxValue) { (min, sub) =>
+ val subMin = sub._2.minClock
+ // A subscription is holding back the _minClock;
+ // we send AckRequest to its tasks to push _minClock forward
+ if (subMin == _minClock) {
+ sub._2.sendAckRequestOnStallingTime(_minClock)
+ }
+ Math.min(min, subMin)
+ }
+
+ _minClock = Math.max(life.birth, Math.min(upstreamMinClock, subMinClock))
+
+ val update = UpdateClock(taskId, _minClock)
+ context.system.scheduler.scheduleOnce(CLOCK_REPORT_INTERVAL) {
+ appMaster ! update
+ }
+
+ // Checks whether current task is dead.
+ if (_minClock > life.death) {
+ // There will be no more message received...
+ val unRegister = UnRegisterTask(taskId, executorId)
+ executor ! unRegister
+
+ LOG.info(s"Sending $unRegister, current minclock: ${_minClock}, life: $life")
+ }
+
+ case ChangeTask(_, dagVersion, life, subscribers) =>
+ this.life = life
+ subscribers.foreach { subscriber =>
+ val processorId = subscriber.processorId
+ val subscription = getSubscription(processorId)
+ subscription match {
+ case Some(subscription) =>
+ subscription.changeLife(subscriber.lifeTime cross this.life)
+ case None =>
+ val subscription = new Subscription(appId, executorId, taskId, subscriber,
+ sessionId, this, maxPendingMessageCount, ackOnceEveryMessageCount)
+ subscription.start()
+ subscriptions :+=(subscriber.processorId, subscription)
+ // Sorting, keep the order
+ subscriptions = subscriptions.sortBy(_._1)
+ }
+ }
+ sender ! TaskChanged(taskId, dagVersion)
+ case LatencyProbe(timeStamp) =>
+ receiveLatency.update(System.currentTimeMillis() - timeStamp)
+ case send: SendMessageLoss =>
+ LOG.info("received SendMessageLoss")
+ throw new MsgLostException
+ case other: AnyRef =>
+ queue.add(other)
+ doHandleMessage()
+ }
+
+ /**
+ * Returns min clock of this task
+ */
+ def minClock: TimeStamp = _minClock
+
+ /**
+ * Returns min clock of upstream task
+ */
+ def getUpstreamMinClock: TimeStamp = upstreamMinClock
+
+ private def receiveMessage(msg: Message, sender: ActorRef): Unit = {
+ val messageAfterCheck = securityChecker.checkMessage(msg, sender)
+ messageAfterCheck match {
+ case Some(msg) =>
+ queue.add(msg)
+ doHandleMessage()
+ case None =>
+ // TODO: Indicate the error and avoid the LOG flood
+ // LOG.error(s"Task $taskId drop message $msg")
+ }
+ }
+
+ private def getSubscription(processorId: ProcessorId): Option[Subscription] = {
+ subscriptions.find(_._1 == processorId).map(_._2)
+ }
+}
+
+object TaskActor {
+ // 3 seconds
+ val CLOCK_SYNC_TIMEOUT_INTERVAL = 3 * 1000
+
+ // If the message comes from an unknown source, securityChecker will drop it
+ class SecurityChecker(task_id: TaskId, self: ActorRef) {
+
+ private val LOG: Logger = LogUtil.getLogger(getClass, task = task_id)
+
+ // Uses mutable HashMap for performance optimization
+ private val receivedMsgCount = new IntShortHashMap()
+
+ // Tricky performance optimization to save memory.
+ // We store the session Id in the uid of ActorPath
+ // ActorPath.hashCode is same as uid.
+ private def getSessionId(actor: ActorRef): Int = {
+ // TODO: As method uid is protected in [akka] package. We
+ // are using hashCode instead of uid.
+ actor.hashCode()
+ }
+
+ def handleInitialAckRequest(ackRequest: InitialAckRequest): Ack = {
+ LOG.debug(s"Handle InitialAckRequest for session $ackRequest")
+ val sessionId = ackRequest.sessionId
+ if (sessionId == NONE_SESSION) {
+ LOG.error(s"SessionId is not initialized, ackRequest: $ackRequest")
+ null
+ } else {
+ receivedMsgCount.put(sessionId, 0)
+ Ack(task_id, 0, 0, sessionId)
+ }
+ }
+
+ def generateAckResponse(ackRequest: AckRequest, sender: ActorRef, incrementCount: Int): Ack = {
+ val sessionId = ackRequest.sessionId
+ if (receivedMsgCount.containsKey(sessionId)) {
+ // Increments more count for each AckRequest
+ // to throttle the number of unacked AckRequest
+ receivedMsgCount.put(sessionId, (receivedMsgCount.get(sessionId) + incrementCount).toShort)
+ Ack(task_id, ackRequest.seq, receivedMsgCount.get(sessionId), ackRequest.sessionId)
+ } else {
+ LOG.error(s"get unknown AckRequest $ackRequest from ${sender.toString()}")
+ null
+ }
+ }
+
+ // If the message comes from an unknown source, then drop it
+ def checkMessage(message: Message, sender: ActorRef): Option[Message] = {
+ if (sender.equals(self)) {
+ Some(message)
+ } else {
+ val sessionId = getSessionId(sender)
+ if (receivedMsgCount.containsKey(sessionId)) {
+ receivedMsgCount.put(sessionId, (receivedMsgCount.get(sessionId) + 1).toShort)
+ Some(message)
+ } else {
+ // This is an illegal message,
+ LOG.debug(s"received message before receive the first AckRequest, session $sessionId")
+ None
+ }
+ }
+ }
+ }
+
+ case class SendAck(ack: Ack, targetTask: TaskId)
+
+ case object FLUSH
+
+ val NONE_SESSION = -1
+
+ case class MessageAndSender(msg: AnyRef, sender: ActorRef)
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/task/TaskContextData.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/task/TaskContextData.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/task/TaskContextData.scala
new file mode 100644
index 0000000..0d12bc9
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/task/TaskContextData.scala
@@ -0,0 +1,32 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.task
+
+import akka.actor.ActorRef
+
+import org.apache.gearpump.streaming.LifeTime
+
+case class TaskContextData(
+ executorId: Int,
+ appId: Int,
+ appName: String,
+ appMaster: ActorRef,
+ parallelism: Int,
+ life: LifeTime,
+ subscribers: List[Subscriber])
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/task/TaskControlMessage.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/task/TaskControlMessage.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/task/TaskControlMessage.scala
new file mode 100644
index 0000000..e537f99
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/task/TaskControlMessage.scala
@@ -0,0 +1,72 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.task
+
+import org.apache.gearpump.TimeStamp
+import org.apache.gearpump.streaming.ProcessorId
+
+/*
+ * Initial AckRequest
+ */
+case class InitialAckRequest(taskId: TaskId, sessionId: Int)
+
+/*
+ Here the sessionId filed is used to distinguish messages
+ between different replays after the application restart
+ */
+case class AckRequest(taskId: TaskId, seq: Short, sessionId: Int)
+
+/**
+ * Ack back to sender task actor.
+ *
+ * @param seq The seq field represents the expected number of received messages and the
+ * actualReceivedNum field means the actual received number since start.
+ */
+case class Ack(taskId: TaskId, seq: Short, actualReceivedNum: Short, sessionId: Int)
+
+sealed trait ClockEvent
+
+case class UpdateClock(taskId: TaskId, time: TimeStamp) extends ClockEvent
+
+object GetLatestMinClock extends ClockEvent
+
+case class GetUpstreamMinClock(taskId: TaskId) extends ClockEvent
+
+case class UpstreamMinClock(latestMinClock: TimeStamp)
+
+case class LatestMinClock(clock: TimeStamp)
+
+case class ReportCheckpointClock(taskId: TaskId, clock: TimeStamp)
+
+case object GetCheckpointClock
+
+case class CheckpointClock(clock: Option[TimeStamp])
+
+case object GetStartClock
+
+case class StartClock(clock: TimeStamp)
+
+/** Probe the latency between two upstream to downstream tasks. */
+case class LatencyProbe(timestamp: Long)
+
+case class SendMessageLoss()
+
+case object GetDAG
+
+case class CheckProcessorDeath(processorId: ProcessorId)
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/task/TaskId.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/task/TaskId.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/task/TaskId.scala
new file mode 100644
index 0000000..b44293c
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/task/TaskId.scala
@@ -0,0 +1,28 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.task
+
+import org.apache.gearpump.streaming._
+
+case class TaskId(processorId: ProcessorId, index: TaskIndex)
+
+object TaskId {
+ def toLong(id: TaskId): Long = (id.processorId.toLong << 32) + id.index
+ def fromLong(id: Long): TaskId = TaskId(((id >> 32) & 0xFFFFFFFF).toInt, (id & 0xFFFFFFFF).toInt)
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/task/TaskMessageSerializer.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/task/TaskMessageSerializer.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/task/TaskMessageSerializer.scala
new file mode 100644
index 0000000..591dd46
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/task/TaskMessageSerializer.scala
@@ -0,0 +1,28 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.task
+
+import java.io.{DataInput, DataOutput}
+
+trait TaskMessageSerializer[T] {
+ def write(dataOutput: DataOutput, obj: T)
+
+ def read(dataInput: DataInput): T
+
+ def getLength(obj: T): Int
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/task/TaskUtil.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/task/TaskUtil.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/task/TaskUtil.scala
new file mode 100644
index 0000000..7459c64
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/task/TaskUtil.scala
@@ -0,0 +1,33 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.task
+
+object TaskUtil {
+
+ /**
+ * Resolves a classname to a Task class.
+ *
+ * @param className the class name to resolve
+ * @return resolved class
+ */
+ def loadClass(className: String): Class[_ <: Task] = {
+ val loader = Thread.currentThread().getContextClassLoader()
+ loader.loadClass(className).asSubclass(classOf[Task])
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/task/TaskWrapper.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/task/TaskWrapper.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/task/TaskWrapper.scala
new file mode 100644
index 0000000..cd33f7e
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/task/TaskWrapper.scala
@@ -0,0 +1,134 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.task
+
+import scala.concurrent.duration.FiniteDuration
+
+import akka.actor.Actor._
+import akka.actor.{ActorRef, ActorSystem, Cancellable, Props}
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.util.LogUtil
+import org.apache.gearpump.{Message, TimeStamp}
+
+/**
+ * This provides TaskContext for user defined tasks
+ *
+ * @param taskClass task class
+ * @param context context class
+ * @param userConf user config
+ */
+class TaskWrapper(
+ val taskId: TaskId, taskClass: Class[_ <: Task], context: TaskContextData,
+ userConf: UserConfig) extends TaskContext with TaskInterface {
+
+ private val LOG = LogUtil.getLogger(taskClass, task = taskId)
+
+ private var actor: TaskActor = null
+
+ private var task: Option[Task] = None
+
+ def setTaskActor(actor: TaskActor): Unit = this.actor = actor
+
+ override def appId: Int = context.appId
+
+ override def appName: String = context.appName
+
+ override def executorId: Int = context.executorId
+
+ override def parallelism: Int = context.parallelism
+
+ override def appMaster: ActorRef = context.appMaster
+
+ override def output(msg: Message): Unit = actor.output(msg)
+
+ /**
+ * See [[org.apache.gearpump.streaming.task.TaskActor]]
+ * output(arrayIndex: Int, msg: Message): Unit
+ *
+ * @param index, not same as ProcessorId
+ */
+ def output(index: Int, msg: Message): Unit = actor.output(index, msg)
+
+ /**
+ * Use with caution, output unmanaged message to target tasks
+ *
+ * @param msg message to output
+ * @param tasks the tasks to output to
+ */
+ def outputUnManaged(msg: AnyRef, tasks: TaskId*): Unit = {
+ actor.transport(msg, tasks: _*)
+ }
+
+ override def self: ActorRef = actor.context.self
+
+ override def sender: ActorRef = actor.context.sender()
+
+ def system: ActorSystem = actor.context.system
+
+ override def actorOf(props: Props): ActorRef = actor.context.actorOf(props)
+
+ override def actorOf(props: Props, name: String): ActorRef = actor.context.actorOf(props, name)
+
+ override def onStart(startTime: StartTime): Unit = {
+ if (None != task) {
+ LOG.error(s"Task.onStart should not be called multiple times... ${task.getClass}")
+ }
+ val constructor = taskClass.getConstructor(classOf[TaskContext], classOf[UserConfig])
+ task = Some(constructor.newInstance(this, userConf))
+ task.foreach(_.onStart(startTime))
+ }
+
+ override def onNext(msg: Message): Unit = task.foreach(_.onNext(msg))
+
+ override def onStop(): Unit = {
+ task.foreach(_.onStop())
+ task = None
+ }
+
+ override def receiveUnManagedMessage: Receive = {
+ task.map(_.receiveUnManagedMessage).getOrElse(defaultMessageHandler)
+ }
+
+ override def upstreamMinClock: TimeStamp = {
+ actor.getUpstreamMinClock
+ }
+
+ def schedule(initialDelay: FiniteDuration, interval: FiniteDuration)(f: => Unit): Cancellable = {
+ val dispatcher = actor.context.system.dispatcher
+ actor.context.system.scheduler.schedule(initialDelay, interval)(f)(dispatcher)
+ }
+
+ def scheduleOnce(initialDelay: FiniteDuration)(f: => Unit): Cancellable = {
+ val dispatcher = actor.context.system.dispatcher
+ actor.context.system.scheduler.scheduleOnce(initialDelay)(f)(dispatcher)
+ }
+
+ private def defaultMessageHandler: Receive = {
+ case msg =>
+ LOG.error("Failed! Received unknown message " + "taskId: " + taskId + ", " + msg.toString)
+ }
+
+ /**
+ * Logger is environment dependant, it should be provided by
+ * containing environment.
+ */
+ override def logger: Logger = LOG
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/transaction/api/CheckpointStore.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/transaction/api/CheckpointStore.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/transaction/api/CheckpointStore.scala
new file mode 100644
index 0000000..2ef8610
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/transaction/api/CheckpointStore.scala
@@ -0,0 +1,42 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.transaction.api
+
+import org.apache.gearpump.TimeStamp
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.task.TaskContext
+
+/**
+ * CheckpointStore persistently stores mapping of timestamp to checkpoint
+ * it's possible that two checkpoints have the same timestamp
+ * CheckpointStore needs to handle this either during write or read
+ */
+trait CheckpointStore {
+
+ def persist(timeStamp: TimeStamp, checkpoint: Array[Byte]): Unit
+
+ def recover(timestamp: TimeStamp): Option[Array[Byte]]
+
+ def close(): Unit
+}
+
+trait CheckpointStoreFactory extends java.io.Serializable {
+ def getCheckpointStore(conf: UserConfig, taskContext: TaskContext): CheckpointStore
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/transaction/api/MessageDecoder.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/transaction/api/MessageDecoder.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/transaction/api/MessageDecoder.scala
new file mode 100644
index 0000000..0615078
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/transaction/api/MessageDecoder.scala
@@ -0,0 +1,29 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.transaction.api
+
+import org.apache.gearpump.Message
+
+/**
+ * MessageDecoder decodes raw bytes to Message It is usually written by end user and
+ * passed into TimeReplayableSource
+ */
+trait MessageDecoder extends java.io.Serializable {
+ def fromBytes(bytes: Array[Byte]): Message
+}
[06/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/dsl/plan/OpTranslator.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/dsl/plan/OpTranslator.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/dsl/plan/OpTranslator.scala
new file mode 100644
index 0000000..56d31db
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/dsl/plan/OpTranslator.scala
@@ -0,0 +1,296 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.dsl.plan
+
+import scala.collection.TraversableOnce
+
+import akka.actor.ActorSystem
+import org.slf4j.Logger
+
+import org.apache.gearpump._
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.Constants._
+import org.apache.gearpump.streaming.Processor
+import org.apache.gearpump.streaming.Processor.DefaultProcessor
+import org.apache.gearpump.streaming.dsl.op._
+import org.apache.gearpump.streaming.dsl.plan.OpTranslator._
+import org.apache.gearpump.streaming.sink.DataSink
+import org.apache.gearpump.streaming.source.DataSource
+import org.apache.gearpump.streaming.task.{StartTime, Task, TaskContext}
+import org.apache.gearpump.util.LogUtil
+
+/**
+ * Translates a OP to a TaskDescription
+ */
+class OpTranslator extends java.io.Serializable {
+ val LOG: Logger = LogUtil.getLogger(getClass)
+
+ def translate(ops: OpChain)(implicit system: ActorSystem): Processor[_ <: Task] = {
+
+ val baseConfig = ops.conf
+
+ ops.ops.head match {
+ case op: MasterOp =>
+ val tail = ops.ops.tail
+ val func = toFunction(tail)
+ val userConfig = baseConfig.withValue(GEARPUMP_STREAMING_OPERATOR, func)
+
+ op match {
+ case DataSourceOp(dataSource, parallism, conf, description) =>
+ Processor[SourceTask[Object, Object]](parallism,
+ description = description + "." + func.description,
+ userConfig.withValue(GEARPUMP_STREAMING_SOURCE, dataSource))
+ case groupby@GroupByOp(_, parallism, description, _) =>
+ Processor[GroupByTask[Object, Object, Object]](parallism,
+ description = description + "." + func.description,
+ userConfig.withValue(GEARPUMP_STREAMING_GROUPBY_FUNCTION, groupby))
+ case merge: MergeOp =>
+ Processor[TransformTask[Object, Object]](1,
+ description = op.description + "." + func.description,
+ userConfig)
+ case ProcessorOp(processor, parallism, conf, description) =>
+ DefaultProcessor(parallism,
+ description = description + "." + func.description,
+ userConfig, processor)
+ case DataSinkOp(dataSink, parallelism, conf, description) =>
+ Processor[SinkTask[Object]](parallelism,
+ description = description + func.description,
+ userConfig.withValue(GEARPUMP_STREAMING_SINK, dataSink))
+ }
+ case op: SlaveOp[_] =>
+ val func = toFunction(ops.ops)
+ val userConfig = baseConfig.withValue(GEARPUMP_STREAMING_OPERATOR, func)
+
+ Processor[TransformTask[Object, Object]](1,
+ description = func.description,
+ taskConf = userConfig)
+ case chain: OpChain =>
+ throw new RuntimeException("Not supposed to be called!")
+ }
+ }
+
+ private def toFunction(ops: List[Op]): SingleInputFunction[Object, Object] = {
+ val func: SingleInputFunction[Object, Object] = new DummyInputFunction[Object]()
+ val totalFunction = ops.foldLeft(func) { (fun, op) =>
+
+ val opFunction = op match {
+ case flatmap: FlatMapOp[Object @unchecked, Object @unchecked] =>
+ new FlatMapFunction(flatmap.fun, flatmap.description)
+ case reduce: ReduceOp[Object @unchecked] =>
+ new ReduceFunction(reduce.fun, reduce.description)
+ case _ =>
+ throw new RuntimeException("Not supposed to be called!")
+ }
+ fun.andThen(opFunction.asInstanceOf[SingleInputFunction[Object, Object]])
+ }
+ totalFunction.asInstanceOf[SingleInputFunction[Object, Object]]
+ }
+}
+
+object OpTranslator {
+
+ trait SingleInputFunction[IN, OUT] extends Serializable {
+ def process(value: IN): TraversableOnce[OUT]
+ def andThen[OUTER](other: SingleInputFunction[OUT, OUTER]): SingleInputFunction[IN, OUTER] = {
+ new AndThen(this, other)
+ }
+
+ def description: String
+ }
+
+ class DummyInputFunction[T] extends SingleInputFunction[T, T] {
+ override def andThen[OUTER](other: SingleInputFunction[T, OUTER])
+ : SingleInputFunction[T, OUTER] = {
+ other
+ }
+
+ // Should never be called
+ override def process(value: T): TraversableOnce[T] = None
+
+ override def description: String = ""
+ }
+
+ class AndThen[IN, MIDDLE, OUT](
+ first: SingleInputFunction[IN, MIDDLE], second: SingleInputFunction[MIDDLE, OUT])
+ extends SingleInputFunction[IN, OUT] {
+
+ override def process(value: IN): TraversableOnce[OUT] = {
+ first.process(value).flatMap(second.process(_))
+ }
+
+ override def description: String = {
+ Option(first.description).flatMap { description =>
+ Option(second.description).map(description + "." + _)
+ }.getOrElse(null)
+ }
+ }
+
+ class FlatMapFunction[IN, OUT](fun: IN => TraversableOnce[OUT], descriptionMessage: String)
+ extends SingleInputFunction[IN, OUT] {
+
+ override def process(value: IN): TraversableOnce[OUT] = {
+ fun(value)
+ }
+
+ override def description: String = {
+ this.descriptionMessage
+ }
+ }
+
+ class ReduceFunction[T](fun: (T, T) => T, descriptionMessage: String)
+ extends SingleInputFunction[T, T] {
+
+ private var state: Any = null
+
+ override def process(value: T): TraversableOnce[T] = {
+ if (state == null) {
+ state = value
+ } else {
+ state = fun(state.asInstanceOf[T], value)
+ }
+ Some(state.asInstanceOf[T])
+ }
+
+ override def description: String = descriptionMessage
+ }
+
+ class GroupByTask[IN, GROUP, OUT](
+ groupBy: IN => GROUP, taskContext: TaskContext, userConf: UserConfig)
+ extends Task(taskContext, userConf) {
+
+ def this(taskContext: TaskContext, userConf: UserConfig) = {
+ this(userConf.getValue[GroupByOp[IN, GROUP]](
+ GEARPUMP_STREAMING_GROUPBY_FUNCTION )(taskContext.system).get.fun,
+ taskContext, userConf)
+ }
+
+ private var groups = Map.empty[GROUP, SingleInputFunction[IN, OUT]]
+
+ override def onStart(startTime: StartTime): Unit = {
+ }
+
+ override def onNext(msg: Message): Unit = {
+ val time = msg.timestamp
+
+ val group = groupBy(msg.msg.asInstanceOf[IN])
+ if (!groups.contains(group)) {
+ val operator =
+ userConf.getValue[SingleInputFunction[IN, OUT]](GEARPUMP_STREAMING_OPERATOR).get
+ groups += group -> operator
+ }
+
+ val operator = groups(group)
+
+ operator.process(msg.msg.asInstanceOf[IN]).foreach { msg =>
+ taskContext.output(new Message(msg.asInstanceOf[AnyRef], time))
+ }
+ }
+ }
+
+ class SourceTask[T, OUT](
+ source: DataSource, operator: Option[SingleInputFunction[T, OUT]], taskContext: TaskContext,
+ userConf: UserConfig)
+ extends Task(taskContext, userConf) {
+
+ def this(taskContext: TaskContext, userConf: UserConfig) = {
+ this(
+ userConf.getValue[DataSource](GEARPUMP_STREAMING_SOURCE)(taskContext.system).get,
+ userConf.getValue[SingleInputFunction[T, OUT]](GEARPUMP_STREAMING_OPERATOR)(
+ taskContext.system),
+ taskContext, userConf)
+ }
+
+ override def onStart(startTime: StartTime): Unit = {
+ source.open(taskContext, startTime.startTime)
+ self ! Message("start", System.currentTimeMillis())
+ }
+
+ override def onNext(msg: Message): Unit = {
+ val time = System.currentTimeMillis()
+ Option(source.read()).foreach { msg =>
+ operator match {
+ case Some(operator) =>
+ operator match {
+ case bad: DummyInputFunction[T] =>
+ taskContext.output(msg)
+ case _ =>
+ operator.process(msg.msg.asInstanceOf[T]).foreach(msg => {
+ taskContext.output(new Message(msg.asInstanceOf[AnyRef], time))
+ })
+ }
+ case None =>
+ taskContext.output(msg)
+ }
+ }
+
+ self ! Message("next", System.currentTimeMillis())
+ }
+
+ override def onStop(): Unit = {
+ source.close()
+ }
+ }
+
+ class TransformTask[IN, OUT](
+ operator: Option[SingleInputFunction[IN, OUT]], taskContext: TaskContext,
+ userConf: UserConfig) extends Task(taskContext, userConf) {
+
+ def this(taskContext: TaskContext, userConf: UserConfig) = {
+ this(userConf.getValue[SingleInputFunction[IN, OUT]](
+ GEARPUMP_STREAMING_OPERATOR)(taskContext.system), taskContext, userConf)
+ }
+
+ override def onStart(startTime: StartTime): Unit = {
+ }
+
+ override def onNext(msg: Message): Unit = {
+ val time = msg.timestamp
+
+ operator match {
+ case Some(operator) =>
+ operator.process(msg.msg.asInstanceOf[IN]).foreach { msg =>
+ taskContext.output(new Message(msg.asInstanceOf[AnyRef], time))
+ }
+ case None =>
+ taskContext.output(new Message(msg.msg, time))
+ }
+ }
+ }
+
+ class SinkTask[T](dataSink: DataSink, taskContext: TaskContext, userConf: UserConfig)
+ extends Task(taskContext, userConf) {
+
+ def this(taskContext: TaskContext, userConf: UserConfig) = {
+ this(userConf.getValue[DataSink](GEARPUMP_STREAMING_SINK)(taskContext.system).get,
+ taskContext, userConf)
+ }
+
+ override def onStart(startTime: StartTime): Unit = {
+ dataSink.open(taskContext)
+ }
+
+ override def onNext(msg: Message): Unit = {
+ dataSink.write(msg)
+ }
+
+ override def onStop(): Unit = {
+ dataSink.close()
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/dsl/plan/Planner.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/dsl/plan/Planner.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/dsl/plan/Planner.scala
new file mode 100644
index 0000000..3af5e97
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/dsl/plan/Planner.scala
@@ -0,0 +1,96 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.dsl.plan
+
+import akka.actor.ActorSystem
+
+import org.apache.gearpump.partitioner.{CoLocationPartitioner, HashPartitioner, Partitioner}
+import org.apache.gearpump.streaming.Processor
+import org.apache.gearpump.streaming.dsl.op._
+import org.apache.gearpump.streaming.dsl.partitioner.GroupByPartitioner
+import org.apache.gearpump.streaming.task.Task
+import org.apache.gearpump.util.Graph
+
+class Planner {
+
+ /*
+ * Converts Dag of Op to Dag of TaskDescription. TaskDescription is part of the low
+ * level Graph API.
+ */
+ def plan(dag: Graph[Op, OpEdge])(implicit system: ActorSystem)
+ : Graph[Processor[_ <: Task], _ <: Partitioner] = {
+
+ val opTranslator = new OpTranslator()
+
+ val newDag = optimize(dag)
+ newDag.mapEdge { (node1, edge, node2) =>
+ edge match {
+ case Shuffle =>
+ node2.head match {
+ case groupBy: GroupByOp[Any @unchecked, Any @unchecked] =>
+ new GroupByPartitioner(groupBy.fun)
+ case _ => new HashPartitioner
+ }
+ case Direct =>
+ new CoLocationPartitioner
+ }
+ }.mapVertex { opChain =>
+ opTranslator.translate(opChain)
+ }
+ }
+
+ private def optimize(dag: Graph[Op, OpEdge]): Graph[OpChain, OpEdge] = {
+ val newGraph = dag.mapVertex(op => OpChain(List(op)))
+
+ val nodes = newGraph.topologicalOrderWithCirclesIterator.toList.reverse
+ for (node <- nodes) {
+ val outGoingEdges = newGraph.outgoingEdgesOf(node)
+ for (edge <- outGoingEdges) {
+ merge(newGraph, edge._1, edge._3)
+ }
+ }
+ newGraph
+ }
+
+ private def merge(dag: Graph[OpChain, OpEdge], node1: OpChain, node2: OpChain)
+ : Graph[OpChain, OpEdge] = {
+ if (dag.outDegreeOf(node1) == 1 &&
+ dag.inDegreeOf(node2) == 1 &&
+ // For processor node, we don't allow it to merge with downstream operators
+ !node1.head.isInstanceOf[ProcessorOp[_ <: Task]]) {
+ val (_, edge, _) = dag.outgoingEdgesOf(node1)(0)
+ if (edge == Direct) {
+ val opList = OpChain(node1.ops ++ node2.ops)
+ dag.addVertex(opList)
+ for (incomingEdge <- dag.incomingEdgesOf(node1)) {
+ dag.addEdge(incomingEdge._1, incomingEdge._2, opList)
+ }
+
+ for (outgoingEdge <- dag.outgoingEdgesOf(node2)) {
+ dag.addEdge(opList, outgoingEdge._2, outgoingEdge._3)
+ }
+
+ // Remove the old vertex
+ dag.removeVertex(node1)
+ dag.removeVertex(node2)
+ }
+ }
+ dag
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/executor/Executor.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/executor/Executor.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/executor/Executor.scala
new file mode 100644
index 0000000..0eeb0eb
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/executor/Executor.scala
@@ -0,0 +1,476 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.executor
+
+import java.lang.management.ManagementFactory
+import scala.concurrent.duration._
+
+import akka.actor.SupervisorStrategy.Resume
+import akka.actor._
+import com.typesafe.config.Config
+import org.apache.commons.lang.exception.ExceptionUtils
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.worker.WorkerId
+import org.apache.gearpump.cluster.{ClusterConfig, ExecutorContext, UserConfig}
+import org.apache.gearpump.metrics.Metrics.ReportMetrics
+import org.apache.gearpump.metrics.{JvmMetricsSet, Metrics, MetricsReporterService}
+import org.apache.gearpump.serializer.SerializationFramework
+import org.apache.gearpump.streaming.AppMasterToExecutor.{MsgLostException, TasksChanged, TasksLaunched, _}
+import org.apache.gearpump.streaming.ExecutorToAppMaster.{MessageLoss, RegisterExecutor, RegisterTask, UnRegisterTask}
+import org.apache.gearpump.streaming.ProcessorId
+import org.apache.gearpump.streaming.executor.Executor._
+import org.apache.gearpump.streaming.executor.TaskLauncher.TaskArgument
+import org.apache.gearpump.streaming.task.{Subscriber, TaskId}
+import org.apache.gearpump.transport.{Express, HostPort}
+import org.apache.gearpump.util.Constants._
+import org.apache.gearpump.util.{ActorUtil, Constants, LogUtil, TimeOutScheduler}
+
+/**
+ * Executor is child of AppMaster.
+ * It usually represents a JVM process. It is a container for all tasks.
+ */
+
+// TODO: What if Executor stuck in state DynamicDag and cannot get out???
+// For example, due to some message loss when there is network glitch.
+// Executor will hang there for ever???
+//
+class Executor(executorContext: ExecutorContext, userConf : UserConfig, launcher: ITaskLauncher)
+ extends Actor with TimeOutScheduler{
+
+ def this(executorContext: ExecutorContext, userConf: UserConfig) = {
+ this(executorContext, userConf, TaskLauncher(executorContext, userConf))
+ }
+
+ import context.dispatcher
+ import executorContext.{appId, appMaster, executorId, resource, worker}
+
+ private val LOG: Logger = LogUtil.getLogger(getClass, executor = executorId, app = appId)
+
+ private implicit val timeOut = FUTURE_TIMEOUT
+ private val address = ActorUtil.getFullPath(context.system, self.path)
+ private val systemConfig = context.system.settings.config
+ private val serializerPool = getSerializerPool()
+ private val taskDispatcher = systemConfig.getString(Constants.GEARPUMP_TASK_DISPATCHER)
+
+ private var state = State.ACTIVE
+ private var transitionStart = 0L
+ // States transition start, in unix time
+ private var transitionEnd = 0L
+ // States transition end, in unix time
+ private val transitWarningThreshold = 5000 // ms,
+
+ // Starts health check Ticks
+ self ! HealthCheck
+
+ LOG.info(s"Executor $executorId has been started, start to register itself...")
+ LOG.info(s"Executor actor path: ${ActorUtil.getFullPath(context.system, self.path)}")
+
+ appMaster ! RegisterExecutor(self, executorId, resource, worker)
+ context.watch(appMaster)
+
+ private var tasks = Map.empty[TaskId, ActorRef]
+ private val taskArgumentStore = new TaskArgumentStore()
+
+ val express = Express(context.system)
+
+ val metricsEnabled = systemConfig.getBoolean(GEARPUMP_METRIC_ENABLED)
+
+ if (metricsEnabled) {
+ // Registers jvm metrics
+ Metrics(context.system).register(new JvmMetricsSet(s"app$appId.executor$executorId"))
+
+ val metricsReportService = context.actorOf(Props(new MetricsReporterService(
+ Metrics(context.system))))
+ appMaster.tell(ReportMetrics, metricsReportService)
+ }
+
+ private val NOT_INITIALIZED = -1
+ def receive: Receive = applicationReady(dagVersion = NOT_INITIALIZED)
+
+ private def getTaskId(actorRef: ActorRef): Option[TaskId] = {
+ tasks.find(_._2 == actorRef).map(_._1)
+ }
+
+ override val supervisorStrategy =
+ OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1.minute) {
+ case _: MsgLostException =>
+ val taskId = getTaskId(sender)
+ val cause = s"We got MessageLossException from task ${getTaskId(sender)}, " +
+ s"replaying application..."
+ LOG.error(cause)
+ taskId.foreach(appMaster ! MessageLoss(executorId, _, cause))
+ Resume
+ case ex: Throwable =>
+ val taskId = getTaskId(sender)
+ val errorMsg = s"We got ${ex.getClass.getName} from $taskId, we will treat it as" +
+ s" MessageLoss, so that the system will replay all lost message"
+ LOG.error(errorMsg, ex)
+ val detailErrorMsg = errorMsg + "\n" + ExceptionUtils.getStackTrace(ex)
+ taskId.foreach(appMaster ! MessageLoss(executorId, _, detailErrorMsg))
+ Resume
+ }
+
+ private def launchTask(taskId: TaskId, argument: TaskArgument): ActorRef = {
+ launcher.launch(List(taskId), argument, context, serializerPool, taskDispatcher).values.head
+ }
+
+ private def assertVersion(expectVersion: Int, version: Int, clue: Any): Unit = {
+ if (expectVersion != version) {
+ val errorMessage = s"Version mismatch: we expect dag version $expectVersion, " +
+ s"but get $version; clue: $clue"
+ LOG.error(errorMessage)
+ throw new DagVersionMismatchException(errorMessage)
+ }
+ }
+
+ def dynamicDagPhase1(
+ dagVersion: Int, launched: List[TaskId], changed: List[ChangeTask], registered: List[TaskId])
+ : Receive = {
+ state = State.DYNAMIC_DAG_PHASE1
+ box({
+ case launch@LaunchTasks(taskIds, version, processorDescription,
+ subscribers: List[Subscriber]) => {
+ assertVersion(dagVersion, version, clue = launch)
+
+ LOG.info(s"Launching Task $taskIds for app: $appId")
+ val taskArgument = TaskArgument(version, processorDescription, subscribers)
+ taskIds.foreach(taskArgumentStore.add(_, taskArgument))
+ val newAdded = launcher.launch(taskIds, taskArgument, context, serializerPool,
+ taskDispatcher)
+ newAdded.foreach { newAddedTask =>
+ context.watch(newAddedTask._2)
+ }
+ tasks ++= newAdded
+ sender ! TasksLaunched
+ context.become(dynamicDagPhase1(version, launched ++ taskIds, changed, registered))
+ }
+ case change@ChangeTasks(taskIds, version, life, subscribers) =>
+ assertVersion(dagVersion, version, clue = change)
+
+ LOG.info(s"Change Tasks $taskIds for app: $appId, verion: $life, $dagVersion, $subscribers")
+
+ val newChangedTasks = taskIds.map { taskId =>
+ for (taskArgument <- taskArgumentStore.get(dagVersion, taskId)) {
+ val processorDescription = taskArgument.processorDescription.copy(life = life)
+ taskArgumentStore.add(taskId, TaskArgument(dagVersion, processorDescription,
+ subscribers))
+ }
+ ChangeTask(taskId, dagVersion, life, subscribers)
+ }
+ sender ! TasksChanged(taskIds)
+ context.become(dynamicDagPhase1(dagVersion, launched, changed ++ newChangedTasks,
+ registered))
+
+ case locations@TaskLocationsReady(taskLocations, version) =>
+ LOG.info(s"TaskLocations Ready...")
+ assertVersion(dagVersion, version, clue = locations)
+
+ // Check whether all tasks has been registered.
+ if ((launched.toSet -- registered.toSet).isEmpty) {
+ // Confirm all tasks has been registered.
+ val result = taskLocations.locations.filter {
+ location => !location._1.equals(express.localHost)
+ }.flatMap { kv =>
+ val (host, taskIdList) = kv
+ taskIdList.map(taskId => (TaskId.toLong(taskId), host))
+ }
+
+ val replyTo = sender
+ express.startClients(taskLocations.locations.keySet).foreach { _ =>
+ express.remoteAddressMap.send(result)
+ express.remoteAddressMap.future().foreach { _ =>
+ LOG.info(s"sending TaskLocationsReceived back to appmaster")
+ replyTo ! TaskLocationsReceived(version, executorId)
+ }
+ }
+ context.become(dynamicDagPhase2(dagVersion, launched, changed))
+ } else {
+ LOG.error("Inconsistency between AppMaser and Executor! AppMaster thinks DynamicDag " +
+ "transition is ready, while Executor have not get all tasks registered, " +
+ "that task will not be functional...")
+
+ // Reject TaskLocations...
+ val missedTasks = (launched.toSet -- registered.toSet).toList
+ val errorMsg = "We have not received TaskRegistered for following tasks: " +
+ missedTasks.mkString(", ")
+ LOG.error(errorMsg)
+ sender ! TaskLocationsRejected(dagVersion, executorId, errorMsg, null)
+ // Stays with current status...
+ }
+
+ case confirm: TaskRegistered =>
+ tasks.get(confirm.taskId).foreach {
+ case actorRef: ActorRef =>
+ tasks += confirm.taskId -> actorRef
+ actorRef forward confirm
+ }
+ context.become(dynamicDagPhase1(dagVersion, launched, changed,
+ registered :+ confirm.taskId))
+
+ case rejected: TaskRejected =>
+ // Means this task shoud not exists...
+ tasks.get(rejected.taskId).foreach(_ ! PoisonPill)
+ tasks -= rejected.taskId
+ LOG.error(s"Task ${rejected.taskId} is rejected by AppMaster, shutting down it...")
+
+ case register: RegisterTask =>
+ appMaster ! register
+ })
+ }
+
+ def dynamicDagPhase2(dagVersion: Int, launched: List[TaskId], changed: List[ChangeTask])
+ : Receive = {
+ LOG.info("Transit to dynamic Dag Phase2")
+ state = State.DYNAMIC_DAG_PHASE2
+ box {
+ case startAll@StartAllTasks(version) =>
+ LOG.info(s"Start All Tasks...")
+ assertVersion(dagVersion, version, clue = startAll)
+
+ launched.foreach(taskId => tasks.get(taskId).foreach(_ ! StartTask(taskId)))
+ changed.foreach(changeTask => tasks.get(changeTask.taskId).foreach(_ ! changeTask))
+
+ taskArgumentStore.removeNewerVersion(dagVersion)
+ taskArgumentStore.removeObsoleteVersion
+ context.become(applicationReady(dagVersion))
+ }
+ }
+
+ def applicationReady(dagVersion: Int): Receive = {
+ state = State.ACTIVE
+ transitionEnd = System.currentTimeMillis()
+
+ if (dagVersion != NOT_INITIALIZED) {
+ LOG.info("Transit to state Application Ready. This transition takes " +
+ (transitionEnd - transitionStart) + " milliseconds")
+ }
+ box {
+ case start: StartDynamicDag =>
+ LOG.info("received StartDynamicDag")
+ if (start.dagVersion > dagVersion) {
+ transitionStart = System.currentTimeMillis()
+ LOG.info(s"received $start, Executor transit to dag version: ${start.dagVersion} from " +
+ s"current version $dagVersion")
+ context.become(dynamicDagPhase1(start.dagVersion, List.empty[TaskId],
+ List.empty[ChangeTask], List.empty[TaskId]))
+ }
+ case launch: LaunchTasks =>
+ if (launch.dagVersion > dagVersion) {
+ transitionStart = System.currentTimeMillis()
+ LOG.info(s"received $launch, Executor transit to dag " +
+ s"version: ${launch.dagVersion} from current version $dagVersion")
+ context.become(dynamicDagPhase1(launch.dagVersion, List.empty[TaskId],
+ List.empty[ChangeTask], List.empty[TaskId]))
+ self forward launch
+ }
+
+ case change: ChangeTasks =>
+ if (change.dagVersion > dagVersion) {
+ transitionStart = System.currentTimeMillis()
+ LOG.info(s"received $change, Executor transit to dag version: ${change.dagVersion} from" +
+ s" current version $dagVersion")
+ context.become(dynamicDagPhase1(change.dagVersion, List.empty[TaskId],
+ List.empty[ChangeTask], List.empty[TaskId]))
+ self forward change
+ }
+
+ case StopTask(taskId) =>
+ // Old soldiers never die, they just fade away ;)
+ val fadeAwayTask = tasks.get(taskId)
+ if (fadeAwayTask.isDefined) {
+ context.stop(fadeAwayTask.get)
+ }
+ tasks -= taskId
+
+ case unRegister@UnRegisterTask(taskId, _) =>
+ // Sends UnRegisterTask to AppMaster
+ appMaster ! unRegister
+ }
+ }
+
+ def restartingTasks(dagVersion: Int, remain: Int, needRestart: List[TaskId]): Receive = {
+ state = State.RECOVERY
+ box {
+ case TaskStopped(actor) =>
+ for (taskId <- getTaskId(actor)) {
+ if (taskArgumentStore.get(dagVersion, taskId).nonEmpty) {
+ val newNeedRestart = needRestart :+ taskId
+ val newRemain = remain - 1
+ if (newRemain == 0) {
+ val newRestarted = newNeedRestart.map { taskId_ =>
+ val taskActor = launchTask(taskId_, taskArgumentStore.get(dagVersion, taskId_).get)
+ context.watch(taskActor)
+ taskId_ -> taskActor
+ }.toMap
+
+ tasks = newRestarted
+ context.become(dynamicDagPhase1(dagVersion, newNeedRestart, List.empty[ChangeTask],
+ List.empty[TaskId]))
+ } else {
+ context.become(restartingTasks(dagVersion, newRemain, newNeedRestart))
+ }
+ }
+ }
+ }
+ }
+
+ val terminationWatch: Receive = {
+ case Terminated(actor) =>
+ if (actor.compareTo(appMaster) == 0) {
+ LOG.info(s"AppMaster ${appMaster.path.toString} is terminated, shutting down current " +
+ s"executor $appId, $executorId")
+ context.stop(self)
+ } else {
+ self ! TaskStopped(actor)
+ }
+ }
+
+ def onRestartTasks: Receive = {
+ case RestartTasks(dagVersion) =>
+ LOG.info(s"Executor received restart tasks")
+ val tasksToRestart = tasks.keys.count(taskArgumentStore.get(dagVersion, _).nonEmpty)
+ express.remoteAddressMap.send(Map.empty[Long, HostPort])
+ context.become(restartingTasks(dagVersion, remain = tasksToRestart,
+ needRestart = List.empty[TaskId]))
+
+ tasks.values.foreach {
+ case task: ActorRef => task ! PoisonPill
+ }
+ }
+
+ def executorService: Receive = terminationWatch orElse onRestartTasks orElse {
+ case taskChanged: TaskChanged =>
+ // Skip
+ case get: GetExecutorSummary =>
+ val logFile = LogUtil.applicationLogDir(systemConfig)
+ val processorTasks = tasks.keySet.groupBy(_.processorId).mapValues(_.toList).view.force
+ sender ! ExecutorSummary(
+ executorId,
+ worker.workerId,
+ address,
+ logFile.getAbsolutePath,
+ state,
+ tasks.size,
+ processorTasks,
+ jvmName = ManagementFactory.getRuntimeMXBean().getName())
+
+ case query: QueryExecutorConfig =>
+ sender ! ExecutorConfig(ClusterConfig.filterOutDefaultConfig(systemConfig))
+ case HealthCheck =>
+ context.system.scheduler.scheduleOnce(3.second)(HealthCheck)
+ if (state != State.ACTIVE && (transitionEnd - transitionStart) > transitWarningThreshold) {
+ LOG.error(s"Executor status: " + state +
+ s", it takes too long(${transitionEnd - transitionStart}) to do transition")
+ }
+ }
+
+ private def getSerializerPool(): SerializationFramework = {
+ val system = context.system.asInstanceOf[ExtendedActorSystem]
+ val clazz = Class.forName(systemConfig.getString(Constants.GEARPUMP_SERIALIZER_POOL))
+ val pool = clazz.newInstance().asInstanceOf[SerializationFramework]
+ pool.init(system, userConf)
+ pool.asInstanceOf[SerializationFramework]
+ }
+
+ private def unHandled(state: String): Receive = {
+ case other =>
+ LOG.info(s"Received unknown message $other in state: $state")
+ }
+
+ private def box(receive: Receive): Receive = {
+ executorService orElse receive orElse unHandled(state)
+ }
+}
+
+object Executor {
+ case class RestartTasks(dagVersion: Int)
+
+ class TaskArgumentStore {
+
+ private var store = Map.empty[TaskId, List[TaskArgument]]
+
+ def add(taskId: TaskId, task: TaskArgument): Unit = {
+ val list = store.getOrElse(taskId, List.empty[TaskArgument])
+ store += taskId -> (task :: list)
+ }
+
+ def get(dagVersion: Int, taskId: TaskId): Option[TaskArgument] = {
+ store.get(taskId).flatMap { list =>
+ list.find { arg =>
+ arg.dagVersion <= dagVersion
+ }
+ }
+ }
+
+ /**
+ * When the new DAG is successfully deployed, then we should remove obsolete
+ * TaskArgument of old DAG.
+ */
+ def removeObsoleteVersion(): Unit = {
+ store = store.map { kv =>
+ val (k, list) = kv
+ (k, list.take(1))
+ }
+ }
+
+ def removeNewerVersion(currentVersion: Int): Unit = {
+ store = store.map { kv =>
+ val (k, list) = kv
+ (k, list.filter(_.dagVersion <= currentVersion))
+ }
+ }
+ }
+
+ case class TaskStopped(task: ActorRef)
+
+ case class ExecutorSummary(
+ id: Int,
+ workerId: WorkerId,
+ actorPath: String,
+ logFile: String,
+ status: String,
+ taskCount: Int,
+ tasks: Map[ProcessorId, List[TaskId]],
+ jvmName: String
+ )
+
+ object ExecutorSummary {
+ def empty: ExecutorSummary = {
+ ExecutorSummary(0, WorkerId.unspecified, "", "", "", 1, null, jvmName = "")
+ }
+ }
+
+ case class GetExecutorSummary(executorId: Int)
+
+ case class QueryExecutorConfig(executorId: Int)
+
+ case class ExecutorConfig(config: Config)
+
+ class DagVersionMismatchException(msg: String) extends Exception(msg)
+
+ object State {
+ val ACTIVE = "active"
+ val DYNAMIC_DAG_PHASE1 = "dynamic_dag_phase1"
+ val DYNAMIC_DAG_PHASE2 = "dynamic_dag_phase2"
+ val RECOVERY = "dag_recovery"
+ }
+
+ object HealthCheck
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/executor/ExecutorRestartPolicy.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/executor/ExecutorRestartPolicy.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/executor/ExecutorRestartPolicy.scala
new file mode 100644
index 0000000..ef96ab9
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/executor/ExecutorRestartPolicy.scala
@@ -0,0 +1,64 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.executor
+
+import scala.collection.immutable
+import scala.concurrent.duration.Duration
+
+import org.apache.gearpump.streaming.task.TaskId
+import org.apache.gearpump.util.RestartPolicy
+
+/**
+ *
+ * Controls how many retries to recover failed executors.
+ *
+ * @param maxNrOfRetries the number of times a executor is allowed to be restarted,
+ * negative value means no limit, if the limit is exceeded the policy
+ * will not allow to restart the executor
+ * @param withinTimeRange duration of the time window for maxNrOfRetries, Duration.Inf
+ * means no window
+ */
+class ExecutorRestartPolicy(maxNrOfRetries: Int, withinTimeRange: Duration) {
+ private var executorToTaskIds = Map.empty[Int, Set[TaskId]]
+ private var taskRestartPolocies = new immutable.HashMap[TaskId, RestartPolicy]
+
+ def addTaskToExecutor(executorId: Int, taskId: TaskId): Unit = {
+ var taskSetForExecutorId = executorToTaskIds.getOrElse(executorId, Set.empty[TaskId])
+ taskSetForExecutorId += taskId
+ executorToTaskIds += executorId -> taskSetForExecutorId
+ if (!taskRestartPolocies.contains(taskId)) {
+ taskRestartPolocies += taskId -> new RestartPolicy(maxNrOfRetries, withinTimeRange)
+ }
+ }
+
+ def allowRestartExecutor(executorId: Int): Boolean = {
+ executorToTaskIds.get(executorId).map { taskIds =>
+ taskIds.foreach { taskId =>
+ taskRestartPolocies.get(taskId).map { policy =>
+ if (!policy.allowRestart) {
+ // scalastyle:off return
+ return false
+ // scalastyle:on return
+ }
+ }
+ }
+ }
+ true
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/executor/TaskLauncher.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/executor/TaskLauncher.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/executor/TaskLauncher.scala
new file mode 100644
index 0000000..18490ee
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/executor/TaskLauncher.scala
@@ -0,0 +1,83 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.executor
+
+import akka.actor.{Actor, ActorRef, ActorRefFactory, Props}
+
+import org.apache.gearpump.cluster.{ExecutorContext, UserConfig}
+import org.apache.gearpump.serializer.SerializationFramework
+import org.apache.gearpump.streaming.ProcessorDescription
+import org.apache.gearpump.streaming.executor.TaskLauncher.TaskArgument
+import org.apache.gearpump.streaming.task._
+import org.apache.gearpump.streaming.util.ActorPathUtil
+
+trait ITaskLauncher {
+
+ /** Launch a list of task actors */
+ def launch(taskIds: List[TaskId], argument: TaskArgument,
+ context: ActorRefFactory, serializer: SerializationFramework, dispatcher: String)
+ : Map[TaskId, ActorRef]
+}
+
+class TaskLauncher(
+ appId: Int,
+ appName: String,
+ executorId: Int,
+ appMaster: ActorRef,
+ userConf: UserConfig,
+ taskActorClass: Class[_ <: Actor])
+ extends ITaskLauncher{
+
+ override def launch(
+ taskIds: List[TaskId], argument: TaskArgument,
+ context: ActorRefFactory, serializer: SerializationFramework, dispatcher: String)
+ : Map[TaskId, ActorRef] = {
+ import argument.{processorDescription, subscribers}
+
+ val taskConf = userConf.withConfig(processorDescription.taskConf)
+
+ val taskContext = TaskContextData(executorId,
+ appId, appName, appMaster,
+ processorDescription.parallelism,
+ processorDescription.life, subscribers)
+
+ val taskClass = TaskUtil.loadClass(processorDescription.taskClass)
+
+ var tasks = Map.empty[TaskId, ActorRef]
+ taskIds.foreach { taskId =>
+ val task = new TaskWrapper(taskId, taskClass, taskContext, taskConf)
+ val taskActor = context.actorOf(Props(taskActorClass, taskId, taskContext, userConf, task,
+ serializer).withDispatcher(dispatcher), ActorPathUtil.taskActorName(taskId))
+ tasks += taskId -> taskActor
+ }
+ tasks
+ }
+}
+
+object TaskLauncher {
+
+ case class TaskArgument(
+ dagVersion: Int, processorDescription: ProcessorDescription,
+ subscribers: List[Subscriber])
+
+ def apply(executorContext: ExecutorContext, userConf: UserConfig): TaskLauncher = {
+ import executorContext.{appId, appMaster, appName, executorId}
+ new TaskLauncher(appId, appName, executorId, appMaster, userConf, classOf[TaskActor])
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/metrics/ProcessorAggregator.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/metrics/ProcessorAggregator.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/metrics/ProcessorAggregator.scala
new file mode 100644
index 0000000..6721cfc
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/metrics/ProcessorAggregator.scala
@@ -0,0 +1,301 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.metrics
+
+import java.util
+
+import com.typesafe.config.Config
+
+import org.apache.gearpump.TimeStamp
+import org.apache.gearpump.cluster.ClientToMaster.ReadOption
+import org.apache.gearpump.cluster.MasterToClient.HistoryMetricsItem
+import io.gearpump.google.common.collect.Iterators
+import org.apache.gearpump.metrics.Metrics.{Histogram, Meter}
+import org.apache.gearpump.metrics.MetricsAggregator
+import org.apache.gearpump.streaming.metrics.ProcessorAggregator._
+import org.apache.gearpump.util.HistoryMetricsService.HistoryMetricsConfig
+
+/**
+ *
+ * Does aggregation on metrics after grouping by these three attributes:
+ * 1. processorId
+ * 2. time section(represented as a index integer)
+ * 3. metricName(like sendThroughput)
+ *
+ * It assumes that for each [[org.apache.gearpump.cluster.MasterToClient.HistoryMetricsItem]], the
+ * name follow the format app(appId).processor(processorId).task(taskId).(metricName)
+ *
+ * It parses the name to get processorId and metricName. If the parsing fails, then current
+ * [[org.apache.gearpump.cluster.MasterToClient.HistoryMetricsItem]] will be skipped.
+ *
+ * NOTE: this class is optimized for performance.
+ */
+class ProcessorAggregator(historyMetricConfig: HistoryMetricsConfig) extends MetricsAggregator {
+
+ def this(config: Config) = {
+ this(HistoryMetricsConfig(config))
+ }
+
+ private val aggregatorFactory: AggregatorFactory = new AggregatorFactory()
+
+ /**
+ * Accepts options:
+ * key: "readOption", value: one of "readLatest", "readRecent", "readHistory"
+ */
+ override def aggregate(options: Map[String, String],
+ inputs: Iterator[HistoryMetricsItem]): List[HistoryMetricsItem] = {
+ val readOption = options.get(ReadOption.Key).getOrElse(ReadOption.ReadLatest)
+ aggregate(readOption, inputs, System.currentTimeMillis())
+ }
+
+ def aggregate(
+ readOption: ReadOption.ReadOption, inputs: Iterator[HistoryMetricsItem], now: TimeStamp)
+ : List[HistoryMetricsItem] = {
+ val (start, end, interval) = getTimeRange(readOption, now)
+ val timeSlotsCount = ((end - start - 1) / interval + 1).toInt
+ val map = new MultiLayerMap[Aggregator](timeSlotsCount)
+
+ val taskIdentity = new TaskIdentity(0, null)
+ while (inputs.hasNext) {
+ val item = inputs.next()
+
+ if (item.value.isInstanceOf[Meter] || item.value.isInstanceOf[Histogram]) {
+ if (item.time >= start && item.time < end) {
+ val timeIndex = ((item.time - start) / interval).toInt
+
+ if (parseName(item.value.name, taskIdentity)) {
+ var op = map.get(timeIndex, taskIdentity.group)
+ if (op == null) {
+ op = aggregatorFactory.create(item, taskIdentity.group)
+ map.put(timeIndex, taskIdentity.group, op)
+ }
+ op.aggregate(item)
+ }
+ }
+ }
+ }
+
+ val result = new Array[HistoryMetricsItem](map.size)
+ val iterator = map.valueIterator
+ var index = 0
+ while (iterator.hasNext()) {
+ val op = iterator.next()
+ result(index) = op.result
+ index += 1
+ }
+
+ result.toList
+ }
+
+ // Returns (start, end, interval)
+ private def getTimeRange(readOption: ReadOption.ReadOption, now: TimeStamp)
+ : (TimeStamp, TimeStamp, TimeStamp) = {
+ readOption match {
+ case ReadOption.ReadRecent =>
+ val end = now
+ val start = end - (historyMetricConfig.retainRecentDataSeconds) * 1000
+ val interval = historyMetricConfig.retainRecentDataIntervalMs
+ (floor(start, interval), floor(end, interval), interval)
+ case ReadOption.ReadHistory =>
+ val end = now
+ val start = end - (historyMetricConfig.retainHistoryDataHours) * 3600 * 1000
+ val interval = historyMetricConfig.retainHistoryDataIntervalMs
+ (floor(start, interval), floor(end, interval), interval)
+ case _ =>
+ // All data points are aggregated together.
+ (0L, Long.MaxValue, Long.MaxValue)
+ }
+ }
+
+ // The original metrics data is divided by interval points:
+ // time series (0, interval, 2*interval, 3*interval....)
+ // floor(..) make sure the Aggregator use the same set of interval points.
+ private def floor(value: Long, interval: Long): Long = {
+ (value / interval) * interval
+ }
+
+ // Returns "app0.processor0:sendThroughput" as the group Id.
+ private def parseName(name: String, result: TaskIdentity): Boolean = {
+ val taskIndex = name.indexOf(TASK_TAG)
+ if (taskIndex > 0) {
+ val processor = name.substring(0, taskIndex)
+ val typeIndex = name.indexOf(":", taskIndex + 1)
+ if (typeIndex > 0) {
+ result.task = (name.substring(taskIndex + TASK_TAG.length, typeIndex)).toShort
+ val metricName = name.substring(typeIndex)
+ result.group = processor + metricName
+ true
+ } else {
+ false
+ }
+ } else {
+ false
+ }
+ }
+}
+
+object ProcessorAggregator {
+ val readOption = ReadOption.Key
+
+ private val TASK_TAG = ".task"
+
+ private class TaskIdentity(var task: Short, var group: String)
+
+ /**
+ *
+ * MultiLayerMap has multiple layers. For each layer, there
+ * is a hashMap.
+ *
+ * To access a value with get, user need to specify first layer Id, then key.
+ *
+ * This class is optimized for performance.
+ */
+ class MultiLayerMap[Value](layers: Int) {
+
+ private var _size: Int = 0
+ private val map: Array[java.util.HashMap[String, Value]] = createMap(layers)
+
+ /**
+ * @param key key in current layer
+ * @return return null if key is not found
+ */
+ def get(layer: Int, key: String): Value = {
+ if (layer < layers) {
+ map(layer).get(key)
+ } else {
+ null.asInstanceOf[Value]
+ }
+ }
+
+ def put(layer: Int, key: String, value: Value): Unit = {
+ if (layer < layers) {
+ map(layer).put(key, value)
+ _size += 1
+ }
+ }
+
+ def size: Int = _size
+
+ def valueIterator: util.Iterator[Value] = {
+ val iterators = new Array[util.Iterator[Value]](layers)
+ var layer = 0
+ while (layer < layers) {
+ iterators(layer) = map(layer).values().iterator()
+ layer += 1
+ }
+
+ Iterators.concat(iterators: _*)
+ }
+
+ private def createMap(layers: Int) = {
+ val map = new Array[java.util.HashMap[String, Value]](layers)
+ var index = 0
+ val length = map.length
+ while (index < length) {
+ map(index) = new java.util.HashMap[String, Value]()
+ index += 1
+ }
+ map
+ }
+ }
+
+ trait Aggregator {
+ def aggregate(item: HistoryMetricsItem): Unit
+ def result: HistoryMetricsItem
+ }
+
+ class HistogramAggregator(name: String) extends Aggregator {
+
+ var count: Long = 0
+ var mean: Double = 0
+ var stddev: Double = 0
+ var median: Double = 0
+ var p95: Double = 0
+ var p99: Double = 0
+ var p999: Double = 0
+
+ var startTime: TimeStamp = Long.MaxValue
+
+ override def aggregate(item: HistoryMetricsItem): Unit = {
+ val input = item.value.asInstanceOf[Histogram]
+ count += 1
+ mean += input.mean
+ stddev += input.stddev
+ median += input.median
+ p95 += input.p95
+ p99 += input.p99
+ p999 += input.p999
+
+ if (item.time < startTime) {
+ startTime = item.time
+ }
+ }
+
+ override def result: HistoryMetricsItem = {
+ if (count > 0) {
+ HistoryMetricsItem(startTime, Histogram(name, mean / count, stddev / count,
+ median / count, p95 / count, p99 / count, p999 / count))
+ } else {
+ HistoryMetricsItem(0, Histogram(name, 0, 0, 0, 0, 0, 0))
+ }
+ }
+ }
+
+ class MeterAggregator(name: String) extends Aggregator {
+
+ var count: Long = 0
+ var meanRate: Double = 0
+ var m1: Double = 0
+ var rateUnit: String = null
+
+ var startTime: TimeStamp = Long.MaxValue
+
+ override def aggregate(item: HistoryMetricsItem): Unit = {
+
+ val input = item.value.asInstanceOf[Meter]
+ count += input.count
+
+ meanRate += input.meanRate
+ m1 += input.m1
+
+ if (null == rateUnit) {
+ rateUnit = input.rateUnit
+ }
+
+ if (item.time < startTime) {
+ startTime = item.time
+ }
+ }
+
+ override def result: HistoryMetricsItem = {
+ HistoryMetricsItem(startTime, Meter(name, count, meanRate,
+ m1, rateUnit))
+ }
+ }
+
+ class AggregatorFactory {
+ def create(item: HistoryMetricsItem, name: String): Aggregator = {
+ item.value match {
+ case meter: Meter => new MeterAggregator(name)
+ case histogram: Histogram => new HistogramAggregator(name)
+ case _ => null // not supported
+ }
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/metrics/TaskFilterAggregator.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/metrics/TaskFilterAggregator.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/metrics/TaskFilterAggregator.scala
new file mode 100644
index 0000000..6bc8964
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/metrics/TaskFilterAggregator.scala
@@ -0,0 +1,157 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.metrics
+
+import scala.collection.mutable.ListBuffer
+import scala.util.{Failure, Success, Try}
+
+import com.typesafe.config.Config
+
+import org.apache.gearpump.cluster.ClientToMaster.ReadOption
+import org.apache.gearpump.cluster.MasterToClient.HistoryMetricsItem
+import org.apache.gearpump.metrics.MetricsAggregator
+import org.apache.gearpump.util.{Constants, LogUtil}
+
+/**
+ * Filters the latest metrics data by specifying a
+ * processor Id range, and taskId range.
+ */
+class TaskFilterAggregator(maxLimit: Int) extends MetricsAggregator {
+
+ import org.apache.gearpump.streaming.metrics.TaskFilterAggregator._
+
+ def this(config: Config) = {
+ this(config.getInt(Constants.GEARPUMP_METRICS_MAX_LIMIT))
+ }
+ override def aggregate(options: Map[String, String], inputs: Iterator[HistoryMetricsItem])
+ : List[HistoryMetricsItem] = {
+
+ if (options.get(ReadOption.Key) != Some(ReadOption.ReadLatest)) {
+ // Returns empty set
+ List.empty[HistoryMetricsItem]
+ } else {
+ val parsed = Options.parse(options)
+ if (parsed != null) {
+ aggregate(parsed, inputs)
+ } else {
+ List.empty[HistoryMetricsItem]
+ }
+ }
+ }
+
+ def aggregate(options: Options, inputs: Iterator[HistoryMetricsItem])
+ : List[HistoryMetricsItem] = {
+
+ val result = new ListBuffer[HistoryMetricsItem]
+ val effectiveLimit = Math.min(options.limit, maxLimit)
+ var count = 0
+
+ val taskIdentity = new TaskIdentity(0, 0)
+
+ while (inputs.hasNext && count < effectiveLimit) {
+ val item = inputs.next()
+ if (parseName(item.value.name, taskIdentity)) {
+ if (taskIdentity.processor >= options.startProcessor &&
+ taskIdentity.processor < options.endProcessor &&
+ taskIdentity.task >= options.startTask &&
+ taskIdentity.task < options.endTask) {
+ result.prepend(item)
+ count += 1
+ }
+ }
+ }
+ result.toList
+ }
+
+ // Assume the name format is: "app0.processor0.task0:sendThroughput", returns
+ // (processorId, taskId)
+ //
+ // returns true if success
+ private def parseName(name: String, result: TaskIdentity): Boolean = {
+ val processorStart = name.indexOf(PROCESSOR_TAG)
+ if (processorStart != -1) {
+ val taskStart = name.indexOf(TASK_TAG, processorStart + 1)
+ if (taskStart != -1) {
+ val processorId = name.substring(processorStart, taskStart).substring(PROCESSOR_TAG.length)
+ .toInt
+ result.processor = processorId
+ val taskEnd = name.indexOf(":", taskStart + 1)
+ if (taskEnd != -1) {
+ val taskId = name.substring(taskStart, taskEnd).substring(TASK_TAG.length).toInt
+ result.task = taskId
+ true
+ } else {
+ false
+ }
+ } else {
+ false
+ }
+ } else {
+ false
+ }
+ }
+}
+
+object TaskFilterAggregator {
+ val StartTask = "startTask"
+ val EndTask = "endTask"
+ val StartProcessor = "startProcessor"
+ val EndProcessor = "endProcessor"
+ val Limit = "limit"
+
+ val TASK_TAG = ".task"
+ val PROCESSOR_TAG = ".processor"
+
+ private class TaskIdentity(var processor: Int, var task: Int)
+
+ case class Options(
+ limit: Int, startTask: Int, endTask: Int, startProcessor: Int, endProcessor: Int)
+
+ private val LOG = LogUtil.getLogger(getClass)
+
+ object Options {
+
+ def acceptAll: Options = {
+ new Options(Int.MaxValue, 0, Int.MaxValue, 0, Int.MaxValue)
+ }
+
+ def parse(options: Map[String, String]): Options = {
+ // Do sanity check
+ val optionTry = Try {
+ val startTask = options.get(StartTask).map(_.toInt).getOrElse(0)
+ val endTask = options.get(EndTask).map(_.toInt).getOrElse(Integer.MAX_VALUE)
+ val startProcessor = options.get(StartProcessor).map(_.toInt).getOrElse(0)
+ val endProcessor = options.get(EndProcessor).map(_.toInt).getOrElse(Integer.MAX_VALUE)
+ val limit = options.get(Limit).map(_.toInt).getOrElse(DEFAULT_LIMIT)
+ new Options(limit, startTask, endTask, startProcessor, endProcessor)
+ }
+
+ optionTry match {
+ case Success(options) => options
+ case Failure(ex) =>
+ LOG.error("Failed to parse the options in TaskFilterAggregator. Error msg: " +
+ ex.getMessage)
+ null
+ }
+ }
+ }
+
+ val DEFAULT_LIMIT = 1000
+ val MAX_LIMIT = 1000
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/package.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/package.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/package.scala
new file mode 100644
index 0000000..27b1136
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/package.scala
@@ -0,0 +1,25 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump
+
+package object streaming {
+ type ProcessorId = Int
+ type TaskIndex = Int
+ type ExecutorId = Int
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/sink/DataSink.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/sink/DataSink.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/sink/DataSink.scala
new file mode 100644
index 0000000..2d81a1f
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/sink/DataSink.scala
@@ -0,0 +1,65 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.sink
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.streaming.task.TaskContext
+
+/**
+ * Interface to implement custom data sink where result of a DAG is typically written
+ * a DataSink could be a data store like HBase or simply a console
+ *
+ * An example would be like:
+ * {{{
+ * class ConsoleSink extends DataSink[String] {
+ *
+ * def open(context: TaskContext): Unit = {}
+ *
+ * def write(s: String): Unit = {
+ * Console.println(s)
+ * }
+ *
+ * def close(): Unit = {}
+ * }
+ * }}}
+ *
+ * Subclass is required to be serializable
+ */
+trait DataSink extends java.io.Serializable {
+
+ /**
+ * Opens connection to data sink
+ * invoked at onStart() method of [[org.apache.gearpump.streaming.task.Task]]
+ * @param context is the task context at runtime
+ */
+ def open(context: TaskContext): Unit
+
+ /**
+ * Writes message into data sink
+ * invoked at onNext() method of [[org.apache.gearpump.streaming.task.Task]]
+ * @param message wraps data to be written out
+ */
+ def write(message: Message): Unit
+
+ /**
+ * Closes connection to data sink
+ * invoked at onClose() method of [[org.apache.gearpump.streaming.task.Task]]
+ */
+ def close(): Unit
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/sink/DataSinkProcessor.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/sink/DataSinkProcessor.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/sink/DataSinkProcessor.scala
new file mode 100644
index 0000000..973e371
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/sink/DataSinkProcessor.scala
@@ -0,0 +1,49 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.sink
+
+import akka.actor.ActorSystem
+
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.Processor
+
+/**
+ * Utility that helps user to create a DAG ending in [[DataSink]]
+ * user should pass in a [[DataSink]].
+ *
+ * here is an example to build a DAG that does word count and write to KafkaSink
+ * {{{
+ * val split = Processor[Split](1)
+ * val sum = Processor[Sum](1)
+ * val sink = new KafkaSink()
+ * val sinkProcessor = DataSinkProcessor(sink, 1)
+ * val dag = split ~> sum ~> sink
+ * }}}
+ */
+object DataSinkProcessor {
+ def apply(
+ dataSink: DataSink,
+ parallelism: Int,
+ description: String = "",
+ taskConf: UserConfig = UserConfig.empty)(implicit system: ActorSystem)
+ : Processor[DataSinkTask] = {
+ Processor[DataSinkTask](parallelism, description = description,
+ taskConf.withValue[DataSink](DataSinkTask.DATA_SINK, dataSink))
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/sink/DataSinkTask.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/sink/DataSinkTask.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/sink/DataSinkTask.scala
new file mode 100644
index 0000000..eb6118d
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/sink/DataSinkTask.scala
@@ -0,0 +1,50 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.sink
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.task.{StartTime, Task, TaskContext}
+
+object DataSinkTask {
+ val DATA_SINK = "data_sink"
+}
+
+/**
+ * General task that runs any [[DataSink]]
+ */
+class DataSinkTask(context: TaskContext, conf: UserConfig) extends Task(context, conf) {
+ import org.apache.gearpump.streaming.sink.DataSinkTask._
+
+ private val sink = conf.getValue[DataSink](DATA_SINK).get
+
+ override def onStart(startTime: StartTime): Unit = {
+ LOG.info("opening data sink...")
+ sink.open(context)
+ }
+
+ override def onNext(message: Message): Unit = {
+ sink.write(message)
+ }
+
+ override def onStop(): Unit = {
+ LOG.info("closing data sink...")
+ sink.close()
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/source/DataSource.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/source/DataSource.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/source/DataSource.scala
new file mode 100644
index 0000000..0fb6db4
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/source/DataSource.scala
@@ -0,0 +1,70 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.source
+
+import org.apache.gearpump.streaming.task.TaskContext
+import org.apache.gearpump.Message
+
+import scala.util.Random
+
+/**
+ * Interface to implement custom source where data is read into the system.
+ * a DataSource could be a message queue like kafka or simply data generation source.
+ *
+ * An example would be like
+ * {{{
+ * GenMsgSource extends DataSource {
+ *
+ * def open(context: TaskContext, startTime: TimeStamp): Unit = {}
+ *
+ * def read(context: TaskContext): Message = {
+ * Message("message")
+ * }
+ *
+ * def close(): Unit = {}
+ * }
+ * }}}
+ *
+ * subclass is required to be serializable
+ */
+trait DataSource extends java.io.Serializable {
+
+ /**
+ * Opens connection to data source
+ * invoked in onStart() method of [[org.apache.gearpump.streaming.source.DataSourceTask]]
+ *
+ * @param context is the task context at runtime
+ * @param startTime is the start time of system
+ */
+ def open(context: TaskContext, startTime: Long): Unit
+
+ /**
+ * Reads next message from data source and
+ * returns null if no message is available
+ *
+ * @return a [[org.apache.gearpump.Message]] or null
+ */
+ def read(): Message
+
+ /**
+ * Closes connection to data source.
+ * invoked in onStop() method of [[org.apache.gearpump.streaming.source.DataSourceTask]]
+ */
+ def close(): Unit
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/source/DataSourceConfig.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/source/DataSourceConfig.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/source/DataSourceConfig.scala
new file mode 100644
index 0000000..4a76958
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/source/DataSourceConfig.scala
@@ -0,0 +1,25 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.source
+
+object DataSourceConfig {
+
+ val SOURCE_READ_BATCH_SIZE = "gearpump.source.read.batch.size"
+ val SOURCE_TIMESTAMP_FILTER = "gearpump.source.timestamp.filter.class"
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/source/DataSourceProcessor.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/source/DataSourceProcessor.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/source/DataSourceProcessor.scala
new file mode 100644
index 0000000..ddd6c27
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/source/DataSourceProcessor.scala
@@ -0,0 +1,49 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.source
+
+import akka.actor.ActorSystem
+
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.Processor
+
+/**
+ * Utility that helps user to create a DAG starting with [[DataSourceTask]]
+ * user should pass in a [[DataSource]]
+ *
+ * Here is an example to build a DAG that reads from Kafka source followed by word count
+ * {{{
+ * val source = new KafkaSource()
+ * val sourceProcessor = DataSourceProcessor(source, 1)
+ * val split = Processor[Split](1)
+ * val sum = Processor[Sum](1)
+ * val dag = sourceProcessor ~> split ~> sum
+ * }}}
+ */
+object DataSourceProcessor {
+ def apply(
+ dataSource: DataSource,
+ parallelism: Int,
+ description: String = "",
+ taskConf: UserConfig = UserConfig.empty)(implicit system: ActorSystem)
+ : Processor[DataSourceTask] = {
+ Processor[DataSourceTask](parallelism, description = description,
+ taskConf.withValue[DataSource](DataSourceTask.DATA_SOURCE, dataSource))
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/source/DataSourceTask.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/source/DataSourceTask.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/source/DataSourceTask.scala
new file mode 100644
index 0000000..6777721
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/source/DataSourceTask.scala
@@ -0,0 +1,66 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.source
+
+import org.apache.gearpump._
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.task.{StartTime, Task, TaskContext}
+
+object DataSourceTask {
+ val DATA_SOURCE = "data_source"
+}
+
+/**
+ * Default Task container for [[org.apache.gearpump.streaming.source.DataSource]] that
+ * reads from DataSource in batch
+ * See [[org.apache.gearpump.streaming.source.DataSourceProcessor]] for its usage
+ *
+ * DataSourceTask calls:
+ * - `DataSource.open()` in `onStart` and pass in
+ * [[org.apache.gearpump.streaming.task.TaskContext]]
+ * and application start time
+ * - `DataSource.read()` in each `onNext`, which reads a batch of messages
+ * - `DataSource.close()` in `onStop`
+ */
+class DataSourceTask(context: TaskContext, conf: UserConfig) extends Task(context, conf) {
+ import org.apache.gearpump.streaming.source.DataSourceTask._
+
+ private val source = conf.getValue[DataSource](DATA_SOURCE).get
+ private val batchSize = conf.getInt(DataSourceConfig.SOURCE_READ_BATCH_SIZE).getOrElse(1000)
+ private var startTime = 0L
+
+ override def onStart(newStartTime: StartTime): Unit = {
+ startTime = newStartTime.startTime
+ LOG.info(s"opening data source at $startTime")
+ source.open(context, startTime)
+ self ! Message("start", System.currentTimeMillis())
+ }
+
+ override def onNext(message: Message): Unit = {
+ 0.until(batchSize).foreach { _ =>
+ Option(source.read()).foreach(context.output)
+ }
+ self ! Message("continue", System.currentTimeMillis())
+ }
+
+ override def onStop(): Unit = {
+ LOG.info("closing data source...")
+ source.close()
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/source/DefaultTimeStampFilter.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/source/DefaultTimeStampFilter.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/source/DefaultTimeStampFilter.scala
new file mode 100644
index 0000000..df54cc2
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/source/DefaultTimeStampFilter.scala
@@ -0,0 +1,31 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.source
+
+import org.apache.gearpump.streaming.transaction.api.TimeStampFilter
+import org.apache.gearpump.{Message, TimeStamp}
+
+/**
+ * TimeStampFilter filters out messages which have obsolete (smaller) timestamp.
+ */
+class DefaultTimeStampFilter extends TimeStampFilter {
+ override def filter(msg: Message, predicate: TimeStamp): Option[Message] = {
+ Option(msg).find(_.timestamp >= predicate)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/state/api/Monoid.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/state/api/Monoid.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/state/api/Monoid.scala
new file mode 100644
index 0000000..9886a72
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/state/api/Monoid.scala
@@ -0,0 +1,28 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.state.api
+
+trait Monoid[T] extends java.io.Serializable {
+ def plus(l: T, r: T): T
+ def zero: T
+}
+
+trait Group[T] extends Monoid[T] {
+ def minus(l: T, r: T): T
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/state/api/MonoidState.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/state/api/MonoidState.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/state/api/MonoidState.scala
new file mode 100644
index 0000000..0e2f83a
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/state/api/MonoidState.scala
@@ -0,0 +1,52 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.state.api
+
+import org.apache.gearpump.TimeStamp
+
+/**
+ * MonoidState uses Algebird Monoid to aggregate state
+ *
+ * on start, state value is initialized to monoid.zero
+ * on each new message, existing state value is aggregated with
+ * the incoming value using monoid.plus to get a new state value
+ */
+abstract class MonoidState[T](monoid: Monoid[T]) extends PersistentState[T] {
+ // Left state updated by messages before checkpoint time
+ private[state] var left: T = monoid.zero
+ // Right state updated by message after checkpoint time
+ private[state] var right: T = monoid.zero
+
+ protected var checkpointTime = Long.MaxValue
+
+ override def get: Option[T] = Option(monoid.plus(left, right))
+
+ override def setNextCheckpointTime(nextCheckpointTime: TimeStamp): Unit = {
+ checkpointTime = nextCheckpointTime
+ }
+
+ protected def updateState(timestamp: TimeStamp, t: T): Unit = {
+ if (timestamp < checkpointTime) {
+ left = monoid.plus(left, t)
+ } else {
+ right = monoid.plus(right, t)
+ }
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/state/api/PersistentState.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/state/api/PersistentState.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/state/api/PersistentState.scala
new file mode 100644
index 0000000..906d331
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/state/api/PersistentState.scala
@@ -0,0 +1,61 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.state.api
+
+import org.apache.gearpump._
+
+/**
+ * PersistentState is part of the transaction API
+ *
+ * Users could get transaction support from the framework by
+ * conforming to PersistentState APIs and extending PersistentTask
+ * to manage the state
+ */
+trait PersistentState[T] {
+
+ /**
+ * Recovers state to a previous checkpoint
+ * usually invoked by the framework
+ */
+ def recover(timestamp: TimeStamp, bytes: Array[Byte]): Unit
+
+ /**
+ * Updates state on a new message
+ * this is invoked by user
+ */
+ def update(timestamp: TimeStamp, t: T): Unit
+
+ /**
+ * Sets next checkpoint time
+ * should be invoked by the framework
+ */
+ def setNextCheckpointTime(timeStamp: TimeStamp): Unit
+
+ /**
+ * Gets a binary snapshot of state
+ * usually invoked by the framework
+ */
+ def checkpoint(): Array[Byte]
+
+ /**
+ * Unwraps the raw value of state
+ */
+ def get: Option[T]
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/state/api/PersistentTask.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/state/api/PersistentTask.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/state/api/PersistentTask.scala
new file mode 100644
index 0000000..e40d8cd
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/state/api/PersistentTask.scala
@@ -0,0 +1,114 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.state.api
+
+import java.util.concurrent.TimeUnit
+import scala.concurrent.duration.FiniteDuration
+
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.state.impl.{CheckpointManager, PersistentStateConfig}
+import org.apache.gearpump.streaming.task.{ReportCheckpointClock, StartTime, Task, TaskContext}
+import org.apache.gearpump.streaming.transaction.api.CheckpointStoreFactory
+import org.apache.gearpump.util.LogUtil
+import org.apache.gearpump.{Message, TimeStamp}
+
+object PersistentTask {
+ val CHECKPOINT = Message("checkpoint")
+ val LOG = LogUtil.getLogger(getClass)
+}
+
+/**
+ * PersistentTask is part of the transaction API
+ *
+ * Users should extend this task if they want to get transaction support
+ * from the framework
+ */
+abstract class PersistentTask[T](taskContext: TaskContext, conf: UserConfig)
+ extends Task(taskContext, conf) {
+ import taskContext._
+
+ import org.apache.gearpump.streaming.state.api.PersistentTask._
+
+ val checkpointStoreFactory = conf.getValue[CheckpointStoreFactory](
+ PersistentStateConfig.STATE_CHECKPOINT_STORE_FACTORY).get
+ val checkpointStore = checkpointStoreFactory.getCheckpointStore(conf, taskContext)
+ val checkpointInterval = conf.getLong(PersistentStateConfig.STATE_CHECKPOINT_INTERVAL_MS).get
+ val checkpointManager = new CheckpointManager(checkpointInterval, checkpointStore)
+ // System time interval to attempt checkpoint
+ private val checkpointAttemptInterval = 1000L
+
+ /**
+ * Subclass should override this method to pass in a PersistentState. the framework has already
+ * offered two states:
+ * - NonWindowState: state with no time or other boundary
+ * - WindowState: each state is bounded by a time window
+ */
+ def persistentState: PersistentState[T]
+
+ /**
+ * Subclass should override this method to specify how a new message should update state
+ */
+ def processMessage(state: PersistentState[T], message: Message): Unit
+
+ /** Persistent state that will be stored (by checkpointing) automatically to storage like HDFS */
+ val state = persistentState
+
+ final override def onStart(startTime: StartTime): Unit = {
+ val timestamp = startTime.startTime
+ checkpointManager
+ .recover(timestamp)
+ .foreach(state.recover(timestamp, _))
+
+ reportCheckpointClock(timestamp)
+ scheduleCheckpoint(checkpointAttemptInterval)
+ }
+
+ final override def onNext(message: Message): Unit = {
+ message match {
+ case CHECKPOINT =>
+ val upstreamMinClock = taskContext.upstreamMinClock
+ if (checkpointManager.shouldCheckpoint(upstreamMinClock)) {
+ checkpointManager.getCheckpointTime.foreach { checkpointTime =>
+ val serialized = state.checkpoint()
+ checkpointManager.checkpoint(checkpointTime, serialized)
+ .foreach(state.setNextCheckpointTime)
+ taskContext.output(Message(serialized, checkpointTime))
+ reportCheckpointClock(checkpointTime)
+ }
+ }
+ scheduleCheckpoint(checkpointAttemptInterval)
+ case _ =>
+ checkpointManager.update(message.timestamp)
+ .foreach(state.setNextCheckpointTime)
+ processMessage(state, message)
+ }
+ }
+
+ final override def onStop(): Unit = {
+ checkpointManager.close()
+ }
+
+ private def scheduleCheckpoint(interval: Long): Unit = {
+ scheduleOnce(new FiniteDuration(interval, TimeUnit.MILLISECONDS))(self ! CHECKPOINT)
+ }
+
+ private def reportCheckpointClock(timestamp: TimeStamp): Unit = {
+ appMaster ! ReportCheckpointClock(taskContext.taskId, timestamp)
+ }
+}
[38/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/io/gearpump/cluster/worker/Worker.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/io/gearpump/cluster/worker/Worker.scala b/daemon/src/main/scala/io/gearpump/cluster/worker/Worker.scala
deleted file mode 100644
index 0568641..0000000
--- a/daemon/src/main/scala/io/gearpump/cluster/worker/Worker.scala
+++ /dev/null
@@ -1,580 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.worker
-
-import java.io.File
-import java.lang.management.ManagementFactory
-import java.net.URL
-import java.util.concurrent.{Executors, TimeUnit}
-import scala.concurrent.duration._
-import scala.concurrent.{ExecutionContext, Future, Promise}
-import scala.util.{Failure, Success, Try}
-
-import akka.actor.SupervisorStrategy.Stop
-import akka.actor._
-import com.typesafe.config.{ConfigValueFactory, Config, ConfigFactory}
-import org.slf4j.Logger
-
-import io.gearpump.cluster.AppMasterToMaster.{GetWorkerData, WorkerData}
-import io.gearpump.cluster.AppMasterToWorker._
-import io.gearpump.cluster.ClientToMaster.{QueryHistoryMetrics, QueryWorkerConfig}
-import io.gearpump.cluster.MasterToClient.{HistoryMetrics, HistoryMetricsItem, WorkerConfig}
-import io.gearpump.cluster.MasterToWorker._
-import io.gearpump.cluster.WorkerToAppMaster._
-import io.gearpump.cluster.WorkerToMaster._
-import io.gearpump.cluster.master.Master.MasterInfo
-import io.gearpump.cluster.scheduler.Resource
-import io.gearpump.cluster.worker.Worker.ExecutorWatcher
-import io.gearpump.cluster.{ClusterConfig, ExecutorJVMConfig}
-import io.gearpump.jarstore.JarStoreService
-import io.gearpump.metrics.Metrics.ReportMetrics
-import io.gearpump.metrics.{JvmMetricsSet, Metrics, MetricsReporterService}
-import io.gearpump.util.ActorSystemBooter.Daemon
-import io.gearpump.util.Constants._
-import io.gearpump.util.HistoryMetricsService.HistoryMetricsConfig
-import io.gearpump.util.{TimeOutScheduler, _}
-
-/**
- * Worker is used to track the resource on single machine, it is like
- * the node manager of YARN.
- *
- * @param masterProxy masterProxy is used to resolve the master
- */
-private[cluster] class Worker(masterProxy: ActorRef) extends Actor with TimeOutScheduler {
- private val systemConfig: Config = context.system.settings.config
-
- private val address = ActorUtil.getFullPath(context.system, self.path)
- private var resource = Resource.empty
- private var allocatedResources = Map[ActorRef, Resource]()
- private var executorsInfo = Map[ActorRef, ExecutorSlots]()
- private var id: WorkerId = WorkerId.unspecified
- private val createdTime = System.currentTimeMillis()
- private var masterInfo: MasterInfo = null
- private var executorNameToActor = Map.empty[String, ActorRef]
- private val executorProcLauncher: ExecutorProcessLauncher = getExecutorProcLauncher()
- private val jarStoreService = JarStoreService.get(systemConfig)
- jarStoreService.init(systemConfig, context.system)
-
- private val ioPool = ExecutionContext.fromExecutorService(Executors.newCachedThreadPool())
- private val resourceUpdateTimeoutMs = 30000 // Milliseconds
-
- private var totalSlots: Int = 0
-
- val metricsEnabled = systemConfig.getBoolean(GEARPUMP_METRIC_ENABLED)
- var historyMetricsService: Option[ActorRef] = None
-
- override def receive: Receive = null
- var LOG: Logger = LogUtil.getLogger(getClass)
-
- def service: Receive =
- appMasterMsgHandler orElse
- clientMessageHandler orElse
- metricsService orElse
- terminationWatch(masterInfo.master) orElse
- ActorUtil.defaultMsgHandler(self)
-
- def metricsService: Receive = {
- case query: QueryHistoryMetrics =>
- if (historyMetricsService.isEmpty) {
- // Returns empty metrics so that we don't hang the UI
- sender ! HistoryMetrics(query.path, List.empty[HistoryMetricsItem])
- } else {
- historyMetricsService.get forward query
- }
- }
-
- private var metricsInitialized = false
-
- val getHistoryMetricsConfig = HistoryMetricsConfig(systemConfig)
-
- private def initializeMetrics(): Unit = {
- // Registers jvm metrics
- val metricsSetName = "worker" + WorkerId.render(id)
- Metrics(context.system).register(new JvmMetricsSet(metricsSetName))
-
- historyMetricsService = if (metricsEnabled) {
- val historyMetricsService = {
- context.actorOf(Props(new HistoryMetricsService(metricsSetName, getHistoryMetricsConfig)))
- }
-
- val metricsReportService = context.actorOf(Props(
- new MetricsReporterService(Metrics(context.system))))
- historyMetricsService.tell(ReportMetrics, metricsReportService)
- Some(historyMetricsService)
- } else {
- None
- }
- }
-
- def waitForMasterConfirm(timeoutTicker: Cancellable): Receive = {
-
- // If master get disconnected, the WorkerRegistered may be triggered multiple times.
- case WorkerRegistered(id, masterInfo) =>
- this.id = id
-
- // Adds the flag check, so that we don't re-initialize the metrics when worker re-register
- // itself.
- if (!metricsInitialized) {
- initializeMetrics()
- metricsInitialized = true
- }
-
- this.masterInfo = masterInfo
- timeoutTicker.cancel()
- context.watch(masterInfo.master)
- this.LOG = LogUtil.getLogger(getClass, worker = id)
- LOG.info(s"Worker is registered. " +
- s"actor path: ${ActorUtil.getFullPath(context.system, self.path)} ....")
- sendMsgWithTimeOutCallBack(masterInfo.master, ResourceUpdate(self, id, resource),
- resourceUpdateTimeoutMs, updateResourceTimeOut())
- context.become(service)
- }
-
- private def updateResourceTimeOut(): Unit = {
- LOG.error(s"Update worker resource time out")
- }
-
- def appMasterMsgHandler: Receive = {
- case shutdown@ShutdownExecutor(appId, executorId, reason: String) =>
- val actorName = ActorUtil.actorNameForExecutor(appId, executorId)
- val executorToStop = executorNameToActor.get(actorName)
- if (executorToStop.isDefined) {
- LOG.info(s"Shutdown executor ${actorName}(${executorToStop.get.path.toString}) " +
- s"due to: $reason")
- executorToStop.get.forward(shutdown)
- } else {
- LOG.error(s"Cannot find executor $actorName, ignore this message")
- sender ! ShutdownExecutorFailed(s"Can not find executor $executorId for app $appId")
- }
- case launch: LaunchExecutor =>
- LOG.info(s"$launch")
- if (resource < launch.resource) {
- sender ! ExecutorLaunchRejected("There is no free resource on this machine")
- } else {
- val actorName = ActorUtil.actorNameForExecutor(launch.appId, launch.executorId)
-
- val executor = context.actorOf(Props(classOf[ExecutorWatcher], launch, masterInfo, ioPool,
- jarStoreService, executorProcLauncher))
- executorNameToActor += actorName -> executor
-
- resource = resource - launch.resource
- allocatedResources = allocatedResources + (executor -> launch.resource)
-
- reportResourceToMaster()
- executorsInfo += executor ->
- ExecutorSlots(launch.appId, launch.executorId, launch.resource.slots)
- context.watch(executor)
- }
- case UpdateResourceFailed(reason, ex) =>
- LOG.error(reason)
- context.stop(self)
- case UpdateResourceSucceed =>
- LOG.info(s"Update resource succeed")
- case GetWorkerData(workerId) =>
- val aliveFor = System.currentTimeMillis() - createdTime
- val logDir = LogUtil.daemonLogDir(systemConfig).getAbsolutePath
- val userDir = System.getProperty("user.dir")
- sender ! WorkerData(WorkerSummary(
- id, "active",
- address,
- aliveFor,
- logDir,
- executorsInfo.values.toArray,
- totalSlots,
- resource.slots,
- userDir,
- jvmName = ManagementFactory.getRuntimeMXBean().getName(),
- resourceManagerContainerId = systemConfig.getString(
- GEARPUMP_WORKER_RESOURCE_MANAGER_CONTAINER_ID),
- historyMetricsConfig = getHistoryMetricsConfig)
- )
- case ChangeExecutorResource(appId, executorId, usedResource) =>
- for (executor <- executorActorRef(appId, executorId);
- allocatedResource <- allocatedResources.get(executor)) {
-
- allocatedResources += executor -> usedResource
- resource = resource + allocatedResource - usedResource
- reportResourceToMaster()
-
- if (usedResource == Resource(0)) {
- allocatedResources -= executor
- // stop executor if there is no resource binded to it.
- LOG.info(s"Shutdown executor $executorId because the resource used is zero")
- executor ! ShutdownExecutor(appId, executorId,
- "Shutdown executor because the resource used is zero")
- }
- }
- }
-
- private def reportResourceToMaster(): Unit = {
- sendMsgWithTimeOutCallBack(masterInfo.master,
- ResourceUpdate(self, id, resource), resourceUpdateTimeoutMs, updateResourceTimeOut())
- }
-
- private def executorActorRef(appId: Int, executorId: Int): Option[ActorRef] = {
- val actorName = ActorUtil.actorNameForExecutor(appId, executorId)
- executorNameToActor.get(actorName)
- }
-
- def clientMessageHandler: Receive = {
- case QueryWorkerConfig(workerId) =>
- if (this.id == workerId) {
- sender ! WorkerConfig(ClusterConfig.filterOutDefaultConfig(systemConfig))
- } else {
- sender ! WorkerConfig(ConfigFactory.empty)
- }
- }
-
- private def retryRegisterWorker(workerId: WorkerId, timeOutSeconds: Int): Cancellable = {
- repeatActionUtil(
- seconds = timeOutSeconds,
- action = () => {
- masterProxy ! RegisterWorker(workerId)
- },
- onTimeout = () => {
- LOG.error(s"Failed to register the worker $workerId after retrying for $timeOutSeconds " +
- s"seconds, abort and kill the worker...")
- self ! PoisonPill
- })
- }
-
- def terminationWatch(master: ActorRef): Receive = {
- case Terminated(actor) =>
- if (actor.compareTo(master) == 0) {
- // Parent master is down, no point to keep worker anymore. Let's make suicide to free
- // resources
- LOG.info(s"Master cannot be contacted, find a new master ...")
- context.become(waitForMasterConfirm(retryRegisterWorker(id, timeOutSeconds = 30)))
- } else if (ActorUtil.isChildActorPath(self, actor)) {
- // One executor is down,
- LOG.info(s"Executor is down ${getExecutorName(actor)}")
-
- val allocated = allocatedResources.get(actor)
- if (allocated.isDefined) {
- resource = resource + allocated.get
- executorsInfo -= actor
- allocatedResources = allocatedResources - actor
- sendMsgWithTimeOutCallBack(master, ResourceUpdate(self, id, resource),
- resourceUpdateTimeoutMs, updateResourceTimeOut())
- }
- }
- }
-
- private def getExecutorName(actorRef: ActorRef): Option[String] = {
- executorNameToActor.find(_._2 == actorRef).map(_._1)
- }
-
- private def getExecutorProcLauncher(): ExecutorProcessLauncher = {
- val launcherClazz = Class.forName(
- systemConfig.getString(GEARPUMP_EXECUTOR_PROCESS_LAUNCHER))
- launcherClazz.getConstructor(classOf[Config]).newInstance(systemConfig)
- .asInstanceOf[ExecutorProcessLauncher]
- }
-
- import context.dispatcher
- override def preStart(): Unit = {
- LOG.info(s"RegisterNewWorker")
- totalSlots = systemConfig.getInt(GEARPUMP_WORKER_SLOTS)
- this.resource = Resource(totalSlots)
- masterProxy ! RegisterNewWorker
- context.become(waitForMasterConfirm(registerTimeoutTicker(seconds = 30)))
- }
-
- private def registerTimeoutTicker(seconds: Int): Cancellable = {
- repeatActionUtil(seconds, () => Unit, () => {
- LOG.error(s"Failed to register new worker to Master after waiting for $seconds seconds, " +
- s"abort and kill the worker...")
- self ! PoisonPill
- })
- }
-
- private def repeatActionUtil(seconds: Int, action: () => Unit, onTimeout: () => Unit)
- : Cancellable = {
- val cancelTimeout = context.system.scheduler.schedule(Duration.Zero,
- Duration(2, TimeUnit.SECONDS))(action())
- val cancelSuicide = context.system.scheduler.scheduleOnce(seconds.seconds)(onTimeout())
- new Cancellable {
- def cancel(): Boolean = {
- val result1 = cancelTimeout.cancel()
- val result2 = cancelSuicide.cancel()
- result1 && result2
- }
-
- def isCancelled: Boolean = {
- cancelTimeout.isCancelled && cancelSuicide.isCancelled
- }
- }
- }
-
- override def postStop(): Unit = {
- LOG.info(s"Worker is going down....")
- ioPool.shutdown()
- context.system.terminate()
- }
-}
-
-private[cluster] object Worker {
-
- case class ExecutorResult(result: Try[Int])
-
- class ExecutorWatcher(
- launch: LaunchExecutor,
- masterInfo: MasterInfo,
- ioPool: ExecutionContext,
- jarStoreService: JarStoreService,
- procLauncher: ExecutorProcessLauncher) extends Actor {
- import launch.{appId, executorId, resource}
-
- private val LOG: Logger = LogUtil.getLogger(getClass, app = appId, executor = executorId)
-
- val executorConfig: Config = {
- val workerConfig = context.system.settings.config
-
- val submissionConfig = Option(launch.executorJvmConfig).flatMap { jvmConfig =>
- Option(jvmConfig.executorAkkaConfig)
- }.getOrElse(ConfigFactory.empty())
-
- resolveExecutorConfig(workerConfig, submissionConfig)
- }
-
- // For some config, worker has priority, for others, user Application submission config
- // have priorities.
- private def resolveExecutorConfig(workerConfig: Config, submissionConfig: Config): Config = {
- val config = submissionConfig.withoutPath(GEARPUMP_HOSTNAME)
- .withoutPath(GEARPUMP_CLUSTER_MASTERS)
- .withoutPath(GEARPUMP_HOME)
- .withoutPath(GEARPUMP_LOG_DAEMON_DIR)
- .withoutPath(GEARPUMP_CLUSTER_EXECUTOR_WORKER_SHARE_SAME_PROCESS)
- // Falls back to workerConfig
- .withFallback(workerConfig)
-
- // Minimum supported akka.scheduler.tick-duration on Windows is 10ms
- val duration = config.getInt(AKKA_SCHEDULER_TICK_DURATION)
- val updatedConf = if (akka.util.Helpers.isWindows && duration < 10) {
- LOG.warn(s"$AKKA_SCHEDULER_TICK_DURATION on Windows must be larger than 10ms, set to 10ms")
- config.withValue(AKKA_SCHEDULER_TICK_DURATION, ConfigValueFactory.fromAnyRef(10))
- } else {
- config
- }
-
- // Excludes reference.conf, and JVM properties..
- ClusterConfig.filterOutDefaultConfig(updatedConf)
- }
-
- implicit val executorService = ioPool
-
- private val executorHandler = {
- val ctx = launch.executorJvmConfig
-
- if (executorConfig.getBoolean(GEARPUMP_CLUSTER_EXECUTOR_WORKER_SHARE_SAME_PROCESS)) {
- new ExecutorHandler {
- val exitPromise = Promise[Int]()
- val app = context.actorOf(Props(new InJvmExecutor(launch, exitPromise)))
-
- override def destroy(): Unit = {
- context.stop(app)
- }
- override def exitValue: Future[Int] = {
- exitPromise.future
- }
- }
- } else {
- createProcess(ctx)
- }
- }
-
- private def createProcess(ctx: ExecutorJVMConfig): ExecutorHandler = {
-
- val process = Future {
- val jarPath = ctx.jar.map { appJar =>
- val tempFile = File.createTempFile(appJar.name, ".jar")
- jarStoreService.copyToLocalFile(tempFile, appJar.filePath)
- val file = new URL("file:" + tempFile)
- file.getFile
- }
-
- val configFile = {
- val configFile = File.createTempFile("gearpump", ".conf")
- ClusterConfig.saveConfig(executorConfig, configFile)
- val file = new URL("file:" + configFile)
- file.getFile
- }
-
- val classPath = filterOutDaemonLib(Util.getCurrentClassPath) ++
- ctx.classPath.map(path => expandEnviroment(path)) ++
- jarPath.map(Array(_)).getOrElse(Array.empty[String])
-
- val appLogDir = executorConfig.getString(GEARPUMP_LOG_APPLICATION_DIR)
- val logArgs = List(
- s"-D${GEARPUMP_APPLICATION_ID}=${launch.appId}",
- s"-D${GEARPUMP_EXECUTOR_ID}=${launch.executorId}",
- s"-D${GEARPUMP_MASTER_STARTTIME}=${getFormatedTime(masterInfo.startTime)}",
- s"-D${GEARPUMP_LOG_APPLICATION_DIR}=${appLogDir}")
- val configArgs = List(s"-D${GEARPUMP_CUSTOM_CONFIG_FILE}=$configFile")
-
- val username = List(s"-D${GEARPUMP_USERNAME}=${ctx.username}")
-
- // Remote debug executor process
- val remoteDebugFlag = executorConfig.getBoolean(GEARPUMP_REMOTE_DEBUG_EXECUTOR_JVM)
- val remoteDebugConfig = if (remoteDebugFlag) {
- val availablePort = Util.findFreePort().get
- List(
- "-Xdebug",
- s"-Xrunjdwp:server=y,transport=dt_socket,address=${availablePort},suspend=n",
- s"-D${GEARPUMP_REMOTE_DEBUG_PORT}=$availablePort"
- )
- } else {
- List.empty[String]
- }
-
- val verboseGCFlag = executorConfig.getBoolean(GEARPUMP_VERBOSE_GC)
- val verboseGCConfig = if (verboseGCFlag) {
- List(
- s"-Xloggc:${appLogDir}/gc-app${launch.appId}-executor-${launch.executorId}.log",
- "-verbose:gc",
- "-XX:+PrintGCDetails",
- "-XX:+PrintGCDateStamps",
- "-XX:+PrintTenuringDistribution",
- "-XX:+PrintGCApplicationConcurrentTime",
- "-XX:+PrintGCApplicationStoppedTime"
- )
- } else {
- List.empty[String]
- }
-
- val ipv4 = List(s"-D${PREFER_IPV4}=true")
-
- val options = ctx.jvmArguments ++ username ++
- logArgs ++ remoteDebugConfig ++ verboseGCConfig ++ ipv4 ++ configArgs
-
- LOG.info(s"Launch executor, classpath: ${classPath.mkString(File.pathSeparator)}")
- val process = procLauncher.createProcess(appId, executorId, resource, executorConfig,
- options, classPath, ctx.mainClass, ctx.arguments)
-
- ProcessInfo(process, jarPath, configFile)
- }
-
- new ExecutorHandler {
-
- var destroyed = false
-
- override def destroy(): Unit = {
- LOG.info(s"Destroy executor process ${ctx.mainClass}")
- if (!destroyed) {
- destroyed = true
- process.foreach { info =>
- info.process.destroy()
- info.jarPath.foreach(new File(_).delete())
- new File(info.configFile).delete()
- }
- }
- }
-
- override def exitValue: Future[Int] = {
- process.flatMap { info =>
- val exit = info.process.exitValue()
- if (exit == 0) {
- Future.successful(0)
- } else {
- Future.failed[Int](new Exception(s"Executor exit with failure, exit value: $exit, " +
- s"error summary: ${info.process.logger.error}"))
- }
- }
- }
- }
- }
-
- private def expandEnviroment(path: String): String = {
- // TODO: extend this to support more environment.
- path.replace(s"<${GEARPUMP_HOME}>", executorConfig.getString(GEARPUMP_HOME))
- }
-
- override def preStart(): Unit = {
- executorHandler.exitValue.onComplete { value =>
- procLauncher.cleanProcess(appId, executorId)
- val result = ExecutorResult(value)
- self ! result
- }
- }
-
- override def postStop(): Unit = {
- executorHandler.destroy()
- }
-
- // The folders are under ${GEARPUMP_HOME}
- val daemonPathPattern = List("lib" + File.separator + "daemon", "lib" +
- File.separator + "yarn")
-
- override def receive: Receive = {
- case ShutdownExecutor(appId, executorId, reason: String) =>
- executorHandler.destroy()
- sender ! ShutdownExecutorSucceed(appId, executorId)
- context.stop(self)
- case ExecutorResult(executorResult) =>
- executorResult match {
- case Success(exit) => LOG.info("Executor exit normally with exit value " + exit)
- case Failure(e) => LOG.error("Executor exit with errors", e)
- }
- context.stop(self)
- }
-
- private def getFormatedTime(timestamp: Long): String = {
- val datePattern = "yyyy-MM-dd-HH-mm"
- val format = new java.text.SimpleDateFormat(datePattern)
- format.format(timestamp)
- }
-
- private def filterOutDaemonLib(classPath: Array[String]): Array[String] = {
- classPath.filterNot(matchDaemonPattern(_))
- }
-
- private def matchDaemonPattern(path: String): Boolean = {
- daemonPathPattern.exists(path.contains(_))
- }
- }
-
- trait ExecutorHandler {
- def destroy(): Unit
- def exitValue: Future[Int]
- }
-
- case class ProcessInfo(process: RichProcess, jarPath: Option[String], configFile: String)
-
- /**
- * Starts the executor in the same JVM as worker.
- */
- class InJvmExecutor(launch: LaunchExecutor, exit: Promise[Int])
- extends Daemon(launch.executorJvmConfig.arguments(0), launch.executorJvmConfig.arguments(1)) {
- private val exitCode = 0
-
- override val supervisorStrategy =
- OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1.minute) {
- case ex: Throwable =>
- LOG.error(s"system $name stopped ", ex)
- exit.failure(ex)
- Stop
- }
-
- override def postStop(): Unit = {
- if (!exit.isCompleted) {
- exit.success(exitCode)
- }
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/io/gearpump/jarstore/dfs/DFSJarStoreService.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/io/gearpump/jarstore/dfs/DFSJarStoreService.scala b/daemon/src/main/scala/io/gearpump/jarstore/dfs/DFSJarStoreService.scala
deleted file mode 100644
index 305bdc1..0000000
--- a/daemon/src/main/scala/io/gearpump/jarstore/dfs/DFSJarStoreService.scala
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.jarstore.dfs
-
-import java.io.File
-
-import akka.actor.ActorSystem
-import com.typesafe.config.Config
-import org.apache.hadoop.conf.Configuration
-import org.apache.hadoop.fs.Path
-import org.apache.hadoop.fs.permission.{FsAction, FsPermission}
-import org.slf4j.Logger
-
-import io.gearpump.jarstore.{FilePath, JarStoreService}
-import io.gearpump.util.{Constants, LogUtil}
-
-/**
- * DFSJarStoreService store the uploaded jar on HDFS
- */
-class DFSJarStoreService extends JarStoreService {
- private val LOG: Logger = LogUtil.getLogger(getClass)
- private var rootPath: Path = null
-
- override val scheme: String = "hdfs"
-
- override def init(config: Config, actorRefFactory: ActorSystem): Unit = {
- rootPath = new Path(config.getString(Constants.GEARPUMP_APP_JAR_STORE_ROOT_PATH))
- val fs = rootPath.getFileSystem(new Configuration())
- if (!fs.exists(rootPath)) {
- fs.mkdirs(rootPath, new FsPermission(FsAction.ALL, FsAction.ALL, FsAction.ALL))
- }
- }
-
- /**
- * This function will copy the remote file to local file system, called from client side.
- *
- * @param localFile The destination of file path
- * @param remotePath The remote file path from JarStore
- */
- override def copyToLocalFile(localFile: File, remotePath: FilePath): Unit = {
- LOG.info(s"Copying to local file: ${localFile.getAbsolutePath} from ${remotePath}")
- val filePath = new Path(rootPath, remotePath.path)
- val fs = filePath.getFileSystem(new Configuration())
- val target = new Path(localFile.toURI().toString)
- fs.copyToLocalFile(filePath, target)
- }
-
- /**
- * This function will copy the local file to the remote JarStore, called from client side.
- *
- * @param localFile The local file
- */
- override def copyFromLocal(localFile: File): FilePath = {
- val remotePath = FilePath(Math.abs(new java.util.Random().nextLong()).toString)
- LOG.info(s"Copying from local file: ${localFile.getAbsolutePath} to ${remotePath}")
- val filePath = new Path(rootPath, remotePath.path)
- val fs = filePath.getFileSystem(new Configuration())
- fs.copyFromLocalFile(new Path(localFile.toURI.toString), filePath)
- remotePath
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/io/gearpump/jarstore/local/LocalJarStore.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/io/gearpump/jarstore/local/LocalJarStore.scala b/daemon/src/main/scala/io/gearpump/jarstore/local/LocalJarStore.scala
deleted file mode 100644
index fa1a240..0000000
--- a/daemon/src/main/scala/io/gearpump/jarstore/local/LocalJarStore.scala
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.jarstore.local
-
-import java.io.File
-
-import akka.actor.{Actor, Stash}
-import akka.pattern.pipe
-import org.slf4j.Logger
-
-import io.gearpump.cluster.ClientToMaster.{GetJarStoreServer, JarStoreServerAddress}
-import io.gearpump.util._
-
-/**
- * LocalJarStore store the uploaded jar on local disk.
- */
-class LocalJarStore(rootDirPath: String) extends Actor with Stash {
- private val LOG: Logger = LogUtil.getLogger(getClass)
-
- val host = context.system.settings.config.getString(Constants.GEARPUMP_HOSTNAME)
- val rootDirectory = new File(rootDirPath)
-
- FileUtils.forceMkdir(rootDirectory)
-
- val server = new FileServer(context.system, host, 0, rootDirectory)
-
- implicit val timeout = Constants.FUTURE_TIMEOUT
- implicit val executionContext = context.dispatcher
-
- server.start pipeTo self
-
- def receive: Receive = {
- case FileServer.Port(port) =>
- context.become(listen(port))
- unstashAll()
- case _ =>
- stash()
- }
-
- def listen(port: Int): Receive = {
- case GetJarStoreServer =>
- sender ! JarStoreServerAddress(s"http://$host:$port/")
- }
-
- override def postStop(): Unit = {
- server.stop
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/io/gearpump/jarstore/local/LocalJarStoreService.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/io/gearpump/jarstore/local/LocalJarStoreService.scala b/daemon/src/main/scala/io/gearpump/jarstore/local/LocalJarStoreService.scala
deleted file mode 100644
index 969ce90..0000000
--- a/daemon/src/main/scala/io/gearpump/jarstore/local/LocalJarStoreService.scala
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.jarstore.local
-
-import java.io.File
-import java.util.concurrent.TimeUnit
-import scala.collection.JavaConverters._
-import scala.concurrent.duration.Duration
-import scala.concurrent.{Await, ExecutionContext, Future}
-
-import akka.actor.{ActorRef, ActorSystem}
-import akka.pattern.ask
-import com.typesafe.config.Config
-import org.slf4j.Logger
-
-import io.gearpump.cluster.ClientToMaster.{GetJarStoreServer, JarStoreServerAddress}
-import io.gearpump.cluster.master.MasterProxy
-import io.gearpump.jarstore.{FilePath, JarStoreService}
-import io.gearpump.util._
-
-/**
- * LocalJarStoreService store the uploaded jar on local disk.
- */
-class LocalJarStoreService extends JarStoreService {
- private def LOG: Logger = LogUtil.getLogger(getClass)
- private implicit val timeout = Constants.FUTURE_TIMEOUT
- private var system: akka.actor.ActorSystem = null
- private var master: ActorRef = null
- private implicit def dispatcher: ExecutionContext = system.dispatcher
-
- override val scheme: String = "file"
-
- override def init(config: Config, system: ActorSystem): Unit = {
- this.system = system
- val masters = config.getStringList(Constants.GEARPUMP_CLUSTER_MASTERS)
- .asScala.flatMap(Util.parseHostList)
- master = system.actorOf(MasterProxy.props(masters), s"masterproxy${Util.randInt()}")
- }
-
- private lazy val client = (master ? GetJarStoreServer).asInstanceOf[Future[JarStoreServerAddress]]
- .map { address =>
- val client = new FileServer.Client(system, address.url)
- client
- }
-
- /**
- * This function will copy the remote file to local file system, called from client side.
- *
- * @param localFile The destination of file path
- * @param remotePath The remote file path from JarStore
- */
- override def copyToLocalFile(localFile: File, remotePath: FilePath): Unit = {
- LOG.info(s"Copying to local file: ${localFile.getAbsolutePath} from $remotePath")
- val future = client.flatMap(_.download(remotePath, localFile))
- Await.ready(future, Duration(60, TimeUnit.SECONDS))
- }
-
- /**
- * This function will copy the local file to the remote JarStore, called from client side.
- * @param localFile The local file
- */
- override def copyFromLocal(localFile: File): FilePath = {
- val future = client.flatMap(_.upload(localFile))
- Await.result(future, Duration(60, TimeUnit.SECONDS))
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/io/gearpump/util/FileDirective.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/io/gearpump/util/FileDirective.scala b/daemon/src/main/scala/io/gearpump/util/FileDirective.scala
deleted file mode 100644
index 1824a22..0000000
--- a/daemon/src/main/scala/io/gearpump/util/FileDirective.scala
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.util
-
-import java.io.File
-import scala.concurrent.{ExecutionContext, Future}
-
-import akka.http.scaladsl.model.{HttpEntity, MediaTypes, Multipart}
-import akka.http.scaladsl.server.Directives._
-import akka.http.scaladsl.server._
-import akka.stream.Materializer
-import akka.stream.scaladsl.FileIO
-import akka.util.ByteString
-
-/**
- * FileDirective is a set of Akka-http directive to upload/download
- * huge binary files to/from Akka-Http server.
- */
-object FileDirective {
-
- // Form field name
- type Name = String
-
- val CHUNK_SIZE = 262144
-
- /**
- * File information after a file is uploaded to server.
- *
- * @param originFileName original file name when user upload it in browser.
- * @param file file name after the file is saved to server.
- * @param length the length of the file
- */
- case class FileInfo(originFileName: String, file: File, length: Long)
-
- class Form(val fields: Map[Name, FormField]) {
- def getFile(fieldName: String): Option[FileInfo] = {
- fields.get(fieldName).flatMap {
- case Left(file) => Option(file)
- case Right(_) => None
- }
- }
-
- def getValue(fieldName: String): Option[String] = {
- fields.get(fieldName).flatMap {
- case Left(_) => None
- case Right(value) => Option(value)
- }
- }
- }
-
- type FormField = Either[FileInfo, String]
-
- /**
- * directive to uploadFile, it store the uploaded files
- * to temporary directory, and return a Map from form field name
- * to FileInfo.
- */
- def uploadFile: Directive1[Form] = {
- uploadFileTo(null)
- }
-
- /**
- * Store the uploaded files to specific rootDirectory.
- *
- * @param rootDirectory directory to store the files.
- * @return
- */
- def uploadFileTo(rootDirectory: File): Directive1[Form] = {
- Directive[Tuple1[Form]] { inner =>
- extractMaterializer {implicit mat =>
- extractExecutionContext {implicit ec =>
- uploadFileImpl(rootDirectory)(mat, ec) { filesFuture =>
- ctx => {
- filesFuture.map(map => inner(Tuple1(map))).flatMap(route => route(ctx))
- }
- }
- }
- }
- }
- }
-
- // Downloads file from server
- def downloadFile(file: File): Route = {
- val responseEntity = HttpEntity(
- MediaTypes.`application/octet-stream`,
- file.length,
- FileIO.fromFile(file, CHUNK_SIZE))
- complete(responseEntity)
- }
-
- private def uploadFileImpl(rootDirectory: File)(implicit mat: Materializer, ec: ExecutionContext)
- : Directive1[Future[Form]] = {
- Directive[Tuple1[Future[Form]]] { inner =>
- entity(as[Multipart.FormData]) { (formdata: Multipart.FormData) =>
- val form = formdata.parts.mapAsync(1) { p =>
- if (p.filename.isDefined) {
-
- // Reserve the suffix
- val targetPath = File.createTempFile(s"userfile_${p.name}_",
- s"${p.filename.getOrElse("")}", rootDirectory)
- val written = p.entity.dataBytes.runWith(FileIO.toFile(targetPath))
- written.map(written =>
- if (written.count > 0) {
- Map(p.name -> Left(FileInfo(p.filename.get, targetPath, written.count)))
- } else {
- Map.empty[Name, FormField]
- })
- } else {
- val valueFuture = p.entity.dataBytes.runFold(ByteString.empty) {(total, input) =>
- total ++ input
- }
- valueFuture.map{value =>
- Map(p.name -> Right(value.utf8String))
- }
- }
- }.runFold(new Form(Map.empty[Name, FormField])) {(set, value) =>
- new Form(set.fields ++ value)
- }
-
- inner(Tuple1(form))
- }
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/io/gearpump/util/FileServer.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/io/gearpump/util/FileServer.scala b/daemon/src/main/scala/io/gearpump/util/FileServer.scala
deleted file mode 100644
index bf389f7..0000000
--- a/daemon/src/main/scala/io/gearpump/util/FileServer.scala
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.util
-
-import java.io.File
-import scala.concurrent.{ExecutionContext, Future}
-
-import akka.actor.ActorSystem
-import akka.http.scaladsl.Http
-import akka.http.scaladsl.Http.ServerBinding
-import akka.http.scaladsl.marshalling.Marshal
-import akka.http.scaladsl.model.Uri.{Path, Query}
-import akka.http.scaladsl.model.{HttpEntity, HttpRequest, MediaTypes, Multipart, _}
-import akka.http.scaladsl.server.Directives._
-import akka.http.scaladsl.server._
-import akka.http.scaladsl.unmarshalling.Unmarshal
-import akka.stream.ActorMaterializer
-import akka.stream.scaladsl.{FileIO, Sink, Source}
-import spray.json.DefaultJsonProtocol._
-import spray.json.JsonFormat
-
-import io.gearpump.jarstore.FilePath
-import io.gearpump.util.FileDirective._
-import io.gearpump.util.FileServer.Port
-
-/**
- * A simple file server implemented with akka-http to store/fetch large
- * binary files.
- */
-class FileServer(system: ActorSystem, host: String, port: Int = 0, rootDirectory: File) {
- import system.dispatcher
- implicit val actorSystem = system
- implicit val materializer = ActorMaterializer()
- implicit def ec: ExecutionContext = system.dispatcher
-
- val route: Route = {
- path("upload") {
- uploadFileTo(rootDirectory) { form =>
- val fileName = form.fields.headOption.flatMap { pair =>
- val (_, fileInfo) = pair
- fileInfo match {
- case Left(file) => Option(file.file).map(_.getName)
- case Right(_) => None
- }
- }
-
- if (fileName.isDefined) {
- complete(fileName.get)
- } else {
- failWith(new Exception("File not found in the uploaded form"))
- }
- }
- } ~
- path("download") {
- parameters("file") { file: String =>
- downloadFile(new File(rootDirectory, file))
- }
- } ~
- pathEndOrSingleSlash {
- extractUri { uri =>
- val upload = uri.withPath(Uri.Path("/upload")).toString()
- val entity = HttpEntity(ContentTypes.`text/html(UTF-8)`,
- s"""
- |
- |<h2>Please specify a file to upload:</h2>
- |<form action="$upload" enctype="multipart/form-data" method="post">
- |<input type="file" name="datafile" size="40">
- |</p>
- |<div>
- |<input type="submit" value="Submit">
- |</div>
- |</form>
- """.stripMargin)
- complete(entity)
- }
- }
- }
-
- private var connection: Future[ServerBinding] = null
-
- def start: Future[Port] = {
- connection = Http().bindAndHandle(Route.handlerFlow(route), host, port)
- connection.map(address => Port(address.localAddress.getPort))
- }
-
- def stop: Future[Unit] = {
- connection.flatMap(_.unbind())
- }
-}
-
-object FileServer {
-
- implicit def filePathFormat: JsonFormat[FilePath] = jsonFormat1(FilePath.apply)
-
- case class Port(port: Int)
-
- /**
- * Client of [[io.gearpump.util.FileServer]]
- */
- class Client(system: ActorSystem, host: String, port: Int) {
-
- def this(system: ActorSystem, url: String) = {
- this(system, Uri(url).authority.host.address(), Uri(url).authority.port)
- }
-
- private implicit val actorSystem = system
- private implicit val materializer = ActorMaterializer()
- private implicit val ec = system.dispatcher
-
- val server = Uri(s"http://$host:$port")
- val httpClient = Http(system).outgoingConnection(server.authority.host.address(),
- server.authority.port)
-
- def upload(file: File): Future[FilePath] = {
- val target = server.withPath(Path("/upload"))
-
- val request = entity(file).map { entity =>
- HttpRequest(HttpMethods.POST, uri = target, entity = entity)
- }
-
- val response = Source.fromFuture(request).via(httpClient).runWith(Sink.head)
- response.flatMap { some =>
- Unmarshal(some).to[String]
- }.map { path =>
- FilePath(path)
- }
- }
-
- def download(remoteFile: FilePath, saveAs: File): Future[Unit] = {
- val download = server.withPath(Path("/download")).withQuery(Query("file" -> remoteFile.path))
- // Download file to local
- val response = Source.single(HttpRequest(uri = download)).via(httpClient).runWith(Sink.head)
- val downloaded = response.flatMap { response =>
- response.entity.dataBytes.runWith(FileIO.toFile(saveAs))
- }
- downloaded.map(written => Unit)
- }
-
- private def entity(file: File)(implicit ec: ExecutionContext): Future[RequestEntity] = {
- val entity = HttpEntity(MediaTypes.`application/octet-stream`, file.length(),
- FileIO.fromFile(file, chunkSize = 100000))
- val body = Source.single(
- Multipart.FormData.BodyPart(
- "uploadfile",
- entity,
- Map("filename" -> file.getName)))
- val form = Multipart.FormData(body)
-
- Marshal(form).to[RequestEntity]
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/org/apache/gearpump/cluster/DaemonMessage.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/org/apache/gearpump/cluster/DaemonMessage.scala b/daemon/src/main/scala/org/apache/gearpump/cluster/DaemonMessage.scala
new file mode 100644
index 0000000..9e55be6
--- /dev/null
+++ b/daemon/src/main/scala/org/apache/gearpump/cluster/DaemonMessage.scala
@@ -0,0 +1,51 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.cluster
+
+import akka.actor.ActorRef
+
+import org.apache.gearpump.cluster.master.Master.MasterInfo
+import org.apache.gearpump.cluster.scheduler.Resource
+import org.apache.gearpump.cluster.worker.WorkerId
+
+/**
+ * Cluster Bootup Flow
+ */
+object WorkerToMaster {
+
+ /** When an worker is started, it sends RegisterNewWorker */
+ case object RegisterNewWorker
+
+ /** When worker lose connection with master, it tries to register itself again with old Id. */
+ case class RegisterWorker(workerId: WorkerId)
+
+ /** Worker is responsible to broadcast its current status to master */
+ case class ResourceUpdate(worker: ActorRef, workerId: WorkerId, resource: Resource)
+}
+
+object MasterToWorker {
+
+ /** Master confirm the reception of RegisterNewWorker or RegisterWorker */
+ case class WorkerRegistered(workerId: WorkerId, masterInfo: MasterInfo)
+
+ /** Worker have not received reply from master */
+ case class UpdateResourceFailed(reason: String = null, ex: Throwable = null)
+
+ /** Master is synced with worker on resource slots managed by current worker */
+ case object UpdateResourceSucceed
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/org/apache/gearpump/cluster/embedded/EmbeddedCluster.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/org/apache/gearpump/cluster/embedded/EmbeddedCluster.scala b/daemon/src/main/scala/org/apache/gearpump/cluster/embedded/EmbeddedCluster.scala
new file mode 100644
index 0000000..9bde4d1
--- /dev/null
+++ b/daemon/src/main/scala/org/apache/gearpump/cluster/embedded/EmbeddedCluster.scala
@@ -0,0 +1,95 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.embedded
+
+import scala.collection.JavaConverters._
+import scala.concurrent.Await
+import scala.concurrent.duration.Duration
+
+import akka.actor.{ActorRef, ActorSystem, Props}
+import com.typesafe.config.{Config, ConfigValueFactory}
+
+import org.apache.gearpump.cluster.ClusterConfig
+import org.apache.gearpump.cluster.client.ClientContext
+import org.apache.gearpump.cluster.master.{Master => MasterActor}
+import org.apache.gearpump.cluster.worker.{Worker => WorkerActor}
+import org.apache.gearpump.util.Constants.{GEARPUMP_CLUSTER_EXECUTOR_WORKER_SHARE_SAME_PROCESS, GEARPUMP_CLUSTER_MASTERS, GEARPUMP_METRIC_ENABLED, MASTER}
+import org.apache.gearpump.util.{LogUtil, Util}
+
+/**
+ * Create a in-process cluster with single worker
+ */
+class EmbeddedCluster(inputConfig: Config) {
+
+ private val workerCount: Int = 1
+ private var _master: ActorRef = null
+ private var _system: ActorSystem = null
+ private var _config: Config = null
+
+ private val LOG = LogUtil.getLogger(getClass)
+
+ def start(): Unit = {
+ val port = Util.findFreePort().get
+ val akkaConf = getConfig(inputConfig, port)
+ _config = akkaConf
+ val system = ActorSystem(MASTER, akkaConf)
+
+ val master = system.actorOf(Props[MasterActor], MASTER)
+
+ 0.until(workerCount).foreach { id =>
+ system.actorOf(Props(classOf[WorkerActor], master), classOf[WorkerActor].getSimpleName + id)
+ }
+ this._master = master
+ this._system = system
+
+ LOG.info("=================================")
+ LOG.info("Local Cluster is started at: ")
+ LOG.info(s" 127.0.0.1:$port")
+ LOG.info(s"To see UI, run command: services -master 127.0.0.1:$port")
+ }
+
+ private def getConfig(inputConfig: Config, port: Int): Config = {
+ val config = inputConfig.
+ withValue("akka.remote.netty.tcp.port", ConfigValueFactory.fromAnyRef(port)).
+ withValue(GEARPUMP_CLUSTER_MASTERS,
+ ConfigValueFactory.fromIterable(List(s"127.0.0.1:$port").asJava)).
+ withValue(GEARPUMP_CLUSTER_EXECUTOR_WORKER_SHARE_SAME_PROCESS,
+ ConfigValueFactory.fromAnyRef(true)).
+ withValue(GEARPUMP_METRIC_ENABLED, ConfigValueFactory.fromAnyRef(true)).
+ withValue("akka.actor.provider",
+ ConfigValueFactory.fromAnyRef("akka.cluster.ClusterActorRefProvider"))
+ config
+ }
+
+ def newClientContext: ClientContext = {
+ ClientContext(_config, _system, _master)
+ }
+
+ def stop(): Unit = {
+ _system.stop(_master)
+ _system.terminate()
+ Await.result(_system.whenTerminated, Duration.Inf)
+ }
+}
+
+object EmbeddedCluster {
+ def apply(): EmbeddedCluster = {
+ new EmbeddedCluster(ClusterConfig.master())
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/org/apache/gearpump/cluster/main/AppSubmitter.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/org/apache/gearpump/cluster/main/AppSubmitter.scala b/daemon/src/main/scala/org/apache/gearpump/cluster/main/AppSubmitter.scala
new file mode 100644
index 0000000..98ec707
--- /dev/null
+++ b/daemon/src/main/scala/org/apache/gearpump/cluster/main/AppSubmitter.scala
@@ -0,0 +1,106 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.cluster.main
+
+import java.io.File
+import java.net.{URL, URLClassLoader}
+import java.util.jar.JarFile
+import scala.util.Try
+
+import org.slf4j.Logger
+
+import org.apache.gearpump.util.{AkkaApp, Constants, LogUtil, Util}
+
+/** Tool to submit an application jar to cluster */
+object AppSubmitter extends AkkaApp with ArgumentsParser {
+ val LOG: Logger = LogUtil.getLogger(getClass)
+
+ override val ignoreUnknownArgument = true
+
+ override val description = "Submit an application to Master by providing a jar"
+
+ override val options: Array[(String, CLIOption[Any])] = Array(
+ "namePrefix" -> CLIOption[String]("<application name prefix>", required = false,
+ defaultValue = Some("")),
+ "jar" -> CLIOption("<application>.jar", required = true),
+ "executors" -> CLIOption[Int]("number of executor to launch", required = false,
+ defaultValue = Some(1)),
+ "verbose" -> CLIOption("<print verbose log on console>", required = false,
+ defaultValue = Some(false)),
+ // For document purpose only, OPTION_CONFIG option is not used here.
+ // OPTION_CONFIG is parsed by parent shell command "Gear" transparently.
+ Gear.OPTION_CONFIG -> CLIOption("custom configuration file", required = false,
+ defaultValue = None))
+
+ def main(akkaConf: Config, args: Array[String]): Unit = {
+
+ val config = parse(args)
+ if (null != config) {
+
+ val verbose = config.getBoolean("verbose")
+ if (verbose) {
+ LogUtil.verboseLogToConsole()
+ }
+
+ val jar = config.getString("jar")
+
+ // Set jar path to be submitted to cluster
+ System.setProperty(Constants.GEARPUMP_APP_JAR, jar)
+ System.setProperty(Constants.APPLICATION_EXECUTOR_NUMBER, config.getInt("executors").toString)
+
+ val namePrefix = config.getString("namePrefix")
+ if (namePrefix.nonEmpty) {
+ if (!Util.validApplicationName(namePrefix)) {
+ throw new Exception(s"$namePrefix is not a valid prefix for an application name")
+ }
+ System.setProperty(Constants.GEARPUMP_APP_NAME_PREFIX, namePrefix)
+ }
+
+ val jarFile = new java.io.File(jar)
+
+ // Start main class
+ if (!jarFile.exists()) {
+ throw new Exception(s"jar $jar does not exist")
+ }
+
+ val classLoader: URLClassLoader = new URLClassLoader(Array(new URL("file:" +
+ jarFile.getAbsolutePath)), Thread.currentThread().getContextClassLoader())
+ val (main, arguments) = parseMain(jarFile, config.remainArgs, classLoader)
+
+ // Set to context classloader. ActorSystem pick context classloader in preference
+ Thread.currentThread().setContextClassLoader(classLoader)
+ val clazz = classLoader.loadClass(main)
+ val mainMethod = clazz.getMethod("main", classOf[Array[String]])
+ mainMethod.invoke(null, arguments)
+ }
+ }
+
+ private def parseMain(jar: File, remainArgs: Array[String], classLoader: ClassLoader)
+ : (String, Array[String]) = {
+ val mainInManifest = Option(new JarFile(jar).getManifest.getMainAttributes.
+ getValue("Main-Class")).getOrElse("")
+
+ if (remainArgs.length > 0 && Try(classLoader.loadClass(remainArgs(0))).isSuccess) {
+ (remainArgs(0), remainArgs.drop(1))
+ } else if (mainInManifest.nonEmpty) {
+ (mainInManifest, remainArgs)
+ } else {
+ throw new Exception("No main class specified")
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/org/apache/gearpump/cluster/main/Gear.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/org/apache/gearpump/cluster/main/Gear.scala b/daemon/src/main/scala/org/apache/gearpump/cluster/main/Gear.scala
new file mode 100644
index 0000000..672fee6
--- /dev/null
+++ b/daemon/src/main/scala/org/apache/gearpump/cluster/main/Gear.scala
@@ -0,0 +1,81 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.cluster.main
+
+import org.slf4j.Logger
+
+import org.apache.gearpump.util.{Constants, LogUtil}
+
+object Gear {
+
+ val OPTION_CONFIG = "conf"
+
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+
+ val commands = Map("app" -> AppSubmitter, "kill" -> Kill,
+ "info" -> Info, "replay" -> Replay, "main" -> MainRunner)
+
+ def usage(): Unit = {
+ val keys = commands.keys.toList.sorted
+ // scalastyle:off println
+ Console.err.println("Usage: " + "<" + keys.mkString("|") + ">")
+ // scalastyle:on println
+ }
+
+ private def executeCommand(command: String, commandArgs: Array[String]) = {
+ commands.get(command).map(_.main(commandArgs))
+ if (!commands.contains(command)) {
+ val allArgs = (command +: commandArgs.toList).toArray
+ MainRunner.main(allArgs)
+ }
+ }
+
+ def main(inputArgs: Array[String]): Unit = {
+ val (configFile, args) = extractConfig(inputArgs)
+ if (configFile != null) {
+ // Sets custom config file...
+ System.setProperty(Constants.GEARPUMP_CUSTOM_CONFIG_FILE, configFile)
+ }
+
+ if (args.length == 0) {
+ usage()
+ } else {
+ val command = args(0)
+ val commandArgs = args.drop(1)
+ executeCommand(command, commandArgs)
+ }
+ }
+
+ private def extractConfig(inputArgs: Array[String]): (String, Array[String]) = {
+ var index = 0
+
+ var result = List.empty[String]
+ var configFile: String = null
+ while (index < inputArgs.length) {
+ val item = inputArgs(index)
+ if (item == s"-$OPTION_CONFIG") {
+ index += 1
+ configFile = inputArgs(index)
+ } else {
+ result = result :+ item
+ }
+ index += 1
+ }
+ (configFile, result.toArray)
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/org/apache/gearpump/cluster/main/Info.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/org/apache/gearpump/cluster/main/Info.scala b/daemon/src/main/scala/org/apache/gearpump/cluster/main/Info.scala
new file mode 100644
index 0000000..bf444a3
--- /dev/null
+++ b/daemon/src/main/scala/org/apache/gearpump/cluster/main/Info.scala
@@ -0,0 +1,53 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.cluster.main
+
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.MasterToAppMaster.AppMastersData
+import org.apache.gearpump.cluster.client.ClientContext
+import org.apache.gearpump.util.{AkkaApp, LogUtil}
+
+/** Tool to query master info */
+object Info extends AkkaApp with ArgumentsParser {
+
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+
+ override val options: Array[(String, CLIOption[Any])] = Array(
+ // For document purpose only, OPTION_CONFIG option is not used here.
+ // OPTION_CONFIG is parsed by parent shell command "Gear" transparently.
+ Gear.OPTION_CONFIG -> CLIOption("custom configuration file", required = false,
+ defaultValue = None))
+
+ override val description = "Query the Application list"
+
+ // scalastyle:off println
+ def main(akkaConf: Config, args: Array[String]): Unit = {
+ val client = ClientContext(akkaConf)
+
+ val AppMastersData(appMasters) = client.listApps
+ Console.println("== Application Information ==")
+ Console.println("====================================")
+ appMasters.foreach { appData =>
+ Console.println(s"application: ${appData.appId}, name: ${appData.appName}, " +
+ s"status: ${appData.status}, worker: ${appData.workerPath}")
+ }
+ client.close()
+ }
+ // scalastyle:on println
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/org/apache/gearpump/cluster/main/Kill.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/org/apache/gearpump/cluster/main/Kill.scala b/daemon/src/main/scala/org/apache/gearpump/cluster/main/Kill.scala
new file mode 100644
index 0000000..17f6214
--- /dev/null
+++ b/daemon/src/main/scala/org/apache/gearpump/cluster/main/Kill.scala
@@ -0,0 +1,50 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.main
+
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.client.ClientContext
+import org.apache.gearpump.util.{AkkaApp, LogUtil}
+
+/** Tool to kill an App */
+object Kill extends AkkaApp with ArgumentsParser {
+
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+
+ override val options: Array[(String, CLIOption[Any])] = Array(
+ "appid" -> CLIOption("<application id>", required = true),
+ // For document purpose only, OPTION_CONFIG option is not used here.
+ // OPTION_CONFIG is parsed by parent shell command "Gear" transparently.
+ Gear.OPTION_CONFIG -> CLIOption("custom configuration file", required = false,
+ defaultValue = None))
+
+ override val description = "Kill an application with application Id"
+
+ def main(akkaConf: Config, args: Array[String]): Unit = {
+ val config = parse(args)
+
+ if (null != config) {
+ val client = ClientContext(akkaConf)
+ LOG.info("Client ")
+ client.shutdown(config.getInt("appid"))
+ client.close()
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/org/apache/gearpump/cluster/main/Local.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/org/apache/gearpump/cluster/main/Local.scala b/daemon/src/main/scala/org/apache/gearpump/cluster/main/Local.scala
new file mode 100644
index 0000000..db71b7b
--- /dev/null
+++ b/daemon/src/main/scala/org/apache/gearpump/cluster/main/Local.scala
@@ -0,0 +1,90 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.main
+
+import scala.collection.JavaConverters._
+import scala.concurrent.Await
+import scala.concurrent.duration.Duration
+
+import akka.actor.{ActorSystem, Props}
+import com.typesafe.config.ConfigValueFactory
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.ClusterConfig
+import org.apache.gearpump.cluster.master.{Master => MasterActor}
+import org.apache.gearpump.cluster.worker.{Worker => WorkerActor}
+import org.apache.gearpump.util.Constants._
+import org.apache.gearpump.util.LogUtil.ProcessType
+import org.apache.gearpump.util.{ActorUtil, AkkaApp, Constants, LogUtil, Util}
+
+object Local extends AkkaApp with ArgumentsParser {
+ override def akkaConfig: Config = ClusterConfig.master()
+
+ var LOG: Logger = LogUtil.getLogger(getClass)
+
+ override val options: Array[(String, CLIOption[Any])] =
+ Array("sameprocess" -> CLIOption[Boolean]("", required = false, defaultValue = Some(false)),
+ "workernum" -> CLIOption[Int]("<how many workers to start>", required = false,
+ defaultValue = Some(2)))
+
+ override val description = "Start a local cluster"
+
+ def main(akkaConf: Config, args: Array[String]): Unit = {
+
+ this.LOG = {
+ LogUtil.loadConfiguration(akkaConf, ProcessType.LOCAL)
+ LogUtil.getLogger(getClass)
+ }
+
+ val config = parse(args)
+ if (null != config) {
+ local(config.getInt("workernum"), config.getBoolean("sameprocess"), akkaConf)
+ }
+ }
+
+ def local(workerCount: Int, sameProcess: Boolean, akkaConf: Config): Unit = {
+ if (sameProcess) {
+ LOG.info("Starting local in same process")
+ System.setProperty("LOCAL", "true")
+ }
+ val masters = akkaConf.getStringList(Constants.GEARPUMP_CLUSTER_MASTERS)
+ .asScala.flatMap(Util.parseHostList)
+ val local = akkaConf.getString(Constants.GEARPUMP_HOSTNAME)
+
+ if (masters.size != 1 && masters.head.host != local) {
+ LOG.error(s"The ${Constants.GEARPUMP_CLUSTER_MASTERS} is not match " +
+ s"with ${Constants.GEARPUMP_HOSTNAME}")
+ } else {
+
+ val hostPort = masters.head
+ implicit val system = ActorSystem(MASTER, akkaConf.
+ withValue("akka.remote.netty.tcp.port", ConfigValueFactory.fromAnyRef(hostPort.port))
+ )
+
+ val master = system.actorOf(Props[MasterActor], MASTER)
+ val masterPath = ActorUtil.getSystemAddress(system).toString + s"/user/$MASTER"
+
+ 0.until(workerCount).foreach { id =>
+ system.actorOf(Props(classOf[WorkerActor], master), classOf[WorkerActor].getSimpleName + id)
+ }
+
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/org/apache/gearpump/cluster/main/MainRunner.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/org/apache/gearpump/cluster/main/MainRunner.scala b/daemon/src/main/scala/org/apache/gearpump/cluster/main/MainRunner.scala
new file mode 100644
index 0000000..c6c9f10
--- /dev/null
+++ b/daemon/src/main/scala/org/apache/gearpump/cluster/main/MainRunner.scala
@@ -0,0 +1,43 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.main
+
+import org.slf4j.Logger
+
+import org.apache.gearpump.util.{AkkaApp, LogUtil}
+
+/** Tool to run any main class by providing a jar */
+object MainRunner extends AkkaApp with ArgumentsParser {
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+
+ override val options: Array[(String, CLIOption[Any])] = Array(
+ // For document purpose only, OPTION_CONFIG option is not used here.
+ // OPTION_CONFIG is parsed by parent shell command "Gear" transparently.
+ Gear.OPTION_CONFIG -> CLIOption("custom configuration file", required = false,
+ defaultValue = None))
+
+ def main(akkaConf: Config, args: Array[String]): Unit = {
+ val mainClazz = args(0)
+ val commandArgs = args.drop(1)
+
+ val clazz = Thread.currentThread().getContextClassLoader().loadClass(mainClazz)
+ val mainMethod = clazz.getMethod("main", classOf[Array[String]])
+ mainMethod.invoke(null, commandArgs)
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/org/apache/gearpump/cluster/main/Master.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/org/apache/gearpump/cluster/main/Master.scala b/daemon/src/main/scala/org/apache/gearpump/cluster/main/Master.scala
new file mode 100644
index 0000000..f1b9bdf
--- /dev/null
+++ b/daemon/src/main/scala/org/apache/gearpump/cluster/main/Master.scala
@@ -0,0 +1,236 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.main
+
+import java.util.concurrent.TimeUnit
+import scala.collection.JavaConverters._
+import scala.collection.immutable
+import scala.concurrent.Await
+import scala.concurrent.duration._
+
+import akka.actor._
+import akka.cluster.ClusterEvent._
+import akka.cluster.ddata.DistributedData
+import akka.cluster.singleton.{ClusterSingletonManager, ClusterSingletonManagerSettings, ClusterSingletonProxy, ClusterSingletonProxySettings}
+import akka.cluster.{Cluster, Member, MemberStatus}
+import com.typesafe.config.ConfigValueFactory
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.ClusterConfig
+import org.apache.gearpump.cluster.master.{Master => MasterActor, MasterNode}
+import org.apache.gearpump.cluster.master.Master.MasterListUpdated
+import org.apache.gearpump.util.Constants._
+import org.apache.gearpump.util.LogUtil.ProcessType
+import org.apache.gearpump.util.{AkkaApp, Constants, LogUtil}
+
+object Master extends AkkaApp with ArgumentsParser {
+
+ private var LOG: Logger = LogUtil.getLogger(getClass)
+
+ override def akkaConfig: Config = ClusterConfig.master()
+
+ override val options: Array[(String, CLIOption[Any])] =
+ Array("ip" -> CLIOption[String]("<master ip address>", required = true),
+ "port" -> CLIOption("<master port>", required = true))
+
+ override val description = "Start Master daemon"
+
+ def main(akkaConf: Config, args: Array[String]): Unit = {
+
+ this.LOG = {
+ LogUtil.loadConfiguration(akkaConf, ProcessType.MASTER)
+ LogUtil.getLogger(getClass)
+ }
+
+ val config = parse(args)
+ master(config.getString("ip"), config.getInt("port"), akkaConf)
+ }
+
+ private def verifyMaster(master: String, port: Int, masters: Iterable[String]) = {
+ masters.exists { hostPort =>
+ hostPort == s"$master:$port"
+ }
+ }
+
+ private def master(ip: String, port: Int, akkaConf: Config): Unit = {
+ val masters = akkaConf.getStringList(Constants.GEARPUMP_CLUSTER_MASTERS).asScala
+
+ if (!verifyMaster(ip, port, masters)) {
+ LOG.error(s"The provided ip $ip and port $port doesn't conform with config at " +
+ s"gearpump.cluster.masters: ${masters.mkString(", ")}")
+ System.exit(-1)
+ }
+
+ val masterList = masters.map(master => s"akka.tcp://${MASTER}@$master").toList.asJava
+ val quorum = masterList.size() / 2 + 1
+ val masterConfig = akkaConf.
+ withValue("akka.remote.netty.tcp.port", ConfigValueFactory.fromAnyRef(port)).
+ withValue(NETTY_TCP_HOSTNAME, ConfigValueFactory.fromAnyRef(ip)).
+ withValue("akka.cluster.seed-nodes", ConfigValueFactory.fromAnyRef(masterList)).
+ withValue(s"akka.cluster.role.${MASTER}.min-nr-of-members",
+ ConfigValueFactory.fromAnyRef(quorum))
+
+ LOG.info(s"Starting Master Actor system $ip:$port, master list: ${masters.mkString(";")}")
+ val system = ActorSystem(MASTER, masterConfig)
+
+ val replicator = DistributedData(system).replicator
+ LOG.info(s"Replicator path: ${replicator.path}")
+
+ // Starts singleton manager
+ val singletonManager = system.actorOf(ClusterSingletonManager.props(
+ singletonProps = Props(classOf[MasterWatcher], MASTER),
+ terminationMessage = PoisonPill,
+ settings = ClusterSingletonManagerSettings(system).withSingletonName(MASTER_WATCHER)
+ .withRole(MASTER)),
+ name = SINGLETON_MANAGER)
+
+ // Start master proxy
+ val masterProxy = system.actorOf(ClusterSingletonProxy.props(
+ singletonManagerPath = s"/user/${SINGLETON_MANAGER}",
+ // The effective singleton is s"${MASTER_WATCHER}/$MASTER" instead of s"${MASTER_WATCHER}".
+ // Master is created when there is a majority of machines started.
+ settings = ClusterSingletonProxySettings(system)
+ .withSingletonName(s"${MASTER_WATCHER}/$MASTER").withRole(MASTER)),
+ name = MASTER
+ )
+
+ LOG.info(s"master proxy is started at ${masterProxy.path}")
+
+ val mainThread = Thread.currentThread()
+ Runtime.getRuntime().addShutdownHook(new Thread() {
+ override def run(): Unit = {
+ if (!system.whenTerminated.isCompleted) {
+ LOG.info("Triggering shutdown hook....")
+
+ system.stop(masterProxy)
+ val cluster = Cluster(system)
+ cluster.leave(cluster.selfAddress)
+ cluster.down(cluster.selfAddress)
+ try {
+ Await.result(system.whenTerminated, Duration(3, TimeUnit.SECONDS))
+ } catch {
+ case ex: Exception => // Ignore
+ }
+ system.terminate()
+ mainThread.join()
+ }
+ }
+ })
+
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+}
+
+class MasterWatcher(role: String) extends Actor with ActorLogging {
+ import context.dispatcher
+
+ val cluster = Cluster(context.system)
+
+ val config = context.system.settings.config
+ val masters = config.getList("akka.cluster.seed-nodes")
+ val quorum = masters.size() / 2 + 1
+
+ val system = context.system
+
+ // Sorts by age, oldest first
+ val ageOrdering = Ordering.fromLessThan[Member] { (a, b) => a.isOlderThan(b) }
+ var membersByAge: immutable.SortedSet[Member] = immutable.SortedSet.empty(ageOrdering)
+
+ def receive: Receive = null
+
+ // Subscribes to MemberEvent, re-subscribe when restart
+ override def preStart(): Unit = {
+ cluster.subscribe(self, classOf[MemberEvent])
+ context.become(waitForInit)
+ }
+ override def postStop(): Unit = {
+ cluster.unsubscribe(self)
+ }
+
+ def matchingRole(member: Member): Boolean = member.hasRole(role)
+
+ def waitForInit: Receive = {
+ case state: CurrentClusterState => {
+ membersByAge = immutable.SortedSet.empty(ageOrdering) ++ state.members.filter(m =>
+ m.status == MemberStatus.Up && matchingRole(m))
+
+ if (membersByAge.size < quorum) {
+ membersByAge.iterator.mkString(",")
+ log.info(s"We cannot get a quorum, $quorum, " +
+ s"shutting down...${membersByAge.iterator.mkString(",")}")
+ context.become(waitForShutdown)
+ self ! MasterWatcher.Shutdown
+ } else {
+ val master = context.actorOf(Props(classOf[MasterActor]), MASTER)
+ notifyMasterMembersChange(master)
+ context.become(waitForClusterEvent(master))
+ }
+ }
+ }
+
+ def waitForClusterEvent(master: ActorRef): Receive = {
+ case MemberUp(m) if matchingRole(m) => {
+ membersByAge += m
+ notifyMasterMembersChange(master)
+ }
+ case mEvent: MemberEvent if (mEvent.isInstanceOf[MemberExited] ||
+ mEvent.isInstanceOf[MemberRemoved]) && matchingRole(mEvent.member) => {
+ log.info(s"member removed ${mEvent.member}")
+ val m = mEvent.member
+ membersByAge -= m
+ if (membersByAge.size < quorum) {
+ log.info(s"We cannot get a quorum, $quorum, " +
+ s"shutting down...${membersByAge.iterator.mkString(",")}")
+ context.become(waitForShutdown)
+ self ! MasterWatcher.Shutdown
+ } else {
+ notifyMasterMembersChange(master)
+ }
+ }
+ }
+
+ private def notifyMasterMembersChange(master: ActorRef): Unit = {
+ val masters = membersByAge.toList.map{ member =>
+ MasterNode(member.address.host.getOrElse("Unknown-Host"),
+ member.address.port.getOrElse(0))
+ }
+ master ! MasterListUpdated(masters)
+ }
+
+ def waitForShutdown: Receive = {
+ case MasterWatcher.Shutdown => {
+ cluster.unsubscribe(self)
+ cluster.leave(cluster.selfAddress)
+ context.stop(self)
+ system.scheduler.scheduleOnce(Duration.Zero) {
+ try {
+ Await.result(system.whenTerminated, Duration(3, TimeUnit.SECONDS))
+ } catch {
+ case ex: Exception => // Ignore
+ }
+ system.terminate()
+ }
+ }
+ }
+}
+
+object MasterWatcher {
+ object Shutdown
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/org/apache/gearpump/cluster/main/Replay.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/org/apache/gearpump/cluster/main/Replay.scala b/daemon/src/main/scala/org/apache/gearpump/cluster/main/Replay.scala
new file mode 100644
index 0000000..d721832
--- /dev/null
+++ b/daemon/src/main/scala/org/apache/gearpump/cluster/main/Replay.scala
@@ -0,0 +1,48 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.cluster.main
+
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.client.ClientContext
+import org.apache.gearpump.util.{AkkaApp, LogUtil}
+
+// Internal tool to restart an application
+object Replay extends AkkaApp with ArgumentsParser {
+
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+
+ override val options: Array[(String, CLIOption[Any])] = Array(
+ "appid" -> CLIOption("<application id>", required = true),
+ // For document purpose only, OPTION_CONFIG option is not used here.
+ // OPTION_CONFIG is parsed by parent shell command "Gear" transparently.
+ Gear.OPTION_CONFIG -> CLIOption("custom configuration file", required = false,
+ defaultValue = None))
+
+ override val description = "Replay the application from current min clock(low watermark)"
+
+ def main(akkaConf: Config, args: Array[String]): Unit = {
+ val config = parse(args)
+
+ if (null != config) {
+ val client = ClientContext(akkaConf)
+ client.replayFromTimestampWindowTrailingEdge(config.getInt("appid"))
+ client.close()
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/org/apache/gearpump/cluster/main/Worker.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/org/apache/gearpump/cluster/main/Worker.scala b/daemon/src/main/scala/org/apache/gearpump/cluster/main/Worker.scala
new file mode 100644
index 0000000..58a9dec
--- /dev/null
+++ b/daemon/src/main/scala/org/apache/gearpump/cluster/main/Worker.scala
@@ -0,0 +1,71 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.main
+
+import scala.collection.JavaConverters._
+import scala.concurrent.Await
+import scala.concurrent.duration.Duration
+
+import akka.actor.{ActorSystem, Props}
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.ClusterConfig
+import org.apache.gearpump.cluster.master.MasterProxy
+import org.apache.gearpump.transport.HostPort
+import org.apache.gearpump.util.Constants._
+import org.apache.gearpump.cluster.worker.{Worker => WorkerActor}
+import org.apache.gearpump.util.LogUtil.ProcessType
+import org.apache.gearpump.util.{AkkaApp, LogUtil}
+
+/** Tool to start a worker daemon process */
+object Worker extends AkkaApp with ArgumentsParser {
+ protected override def akkaConfig = ClusterConfig.worker()
+
+ override val description = "Start a worker daemon"
+
+ var LOG: Logger = LogUtil.getLogger(getClass)
+
+ private def uuid = java.util.UUID.randomUUID.toString
+
+ def main(akkaConf: Config, args: Array[String]): Unit = {
+ val id = uuid
+
+ this.LOG = {
+ LogUtil.loadConfiguration(akkaConf, ProcessType.WORKER)
+ // Delay creation of LOG instance to avoid creating an empty log file as we
+ // reset the log file name here
+ LogUtil.getLogger(getClass)
+ }
+
+ val system = ActorSystem(id, akkaConf)
+
+ val masterAddress = akkaConf.getStringList(GEARPUMP_CLUSTER_MASTERS).asScala.map { address =>
+ val hostAndPort = address.split(":")
+ HostPort(hostAndPort(0), hostAndPort(1).toInt)
+ }
+
+ LOG.info(s"Trying to connect to masters " + masterAddress.mkString(",") + "...")
+ val masterProxy = system.actorOf(MasterProxy.props(masterAddress), s"masterproxy${system.name}")
+
+ system.actorOf(Props(classOf[WorkerActor], masterProxy),
+ classOf[WorkerActor].getSimpleName + id)
+
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+}
\ No newline at end of file
[40/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/org/apache/gearpump/cluster/appmaster/AppMasterRuntimeEnvironmentSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/org/apache/gearpump/cluster/appmaster/AppMasterRuntimeEnvironmentSpec.scala b/core/src/test/scala/org/apache/gearpump/cluster/appmaster/AppMasterRuntimeEnvironmentSpec.scala
new file mode 100644
index 0000000..a41856d
--- /dev/null
+++ b/core/src/test/scala/org/apache/gearpump/cluster/appmaster/AppMasterRuntimeEnvironmentSpec.scala
@@ -0,0 +1,140 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.appmaster
+
+import scala.concurrent.Await
+import scala.concurrent.duration.Duration
+
+import akka.actor._
+import akka.testkit.TestProbe
+import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
+
+import org.apache.gearpump.TestProbeUtil._
+import org.apache.gearpump.cluster.AppMasterToMaster.RegisterAppMaster
+import org.apache.gearpump.cluster._
+import org.apache.gearpump.cluster.appmaster.AppMasterRuntimeEnvironment._
+import org.apache.gearpump.cluster.appmaster.AppMasterRuntimeEnvironmentSpec.TestAppMasterEnv
+import org.apache.gearpump.cluster.appmaster.ExecutorSystemScheduler.StartExecutorSystems
+import org.apache.gearpump.cluster.appmaster.MasterConnectionKeeper.MasterConnectionStatus.{MasterConnected, MasterStopped}
+
+class AppMasterRuntimeEnvironmentSpec extends FlatSpec with Matchers with BeforeAndAfterAll {
+ implicit var system: ActorSystem = null
+
+ override def beforeAll(): Unit = {
+ system = ActorSystem("test", TestUtil.DEFAULT_CONFIG)
+ }
+
+ override def afterAll(): Unit = {
+ system.terminate()
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+
+ "MasterWithExecutorSystemProvider" should
+ "forward request StartExecutorSystem to ExecutorSystemProvider" in {
+
+ val client = TestProbe()
+ val master = TestProbe()
+ val provider = TestProbe()
+ val providerProps: Props = provider
+ val masterEnhanced = system.actorOf(Props(
+ new MasterWithExecutorSystemProvider(master.ref, providerProps)))
+
+ val start = StartExecutorSystems(null, null)
+ client.send(masterEnhanced, start)
+ provider.expectMsg(start)
+
+ val anyOtherMessage = "any other message"
+ client.send(masterEnhanced, anyOtherMessage)
+ master.expectMsg(anyOtherMessage)
+ system.stop(masterEnhanced)
+ }
+
+ "LazyStartAppMaster" should "forward command to appmaster when app master started" in {
+
+ val appMaster = TestProbe()
+ val appMasterProps: Props = appMaster
+ val lazyAppMaster = system.actorOf(Props(new LazyStartAppMaster(appId = 0, appMasterProps)))
+ val msg = "Some"
+ lazyAppMaster ! msg
+ lazyAppMaster ! StartAppMaster
+ appMaster.expectMsg(msg)
+
+ system.stop(appMaster.ref)
+ val client = TestProbe()
+ client.watch(lazyAppMaster)
+ client.expectTerminated(lazyAppMaster)
+ }
+
+ "AppMasterRuntimeEnvironment" should "start appMaster when master is connected" in {
+ val TestAppMasterEnv(master, appMaster, masterConnectionKeeper, runtimeEnv) =
+ setupAppMasterRuntimeEnv()
+
+ masterConnectionKeeper.send(runtimeEnv, MasterConnected)
+ appMaster.expectMsg(StartAppMaster)
+ }
+
+ "AppMasterRuntimeEnvironment" should "shutdown itself when master is stopped" in {
+
+ val TestAppMasterEnv(master, appMaster, masterConnectionKeeper, runtimeEnv) =
+ setupAppMasterRuntimeEnv()
+
+ masterConnectionKeeper.send(runtimeEnv, MasterStopped)
+ val client = TestProbe()
+ client.watch(runtimeEnv)
+ client.expectTerminated(runtimeEnv)
+ }
+
+ "AppMasterRuntimeEnvironment" should "shutdown itself when appMaster is stopped" in {
+
+ val TestAppMasterEnv(master, appMaster, masterConnectionKeeper, runtimeEnv) =
+ setupAppMasterRuntimeEnv()
+
+ val client = TestProbe()
+ client.watch(runtimeEnv)
+ system.stop(appMaster.ref)
+ client.expectTerminated(runtimeEnv)
+ }
+
+ private def setupAppMasterRuntimeEnv(): TestAppMasterEnv = {
+ val appContext = AppMasterContext(0, null, null, null, null, null, null)
+ val app = AppDescription("app", "AppMasterClass", null, null)
+ val master = TestProbe()
+ val masterFactory = (_: AppId, _: MasterActorRef) => toProps(master)
+ val appMaster = TestProbe()
+ val appMasterFactory = (_: AppMasterContext, _: AppDescription) => toProps(appMaster)
+ val masterConnectionKeeper = TestProbe()
+ val masterConnectionKeeperFactory =
+ (_: MasterActorRef, _: RegisterAppMaster, _: ListenerActorRef) =>
+ toProps(masterConnectionKeeper)
+
+ val runtimeEnv = system.actorOf(
+ Props(new AppMasterRuntimeEnvironment(
+ appContext, app, List(master.ref.path), masterFactory,
+ appMasterFactory, masterConnectionKeeperFactory)))
+
+ TestAppMasterEnv(master, appMaster, masterConnectionKeeper, runtimeEnv)
+ }
+}
+
+object AppMasterRuntimeEnvironmentSpec {
+
+ case class TestAppMasterEnv(
+ master: TestProbe, appMaster: TestProbe, connectionkeeper: TestProbe,
+ appMasterRuntimeEnv: ActorRef)
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/org/apache/gearpump/cluster/appmaster/ExecutorSystemLauncherSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/org/apache/gearpump/cluster/appmaster/ExecutorSystemLauncherSpec.scala b/core/src/test/scala/org/apache/gearpump/cluster/appmaster/ExecutorSystemLauncherSpec.scala
new file mode 100644
index 0000000..d40e775
--- /dev/null
+++ b/core/src/test/scala/org/apache/gearpump/cluster/appmaster/ExecutorSystemLauncherSpec.scala
@@ -0,0 +1,106 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.appmaster
+
+import org.apache.gearpump.cluster.worker.WorkerId
+
+import scala.concurrent.Await
+import scala.concurrent.duration._
+
+import akka.actor.{ActorSystem, Props}
+import akka.testkit.TestProbe
+import com.typesafe.config.ConfigValueFactory
+import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
+
+import org.apache.gearpump.cluster.AppMasterToWorker.LaunchExecutor
+import org.apache.gearpump.cluster.TestUtil
+import org.apache.gearpump.cluster.WorkerToAppMaster.ExecutorLaunchRejected
+import org.apache.gearpump.cluster.appmaster.ExecutorSystemLauncher._
+import org.apache.gearpump.cluster.appmaster.ExecutorSystemScheduler.Session
+import org.apache.gearpump.cluster.scheduler.Resource
+import org.apache.gearpump.util.ActorSystemBooter.{ActorSystemRegistered, RegisterActorSystem}
+import org.apache.gearpump.util.Constants
+
+class ExecutorSystemLauncherSpec extends FlatSpec with Matchers with BeforeAndAfterAll {
+ implicit var system: ActorSystem = null
+ val workerId: WorkerId = WorkerId(0, 0L)
+ val appId = 0
+ val executorId = 0
+ val url = "akka.tcp://worker@127.0.0.1:3000"
+ val session = Session(null, null)
+ val launchExecutorSystemTimeout = 3000
+ val activeConfig = TestUtil.DEFAULT_CONFIG.
+ withValue(Constants.GEARPUMP_START_EXECUTOR_SYSTEM_TIMEOUT_MS,
+ ConfigValueFactory.fromAnyRef(launchExecutorSystemTimeout))
+
+ override def beforeAll(): Unit = {
+ system = ActorSystem("test", activeConfig)
+ }
+
+ override def afterAll(): Unit = {
+ system.terminate()
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+
+ it should "report success when worker launch the system successfully" in {
+ val worker = TestProbe()
+ val client = TestProbe()
+
+ val launcher = system.actorOf(Props(new ExecutorSystemLauncher(appId, session)))
+ client.watch(launcher)
+ client.send(launcher, LaunchExecutorSystem(WorkerInfo(workerId, worker.ref), 0, Resource(1)))
+
+ worker.expectMsgType[LaunchExecutor]
+ worker.reply(RegisterActorSystem(url))
+
+ worker.expectMsgType[ActorSystemRegistered]
+
+ client.expectMsgType[LaunchExecutorSystemSuccess]
+ client.expectTerminated(launcher)
+ }
+
+ it should "report failure when worker refuse to launch the system explicitly" in {
+ val worker = TestProbe()
+ val client = TestProbe()
+
+ val resource = Resource(4)
+
+ val launcher = system.actorOf(Props(new ExecutorSystemLauncher(appId, session)))
+ client.watch(launcher)
+ client.send(launcher, LaunchExecutorSystem(WorkerInfo(workerId, worker.ref), 0, resource))
+
+ worker.expectMsgType[LaunchExecutor]
+ worker.reply(ExecutorLaunchRejected())
+
+ client.expectMsg(LaunchExecutorSystemRejected(resource, null, session))
+ client.expectTerminated(launcher)
+ }
+
+ it should "report timeout when trying to start a executor system on worker, " +
+ "and worker doesn't response" in {
+ val client = TestProbe()
+ val worker = TestProbe()
+ val launcher = system.actorOf(Props(new ExecutorSystemLauncher(appId, session)))
+ client.send(launcher, LaunchExecutorSystem(WorkerInfo(workerId, worker.ref), 0, Resource(1)))
+ client.watch(launcher)
+ val waitFor = launchExecutorSystemTimeout + 10000
+ client.expectMsgType[LaunchExecutorSystemTimeout](waitFor.milliseconds)
+ client.expectTerminated(launcher, waitFor.milliseconds)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/org/apache/gearpump/cluster/appmaster/ExecutorSystemSchedulerSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/org/apache/gearpump/cluster/appmaster/ExecutorSystemSchedulerSpec.scala b/core/src/test/scala/org/apache/gearpump/cluster/appmaster/ExecutorSystemSchedulerSpec.scala
new file mode 100644
index 0000000..6987af4
--- /dev/null
+++ b/core/src/test/scala/org/apache/gearpump/cluster/appmaster/ExecutorSystemSchedulerSpec.scala
@@ -0,0 +1,141 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.appmaster
+
+import org.apache.gearpump.cluster.worker.WorkerId
+
+import scala.concurrent.Await
+import scala.concurrent.duration._
+
+import akka.actor.{Actor, ActorSystem, Props}
+import akka.testkit.TestProbe
+import org.scalatest.{BeforeAndAfterEach, FlatSpec, Matchers}
+
+import org.apache.gearpump.cluster.AppMasterToMaster.RequestResource
+import org.apache.gearpump.cluster.MasterToAppMaster.ResourceAllocated
+import org.apache.gearpump.cluster.appmaster.ExecutorSystemLauncher._
+import org.apache.gearpump.cluster.appmaster.ExecutorSystemScheduler._
+import org.apache.gearpump.cluster.appmaster.ExecutorSystemSchedulerSpec.{ExecutorSystemLauncherStarted, MockExecutorSystemLauncher}
+import org.apache.gearpump.cluster.scheduler.{Resource, ResourceAllocation, ResourceRequest}
+import org.apache.gearpump.cluster.{AppJar, TestUtil}
+import org.apache.gearpump.jarstore.FilePath
+
+class ExecutorSystemSchedulerSpec extends FlatSpec with Matchers with BeforeAndAfterEach {
+ val appId = 0
+ val workerId = WorkerId(0, 0L)
+ val resource = Resource(1)
+ val resourceRequest = ResourceRequest(resource, WorkerId.unspecified)
+ val mockJar = AppJar("for_test", FilePath("PATH"))
+ val emptyJvmConfig = ExecutorSystemJvmConfig(Array.empty, Array.empty, Some(mockJar), "")
+ val start = StartExecutorSystems(Array(resourceRequest), emptyJvmConfig)
+
+ implicit var system: ActorSystem = null
+ var worker: TestProbe = null
+ var workerInfo: WorkerInfo = null
+ var masterProxy: TestProbe = null
+ var launcher: TestProbe = null
+ var client: TestProbe = null
+
+ override def beforeEach(): Unit = {
+ system = ActorSystem("test", TestUtil.DEFAULT_CONFIG)
+ worker = TestProbe()
+ workerInfo = WorkerInfo(workerId, worker.ref)
+ masterProxy = TestProbe()
+ launcher = TestProbe()
+ client = TestProbe()
+
+ val scheduler = system.actorOf(
+ Props(new ExecutorSystemScheduler(appId, masterProxy.ref, (appId: Int, session: Session) => {
+ Props(new MockExecutorSystemLauncher(launcher, session))
+ })))
+
+ client.send(scheduler, start)
+ masterProxy.expectMsg(RequestResource(appId, resourceRequest))
+ }
+
+ override def afterEach(): Unit = {
+ system.terminate()
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+
+ private def launcherStarted(launcher: TestProbe): Option[ExecutorSystemLauncherStarted] = {
+ val launcherStarted = launcher.receiveOne(15.seconds)
+
+ launcherStarted match {
+ case start: ExecutorSystemLauncherStarted => Some(start)
+ case x =>
+ assert(false, "ExecutorSystemLauncherStarted == false")
+ None
+ }
+ }
+
+ it should "schedule and launch an executor system on target worker successfully" in {
+
+ masterProxy.reply(ResourceAllocated(Array(ResourceAllocation(resource, worker.ref, workerId))))
+
+ val ExecutorSystemLauncherStarted(session) = launcherStarted(launcher).get
+
+ var systemId = 0
+ launcher.expectMsg(LaunchExecutorSystem(workerInfo, systemId, resource))
+
+ val executorSystemProbe = TestProbe()
+ val executorSystem =
+ ExecutorSystem(systemId, null, executorSystemProbe.ref, resource, workerInfo)
+ launcher.reply(LaunchExecutorSystemSuccess(executorSystem, session))
+ client.expectMsg(ExecutorSystemStarted(executorSystem, Some(mockJar)))
+ }
+
+ it should "report failure when resource cannot be allocated" in {
+ client.expectMsg(30.seconds, StartExecutorSystemTimeout)
+ }
+
+ it should "schedule new resouce on new worker " +
+ "when target worker reject creating executor system" in {
+ masterProxy.reply(ResourceAllocated(Array(ResourceAllocation(resource, worker.ref, workerId))))
+ val ExecutorSystemLauncherStarted(session) = launcherStarted(launcher).get
+
+ var systemId = 0
+ launcher.expectMsg(LaunchExecutorSystem(workerInfo, systemId, resource))
+ launcher.reply(LaunchExecutorSystemRejected(resource, "", session))
+ masterProxy.expectMsg(RequestResource(appId, resourceRequest))
+ }
+
+ it should "report failure when resource is allocated, but timeout " +
+ "when starting the executor system" in {
+ masterProxy.reply(ResourceAllocated(Array(ResourceAllocation(resource, worker.ref, workerId))))
+ val ExecutorSystemLauncherStarted(session) = launcherStarted(launcher).get
+
+ var systemId = 0
+ launcher.expectMsg(LaunchExecutorSystem(workerInfo, systemId, resource))
+ launcher.reply(LaunchExecutorSystemTimeout(session))
+ client.expectMsg(StartExecutorSystemTimeout)
+ }
+}
+
+object ExecutorSystemSchedulerSpec {
+ class MockExecutorSystemLauncher(forwardTo: TestProbe, session: Session) extends Actor {
+ forwardTo.ref ! ExecutorSystemLauncherStarted(session)
+
+ def receive: Receive = {
+ case msg => forwardTo.ref forward msg
+ }
+ }
+
+ case class ExecutorSystemLauncherStarted(session: Session)
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/org/apache/gearpump/cluster/appmaster/MasterConnectionKeeperSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/org/apache/gearpump/cluster/appmaster/MasterConnectionKeeperSpec.scala b/core/src/test/scala/org/apache/gearpump/cluster/appmaster/MasterConnectionKeeperSpec.scala
new file mode 100644
index 0000000..163da0a
--- /dev/null
+++ b/core/src/test/scala/org/apache/gearpump/cluster/appmaster/MasterConnectionKeeperSpec.scala
@@ -0,0 +1,118 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.appmaster
+
+import scala.concurrent.Await
+import scala.concurrent.duration._
+
+import akka.actor.{ActorRef, ActorSystem, Props}
+import akka.testkit.TestProbe
+import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
+
+import org.apache.gearpump.cluster.AppMasterToMaster.RegisterAppMaster
+import org.apache.gearpump.cluster.MasterToAppMaster.AppMasterRegistered
+import org.apache.gearpump.cluster.TestUtil
+import org.apache.gearpump.cluster.appmaster.MasterConnectionKeeper.MasterConnectionStatus.{MasterConnected, _}
+import org.apache.gearpump.cluster.appmaster.MasterConnectionKeeperSpec.ConnectionKeeperTestEnv
+import org.apache.gearpump.cluster.master.MasterProxy.WatchMaster
+
+class MasterConnectionKeeperSpec extends FlatSpec with Matchers with BeforeAndAfterAll {
+
+ implicit var system: ActorSystem = null
+ val register = RegisterAppMaster(null, null)
+ val appId = 0
+
+ override def beforeAll(): Unit = {
+ system = ActorSystem("test", TestUtil.DEFAULT_CONFIG)
+ }
+
+ override def afterAll(): Unit = {
+ system.terminate()
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+
+ private def startMasterConnectionKeeper: ConnectionKeeperTestEnv = {
+ val statusChangeSubscriber = TestProbe()
+ val master = TestProbe()
+
+ val keeper = system.actorOf(Props(
+ new MasterConnectionKeeper(register, master.ref, statusChangeSubscriber.ref)))
+ statusChangeSubscriber.watch(keeper)
+
+ master.expectMsgType[WatchMaster]
+
+ // Master is alive, response to RegisterAppMaster
+ master.expectMsgType[RegisterAppMaster]
+ master.reply(AppMasterRegistered(appId))
+
+ // Notify listener that master is alive
+ statusChangeSubscriber.expectMsg(MasterConnected)
+ ConnectionKeeperTestEnv(master, keeper, statusChangeSubscriber)
+ }
+
+ it should "start correctly and notify listener that master is alive" in {
+ startMasterConnectionKeeper
+ }
+
+ it should "re-register the appmaster when master is restarted" in {
+ import org.apache.gearpump.cluster.master.MasterProxy.MasterRestarted
+ val ConnectionKeeperTestEnv(master, keeper, masterChangeListener) = startMasterConnectionKeeper
+
+ // Master is restarted
+ master.send(keeper, MasterRestarted)
+ master.expectMsgType[RegisterAppMaster]
+ master.reply(AppMasterRegistered(appId))
+ masterChangeListener.expectMsg(MasterConnected)
+
+ // Recovery from Master restart is transparent to listener
+ masterChangeListener.expectNoMsg()
+ }
+
+ it should "notify listener and then shutdown itself when master is dead" in {
+ val ConnectionKeeperTestEnv(master, keeper, masterChangeListener) = startMasterConnectionKeeper
+
+ // Master is dead
+ master.send(keeper, MasterStopped)
+
+ // Keeper should tell the listener that master is stopped before shutting down itself
+ masterChangeListener.expectMsg(MasterStopped)
+ masterChangeListener.expectTerminated(keeper)
+ }
+
+ it should "mark the master as dead when timeout" in {
+ val statusChangeSubscriber = TestProbe()
+ val master = TestProbe()
+
+ // MasterConnectionKeeper register itself to master by sending RegisterAppMaster
+ val keeper = system.actorOf(Props(new MasterConnectionKeeper(register,
+ master.ref, statusChangeSubscriber.ref)))
+
+ // Master doesn't reply to keeper,
+ statusChangeSubscriber.watch(keeper)
+
+ // Timeout, keeper notify listener, and then make suicide
+ statusChangeSubscriber.expectMsg(60.seconds, MasterStopped)
+ statusChangeSubscriber.expectTerminated(keeper, 60.seconds)
+ }
+}
+
+object MasterConnectionKeeperSpec {
+ case class ConnectionKeeperTestEnv(
+ master: TestProbe, keeper: ActorRef, masterChangeListener: TestProbe)
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/org/apache/gearpump/cluster/main/ArgumentParserSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/org/apache/gearpump/cluster/main/ArgumentParserSpec.scala b/core/src/test/scala/org/apache/gearpump/cluster/main/ArgumentParserSpec.scala
new file mode 100644
index 0000000..0c7c0c3
--- /dev/null
+++ b/core/src/test/scala/org/apache/gearpump/cluster/main/ArgumentParserSpec.scala
@@ -0,0 +1,63 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.main
+
+import org.scalatest.{FlatSpec, Matchers}
+
+class ArgumentParserSpec extends FlatSpec with Matchers {
+ it should "parse arguments correctly" in {
+
+ val parser = new ArgumentsParser {
+ override val options = Array(
+ "flag" -> CLIOption[Any]("", required = true),
+ "opt1" -> CLIOption[Any]("", required = true),
+ "opt2" -> CLIOption[Any]("", required = true))
+ }
+
+ val result = parser.parse(Array("-flag", "-opt1", "1", "-opt2", "2", "arg1", "arg2"))
+ assert(result.getBoolean("flag"))
+ assert(result.getInt("opt1") == 1)
+ assert(result.getString("opt1") == "1")
+ assert(result.getInt("opt2") == 2)
+
+ assert(result.remainArgs(0) == "arg1")
+ assert(result.remainArgs(1) == "arg2")
+ }
+
+ it should "handle interleaved options and remain args" in {
+
+ val parser = new ArgumentsParser {
+ override val options = Array(
+ "opt1" -> CLIOption[Any]("", required = true))
+ }
+
+ val result = parser.parse(Array("-opt1", "1", "xx.MainClass", "-opt2", "2"))
+ assert(result.getInt("opt1") == 1)
+
+ assert(result.remainArgs.length == 3)
+
+ intercept[Exception] {
+ parser.parse(Array("-opt2"))
+ }
+
+ intercept[Exception] {
+ parser.parse(Array("-opt2", "2", "-opt1"))
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/org/apache/gearpump/cluster/master/AppMasterLauncherSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/org/apache/gearpump/cluster/master/AppMasterLauncherSpec.scala b/core/src/test/scala/org/apache/gearpump/cluster/master/AppMasterLauncherSpec.scala
new file mode 100644
index 0000000..ac08276
--- /dev/null
+++ b/core/src/test/scala/org/apache/gearpump/cluster/master/AppMasterLauncherSpec.scala
@@ -0,0 +1,101 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.master
+
+import org.apache.gearpump.cluster.worker.WorkerId
+
+import scala.util.Success
+
+import akka.actor._
+import akka.testkit.TestProbe
+import com.typesafe.config.Config
+import org.scalatest.{BeforeAndAfterEach, FlatSpec, Matchers}
+
+import org.apache.gearpump.cluster.AppMasterToMaster.RequestResource
+import org.apache.gearpump.cluster.AppMasterToWorker.{LaunchExecutor, ShutdownExecutor}
+import org.apache.gearpump.cluster.MasterToAppMaster.ResourceAllocated
+import org.apache.gearpump.cluster.MasterToClient.SubmitApplicationResult
+import org.apache.gearpump.cluster.WorkerToAppMaster.ExecutorLaunchRejected
+import org.apache.gearpump.cluster.scheduler.{Resource, ResourceAllocation, ResourceRequest}
+import org.apache.gearpump.cluster.{MasterHarness, TestUtil}
+import org.apache.gearpump.util.ActorSystemBooter._
+
+class AppMasterLauncherSpec extends FlatSpec with Matchers
+ with BeforeAndAfterEach with MasterHarness {
+
+ override def config: Config = TestUtil.DEFAULT_CONFIG
+
+ val appId = 1
+ val executorId = 2
+ var master: TestProbe = null
+ var client: TestProbe = null
+ var worker: TestProbe = null
+ var watcher: TestProbe = null
+ var appMasterLauncher: ActorRef = null
+
+ override def beforeEach(): Unit = {
+ startActorSystem()
+ master = createMockMaster()
+ client = TestProbe()(getActorSystem)
+ worker = TestProbe()(getActorSystem)
+ watcher = TestProbe()(getActorSystem)
+ appMasterLauncher = getActorSystem.actorOf(AppMasterLauncher.props(appId, executorId,
+ TestUtil.dummyApp, None, "username", master.ref, Some(client.ref)))
+ watcher watch appMasterLauncher
+ master.expectMsg(RequestResource(appId, ResourceRequest(Resource(1), WorkerId.unspecified)))
+ val resource = ResourceAllocated(
+ Array(ResourceAllocation(Resource(1), worker.ref, WorkerId(0, 0L))))
+ master.reply(resource)
+ worker.expectMsgType[LaunchExecutor]
+ }
+
+ override def afterEach(): Unit = {
+ shutdownActorSystem()
+ }
+
+ "AppMasterLauncher" should "launch appmaster correctly" in {
+ worker.reply(RegisterActorSystem("systempath"))
+ worker.expectMsgType[ActorSystemRegistered]
+
+ worker.expectMsgType[CreateActor]
+ worker.reply(ActorCreated(master.ref, "appmaster"))
+
+ client.expectMsg(SubmitApplicationResult(Success(appId)))
+ watcher.expectTerminated(appMasterLauncher)
+ }
+
+ "AppMasterLauncher" should "reallocate resource if executor launch rejected" in {
+ worker.reply(ExecutorLaunchRejected(""))
+ master.expectMsg(RequestResource(appId, ResourceRequest(Resource(1), WorkerId.unspecified)))
+
+ val resource = ResourceAllocated(
+ Array(ResourceAllocation(Resource(1), worker.ref, WorkerId(0, 0L))))
+ master.reply(resource)
+ worker.expectMsgType[LaunchExecutor]
+
+ worker.reply(RegisterActorSystem("systempath"))
+ worker.expectMsgType[ActorSystemRegistered]
+
+ worker.expectMsgType[CreateActor]
+ worker.reply(CreateActorFailed("", new Exception))
+ worker.expectMsgType[ShutdownExecutor]
+ assert(client.receiveN(1).head.asInstanceOf[SubmitApplicationResult].appId.isFailure)
+ watcher.expectTerminated(appMasterLauncher)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/org/apache/gearpump/cluster/master/ApplicationStateSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/org/apache/gearpump/cluster/master/ApplicationStateSpec.scala b/core/src/test/scala/org/apache/gearpump/cluster/master/ApplicationStateSpec.scala
new file mode 100644
index 0000000..a8adaf0
--- /dev/null
+++ b/core/src/test/scala/org/apache/gearpump/cluster/master/ApplicationStateSpec.scala
@@ -0,0 +1,36 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.master
+
+import org.scalatest.{BeforeAndAfterEach, FlatSpec, Matchers}
+
+import org.apache.gearpump.cluster.appmaster.ApplicationState
+
+class ApplicationStateSpec extends FlatSpec with Matchers with BeforeAndAfterEach {
+
+ "ApplicationState" should "check equal with respect to only appId and attemptId" in {
+ val stateA = ApplicationState(0, "application0", 0, null, null, null, "A")
+ val stateB = ApplicationState(0, "application0", 0, null, null, null, "B")
+ val stateC = ApplicationState(0, "application1", 1, null, null, null, "A")
+
+ assert(stateA == stateB)
+ assert(stateA.hashCode == stateB.hashCode)
+ assert(stateA != stateC)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/org/apache/gearpump/cluster/master/MasterProxySpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/org/apache/gearpump/cluster/master/MasterProxySpec.scala b/core/src/test/scala/org/apache/gearpump/cluster/master/MasterProxySpec.scala
new file mode 100644
index 0000000..ff1e7b1
--- /dev/null
+++ b/core/src/test/scala/org/apache/gearpump/cluster/master/MasterProxySpec.scala
@@ -0,0 +1,24 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.master
+
+class MasterProxySpec {
+
+ // Master proxy retries multiple times to find the master
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/org/apache/gearpump/cluster/master/MasterSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/org/apache/gearpump/cluster/master/MasterSpec.scala b/core/src/test/scala/org/apache/gearpump/cluster/master/MasterSpec.scala
new file mode 100644
index 0000000..4070d8c
--- /dev/null
+++ b/core/src/test/scala/org/apache/gearpump/cluster/master/MasterSpec.scala
@@ -0,0 +1,22 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.master
+
+class MasterSpec {
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/org/apache/gearpump/metrics/MetricsSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/org/apache/gearpump/metrics/MetricsSpec.scala b/core/src/test/scala/org/apache/gearpump/metrics/MetricsSpec.scala
new file mode 100644
index 0000000..aa27d8f
--- /dev/null
+++ b/core/src/test/scala/org/apache/gearpump/metrics/MetricsSpec.scala
@@ -0,0 +1,122 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.metrics
+
+import org.mockito.Matchers._
+import org.mockito.Mockito._
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.{FlatSpec, Matchers}
+
+import io.gearpump.codahale.metrics.{Counter => CodaHaleCounter, Histogram => CodaHaleHistogram, Meter => CodaHaleMeter}
+
+class MetricsSpec extends FlatSpec with Matchers with MockitoSugar {
+
+ "Counter" should "handle sampleRate == 1" in {
+
+ val mockBaseCounter = mock[CodaHaleCounter]
+
+ val counter = new Counter("c", mockBaseCounter)
+
+ counter.inc()
+ counter.inc()
+
+ verify(mockBaseCounter, times(2)).inc(1)
+ }
+
+ "Counter" should "handle sampleRate == 3" in {
+
+ val mockBaseCounter = mock[CodaHaleCounter]
+
+ val counter = new Counter("c", mockBaseCounter, 3)
+
+ counter.inc(1)
+ counter.inc(1)
+ counter.inc(1)
+ counter.inc(1)
+ counter.inc(1)
+ counter.inc(1)
+
+ verify(mockBaseCounter, times(2)).inc(3)
+ }
+
+ "Histogram" should "handle sampleRate == 1" in {
+
+ val mockBaseHistogram = mock[CodaHaleHistogram]
+
+ val histogram = new Histogram("h", mockBaseHistogram)
+
+ histogram.update(3)
+ histogram.update(7)
+ histogram.update(5)
+ histogram.update(9)
+
+ verify(mockBaseHistogram, times(4)).update(anyLong())
+ }
+
+ "Histogram" should "handle sampleRate > 1" in {
+
+ val mockBaseHistogram = mock[CodaHaleHistogram]
+
+ val histogram = new Histogram("h", mockBaseHistogram, 2)
+
+ histogram.update(3)
+ histogram.update(4)
+ histogram.update(5)
+ histogram.update(6)
+
+ verify(mockBaseHistogram, times(1)).update(4L)
+ verify(mockBaseHistogram, times(1)).update(6L)
+ }
+
+ "Meter" should "handle sampleRate == 1" in {
+
+ val mockBaseMeter = mock[CodaHaleMeter]
+
+ val meter = new Meter("m", mockBaseMeter)
+
+ meter.mark()
+ meter.mark(3)
+
+ verify(mockBaseMeter, times(1)).mark(1L)
+ verify(mockBaseMeter, times(1)).mark(3L)
+ }
+
+ "Meter" should "handle sampleRate > 1" in {
+
+ val mockBaseMeter = mock[CodaHaleMeter]
+
+ val meter = new Meter("m", mockBaseMeter, 2)
+
+ meter.mark(1)
+ meter.mark(3)
+
+ meter.mark(5)
+ meter.mark(7)
+
+ verify(mockBaseMeter, times(1)).mark(4L)
+ verify(mockBaseMeter, times(1)).mark(12L)
+ }
+
+ "Metrics" should "have a name" in {
+ val metrics = new Metrics(3)
+ assert(metrics.counter("counter").name == "counter")
+ assert(metrics.histogram("histogram").name == "histogram")
+ assert(metrics.meter("meter").name == "meter")
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/org/apache/gearpump/partitioner/PartitionerSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/org/apache/gearpump/partitioner/PartitionerSpec.scala b/core/src/test/scala/org/apache/gearpump/partitioner/PartitionerSpec.scala
new file mode 100644
index 0000000..14be887
--- /dev/null
+++ b/core/src/test/scala/org/apache/gearpump/partitioner/PartitionerSpec.scala
@@ -0,0 +1,55 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.partitioner
+
+import org.scalatest.{FlatSpec, Matchers}
+
+import org.apache.gearpump.Message
+
+class PartitionerSpec extends FlatSpec with Matchers {
+ val NUM = 10
+
+ "HashPartitioner" should "hash same key to same slots" in {
+ val partitioner = new HashPartitioner
+
+ val data = new Array[Byte](1000)
+ (new java.util.Random()).nextBytes(data)
+ val msg = Message(data)
+
+ val partition = partitioner.getPartition(msg, NUM)
+ assert(partition >= 0 && partition < NUM, "Partition Id should be >= 0")
+
+ assert(partition == partitioner.getPartition(msg, NUM), "multiple run should return" +
+ "consistent result")
+ }
+
+ "ShufflePartitioner" should "hash same key randomly" in {
+ val partitioner = new ShufflePartitioner
+
+ val data = new Array[Byte](1000)
+ (new java.util.Random()).nextBytes(data)
+ val msg = Message(data)
+
+ val partition = partitioner.getPartition(msg, NUM)
+ assert(partition >= 0 && partition < NUM, "Partition Id should be >= 0")
+
+ assert(partition != partitioner.getPartition(msg, NUM), "multiple run should return" +
+ "consistent result")
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/org/apache/gearpump/security/ConfigFileBasedAuthenticatorSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/org/apache/gearpump/security/ConfigFileBasedAuthenticatorSpec.scala b/core/src/test/scala/org/apache/gearpump/security/ConfigFileBasedAuthenticatorSpec.scala
new file mode 100644
index 0000000..ffe47be
--- /dev/null
+++ b/core/src/test/scala/org/apache/gearpump/security/ConfigFileBasedAuthenticatorSpec.scala
@@ -0,0 +1,54 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.security
+
+import scala.concurrent.Await
+import scala.concurrent.duration._
+
+import akka.actor.ActorSystem
+import org.scalatest.{FlatSpec, Matchers}
+
+import org.apache.gearpump.cluster.TestUtil
+
+class ConfigFileBasedAuthenticatorSpec extends FlatSpec with Matchers {
+ it should "authenticate correctly" in {
+ val config = TestUtil.UI_CONFIG
+ implicit val system = ActorSystem("ConfigFileBasedAuthenticatorSpec", config)
+ implicit val ec = system.dispatcher
+ val timeout = 30.seconds
+
+ val authenticator = new ConfigFileBasedAuthenticator(config)
+ val guest = Await.result(authenticator.authenticate("guest", "guest", ec), timeout)
+ val admin = Await.result(authenticator.authenticate("admin", "admin", ec), timeout)
+
+ val nonexist = Await.result(authenticator.authenticate("nonexist", "nonexist", ec), timeout)
+
+ val failedGuest = Await.result(authenticator.authenticate("guest", "wrong", ec), timeout)
+ val failedAdmin = Await.result(authenticator.authenticate("admin", "wrong", ec), timeout)
+
+ assert(guest == Authenticator.Guest)
+ assert(admin == Authenticator.Admin)
+ assert(nonexist == Authenticator.UnAuthenticated)
+ assert(failedGuest == Authenticator.UnAuthenticated)
+ assert(failedAdmin == Authenticator.UnAuthenticated)
+
+ system.terminate()
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/org/apache/gearpump/security/PasswordUtilSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/org/apache/gearpump/security/PasswordUtilSpec.scala b/core/src/test/scala/org/apache/gearpump/security/PasswordUtilSpec.scala
new file mode 100644
index 0000000..1cec360
--- /dev/null
+++ b/core/src/test/scala/org/apache/gearpump/security/PasswordUtilSpec.scala
@@ -0,0 +1,38 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.security
+
+import org.scalatest.{FlatSpec, Matchers}
+
+class PasswordUtilSpec extends FlatSpec with Matchers {
+
+ it should "verify the credential correctly" in {
+ val password = "password"
+
+ val digest1 = PasswordUtil.hash(password)
+ val digest2 = PasswordUtil.hash(password)
+
+ // Uses different salt each time, thus creating different hash.
+ assert(digest1 != digest2)
+
+ // Both are valid hash.
+ assert(PasswordUtil.verify(password, digest1))
+ assert(PasswordUtil.verify(password, digest2))
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/org/apache/gearpump/serializer/SerializerSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/org/apache/gearpump/serializer/SerializerSpec.scala b/core/src/test/scala/org/apache/gearpump/serializer/SerializerSpec.scala
new file mode 100644
index 0000000..d4f4167
--- /dev/null
+++ b/core/src/test/scala/org/apache/gearpump/serializer/SerializerSpec.scala
@@ -0,0 +1,91 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.serializer
+
+import scala.collection.JavaConverters._
+import scala.concurrent.Await
+import scala.concurrent.duration.Duration
+
+import akka.actor.{ActorSystem, ExtendedActorSystem}
+import com.typesafe.config.{ConfigFactory, ConfigValueFactory}
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.{FlatSpec, Matchers}
+
+import org.apache.gearpump.cluster.TestUtil
+import io.gearpump.esotericsoftware.kryo.io.{Input, Output}
+import io.gearpump.esotericsoftware.kryo.{Kryo, Serializer => KryoSerializer}
+import org.apache.gearpump.serializer.SerializerSpec._
+
+class SerializerSpec extends FlatSpec with Matchers with MockitoSugar {
+ val config = ConfigFactory.empty.withValue("gearpump.serializers",
+ ConfigValueFactory.fromAnyRef(Map(classOf[ClassA].getName -> classOf[ClassASerializer].getName,
+ classOf[ClassB].getName -> classOf[ClassBSerializer].getName).asJava))
+
+ "GearpumpSerialization" should "register custom serializers" in {
+ val serialization = new GearpumpSerialization(config)
+ val kryo = new Kryo
+ serialization.customize(kryo)
+
+ val forB = kryo.getRegistration(classOf[ClassB])
+ assert(forB.getSerializer.isInstanceOf[ClassBSerializer])
+
+ val forA = kryo.getRegistration(classOf[ClassA])
+ assert(forA.getSerializer.isInstanceOf[ClassASerializer])
+ }
+
+ "FastKryoSerializer" should "serialize correctly" in {
+ val myConfig = config.withFallback(TestUtil.DEFAULT_CONFIG.withoutPath("gearpump.serializers"))
+ val system = ActorSystem("my", myConfig)
+
+ val serializer = new FastKryoSerializer(system.asInstanceOf[ExtendedActorSystem])
+
+ val bytes = serializer.serialize(new ClassA)
+ val anotherA = serializer.deserialize(bytes)
+
+ assert(anotherA.isInstanceOf[ClassA])
+ system.terminate()
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+}
+
+object SerializerSpec {
+
+ class ClassA {}
+
+ class ClassASerializer extends KryoSerializer[ClassA] {
+ override def write(kryo: Kryo, output: Output, `object`: ClassA): Unit = {
+ output.writeString(classOf[ClassA].getName.toString)
+ }
+
+ override def read(kryo: Kryo, input: Input, `type`: Class[ClassA]): ClassA = {
+ val className = input.readString()
+ Class.forName(className).newInstance().asInstanceOf[ClassA]
+ }
+ }
+
+ class ClassB {}
+
+ class ClassBSerializer extends KryoSerializer[ClassA] {
+ override def write(kryo: Kryo, output: Output, `object`: ClassA): Unit = {}
+
+ override def read(kryo: Kryo, input: Input, `type`: Class[ClassA]): ClassA = {
+ null
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/org/apache/gearpump/transport/MockTransportSerializer.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/org/apache/gearpump/transport/MockTransportSerializer.scala b/core/src/test/scala/org/apache/gearpump/transport/MockTransportSerializer.scala
new file mode 100644
index 0000000..ddeb72d
--- /dev/null
+++ b/core/src/test/scala/org/apache/gearpump/transport/MockTransportSerializer.scala
@@ -0,0 +1,42 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.transport
+
+import java.io.{DataInput, DataOutput}
+import org.apache.gearpump.transport.MockTransportSerializer.NettyMessage
+import org.apache.gearpump.transport.netty.ITransportMessageSerializer
+
+class MockTransportSerializer extends ITransportMessageSerializer {
+ override def getLength(obj: scala.Any): Int = 4
+
+ override def serialize(dataOutput: DataOutput, transportMessage: scala.Any): Unit = {
+ transportMessage match {
+ case msg: NettyMessage =>
+ dataOutput.writeInt(msg.num)
+ }
+ }
+
+ override def deserialize(dataInput: DataInput, length: Int): AnyRef = {
+ NettyMessage(dataInput.readInt())
+ }
+}
+
+object MockTransportSerializer {
+ case class NettyMessage(num: Int)
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/org/apache/gearpump/transport/NettySpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/org/apache/gearpump/transport/NettySpec.scala b/core/src/test/scala/org/apache/gearpump/transport/NettySpec.scala
new file mode 100644
index 0000000..b1a429c
--- /dev/null
+++ b/core/src/test/scala/org/apache/gearpump/transport/NettySpec.scala
@@ -0,0 +1,63 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.transport
+
+import java.util.concurrent.TimeUnit
+
+import scala.concurrent.Await
+import scala.concurrent.duration._
+
+import akka.actor.{ActorRef, ActorSystem}
+import akka.testkit.TestProbe
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.{FlatSpec, Matchers}
+
+import org.apache.gearpump.cluster.TestUtil
+import org.apache.gearpump.transport.MockTransportSerializer.NettyMessage
+import org.apache.gearpump.transport.netty.{TaskMessage, Context}
+import org.apache.gearpump.util.Util
+
+class NettySpec extends FlatSpec with Matchers with MockitoSugar {
+
+ "Netty Transport" should "send and receive message correctly " in {
+ val conf = TestUtil.DEFAULT_CONFIG
+ val system = ActorSystem("transport", conf)
+ val context = new Context(system, conf)
+ val serverActor = TestProbe()(system)
+
+ val port = Util.findFreePort()
+
+ import system.dispatcher
+ system.scheduler.scheduleOnce(Duration(1, TimeUnit.SECONDS)) {
+ context.bind("server", new ActorLookupById {
+ override def lookupLocalActor(id: Long): Option[ActorRef] = Some(serverActor.ref)
+ }, false, port.get)
+ }
+ val client = context.connect(HostPort("127.0.0.1", port.get))
+
+ val data = NettyMessage(0)
+ val msg = new TaskMessage(0, 1, 2, data)
+ client ! msg
+ serverActor.expectMsg(15.seconds, data)
+
+ context.close()
+ system.terminate()
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/org/apache/gearpump/util/ActorSystemBooterSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/org/apache/gearpump/util/ActorSystemBooterSpec.scala b/core/src/test/scala/org/apache/gearpump/util/ActorSystemBooterSpec.scala
new file mode 100644
index 0000000..0d33d44
--- /dev/null
+++ b/core/src/test/scala/org/apache/gearpump/util/ActorSystemBooterSpec.scala
@@ -0,0 +1,118 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.util
+
+import scala.concurrent.Await
+import scala.concurrent.duration.Duration
+
+import akka.actor.{Actor, ActorSystem, Props}
+import akka.testkit.TestProbe
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.{FlatSpec, Matchers}
+
+import org.apache.gearpump.cluster.TestUtil
+import org.apache.gearpump.util.ActorSystemBooter.{ActorCreated, RegisterActorSystem, _}
+import org.apache.gearpump.util.ActorSystemBooterSpec._
+
+class ActorSystemBooterSpec extends FlatSpec with Matchers with MockitoSugar {
+
+ "ActorSystemBooter" should "report its address back" in {
+ val boot = bootSystem()
+ boot.prob.expectMsgType[RegisterActorSystem]
+ boot.shutdown()
+ }
+
+ "ActorSystemBooter" should "terminate itself when parent actor dies" in {
+ val boot = bootSystem()
+ boot.prob.expectMsgType[RegisterActorSystem]
+
+ val dummy = boot.host.actorOf(Props(classOf[Dummy]), "dummy")
+ boot.prob.reply(ActorSystemRegistered(boot.prob.ref))
+ boot.prob.reply(BindLifeCycle(dummy))
+ boot.host.stop(dummy)
+ val terminated = retry(5)(boot.bootedSystem.whenTerminated.isCompleted)
+ assert(terminated)
+ boot.shutdown()
+ }
+
+ "ActorSystemBooter" should "create new actor" in {
+ val boot = bootSystem()
+ boot.prob.expectMsgType[RegisterActorSystem]
+ boot.prob.reply(ActorSystemRegistered(boot.prob.ref))
+ boot.prob.reply(CreateActor(Props(classOf[AcceptThreeArguments], 1, 2, 3), "three"))
+ boot.prob.expectMsgType[ActorCreated]
+
+ boot.prob.reply(CreateActor(Props(classOf[AcceptZeroArguments]), "zero"))
+ boot.prob.expectMsgType[ActorCreated]
+
+ boot.shutdown()
+ }
+
+ private def bootSystem(): Boot = {
+ val booter = ActorSystemBooter(TestUtil.DEFAULT_CONFIG)
+
+ val system = ActorSystem("reportback", TestUtil.DEFAULT_CONFIG)
+
+ val receiver = TestProbe()(system)
+ val address = ActorUtil.getFullPath(system, receiver.ref.path)
+
+ val bootSystem = booter.boot("booter", address)
+
+ Boot(system, receiver, bootSystem)
+ }
+
+ case class Boot(host: ActorSystem, prob: TestProbe, bootedSystem: ActorSystem) {
+ def shutdown(): Unit = {
+ host.terminate()
+ bootedSystem.terminate()
+ Await.result(host.whenTerminated, Duration.Inf)
+ Await.result(bootedSystem.whenTerminated, Duration.Inf)
+ }
+ }
+
+ def retry(seconds: Int)(fn: => Boolean): Boolean = {
+ val result = fn
+ if (result) {
+ result
+ } else {
+ Thread.sleep(1000)
+ retry(seconds - 1)(fn)
+ }
+ }
+}
+
+object ActorSystemBooterSpec {
+ class Dummy extends Actor {
+ def receive: Receive = {
+ case _ =>
+ }
+ }
+
+ class AcceptZeroArguments extends Actor {
+ def receive: Receive = {
+ case _ =>
+ }
+ }
+
+ class AcceptThreeArguments(a: Int, b: Int, c: Int) extends Actor {
+ def receive: Receive = {
+ case _ =>
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/org/apache/gearpump/util/ActorUtilSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/org/apache/gearpump/util/ActorUtilSpec.scala b/core/src/test/scala/org/apache/gearpump/util/ActorUtilSpec.scala
new file mode 100644
index 0000000..534bf00
--- /dev/null
+++ b/core/src/test/scala/org/apache/gearpump/util/ActorUtilSpec.scala
@@ -0,0 +1,40 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.util
+
+import org.scalatest.FlatSpec
+
+import org.apache.gearpump.transport.HostPort
+
+class ActorUtilSpec extends FlatSpec {
+ "masterActorPath" should "construct the ActorPath from HostPort" in {
+ import org.apache.gearpump.util.Constants.MASTER
+
+ val host = "127.0.0.1"
+ val port = 3000
+ val master = HostPort("127.0.0.1", 3000)
+ val masterPath = ActorUtil.getMasterActorPath(master)
+ assert(masterPath.address.port == Some(port))
+ assert(masterPath.address.system == MASTER)
+ assert(masterPath.address.host == Some(host))
+ assert(masterPath.address.protocol == "akka.tcp")
+ assert(masterPath.toStringWithoutAddress == s"/user/$MASTER")
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/org/apache/gearpump/util/ConfigsSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/org/apache/gearpump/util/ConfigsSpec.scala b/core/src/test/scala/org/apache/gearpump/util/ConfigsSpec.scala
new file mode 100644
index 0000000..e7b9d18
--- /dev/null
+++ b/core/src/test/scala/org/apache/gearpump/util/ConfigsSpec.scala
@@ -0,0 +1,99 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.util
+
+import java.io.File
+import scala.concurrent.Await
+import scala.concurrent.duration.Duration
+
+import akka.actor.ActorSystem
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.{FlatSpec, Matchers}
+
+import org.apache.gearpump.cluster.{ClusterConfig, ClusterConfigSource, UserConfig}
+
+class ConfigsSpec extends FlatSpec with Matchers with MockitoSugar {
+ "Typesafe Cluster Configs" should "follow the override rules" in {
+
+ val conf =
+ """
+ gearpump {
+ gear = "gearpump"
+ }
+
+ gearpump-master {
+ conf = "master"
+ }
+ gearpump-worker {
+ conf = "worker"
+ }
+ conf = "base"
+ """
+
+ val file = File.createTempFile("test", ".conf")
+ FileUtils.write(file, conf)
+
+ val raw = ClusterConfig.load(ClusterConfigSource(file.toString))
+
+ assert(raw.master.getString("conf") == "master", "master > base")
+ assert(raw.worker.getString("conf") == "worker", "worker > base")
+ assert(raw.default.getString("conf") == "base", "application > base")
+
+ file.delete()
+ }
+
+ "ClusterConfigSource" should "return empty for non-exist files" in {
+ val source = ClusterConfigSource("non-exist")
+ var config = source.getConfig
+ assert(config.isEmpty)
+
+ val nullCheck = ClusterConfigSource(null)
+ config = nullCheck.getConfig
+ assert(config.isEmpty)
+ }
+
+ "User Config" should "work" in {
+
+ implicit val system = ActorSystem("forSerialization")
+
+ val map = Map[String, String]("key1" -> "1", "key2" -> "value2")
+
+ val user = new UserConfig(map)
+ .withLong("key3", 2L)
+ .withBoolean("key4", value = true)
+ .withFloat("key5", 3.14F)
+ .withDouble("key6", 2.718)
+
+ assert(user.getInt("key1").get == 1)
+ assert(user.getString("key1").get == "1")
+ assert(user.getLong("key3").get == 2L)
+ assert(user.getBoolean("key4").get == true)
+ assert(user.getFloat("key5").get == 3.14F)
+ assert(user.getDouble("key6").get == 2.718)
+
+ val data = new ConfigsSpec.Data(3)
+ assert(data == user.withValue("data", data).getValue[ConfigsSpec.Data]("data").get)
+ system.terminate()
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+}
+
+object ConfigsSpec {
+ case class Data(value: Int)
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/org/apache/gearpump/util/FileUtilsSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/org/apache/gearpump/util/FileUtilsSpec.scala b/core/src/test/scala/org/apache/gearpump/util/FileUtilsSpec.scala
new file mode 100644
index 0000000..7ad83ce
--- /dev/null
+++ b/core/src/test/scala/org/apache/gearpump/util/FileUtilsSpec.scala
@@ -0,0 +1,62 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.util
+
+import java.io.File
+import java.util
+
+import org.scalatest.FlatSpec
+
+import io.gearpump.google.common.io.Files
+
+class FileUtilsSpec extends FlatSpec {
+ val TXT =
+ """
+ |This is a multiple line
+ |text
+ |
+ """.stripMargin
+
+ it should "read/write string correctly" in {
+ val file = File.createTempFile("fileutilspec", ".test")
+ FileUtils.write(file, TXT)
+ assert(FileUtils.read(file) == TXT)
+ file.delete()
+ }
+
+ it should "read/write bytes array correctly" in {
+ val file = File.createTempFile("fileutilspec", ".test")
+ val bytes = TXT.toCharArray.map(_.toByte)
+ FileUtils.writeByteArrayToFile(file, bytes)
+ util.Arrays.equals(bytes, FileUtils.readFileToByteArray(file))
+ file.delete()
+ }
+
+ it should "create directory and all parents" in {
+ val temp = Files.createTempDir()
+ val parent = new File(temp, "sub1")
+ val child = new File(parent, "sub2" + File.separator)
+ FileUtils.forceMkdir(child)
+ assert(child.exists())
+ assert(child.isDirectory)
+ child.delete()
+ parent.delete()
+ temp.delete()
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/org/apache/gearpump/util/GraphSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/org/apache/gearpump/util/GraphSpec.scala b/core/src/test/scala/org/apache/gearpump/util/GraphSpec.scala
new file mode 100644
index 0000000..2b6df78
--- /dev/null
+++ b/core/src/test/scala/org/apache/gearpump/util/GraphSpec.scala
@@ -0,0 +1,213 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.util
+
+import org.scalacheck.Gen
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{Matchers, PropSpec}
+
+import org.apache.gearpump.util.Graph.{Node, Path}
+
+class GraphSpec extends PropSpec with PropertyChecks with Matchers {
+
+ case class Vertex(id: Int)
+ case class Edge(from: Int, to: Int)
+
+ val vertexCount = 100
+
+ property("Graph with no edges should be built correctly") {
+ val vertexSet = Set("A", "B", "C")
+ val graph = Graph(vertexSet.toSeq.map(Node): _*)
+ graph.vertices.toSet shouldBe vertexSet
+ }
+
+ property("Graph with vertices and edges should be built correctly") {
+ val vertices: Array[Vertex] = 0.until(vertexCount).map(Vertex).toArray
+ val genEdge = for {
+ from <- Gen.chooseNum[Int](0, vertexCount - 1)
+ to <- Gen.chooseNum[Int](0, vertexCount - 1)
+ } yield Edge(from, to)
+
+ var graphElements = Array.empty[Path[Vertex, _ <: Edge]]
+ val outDegrees = new Array[Int](vertices.length)
+ val outGoingEdges = vertices.map(_ => Set.empty[(Vertex, Edge, Vertex)])
+ val edgesOf = vertices.map(_ => Set.empty[(Vertex, Edge, Vertex)])
+ vertices.foreach { v =>
+ graphElements :+= Node(v)
+ }
+
+ forAll(genEdge) {
+ e: Edge =>
+ val from = vertices(e.from)
+ val to = vertices(e.to)
+ graphElements :+= from ~ e ~> to
+ outDegrees(e.from) += 1
+
+ val nodeEdgeNode = (from, e, to)
+ outGoingEdges(e.from) += nodeEdgeNode
+
+ edgesOf(e.from) += nodeEdgeNode
+ edgesOf(e.to) += nodeEdgeNode
+ }
+
+ val graph: Graph[Vertex, Edge] = Graph(graphElements: _*)
+ graph.vertices should contain theSameElementsAs vertices
+
+ 0.until(vertices.size).foreach { i =>
+ val v = vertices(i)
+ graph.outgoingEdgesOf(v) should contain theSameElementsAs outGoingEdges(i)
+ graph.edgesOf(v).sortBy(_._1.id)
+ graph.edgesOf(v) should contain theSameElementsAs edgesOf(i)
+ }
+ }
+
+ property("Check empty graph") {
+ val graph = Graph.empty[String, String]
+ assert(graph.isEmpty)
+ }
+
+ property("check level map for a graph") {
+ val graph = Graph.empty[String, String]
+
+ val defaultEdge = "edge"
+
+ graph.addVertex("A")
+ graph.addVertex("B")
+ graph.addVertex("C")
+
+ graph.addEdge("A", defaultEdge, "B")
+ graph.addEdge("B", defaultEdge, "C")
+ graph.addEdge("A", defaultEdge, "C")
+
+ graph.addVertex("D")
+ graph.addVertex("E")
+ graph.addVertex("F")
+
+ graph.addEdge("D", defaultEdge, "E")
+ graph.addEdge("E", defaultEdge, "F")
+ graph.addEdge("D", defaultEdge, "F")
+
+ graph.addEdge("C", defaultEdge, "E")
+
+ val levelMap = graph.vertexHierarchyLevelMap()
+
+ // Check whether the rule holds: : if vertex A -> B, then level(A) < level(B)
+ levelMap("A") < levelMap("B")
+ levelMap("A") < levelMap("C")
+ levelMap("B") < levelMap("C")
+
+ levelMap("D") < levelMap("E")
+ levelMap("D") < levelMap("F")
+ levelMap("E") < levelMap("F")
+
+ levelMap("C") < levelMap("F")
+ }
+
+ property("copy should return a immutalbe new Graph") {
+ val graph = Graph.empty[String, String]
+ val defaultEdge = "edge"
+ graph.addVertex("A")
+ graph.addVertex("B")
+ graph.addEdge("A", defaultEdge, "B")
+
+ val newGraph = graph.copy
+ newGraph.addVertex("C")
+
+ assert(!graph.vertices.toSet.contains("C"), "Graph should be immutable")
+ }
+
+ property("subGraph should return a sub-graph for certain vertex") {
+ val graph = Graph.empty[String, String]
+ val defaultEdge = "edge"
+ graph.addVertex("A")
+ graph.addVertex("B")
+ graph.addVertex("C")
+ graph.addEdge("A", defaultEdge, "B")
+ graph.addEdge("B", defaultEdge, "C")
+ graph.addEdge("A", defaultEdge, "C")
+
+ val subGraph = graph.subGraph("C")
+ assert(subGraph.outDegreeOf("A") != graph.outDegreeOf("A"))
+ }
+
+ property("replaceVertex should hold all upstream downstream relation for a vertex") {
+ val graph = Graph.empty[String, String]
+ val defaultEdge = "edge"
+ graph.addVertex("A")
+ graph.addVertex("B")
+ graph.addVertex("C")
+ graph.addEdge("A", defaultEdge, "B")
+ graph.addEdge("B", defaultEdge, "C")
+
+ val newGraph = graph.copy.replaceVertex("B", "D")
+ assert(newGraph.inDegreeOf("D") == graph.inDegreeOf("B"))
+ assert(newGraph.outDegreeOf("D") == graph.outDegreeOf("B"))
+ }
+
+ property("Cycle detecting should work properly") {
+ val graph = Graph.empty[String, String]
+ val defaultEdge = "edge"
+ graph.addVertex("A")
+ graph.addVertex("B")
+ graph.addVertex("C")
+ graph.addEdge("A", defaultEdge, "B")
+ graph.addEdge("B", defaultEdge, "C")
+
+ assert(!graph.hasCycle())
+
+ graph.addEdge("C", defaultEdge, "B")
+ assert(graph.hasCycle())
+
+ graph.addEdge("C", defaultEdge, "A")
+ assert(graph.hasCycle())
+ }
+
+ property("topologicalOrderIterator and topologicalOrderWithCirclesIterator method should " +
+ "return equal order of graph with no circle") {
+ val graph = Graph(1 ~> 2 ~> 3, 4 ~> 2, 2 ~> 5)
+ val topoNoCircles = graph.topologicalOrderIterator
+ val topoWithCircles = graph.topologicalOrderWithCirclesIterator
+
+ assert(topoNoCircles.zip(topoWithCircles).forall(x => x._1 == x._2))
+ }
+
+ property("Topological sort of graph with circles should work properly") {
+ val graph = Graph(0 ~> 1 ~> 3 ~> 4 ~> 6 ~> 5 ~> 7,
+ 4 ~> 1, 1 ~> 2 ~> 4, 7 ~> 6, 8 ~> 2, 6 ~> 9, 4 ~> 10)
+ val topoWithCircles = graph.topologicalOrderWithCirclesIterator
+ val trueTopoWithCircles = Iterator[Int](0, 8, 1, 3, 4, 2, 6, 5, 7, 10, 9)
+
+ assert(trueTopoWithCircles.zip(topoWithCircles).forall(x => x._1 == x._2))
+ }
+
+ property("Duplicated edges detecting should work properly") {
+ val graph = Graph.empty[String, String]
+ val defaultEdge = "edge"
+ val anotherEdge = "edge2"
+ graph.addVertex("A")
+ graph.addVertex("B")
+ graph.addEdge("A", defaultEdge, "B")
+
+ assert(!graph.hasDuplicatedEdge())
+
+ graph.addEdge("A", anotherEdge, "B")
+
+ assert(graph.hasDuplicatedEdge())
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/org/apache/gearpump/util/TimeOutSchedulerSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/org/apache/gearpump/util/TimeOutSchedulerSpec.scala b/core/src/test/scala/org/apache/gearpump/util/TimeOutSchedulerSpec.scala
new file mode 100644
index 0000000..6f18497
--- /dev/null
+++ b/core/src/test/scala/org/apache/gearpump/util/TimeOutSchedulerSpec.scala
@@ -0,0 +1,75 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.util
+
+import scala.concurrent.duration._
+
+import akka.actor._
+import akka.testkit.{ImplicitSender, TestActorRef, TestKit, TestProbe}
+import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.TestUtil
+
+class TimeOutSchedulerSpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
+ with WordSpecLike with Matchers with BeforeAndAfterAll {
+
+ def this() = this(ActorSystem("WorkerSpec", TestUtil.DEFAULT_CONFIG))
+ val mockActor = TestProbe()
+
+ override def afterAll {
+ TestKit.shutdownActorSystem(system)
+ }
+
+ "The TimeOutScheduler" should {
+ "handle the time out event" in {
+ val testActorRef = TestActorRef(Props(classOf[TestActor], mockActor.ref))
+ val testActor = testActorRef.underlyingActor.asInstanceOf[TestActor]
+ testActor.sendMsgToIgnore()
+ mockActor.expectMsg(30.seconds, MessageTimeOut)
+ }
+ }
+}
+
+case object Echo
+case object MessageTimeOut
+
+class TestActor(mock: ActorRef) extends Actor with TimeOutScheduler {
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+
+ val target = context.actorOf(Props(classOf[EchoActor]))
+
+ override def receive: Receive = {
+ case _ =>
+ }
+
+ def sendMsgToIgnore(): Unit = {
+ sendMsgWithTimeOutCallBack(target, Echo, 2000, sendMsgTimeOut())
+ }
+
+ private def sendMsgTimeOut(): Unit = {
+ mock ! MessageTimeOut
+ }
+}
+
+class EchoActor extends Actor {
+ override def receive: Receive = {
+ case _ =>
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/org/apache/gearpump/util/UtilSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/org/apache/gearpump/util/UtilSpec.scala b/core/src/test/scala/org/apache/gearpump/util/UtilSpec.scala
new file mode 100644
index 0000000..6e6cec1
--- /dev/null
+++ b/core/src/test/scala/org/apache/gearpump/util/UtilSpec.scala
@@ -0,0 +1,46 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.util
+
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.{FlatSpec, Matchers}
+
+import org.apache.gearpump.transport.HostPort
+import org.apache.gearpump.util.Util._
+
+class UtilSpec extends FlatSpec with Matchers with MockitoSugar {
+ it should "work" in {
+
+ assert(findFreePort().isSuccess)
+
+ assert(randInt() != randInt())
+
+ val hosts = parseHostList("host1:1,host2:2")
+ assert(hosts(1) == HostPort("host2", 2))
+
+ assert(Util.getCurrentClassPath.length > 0)
+ }
+
+ it should "check application name properly" in {
+ assert(Util.validApplicationName("_application_1"))
+ assert(Util.validApplicationName("application_1_"))
+ assert(!Util.validApplicationName("0_application_1"))
+ assert(!Util.validApplicationName("_applicat&&ion_1"))
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/resources/META-INF/services/io.gearpump.jarstore.JarStoreService
----------------------------------------------------------------------
diff --git a/daemon/src/main/resources/META-INF/services/io.gearpump.jarstore.JarStoreService b/daemon/src/main/resources/META-INF/services/io.gearpump.jarstore.JarStoreService
deleted file mode 100644
index d226af9..0000000
--- a/daemon/src/main/resources/META-INF/services/io.gearpump.jarstore.JarStoreService
+++ /dev/null
@@ -1,20 +0,0 @@
-#
-# 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.
-#
-
-io.gearpump.jarstore.local.LocalJarStoreService
-io.gearpump.jarstore.dfs.DFSJarStoreService
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/resources/META-INF/services/org.apache.gearpump.jarstore.JarStoreService
----------------------------------------------------------------------
diff --git a/daemon/src/main/resources/META-INF/services/org.apache.gearpump.jarstore.JarStoreService b/daemon/src/main/resources/META-INF/services/org.apache.gearpump.jarstore.JarStoreService
new file mode 100644
index 0000000..bf37316
--- /dev/null
+++ b/daemon/src/main/resources/META-INF/services/org.apache.gearpump.jarstore.JarStoreService
@@ -0,0 +1,20 @@
+#
+# 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.
+#
+
+org.apache.gearpump.jarstore.local.LocalJarStoreService
+org.apache.gearpump.jarstore.dfs.DFSJarStoreService
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/io/gearpump/cluster/DaemonMessage.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/io/gearpump/cluster/DaemonMessage.scala b/daemon/src/main/scala/io/gearpump/cluster/DaemonMessage.scala
deleted file mode 100644
index 420f1b6..0000000
--- a/daemon/src/main/scala/io/gearpump/cluster/DaemonMessage.scala
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.cluster
-
-import akka.actor.ActorRef
-
-import io.gearpump.cluster.master.Master.MasterInfo
-import io.gearpump.cluster.scheduler.Resource
-import io.gearpump.cluster.worker.WorkerId
-
-/**
- * Cluster Bootup Flow
- */
-object WorkerToMaster {
-
- /** When an worker is started, it sends RegisterNewWorker */
- case object RegisterNewWorker
-
- /** When worker lose connection with master, it tries to register itself again with old Id. */
- case class RegisterWorker(workerId: WorkerId)
-
- /** Worker is responsible to broadcast its current status to master */
- case class ResourceUpdate(worker: ActorRef, workerId: WorkerId, resource: Resource)
-}
-
-object MasterToWorker {
-
- /** Master confirm the reception of RegisterNewWorker or RegisterWorker */
- case class WorkerRegistered(workerId: WorkerId, masterInfo: MasterInfo)
-
- /** Worker have not received reply from master */
- case class UpdateResourceFailed(reason: String = null, ex: Throwable = null)
-
- /** Master is synced with worker on resource slots managed by current worker */
- case object UpdateResourceSucceed
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/io/gearpump/cluster/embedded/EmbeddedCluster.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/io/gearpump/cluster/embedded/EmbeddedCluster.scala b/daemon/src/main/scala/io/gearpump/cluster/embedded/EmbeddedCluster.scala
deleted file mode 100644
index 53da645..0000000
--- a/daemon/src/main/scala/io/gearpump/cluster/embedded/EmbeddedCluster.scala
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.embedded
-
-import scala.collection.JavaConverters._
-import scala.concurrent.Await
-import scala.concurrent.duration.Duration
-
-import akka.actor.{ActorRef, ActorSystem, Props}
-import com.typesafe.config.{Config, ConfigValueFactory}
-
-import io.gearpump.cluster.ClusterConfig
-import io.gearpump.cluster.client.ClientContext
-import io.gearpump.cluster.master.{Master => MasterActor}
-import io.gearpump.cluster.worker.{Worker => WorkerActor}
-import io.gearpump.util.Constants.{GEARPUMP_CLUSTER_EXECUTOR_WORKER_SHARE_SAME_PROCESS, GEARPUMP_CLUSTER_MASTERS, GEARPUMP_METRIC_ENABLED, MASTER}
-import io.gearpump.util.{LogUtil, Util}
-
-/**
- * Create a in-process cluster with single worker
- */
-class EmbeddedCluster(inputConfig: Config) {
-
- private val workerCount: Int = 1
- private var _master: ActorRef = null
- private var _system: ActorSystem = null
- private var _config: Config = null
-
- private val LOG = LogUtil.getLogger(getClass)
-
- def start(): Unit = {
- val port = Util.findFreePort().get
- val akkaConf = getConfig(inputConfig, port)
- _config = akkaConf
- val system = ActorSystem(MASTER, akkaConf)
-
- val master = system.actorOf(Props[MasterActor], MASTER)
-
- 0.until(workerCount).foreach { id =>
- system.actorOf(Props(classOf[WorkerActor], master), classOf[WorkerActor].getSimpleName + id)
- }
- this._master = master
- this._system = system
-
- LOG.info("=================================")
- LOG.info("Local Cluster is started at: ")
- LOG.info(s" 127.0.0.1:$port")
- LOG.info(s"To see UI, run command: services -master 127.0.0.1:$port")
- }
-
- private def getConfig(inputConfig: Config, port: Int): Config = {
- val config = inputConfig.
- withValue("akka.remote.netty.tcp.port", ConfigValueFactory.fromAnyRef(port)).
- withValue(GEARPUMP_CLUSTER_MASTERS,
- ConfigValueFactory.fromIterable(List(s"127.0.0.1:$port").asJava)).
- withValue(GEARPUMP_CLUSTER_EXECUTOR_WORKER_SHARE_SAME_PROCESS,
- ConfigValueFactory.fromAnyRef(true)).
- withValue(GEARPUMP_METRIC_ENABLED, ConfigValueFactory.fromAnyRef(true)).
- withValue("akka.actor.provider",
- ConfigValueFactory.fromAnyRef("akka.cluster.ClusterActorRefProvider"))
- config
- }
-
- def newClientContext: ClientContext = {
- ClientContext(_config, _system, _master)
- }
-
- def stop(): Unit = {
- _system.stop(_master)
- _system.terminate()
- Await.result(_system.whenTerminated, Duration.Inf)
- }
-}
-
-object EmbeddedCluster {
- def apply(): EmbeddedCluster = {
- new EmbeddedCluster(ClusterConfig.master())
- }
-}
\ No newline at end of file
[39/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/io/gearpump/cluster/main/AppSubmitter.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/io/gearpump/cluster/main/AppSubmitter.scala b/daemon/src/main/scala/io/gearpump/cluster/main/AppSubmitter.scala
deleted file mode 100644
index 68f778e..0000000
--- a/daemon/src/main/scala/io/gearpump/cluster/main/AppSubmitter.scala
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.cluster.main
-
-import java.io.File
-import java.net.{URL, URLClassLoader}
-import java.util.jar.JarFile
-import scala.util.Try
-
-import org.slf4j.Logger
-
-import io.gearpump.util.{AkkaApp, Constants, LogUtil, Util}
-
-/** Tool to submit an application jar to cluster */
-object AppSubmitter extends AkkaApp with ArgumentsParser {
- val LOG: Logger = LogUtil.getLogger(getClass)
-
- override val ignoreUnknownArgument = true
-
- override val description = "Submit an application to Master by providing a jar"
-
- override val options: Array[(String, CLIOption[Any])] = Array(
- "namePrefix" -> CLIOption[String]("<application name prefix>", required = false,
- defaultValue = Some("")),
- "jar" -> CLIOption("<application>.jar", required = true),
- "executors" -> CLIOption[Int]("number of executor to launch", required = false,
- defaultValue = Some(1)),
- "verbose" -> CLIOption("<print verbose log on console>", required = false,
- defaultValue = Some(false)),
- // For document purpose only, OPTION_CONFIG option is not used here.
- // OPTION_CONFIG is parsed by parent shell command "Gear" transparently.
- Gear.OPTION_CONFIG -> CLIOption("custom configuration file", required = false,
- defaultValue = None))
-
- def main(akkaConf: Config, args: Array[String]): Unit = {
-
- val config = parse(args)
- if (null != config) {
-
- val verbose = config.getBoolean("verbose")
- if (verbose) {
- LogUtil.verboseLogToConsole()
- }
-
- val jar = config.getString("jar")
-
- // Set jar path to be submitted to cluster
- System.setProperty(Constants.GEARPUMP_APP_JAR, jar)
- System.setProperty(Constants.APPLICATION_EXECUTOR_NUMBER, config.getInt("executors").toString)
-
- val namePrefix = config.getString("namePrefix")
- if (namePrefix.nonEmpty) {
- if (!Util.validApplicationName(namePrefix)) {
- throw new Exception(s"$namePrefix is not a valid prefix for an application name")
- }
- System.setProperty(Constants.GEARPUMP_APP_NAME_PREFIX, namePrefix)
- }
-
- val jarFile = new java.io.File(jar)
-
- // Start main class
- if (!jarFile.exists()) {
- throw new Exception(s"jar $jar does not exist")
- }
-
- val classLoader: URLClassLoader = new URLClassLoader(Array(new URL("file:" +
- jarFile.getAbsolutePath)), Thread.currentThread().getContextClassLoader())
- val (main, arguments) = parseMain(jarFile, config.remainArgs, classLoader)
-
- // Set to context classloader. ActorSystem pick context classloader in preference
- Thread.currentThread().setContextClassLoader(classLoader)
- val clazz = classLoader.loadClass(main)
- val mainMethod = clazz.getMethod("main", classOf[Array[String]])
- mainMethod.invoke(null, arguments)
- }
- }
-
- private def parseMain(jar: File, remainArgs: Array[String], classLoader: ClassLoader)
- : (String, Array[String]) = {
- val mainInManifest = Option(new JarFile(jar).getManifest.getMainAttributes.
- getValue("Main-Class")).getOrElse("")
-
- if (remainArgs.length > 0 && Try(classLoader.loadClass(remainArgs(0))).isSuccess) {
- (remainArgs(0), remainArgs.drop(1))
- } else if (mainInManifest.nonEmpty) {
- (mainInManifest, remainArgs)
- } else {
- throw new Exception("No main class specified")
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/io/gearpump/cluster/main/Gear.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/io/gearpump/cluster/main/Gear.scala b/daemon/src/main/scala/io/gearpump/cluster/main/Gear.scala
deleted file mode 100644
index 4423727..0000000
--- a/daemon/src/main/scala/io/gearpump/cluster/main/Gear.scala
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.cluster.main
-
-import org.slf4j.Logger
-
-import io.gearpump.util.{Constants, LogUtil}
-
-object Gear {
-
- val OPTION_CONFIG = "conf"
-
- private val LOG: Logger = LogUtil.getLogger(getClass)
-
- val commands = Map("app" -> AppSubmitter, "kill" -> Kill,
- "info" -> Info, "replay" -> Replay, "main" -> MainRunner)
-
- def usage(): Unit = {
- val keys = commands.keys.toList.sorted
- // scalastyle:off println
- Console.err.println("Usage: " + "<" + keys.mkString("|") + ">")
- // scalastyle:on println
- }
-
- private def executeCommand(command: String, commandArgs: Array[String]) = {
- commands.get(command).map(_.main(commandArgs))
- if (!commands.contains(command)) {
- val allArgs = (command +: commandArgs.toList).toArray
- MainRunner.main(allArgs)
- }
- }
-
- def main(inputArgs: Array[String]): Unit = {
- val (configFile, args) = extractConfig(inputArgs)
- if (configFile != null) {
- // Sets custom config file...
- System.setProperty(Constants.GEARPUMP_CUSTOM_CONFIG_FILE, configFile)
- }
-
- if (args.length == 0) {
- usage()
- } else {
- val command = args(0)
- val commandArgs = args.drop(1)
- executeCommand(command, commandArgs)
- }
- }
-
- private def extractConfig(inputArgs: Array[String]): (String, Array[String]) = {
- var index = 0
-
- var result = List.empty[String]
- var configFile: String = null
- while (index < inputArgs.length) {
- val item = inputArgs(index)
- if (item == s"-$OPTION_CONFIG") {
- index += 1
- configFile = inputArgs(index)
- } else {
- result = result :+ item
- }
- index += 1
- }
- (configFile, result.toArray)
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/io/gearpump/cluster/main/Info.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/io/gearpump/cluster/main/Info.scala b/daemon/src/main/scala/io/gearpump/cluster/main/Info.scala
deleted file mode 100644
index 4922690..0000000
--- a/daemon/src/main/scala/io/gearpump/cluster/main/Info.scala
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.cluster.main
-
-import org.slf4j.Logger
-
-import io.gearpump.cluster.MasterToAppMaster.AppMastersData
-import io.gearpump.cluster.client.ClientContext
-import io.gearpump.util.{AkkaApp, LogUtil}
-
-/** Tool to query master info */
-object Info extends AkkaApp with ArgumentsParser {
-
- private val LOG: Logger = LogUtil.getLogger(getClass)
-
- override val options: Array[(String, CLIOption[Any])] = Array(
- // For document purpose only, OPTION_CONFIG option is not used here.
- // OPTION_CONFIG is parsed by parent shell command "Gear" transparently.
- Gear.OPTION_CONFIG -> CLIOption("custom configuration file", required = false,
- defaultValue = None))
-
- override val description = "Query the Application list"
-
- // scalastyle:off println
- def main(akkaConf: Config, args: Array[String]): Unit = {
- val client = ClientContext(akkaConf)
-
- val AppMastersData(appMasters) = client.listApps
- Console.println("== Application Information ==")
- Console.println("====================================")
- appMasters.foreach { appData =>
- Console.println(s"application: ${appData.appId}, name: ${appData.appName}, " +
- s"status: ${appData.status}, worker: ${appData.workerPath}")
- }
- client.close()
- }
- // scalastyle:on println
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/io/gearpump/cluster/main/Kill.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/io/gearpump/cluster/main/Kill.scala b/daemon/src/main/scala/io/gearpump/cluster/main/Kill.scala
deleted file mode 100644
index 3ce781f..0000000
--- a/daemon/src/main/scala/io/gearpump/cluster/main/Kill.scala
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.main
-
-import org.slf4j.Logger
-
-import io.gearpump.cluster.client.ClientContext
-import io.gearpump.util.{AkkaApp, LogUtil}
-
-/** Tool to kill an App */
-object Kill extends AkkaApp with ArgumentsParser {
-
- private val LOG: Logger = LogUtil.getLogger(getClass)
-
- override val options: Array[(String, CLIOption[Any])] = Array(
- "appid" -> CLIOption("<application id>", required = true),
- // For document purpose only, OPTION_CONFIG option is not used here.
- // OPTION_CONFIG is parsed by parent shell command "Gear" transparently.
- Gear.OPTION_CONFIG -> CLIOption("custom configuration file", required = false,
- defaultValue = None))
-
- override val description = "Kill an application with application Id"
-
- def main(akkaConf: Config, args: Array[String]): Unit = {
- val config = parse(args)
-
- if (null != config) {
- val client = ClientContext(akkaConf)
- LOG.info("Client ")
- client.shutdown(config.getInt("appid"))
- client.close()
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/io/gearpump/cluster/main/Local.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/io/gearpump/cluster/main/Local.scala b/daemon/src/main/scala/io/gearpump/cluster/main/Local.scala
deleted file mode 100644
index d5681df..0000000
--- a/daemon/src/main/scala/io/gearpump/cluster/main/Local.scala
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.main
-
-import scala.collection.JavaConverters._
-import scala.concurrent.Await
-import scala.concurrent.duration.Duration
-
-import akka.actor.{ActorSystem, Props}
-import com.typesafe.config.ConfigValueFactory
-import org.slf4j.Logger
-
-import io.gearpump.cluster.ClusterConfig
-import io.gearpump.cluster.master.{Master => MasterActor}
-import io.gearpump.cluster.worker.{Worker => WorkerActor}
-import io.gearpump.util.Constants._
-import io.gearpump.util.LogUtil.ProcessType
-import io.gearpump.util.{ActorUtil, AkkaApp, Constants, LogUtil, Util}
-
-object Local extends AkkaApp with ArgumentsParser {
- override def akkaConfig: Config = ClusterConfig.master()
-
- var LOG: Logger = LogUtil.getLogger(getClass)
-
- override val options: Array[(String, CLIOption[Any])] =
- Array("sameprocess" -> CLIOption[Boolean]("", required = false, defaultValue = Some(false)),
- "workernum" -> CLIOption[Int]("<how many workers to start>", required = false,
- defaultValue = Some(2)))
-
- override val description = "Start a local cluster"
-
- def main(akkaConf: Config, args: Array[String]): Unit = {
-
- this.LOG = {
- LogUtil.loadConfiguration(akkaConf, ProcessType.LOCAL)
- LogUtil.getLogger(getClass)
- }
-
- val config = parse(args)
- if (null != config) {
- local(config.getInt("workernum"), config.getBoolean("sameprocess"), akkaConf)
- }
- }
-
- def local(workerCount: Int, sameProcess: Boolean, akkaConf: Config): Unit = {
- if (sameProcess) {
- LOG.info("Starting local in same process")
- System.setProperty("LOCAL", "true")
- }
- val masters = akkaConf.getStringList(Constants.GEARPUMP_CLUSTER_MASTERS)
- .asScala.flatMap(Util.parseHostList)
- val local = akkaConf.getString(Constants.GEARPUMP_HOSTNAME)
-
- if (masters.size != 1 && masters.head.host != local) {
- LOG.error(s"The ${Constants.GEARPUMP_CLUSTER_MASTERS} is not match " +
- s"with ${Constants.GEARPUMP_HOSTNAME}")
- } else {
-
- val hostPort = masters.head
- implicit val system = ActorSystem(MASTER, akkaConf.
- withValue("akka.remote.netty.tcp.port", ConfigValueFactory.fromAnyRef(hostPort.port))
- )
-
- val master = system.actorOf(Props[MasterActor], MASTER)
- val masterPath = ActorUtil.getSystemAddress(system).toString + s"/user/$MASTER"
-
- 0.until(workerCount).foreach { id =>
- system.actorOf(Props(classOf[WorkerActor], master), classOf[WorkerActor].getSimpleName + id)
- }
-
- Await.result(system.whenTerminated, Duration.Inf)
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/io/gearpump/cluster/main/MainRunner.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/io/gearpump/cluster/main/MainRunner.scala b/daemon/src/main/scala/io/gearpump/cluster/main/MainRunner.scala
deleted file mode 100644
index 923a646..0000000
--- a/daemon/src/main/scala/io/gearpump/cluster/main/MainRunner.scala
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.main
-
-import org.slf4j.Logger
-
-import io.gearpump.util.{AkkaApp, LogUtil}
-
-/** Tool to run any main class by providing a jar */
-object MainRunner extends AkkaApp with ArgumentsParser {
- private val LOG: Logger = LogUtil.getLogger(getClass)
-
- override val options: Array[(String, CLIOption[Any])] = Array(
- // For document purpose only, OPTION_CONFIG option is not used here.
- // OPTION_CONFIG is parsed by parent shell command "Gear" transparently.
- Gear.OPTION_CONFIG -> CLIOption("custom configuration file", required = false,
- defaultValue = None))
-
- def main(akkaConf: Config, args: Array[String]): Unit = {
- val mainClazz = args(0)
- val commandArgs = args.drop(1)
-
- val clazz = Thread.currentThread().getContextClassLoader().loadClass(mainClazz)
- val mainMethod = clazz.getMethod("main", classOf[Array[String]])
- mainMethod.invoke(null, commandArgs)
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/io/gearpump/cluster/main/Master.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/io/gearpump/cluster/main/Master.scala b/daemon/src/main/scala/io/gearpump/cluster/main/Master.scala
deleted file mode 100644
index eac1c54..0000000
--- a/daemon/src/main/scala/io/gearpump/cluster/main/Master.scala
+++ /dev/null
@@ -1,236 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.main
-
-import java.util.concurrent.TimeUnit
-import scala.collection.JavaConverters._
-import scala.collection.immutable
-import scala.concurrent.Await
-import scala.concurrent.duration._
-
-import akka.actor._
-import akka.cluster.ClusterEvent._
-import akka.cluster.ddata.DistributedData
-import akka.cluster.singleton.{ClusterSingletonManager, ClusterSingletonManagerSettings, ClusterSingletonProxy, ClusterSingletonProxySettings}
-import akka.cluster.{Cluster, Member, MemberStatus}
-import com.typesafe.config.ConfigValueFactory
-import org.slf4j.Logger
-
-import io.gearpump.cluster.ClusterConfig
-import io.gearpump.cluster.master.{Master => MasterActor, MasterNode}
-import io.gearpump.cluster.master.Master.MasterListUpdated
-import io.gearpump.util.Constants._
-import io.gearpump.util.LogUtil.ProcessType
-import io.gearpump.util.{AkkaApp, Constants, LogUtil}
-
-object Master extends AkkaApp with ArgumentsParser {
-
- private var LOG: Logger = LogUtil.getLogger(getClass)
-
- override def akkaConfig: Config = ClusterConfig.master()
-
- override val options: Array[(String, CLIOption[Any])] =
- Array("ip" -> CLIOption[String]("<master ip address>", required = true),
- "port" -> CLIOption("<master port>", required = true))
-
- override val description = "Start Master daemon"
-
- def main(akkaConf: Config, args: Array[String]): Unit = {
-
- this.LOG = {
- LogUtil.loadConfiguration(akkaConf, ProcessType.MASTER)
- LogUtil.getLogger(getClass)
- }
-
- val config = parse(args)
- master(config.getString("ip"), config.getInt("port"), akkaConf)
- }
-
- private def verifyMaster(master: String, port: Int, masters: Iterable[String]) = {
- masters.exists { hostPort =>
- hostPort == s"$master:$port"
- }
- }
-
- private def master(ip: String, port: Int, akkaConf: Config): Unit = {
- val masters = akkaConf.getStringList(Constants.GEARPUMP_CLUSTER_MASTERS).asScala
-
- if (!verifyMaster(ip, port, masters)) {
- LOG.error(s"The provided ip $ip and port $port doesn't conform with config at " +
- s"gearpump.cluster.masters: ${masters.mkString(", ")}")
- System.exit(-1)
- }
-
- val masterList = masters.map(master => s"akka.tcp://${MASTER}@$master").toList.asJava
- val quorum = masterList.size() / 2 + 1
- val masterConfig = akkaConf.
- withValue("akka.remote.netty.tcp.port", ConfigValueFactory.fromAnyRef(port)).
- withValue(NETTY_TCP_HOSTNAME, ConfigValueFactory.fromAnyRef(ip)).
- withValue("akka.cluster.seed-nodes", ConfigValueFactory.fromAnyRef(masterList)).
- withValue(s"akka.cluster.role.${MASTER}.min-nr-of-members",
- ConfigValueFactory.fromAnyRef(quorum))
-
- LOG.info(s"Starting Master Actor system $ip:$port, master list: ${masters.mkString(";")}")
- val system = ActorSystem(MASTER, masterConfig)
-
- val replicator = DistributedData(system).replicator
- LOG.info(s"Replicator path: ${replicator.path}")
-
- // Starts singleton manager
- val singletonManager = system.actorOf(ClusterSingletonManager.props(
- singletonProps = Props(classOf[MasterWatcher], MASTER),
- terminationMessage = PoisonPill,
- settings = ClusterSingletonManagerSettings(system).withSingletonName(MASTER_WATCHER)
- .withRole(MASTER)),
- name = SINGLETON_MANAGER)
-
- // Start master proxy
- val masterProxy = system.actorOf(ClusterSingletonProxy.props(
- singletonManagerPath = s"/user/${SINGLETON_MANAGER}",
- // The effective singleton is s"${MASTER_WATCHER}/$MASTER" instead of s"${MASTER_WATCHER}".
- // Master is created when there is a majority of machines started.
- settings = ClusterSingletonProxySettings(system)
- .withSingletonName(s"${MASTER_WATCHER}/$MASTER").withRole(MASTER)),
- name = MASTER
- )
-
- LOG.info(s"master proxy is started at ${masterProxy.path}")
-
- val mainThread = Thread.currentThread()
- Runtime.getRuntime().addShutdownHook(new Thread() {
- override def run(): Unit = {
- if (!system.whenTerminated.isCompleted) {
- LOG.info("Triggering shutdown hook....")
-
- system.stop(masterProxy)
- val cluster = Cluster(system)
- cluster.leave(cluster.selfAddress)
- cluster.down(cluster.selfAddress)
- try {
- Await.result(system.whenTerminated, Duration(3, TimeUnit.SECONDS))
- } catch {
- case ex: Exception => // Ignore
- }
- system.terminate()
- mainThread.join()
- }
- }
- })
-
- Await.result(system.whenTerminated, Duration.Inf)
- }
-}
-
-class MasterWatcher(role: String) extends Actor with ActorLogging {
- import context.dispatcher
-
- val cluster = Cluster(context.system)
-
- val config = context.system.settings.config
- val masters = config.getList("akka.cluster.seed-nodes")
- val quorum = masters.size() / 2 + 1
-
- val system = context.system
-
- // Sorts by age, oldest first
- val ageOrdering = Ordering.fromLessThan[Member] { (a, b) => a.isOlderThan(b) }
- var membersByAge: immutable.SortedSet[Member] = immutable.SortedSet.empty(ageOrdering)
-
- def receive: Receive = null
-
- // Subscribes to MemberEvent, re-subscribe when restart
- override def preStart(): Unit = {
- cluster.subscribe(self, classOf[MemberEvent])
- context.become(waitForInit)
- }
- override def postStop(): Unit = {
- cluster.unsubscribe(self)
- }
-
- def matchingRole(member: Member): Boolean = member.hasRole(role)
-
- def waitForInit: Receive = {
- case state: CurrentClusterState => {
- membersByAge = immutable.SortedSet.empty(ageOrdering) ++ state.members.filter(m =>
- m.status == MemberStatus.Up && matchingRole(m))
-
- if (membersByAge.size < quorum) {
- membersByAge.iterator.mkString(",")
- log.info(s"We cannot get a quorum, $quorum, " +
- s"shutting down...${membersByAge.iterator.mkString(",")}")
- context.become(waitForShutdown)
- self ! MasterWatcher.Shutdown
- } else {
- val master = context.actorOf(Props(classOf[MasterActor]), MASTER)
- notifyMasterMembersChange(master)
- context.become(waitForClusterEvent(master))
- }
- }
- }
-
- def waitForClusterEvent(master: ActorRef): Receive = {
- case MemberUp(m) if matchingRole(m) => {
- membersByAge += m
- notifyMasterMembersChange(master)
- }
- case mEvent: MemberEvent if (mEvent.isInstanceOf[MemberExited] ||
- mEvent.isInstanceOf[MemberRemoved]) && matchingRole(mEvent.member) => {
- log.info(s"member removed ${mEvent.member}")
- val m = mEvent.member
- membersByAge -= m
- if (membersByAge.size < quorum) {
- log.info(s"We cannot get a quorum, $quorum, " +
- s"shutting down...${membersByAge.iterator.mkString(",")}")
- context.become(waitForShutdown)
- self ! MasterWatcher.Shutdown
- } else {
- notifyMasterMembersChange(master)
- }
- }
- }
-
- private def notifyMasterMembersChange(master: ActorRef): Unit = {
- val masters = membersByAge.toList.map{ member =>
- MasterNode(member.address.host.getOrElse("Unknown-Host"),
- member.address.port.getOrElse(0))
- }
- master ! MasterListUpdated(masters)
- }
-
- def waitForShutdown: Receive = {
- case MasterWatcher.Shutdown => {
- cluster.unsubscribe(self)
- cluster.leave(cluster.selfAddress)
- context.stop(self)
- system.scheduler.scheduleOnce(Duration.Zero) {
- try {
- Await.result(system.whenTerminated, Duration(3, TimeUnit.SECONDS))
- } catch {
- case ex: Exception => // Ignore
- }
- system.terminate()
- }
- }
- }
-}
-
-object MasterWatcher {
- object Shutdown
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/io/gearpump/cluster/main/Replay.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/io/gearpump/cluster/main/Replay.scala b/daemon/src/main/scala/io/gearpump/cluster/main/Replay.scala
deleted file mode 100644
index c9a6e9c..0000000
--- a/daemon/src/main/scala/io/gearpump/cluster/main/Replay.scala
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.cluster.main
-
-import org.slf4j.Logger
-
-import io.gearpump.cluster.client.ClientContext
-import io.gearpump.util.{AkkaApp, LogUtil}
-
-// Internal tool to restart an application
-object Replay extends AkkaApp with ArgumentsParser {
-
- private val LOG: Logger = LogUtil.getLogger(getClass)
-
- override val options: Array[(String, CLIOption[Any])] = Array(
- "appid" -> CLIOption("<application id>", required = true),
- // For document purpose only, OPTION_CONFIG option is not used here.
- // OPTION_CONFIG is parsed by parent shell command "Gear" transparently.
- Gear.OPTION_CONFIG -> CLIOption("custom configuration file", required = false,
- defaultValue = None))
-
- override val description = "Replay the application from current min clock(low watermark)"
-
- def main(akkaConf: Config, args: Array[String]): Unit = {
- val config = parse(args)
-
- if (null != config) {
- val client = ClientContext(akkaConf)
- client.replayFromTimestampWindowTrailingEdge(config.getInt("appid"))
- client.close()
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/io/gearpump/cluster/main/Worker.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/io/gearpump/cluster/main/Worker.scala b/daemon/src/main/scala/io/gearpump/cluster/main/Worker.scala
deleted file mode 100644
index 4818262..0000000
--- a/daemon/src/main/scala/io/gearpump/cluster/main/Worker.scala
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.main
-
-import scala.collection.JavaConverters._
-import scala.concurrent.Await
-import scala.concurrent.duration.Duration
-
-import akka.actor.{ActorSystem, Props}
-import org.slf4j.Logger
-
-import io.gearpump.cluster.ClusterConfig
-import io.gearpump.cluster.master.MasterProxy
-import io.gearpump.cluster.worker.{Worker => WorkerActor}
-import io.gearpump.transport.HostPort
-import io.gearpump.util.Constants._
-import io.gearpump.util.LogUtil.ProcessType
-import io.gearpump.util.{AkkaApp, LogUtil}
-
-/** Tool to start a worker daemon process */
-object Worker extends AkkaApp with ArgumentsParser {
- protected override def akkaConfig = ClusterConfig.worker()
-
- override val description = "Start a worker daemon"
-
- var LOG: Logger = LogUtil.getLogger(getClass)
-
- private def uuid = java.util.UUID.randomUUID.toString
-
- def main(akkaConf: Config, args: Array[String]): Unit = {
- val id = uuid
-
- this.LOG = {
- LogUtil.loadConfiguration(akkaConf, ProcessType.WORKER)
- // Delay creation of LOG instance to avoid creating an empty log file as we
- // reset the log file name here
- LogUtil.getLogger(getClass)
- }
-
- val system = ActorSystem(id, akkaConf)
-
- val masterAddress = akkaConf.getStringList(GEARPUMP_CLUSTER_MASTERS).asScala.map { address =>
- val hostAndPort = address.split(":")
- HostPort(hostAndPort(0), hostAndPort(1).toInt)
- }
-
- LOG.info(s"Trying to connect to masters " + masterAddress.mkString(",") + "...")
- val masterProxy = system.actorOf(MasterProxy.props(masterAddress), s"masterproxy${system.name}")
-
- system.actorOf(Props(classOf[WorkerActor], masterProxy),
- classOf[WorkerActor].getSimpleName + id)
-
- Await.result(system.whenTerminated, Duration.Inf)
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/io/gearpump/cluster/master/AppManager.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/io/gearpump/cluster/master/AppManager.scala b/daemon/src/main/scala/io/gearpump/cluster/master/AppManager.scala
deleted file mode 100644
index 058533e..0000000
--- a/daemon/src/main/scala/io/gearpump/cluster/master/AppManager.scala
+++ /dev/null
@@ -1,341 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.master
-
-import scala.concurrent.Future
-import scala.concurrent.duration._
-import scala.util.{Failure, Success}
-
-import akka.actor._
-import akka.pattern.ask
-import org.slf4j.Logger
-
-import io.gearpump.cluster.AppMasterToMaster.{AppDataSaved, SaveAppDataFailed, _}
-import io.gearpump.cluster.AppMasterToWorker._
-import io.gearpump.cluster.ClientToMaster._
-import io.gearpump.cluster.MasterToAppMaster.{AppMasterData, AppMasterDataRequest, AppMastersDataRequest, _}
-import io.gearpump.cluster.MasterToClient._
-import io.gearpump.cluster.WorkerToAppMaster.{ShutdownExecutorFailed, _}
-import io.gearpump.cluster.appmaster.{AppMasterRuntimeInfo, ApplicationState}
-import io.gearpump.cluster.master.AppManager._
-import io.gearpump.cluster.master.InMemoryKVService.{GetKVResult, PutKVResult, PutKVSuccess, _}
-import io.gearpump.cluster.master.Master._
-import io.gearpump.util.Constants._
-import io.gearpump.util.{ActorUtil, TimeOutScheduler, Util, _}
-
-/**
- * AppManager is dedicated child of Master to manager all applications.
- */
-private[cluster] class AppManager(kvService: ActorRef, launcher: AppMasterLauncherFactory)
- extends Actor with Stash with TimeOutScheduler {
-
- private val LOG: Logger = LogUtil.getLogger(getClass)
-
- private val executorId: Int = APPMASTER_DEFAULT_EXECUTOR_ID
- private val appMasterMaxRetries: Int = 5
- private val appMasterRetryTimeRange: Duration = 20.seconds
-
- implicit val timeout = FUTURE_TIMEOUT
- implicit val executionContext = context.dispatcher
-
- // Next available appId
- private var appId: Int = 1
-
- // From appid to appMaster data
- private var appMasterRegistry = Map.empty[Int, (ActorRef, AppMasterRuntimeInfo)]
-
- // Dead appmaster list
- private var deadAppMasters = Map.empty[Int, (ActorRef, AppMasterRuntimeInfo)]
-
- private var appMasterRestartPolicies = Map.empty[Int, RestartPolicy]
-
- def receive: Receive = null
-
- kvService ! GetKV(MASTER_GROUP, MASTER_STATE)
- context.become(waitForMasterState)
-
- def waitForMasterState: Receive = {
- case GetKVSuccess(_, result) =>
- val masterState = result.asInstanceOf[MasterState]
- if (masterState != null) {
- this.appId = masterState.maxId + 1
- this.deadAppMasters = masterState.deadAppMasters
- this.appMasterRegistry = masterState.appMasterRegistry
- }
- context.become(receiveHandler)
- unstashAll()
- case GetKVFailed(ex) =>
- LOG.error("Failed to get master state, shutting down master to avoid data corruption...")
- context.parent ! PoisonPill
- case msg =>
- LOG.info(s"Get message ${msg.getClass.getSimpleName}")
- stash()
- }
-
- def receiveHandler: Receive = {
- val msg = "Application Manager started. Ready for application submission..."
- LOG.info(msg)
- clientMsgHandler orElse appMasterMessage orElse selfMsgHandler orElse workerMessage orElse
- appDataStoreService orElse terminationWatch
- }
-
- def clientMsgHandler: Receive = {
- case SubmitApplication(app, jar, username) =>
- LOG.info(s"Submit Application ${app.name}($appId) by $username...")
- val client = sender
- if (applicationNameExist(app.name)) {
- client ! SubmitApplicationResult(Failure(
- new Exception(s"Application name ${app.name} already existed")))
- } else {
- context.actorOf(launcher.props(appId, executorId, app, jar, username, context.parent,
- Some(client)), s"launcher${appId}_${Util.randInt()}")
-
- val appState = new ApplicationState(appId, app.name, 0, app, jar, username, null)
- appMasterRestartPolicies += appId ->
- new RestartPolicy(appMasterMaxRetries, appMasterRetryTimeRange)
- kvService ! PutKV(appId.toString, APP_STATE, appState)
- appId += 1
- }
-
- case RestartApplication(appId) =>
- val client = sender()
- (kvService ? GetKV(appId.toString, APP_STATE)).asInstanceOf[Future[GetKVResult]].map {
- case GetKVSuccess(_, result) =>
- val appState = result.asInstanceOf[ApplicationState]
- if (appState != null) {
- LOG.info(s"Shutting down the application (restart), $appId")
- self ! ShutdownApplication(appId)
- self.tell(SubmitApplication(appState.app, appState.jar, appState.username), client)
- } else {
- client ! SubmitApplicationResult(Failure(
- new Exception(s"Failed to restart, because the application $appId does not exist.")
- ))
- }
- case GetKVFailed(ex) =>
- client ! SubmitApplicationResult(Failure(
- new Exception(s"Unable to obtain the Master State. " +
- s"Application $appId will not be restarted.")
- ))
- }
-
- case ShutdownApplication(appId) =>
- LOG.info(s"App Manager Shutting down application $appId")
- val (_, info) = appMasterRegistry.getOrElse(appId, (null, null))
- Option(info) match {
- case Some(info) =>
- val worker = info.worker
- val workerPath = Option(worker).map(_.path).orNull
- LOG.info(s"Shutdown AppMaster at ${workerPath}, appId: $appId, executorId: $executorId")
- cleanApplicationData(appId)
- val shutdown = ShutdownExecutor(appId, executorId,
- s"AppMaster $appId shutdown requested by master...")
- sendMsgWithTimeOutCallBack(worker, shutdown, 30000, shutDownExecutorTimeOut())
- sender ! ShutdownApplicationResult(Success(appId))
- case None =>
- val errorMsg = s"Failed to find regisration information for appId: $appId"
- LOG.error(errorMsg)
- sender ! ShutdownApplicationResult(Failure(new Exception(errorMsg)))
- }
- case ResolveAppId(appId) =>
- val (appMaster, _) = appMasterRegistry.getOrElse(appId, (null, null))
- if (null != appMaster) {
- sender ! ResolveAppIdResult(Success(appMaster))
- } else {
- sender ! ResolveAppIdResult(Failure(new Exception(s"Can not find Application: $appId")))
- }
- case AppMastersDataRequest =>
- var appMastersData = collection.mutable.ListBuffer[AppMasterData]()
- appMasterRegistry.foreach(pair => {
- val (id, (appMaster: ActorRef, info: AppMasterRuntimeInfo)) = pair
- val appMasterPath = ActorUtil.getFullPath(context.system, appMaster.path)
- val workerPath = Option(info.worker).map(worker =>
- ActorUtil.getFullPath(context.system, worker.path))
- appMastersData += AppMasterData(
- AppMasterActive, id, info.appName, appMasterPath, workerPath.orNull,
- info.submissionTime, info.startTime, info.finishTime, info.user)
- })
-
- deadAppMasters.foreach(pair => {
- val (id, (appMaster: ActorRef, info: AppMasterRuntimeInfo)) = pair
- val appMasterPath = ActorUtil.getFullPath(context.system, appMaster.path)
- val workerPath = Option(info.worker).map(worker =>
- ActorUtil.getFullPath(context.system, worker.path))
-
- appMastersData += AppMasterData(
- AppMasterInActive, id, info.appName, appMasterPath, workerPath.orNull,
- info.submissionTime, info.startTime, info.finishTime, info.user)
- })
-
- sender ! AppMastersData(appMastersData.toList)
- case QueryAppMasterConfig(appId) =>
- val config =
- if (appMasterRegistry.contains(appId)) {
- val (_, info) = appMasterRegistry(appId)
- info.config
- } else if (deadAppMasters.contains(appId)) {
- val (_, info) = deadAppMasters(appId)
- info.config
- } else {
- null
- }
- sender ! AppMasterConfig(config)
-
- case appMasterDataRequest: AppMasterDataRequest =>
- val appId = appMasterDataRequest.appId
- val (appStatus, appMaster, info) =
- if (appMasterRegistry.contains(appId)) {
- val (appMaster, info) = appMasterRegistry(appId)
- (AppMasterActive, appMaster, info)
- } else if (deadAppMasters.contains(appId)) {
- val (appMaster, info) = deadAppMasters(appId)
- (AppMasterInActive, appMaster, info)
- } else {
- (AppMasterNonExist, null, null)
- }
-
- appStatus match {
- case AppMasterActive | AppMasterInActive =>
- val appMasterPath = ActorUtil.getFullPath(context.system, appMaster.path)
- val workerPath = Option(info.worker).map(
- worker => ActorUtil.getFullPath(context.system, worker.path)).orNull
- sender ! AppMasterData(
- appStatus, appId, info.appName, appMasterPath, workerPath,
- info.submissionTime, info.startTime, info.finishTime, info.user)
-
- case AppMasterNonExist =>
- sender ! AppMasterData(AppMasterNonExist)
- }
- }
-
- def workerMessage: Receive = {
- case ShutdownExecutorSucceed(appId, executorId) =>
- LOG.info(s"Shut down executor $executorId for application $appId successfully")
- case failed: ShutdownExecutorFailed =>
- LOG.error(failed.reason)
- }
-
- private def shutDownExecutorTimeOut(): Unit = {
- LOG.error(s"Shut down executor time out")
- }
-
- def appMasterMessage: Receive = {
- case RegisterAppMaster(appMaster, registerBack: AppMasterRuntimeInfo) =>
- val startTime = System.currentTimeMillis()
- val register = registerBack.copy(startTime = startTime)
-
- LOG.info(s"Register AppMaster for app: ${register.appId} $register")
- context.watch(appMaster)
- appMasterRegistry += register.appId -> (appMaster, register)
- kvService ! PutKV(MASTER_GROUP, MASTER_STATE,
- MasterState(appId, appMasterRegistry, deadAppMasters))
- sender ! AppMasterRegistered(register.appId)
- }
-
- def appDataStoreService: Receive = {
- case SaveAppData(appId, key, value) =>
- val client = sender
- (kvService ? PutKV(appId.toString, key, value)).asInstanceOf[Future[PutKVResult]].map {
- case PutKVSuccess =>
- client ! AppDataSaved
- case PutKVFailed(k, ex) =>
- client ! SaveAppDataFailed
- }
- case GetAppData(appId, key) =>
- val client = sender
- (kvService ? GetKV(appId.toString, key)).asInstanceOf[Future[GetKVResult]].map {
- case GetKVSuccess(privateKey, value) =>
- client ! GetAppDataResult(key, value)
- case GetKVFailed(ex) =>
- client ! GetAppDataResult(key, null)
- }
- }
-
- def terminationWatch: Receive = {
- case terminate: Terminated =>
- terminate.getAddressTerminated()
- LOG.info(s"AppMaster(${terminate.actor.path}) is terminiated, " +
- s"network down: ${terminate.getAddressTerminated()}")
-
- // Now we assume that the only normal way to stop the application is submitting a
- // ShutdownApplication request
- val application = appMasterRegistry.find { appInfo =>
- val (_, (actorRef, _)) = appInfo
- actorRef.compareTo(terminate.actor) == 0
- }
- if (application.nonEmpty) {
- val appId = application.get._1
- (kvService ? GetKV(appId.toString, APP_STATE)).asInstanceOf[Future[GetKVResult]].map {
- case GetKVSuccess(_, result) =>
- val appState = result.asInstanceOf[ApplicationState]
- if (appState != null) {
- LOG.info(s"Recovering application, $appId")
- self ! RecoverApplication(appState)
- } else {
- LOG.error(s"Cannot find application state for $appId")
- }
- case GetKVFailed(ex) =>
- LOG.error(s"Cannot find master state to recover")
- }
- }
- }
-
- def selfMsgHandler: Receive = {
- case RecoverApplication(state) =>
- val appId = state.appId
- if (appMasterRestartPolicies.get(appId).get.allowRestart) {
- LOG.info(s"AppManager Recovering Application $appId...")
- context.actorOf(launcher.props(appId, executorId, state.app, state.jar, state.username,
- context.parent, None), s"launcher${appId}_${Util.randInt()}")
- } else {
- LOG.error(s"Application $appId failed too many times")
- }
- }
-
- case class RecoverApplication(applicationStatus: ApplicationState)
-
- private def cleanApplicationData(appId: Int): Unit = {
- // Add the dead app to dead appMaster
- appMasterRegistry.get(appId).foreach { pair =>
- val (appMasterActor, info) = pair
- deadAppMasters += appId -> (appMasterActor, info.copy(
- finishTime = System.currentTimeMillis()))
- }
-
- appMasterRegistry -= appId
-
- kvService ! PutKV(MASTER_GROUP, MASTER_STATE,
- MasterState(this.appId, appMasterRegistry, deadAppMasters))
- kvService ! DeleteKVGroup(appId.toString)
- }
-
- private def applicationNameExist(appName: String): Boolean = {
- appMasterRegistry.values.exists(_._2.appName == appName)
- }
-}
-
-object AppManager {
- final val APP_STATE = "app_state"
- // The id is used in KVStore
- final val MASTER_STATE = "master_state"
-
- case class MasterState(
- maxId: Int,
- appMasterRegistry: Map[Int, (ActorRef, AppMasterRuntimeInfo)],
- deadAppMasters: Map[Int, (ActorRef, AppMasterRuntimeInfo)])
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/io/gearpump/cluster/master/InMemoryKVService.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/io/gearpump/cluster/master/InMemoryKVService.scala b/daemon/src/main/scala/io/gearpump/cluster/master/InMemoryKVService.scala
deleted file mode 100644
index 616d3ee..0000000
--- a/daemon/src/main/scala/io/gearpump/cluster/master/InMemoryKVService.scala
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.master
-
-import java.util.concurrent.TimeUnit
-import scala.concurrent.TimeoutException
-import scala.concurrent.duration.Duration
-
-import akka.actor._
-import akka.cluster.Cluster
-import akka.cluster.ddata.Replicator._
-import akka.cluster.ddata.{DistributedData, LWWMap, LWWMapKey}
-import org.slf4j.Logger
-
-import io.gearpump.util.LogUtil
-
-/**
- * A replicated simple in-memory KV service. The replications are stored on all masters.
- */
-class InMemoryKVService extends Actor with Stash {
- import io.gearpump.cluster.master.InMemoryKVService._
-
- private val KV_SERVICE = "gearpump_kvservice"
-
- private val LOG: Logger = LogUtil.getLogger(getClass)
- private val replicator = DistributedData(context.system).replicator
- private implicit val cluster = Cluster(context.system)
-
- // Optimize write path, we can tolerate one master down for recovery.
- private val timeout = Duration(15, TimeUnit.SECONDS)
- private val readMajority = ReadMajority(timeout)
- private val writeMajority = WriteMajority(timeout)
-
- private def groupKey(group: String): LWWMapKey[Any] = {
- LWWMapKey[Any](KV_SERVICE + "_" + group)
- }
-
- def receive: Receive = kvService
-
- def kvService: Receive = {
-
- case GetKV(group: String, key: String) =>
- val request = Request(sender(), key)
- replicator ! Get(groupKey(group), readMajority, Some(request))
- case success@GetSuccess(group: LWWMapKey[Any @unchecked], Some(request: Request)) =>
- val appData = success.get(group)
- LOG.info(s"Successfully retrived group: ${group.id}")
- request.client ! GetKVSuccess(request.key, appData.get(request.key).orNull)
- case NotFound(group: LWWMapKey[Any @unchecked], Some(request: Request)) =>
- LOG.info(s"We cannot find group $group")
- request.client ! GetKVSuccess(request.key, null)
- case GetFailure(group: LWWMapKey[Any @unchecked], Some(request: Request)) =>
- val error = s"Failed to get application data, the request key is ${request.key}"
- LOG.error(error)
- request.client ! GetKVFailed(new Exception(error))
-
- case PutKV(group: String, key: String, value: Any) =>
- val request = Request(sender(), key)
- val update = Update(groupKey(group), LWWMap(), writeMajority, Some(request)) { map =>
- map + (key -> value)
- }
- replicator ! update
- case UpdateSuccess(group: LWWMapKey[Any @unchecked], Some(request: Request)) =>
- request.client ! PutKVSuccess
- case ModifyFailure(group: LWWMapKey[Any @unchecked], error, cause, Some(request: Request)) =>
- request.client ! PutKVFailed(request.key, new Exception(error, cause))
- case UpdateTimeout(group: LWWMapKey[Any @unchecked], Some(request: Request)) =>
- request.client ! PutKVFailed(request.key, new TimeoutException())
-
- case delete@DeleteKVGroup(group: String) =>
- replicator ! Delete(groupKey(group), writeMajority)
- case DeleteSuccess(group) =>
- LOG.info(s"KV Group ${group.id} is deleted")
- case ReplicationDeleteFailure(group) =>
- LOG.error(s"Failed to delete KV Group ${group.id}...")
- case DataDeleted(group) =>
- LOG.error(s"Group ${group.id} is deleted, you can no longer put/get/delete this group...")
- }
-}
-
-object InMemoryKVService {
- /**
- * KV Service related
- */
- case class GetKV(group: String, key: String)
-
- trait GetKVResult
-
- case class GetKVSuccess(key: String, value: Any) extends GetKVResult
-
- case class GetKVFailed(ex: Throwable) extends GetKVResult
-
- case class PutKV(group: String, key: String, value: Any)
-
- case class DeleteKVGroup(group: String)
-
- case class GroupDeleted(group: String) extends GetKVResult with PutKVResult
-
- trait PutKVResult
-
- case object PutKVSuccess extends PutKVResult
-
- case class PutKVFailed(key: String, ex: Throwable) extends PutKVResult
-
- case class Request(client: ActorRef, key: String)
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/io/gearpump/cluster/master/Master.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/io/gearpump/cluster/master/Master.scala b/daemon/src/main/scala/io/gearpump/cluster/master/Master.scala
deleted file mode 100644
index 0dfa381..0000000
--- a/daemon/src/main/scala/io/gearpump/cluster/master/Master.scala
+++ /dev/null
@@ -1,313 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.master
-
-import java.lang.management.ManagementFactory
-import scala.collection.JavaConverters._
-import scala.collection.immutable
-
-import akka.actor._
-import akka.remote.DisassociatedEvent
-import com.typesafe.config.Config
-import org.apache.commons.lang.exception.ExceptionUtils
-import org.slf4j.Logger
-
-import io.gearpump.cluster.AppMasterToMaster._
-import io.gearpump.cluster.ClientToMaster._
-import io.gearpump.cluster.ClusterConfig
-import io.gearpump.cluster.MasterToAppMaster._
-import io.gearpump.cluster.MasterToClient.{HistoryMetrics, HistoryMetricsItem, MasterConfig, ResolveWorkerIdResult}
-import io.gearpump.cluster.MasterToWorker._
-import io.gearpump.cluster.WorkerToMaster._
-import io.gearpump.cluster.master.InMemoryKVService._
-import io.gearpump.cluster.master.Master.{MasterInfo, WorkerTerminated, _}
-import io.gearpump.cluster.scheduler.Scheduler.ApplicationFinished
-import io.gearpump.cluster.worker.WorkerId
-import io.gearpump.jarstore.local.LocalJarStore
-import io.gearpump.metrics.Metrics.ReportMetrics
-import io.gearpump.metrics.{JvmMetricsSet, Metrics, MetricsReporterService}
-import io.gearpump.transport.HostPort
-import io.gearpump.util.Constants._
-import io.gearpump.util.HistoryMetricsService.HistoryMetricsConfig
-import io.gearpump.util._
-
-/**
- * Master Actor who manages resources of the whole cluster.
- * It is like the resource manager of YARN.
- */
-private[cluster] class Master extends Actor with Stash {
- private val LOG: Logger = LogUtil.getLogger(getClass)
- private val systemConfig: Config = context.system.settings.config
- private implicit val timeout = Constants.FUTURE_TIMEOUT
- private val kvService = context.actorOf(Props(new InMemoryKVService()), "kvService")
- // Resources and resourceRequests can be dynamically constructed by
- // heartbeat of worker and appmaster when master singleton is migrated.
- // We don't need to persist them in cluster
- private var appManager: ActorRef = null
-
- private var scheduler: ActorRef = null
-
- private var workers = new immutable.HashMap[ActorRef, WorkerId]
-
- private val birth = System.currentTimeMillis()
-
- private var nextWorkerId = 0
-
- def receive: Receive = null
-
- // Register jvm metrics
- Metrics(context.system).register(new JvmMetricsSet(s"master"))
-
- LOG.info("master is started at " + ActorUtil.getFullPath(context.system, self.path) + "...")
-
- val jarStoreRootPath = systemConfig.getString(Constants.GEARPUMP_APP_JAR_STORE_ROOT_PATH)
-
- private val jarStore = if (Util.isLocalPath(jarStoreRootPath)) {
- Some(context.actorOf(Props(classOf[LocalJarStore], jarStoreRootPath)))
- } else {
- None
- }
-
- private val hostPort = HostPort(ActorUtil.getSystemAddress(context.system).hostPort)
-
- // Maintain the list of active masters.
- private var masters: List[MasterNode] = {
- // Add myself into the list of initial masters.
- List(MasterNode(hostPort.host, hostPort.port))
- }
-
- val metricsEnabled = systemConfig.getBoolean(GEARPUMP_METRIC_ENABLED)
-
- val getHistoryMetricsConfig = HistoryMetricsConfig(systemConfig)
- val historyMetricsService = if (metricsEnabled) {
- val historyMetricsService = {
- context.actorOf(Props(new HistoryMetricsService("master", getHistoryMetricsConfig)))
- }
-
- val metricsReportService = context.actorOf(
- Props(new MetricsReporterService(Metrics(context.system))))
- historyMetricsService.tell(ReportMetrics, metricsReportService)
- Some(historyMetricsService)
- } else {
- None
- }
-
- kvService ! GetKV(MASTER_GROUP, WORKER_ID)
- context.become(waitForNextWorkerId)
-
- def waitForNextWorkerId: Receive = {
- case GetKVSuccess(_, result) =>
- if (result != null) {
- this.nextWorkerId = result.asInstanceOf[Int]
- } else {
- LOG.warn("Cannot find existing state in the distributed cluster...")
- }
- context.become(receiveHandler)
- unstashAll()
- case GetKVFailed(ex) =>
- LOG.error("Failed to get worker id, shutting down master to avoid data corruption...")
- context.parent ! PoisonPill
- case msg =>
- LOG.info(s"Get message ${msg.getClass.getSimpleName}")
- stash()
- }
-
- def receiveHandler: Receive = workerMsgHandler orElse
- appMasterMsgHandler orElse
- onMasterListChange orElse
- clientMsgHandler orElse
- metricsService orElse
- jarStoreService orElse
- terminationWatch orElse
- disassociated orElse
- kvServiceMsgHandler orElse
- ActorUtil.defaultMsgHandler(self)
-
- def workerMsgHandler: Receive = {
- case RegisterNewWorker =>
- val workerId = WorkerId(nextWorkerId, System.currentTimeMillis())
- nextWorkerId += 1
- kvService ! PutKV(MASTER_GROUP, WORKER_ID, nextWorkerId)
- val workerHostname = ActorUtil.getHostname(sender())
- LOG.info(s"Register new from $workerHostname ....")
- self forward RegisterWorker(workerId)
-
- case RegisterWorker(id) =>
- context.watch(sender())
- sender ! WorkerRegistered(id, MasterInfo(self, birth))
- scheduler forward WorkerRegistered(id, MasterInfo(self, birth))
- workers += (sender() -> id)
- val workerHostname = ActorUtil.getHostname(sender())
- LOG.info(s"Register Worker with id $id from $workerHostname ....")
- case resourceUpdate: ResourceUpdate =>
- scheduler forward resourceUpdate
- }
-
- def jarStoreService: Receive = {
- case GetJarStoreServer =>
- jarStore.foreach(_ forward GetJarStoreServer)
- }
-
- def kvServiceMsgHandler: Receive = {
- case PutKVSuccess =>
- // Skip
- case PutKVFailed(key, exception) =>
- LOG.error(s"Put KV of key $key to InMemoryKVService failed.\n" +
- ExceptionUtils.getStackTrace(exception))
- }
-
- def metricsService: Receive = {
- case query: QueryHistoryMetrics =>
- if (historyMetricsService.isEmpty) {
- // Returns empty metrics so that we don't hang the UI
- sender ! HistoryMetrics(query.path, List.empty[HistoryMetricsItem])
- } else {
- historyMetricsService.get forward query
- }
- }
-
- def appMasterMsgHandler: Receive = {
- case request: RequestResource =>
- scheduler forward request
- case registerAppMaster: RegisterAppMaster =>
- // Forward to appManager
- appManager forward registerAppMaster
- case save: SaveAppData =>
- appManager forward save
- case get: GetAppData =>
- appManager forward get
- case GetAllWorkers =>
- sender ! WorkerList(workers.values.toList)
- case GetMasterData =>
- val aliveFor = System.currentTimeMillis() - birth
- val logFileDir = LogUtil.daemonLogDir(systemConfig).getAbsolutePath
- val userDir = System.getProperty("user.dir")
-
- val masterDescription =
- MasterSummary(
- MasterNode(hostPort.host, hostPort.port),
- masters,
- aliveFor,
- logFileDir,
- jarStoreRootPath,
- MasterStatus.Synced,
- userDir,
- List.empty[MasterActivity],
- jvmName = ManagementFactory.getRuntimeMXBean().getName(),
- historyMetricsConfig = getHistoryMetricsConfig
- )
-
- sender ! MasterData(masterDescription)
-
- case invalidAppMaster: InvalidAppMaster =>
- appManager forward invalidAppMaster
- }
-
- import scala.util.{Failure, Success}
-
- def onMasterListChange: Receive = {
- case MasterListUpdated(masters: List[MasterNode]) =>
- this.masters = masters
- }
-
- def clientMsgHandler: Receive = {
- case app: SubmitApplication =>
- LOG.debug(s"Receive from client, SubmitApplication $app")
- appManager.forward(app)
- case app: RestartApplication =>
- LOG.debug(s"Receive from client, RestartApplication $app")
- appManager.forward(app)
- case app: ShutdownApplication =>
- LOG.debug(s"Receive from client, Shutting down Application ${app.appId}")
- scheduler ! ApplicationFinished(app.appId)
- appManager.forward(app)
- case app: ResolveAppId =>
- LOG.debug(s"Receive from client, resolving appId ${app.appId} to ActorRef")
- appManager.forward(app)
- case resolve: ResolveWorkerId =>
- LOG.debug(s"Receive from client, resolving workerId ${resolve.workerId}")
- val worker = workers.find(_._2 == resolve.workerId)
- worker match {
- case Some(worker) => sender ! ResolveWorkerIdResult(Success(worker._1))
- case None => sender ! ResolveWorkerIdResult(Failure(
- new Exception(s"cannot find worker ${resolve.workerId}")))
- }
- case AppMastersDataRequest =>
- LOG.debug("Master received AppMastersDataRequest")
- appManager forward AppMastersDataRequest
- case appMasterDataRequest: AppMasterDataRequest =>
- LOG.debug("Master received AppMasterDataRequest")
- appManager forward appMasterDataRequest
- case query: QueryAppMasterConfig =>
- LOG.debug("Master received QueryAppMasterConfig")
- appManager forward query
- case QueryMasterConfig =>
- sender ! MasterConfig(ClusterConfig.filterOutDefaultConfig(systemConfig))
- }
-
- def disassociated: Receive = {
- case disassociated: DisassociatedEvent =>
- LOG.info(s" disassociated ${disassociated.remoteAddress}")
- }
-
- def terminationWatch: Receive = {
- case t: Terminated =>
- val actor = t.actor
- LOG.info(s"worker ${actor.path} get terminated, is it due to network reason?" +
- t.getAddressTerminated())
-
- LOG.info("Let's filter out dead resources...")
- // Filters out dead worker resource
- if (workers.keySet.contains(actor)) {
- scheduler ! WorkerTerminated(workers.get(actor).get)
- workers -= actor
- }
- }
-
- override def preStart(): Unit = {
- val path = ActorUtil.getFullPath(context.system, self.path)
- LOG.info(s"master path is $path")
- val schedulerClass = Class.forName(
- systemConfig.getString(Constants.GEARPUMP_SCHEDULING_SCHEDULER))
-
- appManager = context.actorOf(Props(new AppManager(kvService, AppMasterLauncher)),
- classOf[AppManager].getSimpleName)
- scheduler = context.actorOf(Props(schedulerClass))
- context.system.eventStream.subscribe(self, classOf[DisassociatedEvent])
- }
-}
-
-object Master {
- final val MASTER_GROUP = "master_group"
-
- final val WORKER_ID = "next_worker_id"
-
- case class WorkerTerminated(workerId: WorkerId)
-
- case class MasterInfo(master: ActorRef, startTime: Long = 0L)
-
- /** Notify the subscriber that master actor list has been updated */
- case class MasterListUpdated(masters: List[MasterNode])
-
- object MasterInfo {
- def empty: MasterInfo = MasterInfo(null)
- }
-
- case class SlotStatus(totalSlots: Int, availableSlots: Int)
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/io/gearpump/cluster/scheduler/PriorityScheduler.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/io/gearpump/cluster/scheduler/PriorityScheduler.scala b/daemon/src/main/scala/io/gearpump/cluster/scheduler/PriorityScheduler.scala
deleted file mode 100644
index 5df008e..0000000
--- a/daemon/src/main/scala/io/gearpump/cluster/scheduler/PriorityScheduler.scala
+++ /dev/null
@@ -1,155 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.scheduler
-
-import scala.collection.mutable
-
-import akka.actor.ActorRef
-
-import io.gearpump.cluster.AppMasterToMaster.RequestResource
-import io.gearpump.cluster.MasterToAppMaster.ResourceAllocated
-import io.gearpump.cluster.scheduler.Relaxation._
-import io.gearpump.cluster.scheduler.Scheduler.PendingRequest
-import io.gearpump.cluster.worker.WorkerId
-
-/** Assign resource to application based on the priority of the application */
-class PriorityScheduler extends Scheduler {
- private var resourceRequests = new mutable.PriorityQueue[PendingRequest]()(requestOrdering)
-
- def requestOrdering: Ordering[PendingRequest] = new Ordering[PendingRequest] {
- override def compare(x: PendingRequest, y: PendingRequest): Int = {
- var res = x.request.priority.id - y.request.priority.id
- if (res == 0) {
- res = y.timeStamp.compareTo(x.timeStamp)
- }
- res
- }
- }
-
- override def receive: Receive = super.handleScheduleMessage orElse resourceRequestHandler
-
- override def allocateResource(): Unit = {
- var scheduleLater = Array.empty[PendingRequest]
- val resourcesSnapShot = resources.clone()
- var allocated = Resource.empty
- val totalResource = Resource(resourcesSnapShot.values.map(_._2.slots).sum)
-
- while (resourceRequests.nonEmpty && (allocated < totalResource)) {
- val PendingRequest(appId, appMaster, request, timeStamp) = resourceRequests.dequeue()
- request.relaxation match {
- case ANY =>
- val allocations = allocateFairly(resourcesSnapShot, request)
- val newAllocated = Resource(allocations.map(_.resource.slots).sum)
- if (allocations.nonEmpty) {
- appMaster ! ResourceAllocated(allocations.toArray)
- }
- if (newAllocated < request.resource) {
- val remainingRequest = request.resource - newAllocated
- val remainingExecutors = request.executorNum - allocations.length
- val newResourceRequest = request.copy(resource = remainingRequest,
- executorNum = remainingExecutors)
- scheduleLater = scheduleLater :+
- PendingRequest(appId, appMaster, newResourceRequest, timeStamp)
- }
- allocated = allocated + newAllocated
- case ONEWORKER =>
- val availableResource = resourcesSnapShot.find { params =>
- val (_, (_, resource)) = params
- resource > request.resource
- }
- if (availableResource.nonEmpty) {
- val (workerId, (worker, resource)) = availableResource.get
- allocated = allocated + request.resource
- appMaster ! ResourceAllocated(Array(ResourceAllocation(request.resource, worker,
- workerId)))
- resourcesSnapShot.update(workerId, (worker, resource - request.resource))
- } else {
- scheduleLater = scheduleLater :+ PendingRequest(appId, appMaster, request, timeStamp)
- }
- case SPECIFICWORKER =>
- val workerAndResource = resourcesSnapShot.get(request.workerId)
- if (workerAndResource.nonEmpty && workerAndResource.get._2 > request.resource) {
- val (worker, availableResource) = workerAndResource.get
- appMaster ! ResourceAllocated(Array(ResourceAllocation(request.resource, worker,
- request.workerId)))
- allocated = allocated + request.resource
- resourcesSnapShot.update(request.workerId, (worker,
- availableResource - request.resource))
- } else {
- scheduleLater = scheduleLater :+ PendingRequest(appId, appMaster, request, timeStamp)
- }
- }
- }
- for (request <- scheduleLater)
- resourceRequests.enqueue(request)
- }
-
- def resourceRequestHandler: Receive = {
- case RequestResource(appId, request) =>
- LOG.info(s"Request resource: appId: $appId, slots: ${request.resource.slots}, " +
- s"relaxation: ${request.relaxation}, executor number: ${request.executorNum}")
- val appMaster = sender()
- resourceRequests.enqueue(new PendingRequest(appId, appMaster, request,
- System.currentTimeMillis()))
- allocateResource()
- }
-
- override def doneApplication(appId: Int): Unit = {
- resourceRequests = resourceRequests.filter(_.appId != appId)
- }
-
- private def allocateFairly(
- resources: mutable.HashMap[WorkerId, (ActorRef, Resource)], request: ResourceRequest)
- : List[ResourceAllocation] = {
- val workerNum = resources.size
- var allocations = List.empty[ResourceAllocation]
- var totalAvailable = Resource(resources.values.map(_._2.slots).sum)
- var remainingRequest = request.resource
- var remainingExecutors = Math.min(request.executorNum, request.resource.slots)
-
- while (remainingExecutors > 0 && !totalAvailable.isEmpty) {
- val exeutorNum = Math.min(workerNum, remainingExecutors)
- val toRequest = Resource(remainingRequest.slots * exeutorNum / remainingExecutors)
-
- val sortedResources = resources.toArray.sortBy(_._2._2.slots)(Ordering[Int].reverse)
- val pickedResources = sortedResources.take(exeutorNum)
-
- val flattenResource = pickedResources.zipWithIndex.flatMap { workerWithIndex =>
- val ((workerId, (worker, resource)), index) = workerWithIndex
- 0.until(resource.slots).map(seq => ((workerId, worker), seq * workerNum + index))
- }.sortBy(_._2).map(_._1)
-
- if (flattenResource.length < toRequest.slots) {
- // Can not safisfy the user's requirements
- totalAvailable = Resource.empty
- } else {
- flattenResource.take(toRequest.slots).groupBy(actor => actor).mapValues(_.length).
- toArray.foreach { params =>
- val ((workerId, worker), slots) = params
- resources.update(workerId, (worker, resources.get(workerId).get._2 - Resource(slots)))
- allocations :+= ResourceAllocation(Resource(slots), worker, workerId)
- }
- totalAvailable -= toRequest
- remainingRequest -= toRequest
- remainingExecutors -= exeutorNum
- }
- }
- allocations
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/io/gearpump/cluster/scheduler/Scheduler.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/io/gearpump/cluster/scheduler/Scheduler.scala b/daemon/src/main/scala/io/gearpump/cluster/scheduler/Scheduler.scala
deleted file mode 100644
index ccd105f..0000000
--- a/daemon/src/main/scala/io/gearpump/cluster/scheduler/Scheduler.scala
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.cluster.scheduler
-
-import scala.collection.mutable
-
-import akka.actor.{Actor, ActorRef}
-import org.slf4j.Logger
-
-import io.gearpump.TimeStamp
-import io.gearpump.cluster.MasterToWorker.{UpdateResourceFailed, UpdateResourceSucceed, WorkerRegistered}
-import io.gearpump.cluster.WorkerToMaster.ResourceUpdate
-import io.gearpump.cluster.master.Master.WorkerTerminated
-import io.gearpump.cluster.scheduler.Scheduler.ApplicationFinished
-import io.gearpump.cluster.worker.WorkerId
-import io.gearpump.util.LogUtil
-
-/**
- * Scheduler schedule resource for different applications.
- */
-abstract class Scheduler extends Actor {
- val LOG: Logger = LogUtil.getLogger(getClass)
- protected var resources = new mutable.HashMap[WorkerId, (ActorRef, Resource)]
-
- def handleScheduleMessage: Receive = {
- case WorkerRegistered(id, _) =>
- if (!resources.contains(id)) {
- LOG.info(s"Worker $id added to the scheduler")
- resources.put(id, (sender, Resource.empty))
- }
- case update@ResourceUpdate(worker, workerId, resource) =>
- LOG.info(s"$update...")
- if (resources.contains(workerId)) {
- val resourceReturned = resource > resources.get(workerId).get._2
- resources.update(workerId, (worker, resource))
- if (resourceReturned) {
- allocateResource()
- }
- sender ! UpdateResourceSucceed
- }
- else {
- sender ! UpdateResourceFailed(
- s"ResourceUpdate failed! The worker $workerId has not been registered into master")
- }
- case WorkerTerminated(workerId) =>
- if (resources.contains(workerId)) {
- resources -= workerId
- }
- case ApplicationFinished(appId) =>
- doneApplication(appId)
- }
-
- def allocateResource(): Unit
-
- def doneApplication(appId: Int): Unit
-}
-
-object Scheduler {
- case class PendingRequest(
- appId: Int, appMaster: ActorRef, request: ResourceRequest, timeStamp: TimeStamp)
-
- case class ApplicationFinished(appId: Int)
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/io/gearpump/cluster/worker/DefaultExecutorProcessLauncher.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/io/gearpump/cluster/worker/DefaultExecutorProcessLauncher.scala b/daemon/src/main/scala/io/gearpump/cluster/worker/DefaultExecutorProcessLauncher.scala
deleted file mode 100644
index f97a209..0000000
--- a/daemon/src/main/scala/io/gearpump/cluster/worker/DefaultExecutorProcessLauncher.scala
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.cluster.worker
-
-import java.io.File
-
-import com.typesafe.config.Config
-import org.slf4j.Logger
-
-import io.gearpump.cluster.scheduler.Resource
-import io.gearpump.util.{LogUtil, RichProcess, Util}
-
-/** Launcher to start an executor process */
-class DefaultExecutorProcessLauncher(val config: Config) extends ExecutorProcessLauncher {
- private val LOG: Logger = LogUtil.getLogger(getClass)
-
- override def createProcess(
- appId: Int, executorId: Int, resource: Resource, config: Config, options: Array[String],
- classPath: Array[String], mainClass: String, arguments: Array[String]): RichProcess = {
-
- LOG.info(s"Launch executor, classpath: ${classPath.mkString(File.pathSeparator)}")
- Util.startProcess(options, classPath, mainClass, arguments)
- }
-
- override def cleanProcess(appId: Int, executorId: Int): Unit = {}
-}
[47/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/cluster/appmaster/ApplicationState.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/cluster/appmaster/ApplicationState.scala b/core/src/main/scala/io/gearpump/cluster/appmaster/ApplicationState.scala
deleted file mode 100644
index 3b967f4..0000000
--- a/core/src/main/scala/io/gearpump/cluster/appmaster/ApplicationState.scala
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.appmaster
-
-import io.gearpump.cluster.{AppDescription, AppJar}
-
-/**
- * This state for single application, it is be distributed across the masters.
- */
-case class ApplicationState(
- appId: Int, appName: String, attemptId: Int, app: AppDescription, jar: Option[AppJar],
- username: String, state: Any) extends Serializable {
-
- override def equals(other: Any): Boolean = {
- other match {
- case that: ApplicationState =>
- if (appId == that.appId && attemptId == that.attemptId) {
- true
- } else {
- false
- }
- case _ =>
- false
- }
- }
-
- override def hashCode: Int = {
- import akka.routing.MurmurHash._
- extendHash(appId, attemptId, startMagicA, startMagicB)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/cluster/appmaster/ExecutorSystem.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/cluster/appmaster/ExecutorSystem.scala b/core/src/main/scala/io/gearpump/cluster/appmaster/ExecutorSystem.scala
deleted file mode 100644
index 6fcb5e7..0000000
--- a/core/src/main/scala/io/gearpump/cluster/appmaster/ExecutorSystem.scala
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.appmaster
-
-import akka.actor.{ActorRef, Address, PoisonPill}
-
-import io.gearpump.cluster.scheduler.Resource
-import io.gearpump.cluster.worker.WorkerId
-import io.gearpump.util.ActorSystemBooter.BindLifeCycle
-
-case class WorkerInfo(workerId: WorkerId, ref: ActorRef)
-
-/**
- * Configurations to start an executor system on remote machine
- *
- * @param address Remote address where we start an Actor System.
- */
-case class ExecutorSystem(executorSystemId: Int, address: Address, daemon:
- ActorRef, resource: Resource, worker: WorkerInfo) {
- def bindLifeCycleWith(actor: ActorRef): Unit = {
- daemon ! BindLifeCycle(actor)
- }
-
- def shutdown(): Unit = {
- daemon ! PoisonPill
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/cluster/appmaster/ExecutorSystemLauncher.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/cluster/appmaster/ExecutorSystemLauncher.scala b/core/src/main/scala/io/gearpump/cluster/appmaster/ExecutorSystemLauncher.scala
deleted file mode 100644
index 78432f4..0000000
--- a/core/src/main/scala/io/gearpump/cluster/appmaster/ExecutorSystemLauncher.scala
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.appmaster
-
-import scala.concurrent.duration._
-
-import akka.actor._
-import org.slf4j.Logger
-
-import io.gearpump.cluster.AppMasterToWorker.LaunchExecutor
-import io.gearpump.cluster.ExecutorJVMConfig
-import io.gearpump.cluster.WorkerToAppMaster._
-import io.gearpump.cluster.appmaster.ExecutorSystemLauncher._
-import io.gearpump.cluster.appmaster.ExecutorSystemScheduler.{ExecutorSystemJvmConfig, Session}
-import io.gearpump.cluster.scheduler.Resource
-import io.gearpump.util.ActorSystemBooter.{ActorSystemRegistered, RegisterActorSystem}
-import io.gearpump.util.{ActorSystemBooter, ActorUtil, Constants, LogUtil}
-
-/**
- * This launches single executor system on target worker.
- *
- * Please use ExecutorSystemLauncher.props() to construct this actor
- *
- * @param session The session that request to launch executor system
- */
-private[appmaster]
-class ExecutorSystemLauncher(appId: Int, session: Session) extends Actor {
-
- private val LOG: Logger = LogUtil.getLogger(getClass)
-
- val scheduler = context.system.scheduler
- implicit val executionContext = context.dispatcher
-
- private val systemConfig = context.system.settings.config
- val timeoutSetting = systemConfig.getInt(Constants.GEARPUMP_START_EXECUTOR_SYSTEM_TIMEOUT_MS)
-
- val timeout = scheduler.scheduleOnce(timeoutSetting.milliseconds,
- self, LaunchExecutorSystemTimeout(session))
-
- def receive: Receive = waitForLaunchCommand
-
- def waitForLaunchCommand: Receive = {
- case LaunchExecutorSystem(worker, executorSystemId, resource) =>
- val launcherPath = ActorUtil.getFullPath(context.system, self.path)
- val jvmConfig = Option(session.executorSystemJvmConfig)
- .map(getExecutorJvmConfig(_, s"app${appId}system${executorSystemId}", launcherPath)).orNull
-
- val launch = LaunchExecutor(appId, executorSystemId, resource, jvmConfig)
- LOG.info(s"Launching Executor ...appId: $appId, executorSystemId: $executorSystemId, " +
- s"slots: ${resource.slots} on worker $worker")
-
- worker.ref ! launch
- context.become(waitForActorSystemToStart(sender, launch, worker, executorSystemId))
- }
-
- def waitForActorSystemToStart(
- replyTo: ActorRef, launch: LaunchExecutor, worker: WorkerInfo, executorSystemId: Int)
- : Receive = {
- case RegisterActorSystem(systemPath) =>
- import launch._
- timeout.cancel()
- LOG.info(s"Received RegisterActorSystem $systemPath for session ${session.requestor}")
- sender ! ActorSystemRegistered(worker.ref)
- val system =
- ExecutorSystem(executorId, AddressFromURIString(systemPath), sender, resource, worker)
- replyTo ! LaunchExecutorSystemSuccess(system, session)
- context.stop(self)
- case reject@ExecutorLaunchRejected(reason, ex) =>
- LOG.error(s"Executor Launch ${launch.resource} failed reason: $reason", ex)
- replyTo ! LaunchExecutorSystemRejected(launch.resource, reason, session)
- context.stop(self)
- case timeout: LaunchExecutorSystemTimeout =>
- LOG.error(s"The Executor ActorSystem $executorSystemId has not been started in time")
- replyTo ! timeout
- context.stop(self)
- }
-}
-
-private[appmaster]
-object ExecutorSystemLauncher {
-
- case class LaunchExecutorSystem(worker: WorkerInfo, systemId: Int, resource: Resource)
-
- case class LaunchExecutorSystemSuccess(system: ExecutorSystem, session: Session)
-
- case class LaunchExecutorSystemRejected(resource: Resource, reason: Any, session: Session)
-
- case class LaunchExecutorSystemTimeout(session: Session)
-
- private def getExecutorJvmConfig(conf: ExecutorSystemJvmConfig, systemName: String,
- reportBack: String): ExecutorJVMConfig = {
- Option(conf).map { conf =>
- import conf._
- ExecutorJVMConfig(classPath, jvmArguments, classOf[ActorSystemBooter].getName,
- Array(systemName, reportBack), jar, username, executorAkkaConfig)
- }.getOrElse(null)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/cluster/appmaster/ExecutorSystemScheduler.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/cluster/appmaster/ExecutorSystemScheduler.scala b/core/src/main/scala/io/gearpump/cluster/appmaster/ExecutorSystemScheduler.scala
deleted file mode 100644
index c5ec600..0000000
--- a/core/src/main/scala/io/gearpump/cluster/appmaster/ExecutorSystemScheduler.scala
+++ /dev/null
@@ -1,190 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.appmaster
-
-import scala.concurrent.duration._
-
-import akka.actor._
-import com.typesafe.config.Config
-
-import io.gearpump.cluster.AppMasterToMaster.RequestResource
-import io.gearpump.cluster.MasterToAppMaster.ResourceAllocated
-import io.gearpump.cluster._
-import io.gearpump.cluster.appmaster.ExecutorSystemLauncher._
-import io.gearpump.cluster.appmaster.ExecutorSystemScheduler._
-import io.gearpump.cluster.scheduler.{ResourceAllocation, ResourceRequest}
-import io.gearpump.cluster.worker.WorkerId
-import io.gearpump.util.{Constants, LogUtil}
-
-/**
- * ExecutorSystem is also a type of resource, this class schedules ExecutorSystem for AppMaster.
- * AppMaster can use this class to directly request a live executor actor systems. The communication
- * in the background with Master and Worker is hidden from AppMaster.
- *
- * Please use ExecutorSystemScheduler.props() to construct this actor
- */
-private[appmaster]
-class ExecutorSystemScheduler(appId: Int, masterProxy: ActorRef,
- executorSystemLauncher: (Int, Session) => Props) extends Actor {
-
- private val LOG = LogUtil.getLogger(getClass, app = appId)
- implicit val timeout = Constants.FUTURE_TIMEOUT
- implicit val actorSystem = context.system
- var currentSystemId = 0
-
- var resourceAgents = Map.empty[Session, ActorRef]
-
- def receive: Receive = {
- clientCommands orElse resourceAllocationMessageHandler orElse executorSystemMessageHandler
- }
-
- def clientCommands: Receive = {
- case start: StartExecutorSystems =>
- LOG.info(s"starting executor systems (ExecutorSystemConfig(${start.executorSystemConfig}), " +
- s"Resources(${start.resources.mkString(",")}))")
- val requestor = sender()
- val executorSystemConfig = start.executorSystemConfig
- val session = Session(requestor, executorSystemConfig)
- val agent = resourceAgents.getOrElse(session,
- context.actorOf(Props(new ResourceAgent(masterProxy, session))))
- resourceAgents = resourceAgents + (session -> agent)
-
- start.resources.foreach { resource =>
- agent ! RequestResource(appId, resource)
- }
-
- case StopExecutorSystem(executorSystem) =>
- executorSystem.shutdown
- }
-
- def resourceAllocationMessageHandler: Receive = {
- case ResourceAllocatedForSession(allocations, session) =>
- if (isSessionAlive(session)) {
- allocations.foreach { resourceAllocation =>
- val ResourceAllocation(resource, worker, workerId) = resourceAllocation
-
- val launcher = context.actorOf(executorSystemLauncher(appId, session))
- launcher ! LaunchExecutorSystem(WorkerInfo(workerId, worker), currentSystemId, resource)
- currentSystemId = currentSystemId + 1
- }
- }
- case ResourceAllocationTimeOut(session) =>
- if (isSessionAlive(session)) {
- resourceAgents = resourceAgents - session
- session.requestor ! StartExecutorSystemTimeout
- }
- }
-
- def executorSystemMessageHandler: Receive = {
- case LaunchExecutorSystemSuccess(system, session) =>
- if (isSessionAlive(session)) {
- LOG.info("LaunchExecutorSystemSuccess, send back to " + session.requestor)
- system.bindLifeCycleWith(self)
- session.requestor ! ExecutorSystemStarted(system, session.executorSystemJvmConfig.jar)
- } else {
- LOG.error("We get a ExecutorSystem back, but resource requestor is no longer valid. " +
- "Will shutdown the allocated system")
- system.shutdown
- }
- case LaunchExecutorSystemTimeout(session) =>
- if (isSessionAlive(session)) {
- LOG.error(s"Failed to launch executor system for ${session.requestor} due to timeout")
- session.requestor ! StartExecutorSystemTimeout
- }
-
- case LaunchExecutorSystemRejected(resource, reason, session) =>
- if (isSessionAlive(session)) {
- LOG.error(s"Failed to launch executor system, due to $reason, " +
- s"will ask master to allocate new resources $resource")
- resourceAgents.get(session).map { resourceAgent: ActorRef =>
- resourceAgent ! RequestResource(appId, ResourceRequest(resource, WorkerId.unspecified))
- }
- }
- }
-
- private def isSessionAlive(session: Session): Boolean = {
- Option(session).flatMap(session => resourceAgents.get(session)).nonEmpty
- }
-}
-
-object ExecutorSystemScheduler {
-
- case class StartExecutorSystems(
- resources: Array[ResourceRequest], executorSystemConfig: ExecutorSystemJvmConfig)
-
- case class ExecutorSystemStarted(system: ExecutorSystem, boundedJar: Option[AppJar])
-
- case class StopExecutorSystem(system: ExecutorSystem)
-
- case object StartExecutorSystemTimeout
-
- case class ExecutorSystemJvmConfig(classPath: Array[String], jvmArguments: Array[String],
- jar: Option[AppJar], username: String, executorAkkaConfig: Config = null)
-
- /**
- * For each client which ask for an executor system, the scheduler will create a session for it.
- *
- */
- private[appmaster]
- case class Session(requestor: ActorRef, executorSystemJvmConfig: ExecutorSystemJvmConfig)
-
- /**
- * This is a agent for session to request resource
- *
- * @param session the original requester of the resource requests
- */
- private[appmaster]
- class ResourceAgent(master: ActorRef, session: Session) extends Actor {
- private var resourceRequestor: ActorRef = null
- var timeOutClock: Cancellable = null
- private var unallocatedResource: Int = 0
-
- import context.dispatcher
-
- import io.gearpump.util.Constants._
-
- val timeout = context.system.settings.config.getInt(GEARPUMP_RESOURCE_ALLOCATION_TIMEOUT)
-
- def receive: Receive = {
- case request: RequestResource =>
- unallocatedResource += request.request.resource.slots
- Option(timeOutClock).map(_.cancel)
- timeOutClock = context.system.scheduler.scheduleOnce(
- timeout.seconds, self, ResourceAllocationTimeOut(session))
- resourceRequestor = sender
- master ! request
- case ResourceAllocated(allocations) =>
- unallocatedResource -= allocations.map(_.resource.slots).sum
- resourceRequestor forward ResourceAllocatedForSession(allocations, session)
- case timeout: ResourceAllocationTimeOut =>
- if (unallocatedResource > 0) {
- resourceRequestor ! ResourceAllocationTimeOut(session)
- // We will not receive any ResourceAllocation after timeout
- context.stop(self)
- }
- }
- }
-
- private[ExecutorSystemScheduler]
- case class ResourceAllocatedForSession(resource: Array[ResourceAllocation], session: Session)
-
- private[ExecutorSystemScheduler]
- case class ResourceAllocationTimeOut(session: Session)
-
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/cluster/appmaster/MasterConnectionKeeper.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/cluster/appmaster/MasterConnectionKeeper.scala b/core/src/main/scala/io/gearpump/cluster/appmaster/MasterConnectionKeeper.scala
deleted file mode 100644
index f8c8503..0000000
--- a/core/src/main/scala/io/gearpump/cluster/appmaster/MasterConnectionKeeper.scala
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.appmaster
-
-import java.util.concurrent.TimeUnit
-import scala.concurrent.duration.FiniteDuration
-
-import akka.actor._
-
-import io.gearpump.cluster.AppMasterToMaster.RegisterAppMaster
-import io.gearpump.cluster.MasterToAppMaster.AppMasterRegistered
-import io.gearpump.cluster.appmaster.MasterConnectionKeeper.AppMasterRegisterTimeout
-import io.gearpump.cluster.appmaster.MasterConnectionKeeper.MasterConnectionStatus.{MasterConnected, MasterStopped}
-import io.gearpump.cluster.master.MasterProxy.{MasterRestarted, WatchMaster}
-import io.gearpump.util.LogUtil
-
-/**
- * Watches the liveness of Master.
- *
- * When Master is restarted, it sends RegisterAppMaster to the new Master instance.
- * If Master is stopped, it sends the MasterConnectionStatus to listener
- *
- * please use MasterConnectionKeeper.props() to construct this actor
- */
-private[appmaster]
-class MasterConnectionKeeper(
- register: RegisterAppMaster, masterProxy: ActorRef, masterStatusListener: ActorRef)
- extends Actor {
-
- import context.dispatcher
-
- private val LOG = LogUtil.getLogger(getClass)
- private var master: ActorRef = null
-
- // Subscribe self to masterProxy,
- masterProxy ! WatchMaster(self)
-
- def registerAppMaster: Cancellable = {
- masterProxy ! register
- context.system.scheduler.scheduleOnce(FiniteDuration(30, TimeUnit.SECONDS),
- self, AppMasterRegisterTimeout)
- }
-
- context.become(waitMasterToConfirm(registerAppMaster))
-
- def waitMasterToConfirm(cancelRegister: Cancellable): Receive = {
- case AppMasterRegistered(appId) =>
- cancelRegister.cancel()
- masterStatusListener ! MasterConnected
- context.become(masterLivenessListener)
- case AppMasterRegisterTimeout =>
- cancelRegister.cancel()
- masterStatusListener ! MasterStopped
- context.stop(self)
- }
-
- def masterLivenessListener: Receive = {
- case MasterRestarted =>
- LOG.info("Master restarted, re-registering appmaster....")
- context.become(waitMasterToConfirm(registerAppMaster))
- case MasterStopped =>
- LOG.info("Master is dead, killing this AppMaster....")
- masterStatusListener ! MasterStopped
- context.stop(self)
- }
-
- def receive: Receive = null
-}
-
-private[appmaster] object MasterConnectionKeeper {
-
- case object AppMasterRegisterTimeout
-
- object MasterConnectionStatus {
-
- case object MasterConnected
-
- case object MasterStopped
-
- }
-
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/cluster/client/ClientContext.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/cluster/client/ClientContext.scala b/core/src/main/scala/io/gearpump/cluster/client/ClientContext.scala
deleted file mode 100644
index 41c01d8..0000000
--- a/core/src/main/scala/io/gearpump/cluster/client/ClientContext.scala
+++ /dev/null
@@ -1,185 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.client
-
-import java.util.concurrent.TimeUnit
-import scala.collection.JavaConverters._
-import scala.concurrent.duration.Duration
-import scala.concurrent.{Await, Future}
-import scala.util.Try
-
-import akka.actor.{ActorRef, ActorSystem}
-import akka.util.Timeout
-import com.typesafe.config.{Config, ConfigValueFactory}
-import org.slf4j.Logger
-
-import io.gearpump.cluster.MasterToAppMaster.{AppMastersData, ReplayFromTimestampWindowTrailingEdge}
-import io.gearpump.cluster.MasterToClient.ReplayApplicationResult
-import io.gearpump.cluster._
-import io.gearpump.cluster.master.MasterProxy
-import io.gearpump.jarstore.JarStoreService
-import io.gearpump.util.Constants._
-import io.gearpump.util.{ActorUtil, Constants, LogUtil, Util}
-
-/**
- * ClientContext is a user facing util to submit/manage an application.
- *
- * TODO: add interface to query master here
- */
-class ClientContext(config: Config, sys: ActorSystem, _master: ActorRef) {
-
- def this(system: ActorSystem) = {
- this(system.settings.config, system, null)
- }
-
- def this(config: Config) = {
- this(config, null, null)
- }
-
- private val LOG: Logger = LogUtil.getLogger(getClass)
- private implicit val timeout = Timeout(5, TimeUnit.SECONDS)
-
- implicit val system = Option(sys).getOrElse(ActorSystem(s"client${Util.randInt()}", config))
- LOG.info(s"Starting system ${system.name}")
- val shouldCleanupSystem = Option(sys).isEmpty
-
- private val jarStoreService = JarStoreService.get(config)
- jarStoreService.init(config, system)
-
- private lazy val master: ActorRef = {
- val masters = config.getStringList(Constants.GEARPUMP_CLUSTER_MASTERS).asScala
- .flatMap(Util.parseHostList)
- val master = Option(_master).getOrElse(system.actorOf(MasterProxy.props(masters),
- s"masterproxy${system.name}"))
- LOG.info(s"Creating master proxy ${master} for master list: $masters")
- master
- }
-
- /**
- * Submits an application with default jar setting. Use java property "gearpump.app.jar" if
- * defined. Otherwise, it assumes the jar is on the target runtime classpath, thus will
- * not send the jar across the wire.
- */
- def submit(app: Application): Int = {
- submit(app, System.getProperty(GEARPUMP_APP_JAR))
- }
-
- def submit(app: Application, jar: String): Int = {
- submit(app, jar, getExecutorNum())
- }
-
- def submit(app: Application, jar: String, executorNum: Int): Int = {
- val client = getMasterClient
- val appName = checkAndAddNamePrefix(app.name, System.getProperty(GEARPUMP_APP_NAME_PREFIX))
- val submissionConfig = getSubmissionConfig(config)
- .withValue(APPLICATION_EXECUTOR_NUMBER, ConfigValueFactory.fromAnyRef(executorNum))
- val appDescription =
- AppDescription(appName, app.appMaster.getName, app.userConfig, submissionConfig)
- val appJar = Option(jar).map(loadFile)
- client.submitApplication(appDescription, appJar)
- }
-
- private def getExecutorNum(): Int = {
- Try(System.getProperty(APPLICATION_EXECUTOR_NUMBER).toInt).getOrElse(1)
- }
-
- private def getSubmissionConfig(config: Config): Config = {
- ClusterConfig.filterOutDefaultConfig(config)
- }
-
- def replayFromTimestampWindowTrailingEdge(appId: Int): ReplayApplicationResult = {
- import scala.concurrent.ExecutionContext.Implicits.global
- val result = Await.result(
- ActorUtil.askAppMaster[ReplayApplicationResult](master,
- appId, ReplayFromTimestampWindowTrailingEdge(appId)), Duration.Inf)
- result
- }
-
- def askAppMaster[T](appId: Int, msg: Any): Future[T] = {
- import scala.concurrent.ExecutionContext.Implicits.global
- ActorUtil.askAppMaster[T](master, appId, msg)
- }
-
- def listApps: AppMastersData = {
- val client = getMasterClient
- client.listApplications
- }
-
- def shutdown(appId: Int): Unit = {
- val client = getMasterClient
- client.shutdownApplication(appId)
- }
-
- def resolveAppID(appId: Int): ActorRef = {
- val client = getMasterClient
- client.resolveAppId(appId)
- }
-
- def close(): Unit = {
- if (shouldCleanupSystem) {
- LOG.info(s"Shutting down system ${system.name}")
- system.terminate()
- }
- }
-
- private def loadFile(jarPath: String): AppJar = {
- val jarFile = new java.io.File(jarPath)
- val path = jarStoreService.copyFromLocal(jarFile)
- AppJar(jarFile.getName, path)
- }
-
- private def checkAndAddNamePrefix(appName: String, namePrefix: String): String = {
- val fullName = if (namePrefix != null && namePrefix != "") {
- namePrefix + "_" + appName
- } else {
- appName
- }
- if (!Util.validApplicationName(fullName)) {
- close()
- val error = s"The application name $appName is not a proper name. An app name can " +
- "be a sequence of letters, numbers or underscore character \"_\""
- throw new Exception(error)
- }
- fullName
- }
-
- private def getMasterClient: MasterClient = {
- val timeout = Try(config.getInt(Constants.GEARPUMP_MASTERCLIENT_TIMEOUT)).getOrElse(90)
- new MasterClient(master, akka.util.Timeout(timeout, TimeUnit.SECONDS))
- }
-}
-
-object ClientContext {
-
- def apply(): ClientContext = new ClientContext(ClusterConfig.default(), null, null)
-
- def apply(system: ActorSystem): ClientContext = {
- new ClientContext(ClusterConfig.default(), system, null)
- }
-
- def apply(system: ActorSystem, master: ActorRef): ClientContext = {
- new ClientContext(ClusterConfig.default(), system, master)
- }
-
- def apply(config: Config): ClientContext = new ClientContext(config, null, null)
-
- def apply(config: Config, system: ActorSystem, master: ActorRef): ClientContext = {
- new ClientContext(config, system, master)
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/cluster/client/MasterClient.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/cluster/client/MasterClient.scala b/core/src/main/scala/io/gearpump/cluster/client/MasterClient.scala
deleted file mode 100644
index 9edaf46..0000000
--- a/core/src/main/scala/io/gearpump/cluster/client/MasterClient.scala
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.client
-
-import scala.concurrent.duration.Duration
-import scala.concurrent.{Await, Future}
-import scala.util.{Failure, Success}
-
-import akka.actor.ActorRef
-import akka.pattern.ask
-import akka.util.Timeout
-
-import io.gearpump.cluster.ClientToMaster._
-import io.gearpump.cluster.MasterToAppMaster.{AppMastersData, AppMastersDataRequest}
-import io.gearpump.cluster.MasterToClient.{ResolveAppIdResult, ShutdownApplicationResult, SubmitApplicationResult}
-import io.gearpump.cluster.{AppDescription, AppJar}
-
-/**
- * Client to inter-operate with Master node.
- *
- * NOTE: Stateless, thread safe
- */
-class MasterClient(master: ActorRef, timeout: Timeout) {
- implicit val masterClientTimeout = timeout
-
- def submitApplication(app: AppDescription, appJar: Option[AppJar]): Int = {
- val result = Await.result(
- (master ? SubmitApplication(app, appJar)).asInstanceOf[Future[SubmitApplicationResult]],
- Duration.Inf)
- val appId = result.appId match {
- case Success(appId) =>
- // scalastyle:off println
- Console.println(s"Submit application succeed. The application id is $appId")
- // scalastyle:on println
- appId
- case Failure(ex) => throw ex
- }
- appId
- }
-
- def resolveAppId(appId: Int): ActorRef = {
- val result = Await.result(
- (master ? ResolveAppId(appId)).asInstanceOf[Future[ResolveAppIdResult]], Duration.Inf)
- result.appMaster match {
- case Success(appMaster) => appMaster
- case Failure(ex) => throw ex
- }
- }
-
- def shutdownApplication(appId: Int): Unit = {
- val result = Await.result(
- (master ? ShutdownApplication(appId)).asInstanceOf[Future[ShutdownApplicationResult]],
- Duration.Inf)
- result.appId match {
- case Success(_) =>
- case Failure(ex) => throw ex
- }
- }
-
- def listApplications: AppMastersData = {
- val result = Await.result(
- (master ? AppMastersDataRequest).asInstanceOf[Future[AppMastersData]], Duration.Inf)
- result
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/cluster/main/ArgumentsParser.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/cluster/main/ArgumentsParser.scala b/core/src/main/scala/io/gearpump/cluster/main/ArgumentsParser.scala
deleted file mode 100644
index 209f831..0000000
--- a/core/src/main/scala/io/gearpump/cluster/main/ArgumentsParser.scala
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.main
-
-import io.gearpump.cluster.main.ArgumentsParser.Syntax
-
-case class CLIOption[+T](
- description: String = "", required: Boolean = false, defaultValue: Option[T] = None)
-
-class ParseResult(optionMap: Map[String, String], remainArguments: Array[String]) {
- def getInt(key: String): Int = optionMap.get(key).get.toInt
-
- def getString(key: String): String = optionMap.get(key).get
-
- def getBoolean(key: String): Boolean = optionMap.get(key).get.toBoolean
-
- def exists(key: String): Boolean = !(optionMap.getOrElse(key, "").isEmpty)
-
- def remainArgs: Array[String] = this.remainArguments
-}
-
-/**
- * Parser for command line arguments
- *
- * Grammar: -option1 value1 -option2 value3 -flag1 -flag2 remainArg1 remainArg2...
- */
-trait ArgumentsParser {
-
- val ignoreUnknownArgument = false
-
- // scalastyle:off println
- def help(): Unit = {
- Console.println(s"\nHelp: $description")
- var usage = List.empty[String]
- options.map(kv => if (kv._2.required) {
- usage = usage :+ s"-${kv._1} (required:${kv._2.required})${kv._2.description}"
- } else {
- usage = usage :+ s"-${kv._1} (required:${kv._2.required}, " +
- s"default:${kv._2.defaultValue.getOrElse("")})${kv._2.description}"
- })
- usage :+= remainArgs.map(k => s"<$k>").mkString(" ")
- usage.foreach(Console.println(_))
- }
- // scalastyle:on println
-
- def parse(args: Array[String]): ParseResult = {
- val syntax = Syntax(options, remainArgs, ignoreUnknownArgument)
- ArgumentsParser.parse(syntax, args)
- }
-
- val description: String = ""
- val options: Array[(String, CLIOption[Any])] = Array.empty[(String, CLIOption[Any])]
- val remainArgs: Array[String] = Array.empty[String]
-}
-
-object ArgumentsParser {
-
- case class Syntax(
- val options: Array[(String, CLIOption[Any])], val remainArgs: Array[String],
- val ignoreUnknownArgument: Boolean)
-
- def parse(syntax: Syntax, args: Array[String]): ParseResult = {
- import syntax.{ignoreUnknownArgument, options, remainArgs}
- var config = Map.empty[String, String]
- var remain = Array.empty[String]
-
- def doParse(argument: List[String]): Unit = {
- argument match {
- case Nil => Unit // true if everything processed successfully
-
- case key :: value :: rest if key.startsWith("-") && !value.startsWith("-") =>
- val fixedKey = key.substring(1)
- if (!options.map(_._1).contains(fixedKey)) {
- if (!ignoreUnknownArgument) {
- throw new Exception(s"found unknown option $fixedKey")
- } else {
- remain ++= Array(key, value)
- }
- } else {
- config += fixedKey -> value
- }
- doParse(rest)
-
- case key :: rest if key.startsWith("-") =>
- val fixedKey = key.substring(1)
- if (!options.map(_._1).contains(fixedKey)) {
- throw new Exception(s"found unknown option $fixedKey")
- } else {
- config += fixedKey -> "true"
- }
- doParse(rest)
-
- case value :: rest =>
- // scalastyle:off println
- Console.err.println(s"Warning: get unknown argument $value, maybe it is a main class")
- // scalastyle:on println
- remain ++= value :: rest
- doParse(Nil)
- }
- }
- doParse(args.toList)
-
- options.foreach { pair =>
- val (key, option) = pair
- if (!config.contains(key) && !option.required) {
- config += key -> option.defaultValue.getOrElse("").toString
- }
- }
-
- options.foreach { pair =>
- val (key, value) = pair
- if (config.get(key).isEmpty) {
- throw new Exception(s"Missing option ${key}...")
- }
- }
-
- if (remain.length < remainArgs.length) {
- throw new Exception(s"Missing arguments ...")
- }
-
- new ParseResult(config, remain)
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/cluster/master/AppMasterLauncher.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/cluster/master/AppMasterLauncher.scala b/core/src/main/scala/io/gearpump/cluster/master/AppMasterLauncher.scala
deleted file mode 100644
index fb3e5c4..0000000
--- a/core/src/main/scala/io/gearpump/cluster/master/AppMasterLauncher.scala
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.master
-
-import java.util.concurrent.{TimeUnit, TimeoutException}
-import scala.collection.JavaConverters._
-import scala.concurrent.duration.Duration
-import scala.util.{Failure, Success}
-
-import akka.actor.{Actor, ActorRef, Props, _}
-import com.typesafe.config.Config
-import org.slf4j.Logger
-
-import io.gearpump.cluster.AppMasterToMaster.RequestResource
-import io.gearpump.cluster.AppMasterToWorker.{LaunchExecutor, ShutdownExecutor}
-import io.gearpump.cluster.MasterToAppMaster.ResourceAllocated
-import io.gearpump.cluster.MasterToClient.SubmitApplicationResult
-import io.gearpump.cluster.WorkerToAppMaster.ExecutorLaunchRejected
-import io.gearpump.cluster.appmaster.{AppMasterRuntimeEnvironment, AppMasterRuntimeInfo, WorkerInfo}
-import io.gearpump.cluster.scheduler.{Resource, ResourceAllocation, ResourceRequest}
-import io.gearpump.cluster.worker.WorkerId
-import io.gearpump.cluster.{AppDescription, AppJar, _}
-import io.gearpump.transport.HostPort
-import io.gearpump.util.ActorSystemBooter._
-import io.gearpump.util.Constants._
-import io.gearpump.util.{ActorSystemBooter, ActorUtil, LogUtil, Util}
-
-/**
- *
- * AppMasterLauncher is a child Actor of AppManager, it is responsible
- * to launch the AppMaster on the cluster.
- */
-class AppMasterLauncher(
- appId: Int, executorId: Int, app: AppDescription,
- jar: Option[AppJar], username: String, master: ActorRef, client: Option[ActorRef])
- extends Actor {
- private val LOG: Logger = LogUtil.getLogger(getClass, app = appId)
-
- val scheduler = context.system.scheduler
- val systemConfig = context.system.settings.config
- val TIMEOUT = Duration(15, TimeUnit.SECONDS)
-
- val appMasterAkkaConfig: Config = app.clusterConfig
-
- LOG.info(s"Ask Master resource to start AppMaster $appId...")
- master ! RequestResource(appId, ResourceRequest(Resource(1), WorkerId.unspecified))
-
- def receive: Receive = waitForResourceAllocation
-
- def waitForResourceAllocation: Receive = {
- case ResourceAllocated(allocations) =>
-
- val ResourceAllocation(resource, worker, workerId) = allocations(0)
- LOG.info(s"Resource allocated for appMaster $appId on worker ${workerId}(${worker.path})")
-
- val submissionTime = System.currentTimeMillis()
-
- val appMasterInfo = AppMasterRuntimeInfo(appId, app.name, worker, username,
- submissionTime, config = appMasterAkkaConfig)
- val workerInfo = WorkerInfo(workerId, worker)
- val appMasterContext =
- AppMasterContext(appId, username, resource, workerInfo, jar, null, appMasterInfo)
- LOG.info(s"Try to launch a executor for AppMaster on worker ${workerId} for app $appId")
- val name = ActorUtil.actorNameForExecutor(appId, executorId)
- val selfPath = ActorUtil.getFullPath(context.system, self.path)
-
- val jvmSetting =
- Util.resolveJvmSetting(appMasterAkkaConfig.withFallback(systemConfig)).appMater
- val executorJVM = ExecutorJVMConfig(jvmSetting.classPath, jvmSetting.vmargs,
- classOf[ActorSystemBooter].getName, Array(name, selfPath), jar,
- username, appMasterAkkaConfig)
-
- worker ! LaunchExecutor(appId, executorId, resource, executorJVM)
- context.become(waitForActorSystemToStart(worker, appMasterContext, app.userConfig, resource))
- }
-
- def waitForActorSystemToStart(
- worker: ActorRef, appContext: AppMasterContext, user: UserConfig, resource: Resource)
- : Receive = {
- case ExecutorLaunchRejected(reason, ex) =>
- LOG.error(s"Executor Launch failed reason: $reason", ex)
- LOG.info(s"reallocate resource $resource to start appmaster")
- master ! RequestResource(appId, ResourceRequest(resource, WorkerId.unspecified))
- context.become(waitForResourceAllocation)
- case RegisterActorSystem(systemPath) =>
- LOG.info(s"Received RegisterActorSystem $systemPath for AppMaster")
- sender ! ActorSystemRegistered(worker)
-
- val masterAddress = systemConfig.getStringList(GEARPUMP_CLUSTER_MASTERS)
- .asScala.map(HostPort(_)).map(ActorUtil.getMasterActorPath)
- sender ! CreateActor(
- AppMasterRuntimeEnvironment.props(masterAddress, app, appContext), s"appdaemon$appId")
-
- import context.dispatcher
- val appMasterTimeout = scheduler.scheduleOnce(TIMEOUT, self,
- CreateActorFailed(app.appMaster, new TimeoutException))
- context.become(waitForAppMasterToStart(worker, appMasterTimeout))
- }
-
- def waitForAppMasterToStart(worker: ActorRef, cancel: Cancellable): Receive = {
- case ActorCreated(appMaster, _) =>
- cancel.cancel()
- sender ! BindLifeCycle(appMaster)
- LOG.info(s"AppMaster is created, mission complete...")
- replyToClient(SubmitApplicationResult(Success(appId)))
- context.stop(self)
- case CreateActorFailed(name, reason) =>
- cancel.cancel()
- worker ! ShutdownExecutor(appId, executorId, reason.getMessage)
- replyToClient(SubmitApplicationResult(Failure(reason)))
- context.stop(self)
- }
-
- def replyToClient(result: SubmitApplicationResult): Unit = {
- if (client.isDefined) {
- client.get.tell(result, master)
- }
- }
-}
-
-object AppMasterLauncher extends AppMasterLauncherFactory {
- def props(appId: Int, executorId: Int, app: AppDescription, jar: Option[AppJar],
- username: String, master: ActorRef, client: Option[ActorRef]): Props = {
- Props(new AppMasterLauncher(appId, executorId, app, jar, username, master, client))
- }
-}
-
-trait AppMasterLauncherFactory {
- def props(appId: Int, executorId: Int, app: AppDescription, jar: Option[AppJar],
- username: String, master: ActorRef, client: Option[ActorRef]): Props
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/cluster/master/MasterProxy.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/cluster/master/MasterProxy.scala b/core/src/main/scala/io/gearpump/cluster/master/MasterProxy.scala
deleted file mode 100644
index 61d95dc..0000000
--- a/core/src/main/scala/io/gearpump/cluster/master/MasterProxy.scala
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.master
-
-import scala.concurrent.duration.FiniteDuration
-
-import akka.actor._
-import org.slf4j.Logger
-
-import io.gearpump.transport.HostPort
-import io.gearpump.util.{ActorUtil, LogUtil}
-
-/**
- * This works with Master HA. When there are multiple Master nodes,
- * This will find a active one.
- */
-class MasterProxy(masters: Iterable[ActorPath], timeout: FiniteDuration)
- extends Actor with Stash {
- import io.gearpump.cluster.master.MasterProxy._
-
- val LOG: Logger = LogUtil.getLogger(getClass, name = self.path.name)
-
- val contacts = masters.map { url =>
- LOG.info(s"Contacts point URL: $url")
- context.actorSelection(url)
- }
-
- var watchers: List[ActorRef] = List.empty[ActorRef]
-
- import context.dispatcher
-
- def findMaster(): Cancellable = {
- repeatActionUtil(timeout) {
- contacts foreach { contact =>
- LOG.info(s"sending identity to $contact")
- contact ! Identify(None)
- }
- }
- }
-
- context.become(establishing(findMaster()))
-
- LOG.info("Master Proxy is started...")
-
- override def postStop(): Unit = {
- watchers.foreach(_ ! MasterStopped)
- super.postStop()
- }
-
- override def receive: Receive = {
- case _ =>
- }
-
- def establishing(findMaster: Cancellable): Actor.Receive = {
- case ActorIdentity(_, Some(receptionist)) =>
- context watch receptionist
- LOG.info("Connected to [{}]", receptionist.path)
- context.watch(receptionist)
-
- watchers.foreach(_ ! MasterRestarted)
- unstashAll()
- findMaster.cancel()
- context.become(active(receptionist) orElse messageHandler(receptionist))
- case ActorIdentity(_, None) => // ok, use another instead
- case msg =>
- LOG.info(s"Stashing ${msg.getClass.getSimpleName}")
- stash()
- }
-
- def active(receptionist: ActorRef): Actor.Receive = {
- case Terminated(receptionist) =>
- LOG.info("Lost contact with [{}], restablishing connection", receptionist)
- context.become(establishing(findMaster))
- case _: ActorIdentity => // ok, from previous establish, already handled
- case WatchMaster(watcher) =>
- watchers = watchers :+ watcher
- }
-
- def messageHandler(master: ActorRef): Receive = {
- case msg =>
- LOG.debug(s"Get msg ${msg.getClass.getSimpleName}, forwarding to ${master.path}")
- master forward msg
- }
-
- def scheduler: Scheduler = context.system.scheduler
- import scala.concurrent.duration._
- private def repeatActionUtil(timeout: FiniteDuration)(action: => Unit): Cancellable = {
- val send = scheduler.schedule(0.seconds, 2.seconds)(action)
- val suicide = scheduler.scheduleOnce(timeout) {
- send.cancel()
- self ! PoisonPill
- }
-
- new Cancellable {
- def cancel(): Boolean = {
- val result1 = send.cancel()
- val result2 = suicide.cancel()
- result1 && result2
- }
-
- def isCancelled: Boolean = {
- send.isCancelled && suicide.isCancelled
- }
- }
- }
-}
-
-object MasterProxy {
- case object MasterRestarted
- case object MasterStopped
- case class WatchMaster(watcher: ActorRef)
-
- import scala.concurrent.duration._
- def props(masters: Iterable[HostPort], duration: FiniteDuration = 30.seconds): Props = {
- val contacts = masters.map(ActorUtil.getMasterActorPath(_))
- Props(new MasterProxy(contacts, duration))
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/cluster/master/MasterSummary.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/cluster/master/MasterSummary.scala b/core/src/main/scala/io/gearpump/cluster/master/MasterSummary.scala
deleted file mode 100644
index 0996381..0000000
--- a/core/src/main/scala/io/gearpump/cluster/master/MasterSummary.scala
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.master
-
-import io.gearpump.util.HistoryMetricsService.HistoryMetricsConfig
-
-/** Master status. Synced means all masters are live and synced. */
-object MasterStatus {
- type Type = String
- val Synced = "synced"
- val UnSynced = "unsynced"
-}
-
-case class MasterNode(host: String, port: Int) {
- def toTuple: (String, Int) = {
- (host, port)
- }
-}
-
-/**
- * Master information returned for REST API call
- */
-case class MasterSummary(
- leader: MasterNode,
- cluster: List[MasterNode],
- aliveFor: Long,
- logFile: String,
- jarStore: String,
- masterStatus: MasterStatus.Type,
- homeDirectory: String,
- activities: List[MasterActivity],
- jvmName: String,
- historyMetricsConfig: HistoryMetricsConfig = null)
-
-case class MasterActivity(time: Long, event: String)
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/cluster/scheduler/Resource.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/cluster/scheduler/Resource.scala b/core/src/main/scala/io/gearpump/cluster/scheduler/Resource.scala
deleted file mode 100644
index b25162e..0000000
--- a/core/src/main/scala/io/gearpump/cluster/scheduler/Resource.scala
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.scheduler
-
-import akka.actor.ActorRef
-
-import io.gearpump.cluster.worker.WorkerId
-
-case class Resource(slots: Int) {
-
- // scalastyle:off spaces.after.plus
- def +(other: Resource): Resource = Resource(slots + other.slots)
- // scalastyle:on spaces.after.plus
-
- def -(other: Resource): Resource = Resource(slots - other.slots)
-
- def >(other: Resource): Boolean = slots > other.slots
-
- def >=(other: Resource): Boolean = !(this < other)
-
- def <(other: Resource): Boolean = slots < other.slots
-
- def <=(other: Resource): Boolean = !(this > other)
-
- def isEmpty: Boolean = {
- slots == 0
- }
-}
-
-/**
- * Each streaming job can have a priority, the job with higher priority
- * will get scheduled resource earlier than those with lower priority.
- */
-object Priority extends Enumeration {
- type Priority = Value
- val LOW, NORMAL, HIGH = Value
-}
-
-/**
- * Relaxation.ONEWORKER means only resource (slot) from that worker will be accepted by
- * the requestor application job.
- */
-object Relaxation extends Enumeration {
- type Relaxation = Value
-
- // Option ONEWORKER allow user to schedule a task on specific worker.
- val ANY, ONEWORKER, SPECIFICWORKER = Value
-}
-
-import io.gearpump.cluster.scheduler.Priority._
-import io.gearpump.cluster.scheduler.Relaxation._
-
-case class ResourceRequest(
- resource: Resource, workerId: WorkerId, priority: Priority = NORMAL,
- relaxation: Relaxation = ANY, executorNum: Int = 1)
-
-case class ResourceAllocation(resource: Resource, worker: ActorRef, workerId: WorkerId)
-
-object Resource {
- def empty: Resource = new Resource(0)
-
- def min(res1: Resource, res2: Resource): Resource = if (res1.slots < res2.slots) res1 else res2
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/cluster/worker/ExecutorProcessLauncher.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/cluster/worker/ExecutorProcessLauncher.scala b/core/src/main/scala/io/gearpump/cluster/worker/ExecutorProcessLauncher.scala
deleted file mode 100644
index 8581467..0000000
--- a/core/src/main/scala/io/gearpump/cluster/worker/ExecutorProcessLauncher.scala
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.worker
-
-import com.typesafe.config.Config
-
-import io.gearpump.cluster.scheduler.Resource
-import io.gearpump.util.RichProcess
-
-/**
- * ExecutorProcessLauncher is used to launch a process for Executor using given parameters.
- *
- * User can implement this interface to decide the behavior of launching a process.
- * Set "gearpump.worker.executor-process-launcher" to your implemented class name.
- */
-trait ExecutorProcessLauncher {
- val config: Config
-
- /**
- * This function launches a process for Executor using given parameters.
- *
- * @param appId The appId of the executor to be launched
- * @param executorId The executorId of the executor to be launched
- * @param resource The resource allocated for that executor
- * @param options The command options
- * @param classPath The classpath of the process
- * @param mainClass The main class of the process
- * @param arguments The rest arguments
- */
- def createProcess(
- appId: Int, executorId: Int, resource: Resource, config: Config, options: Array[String],
- classPath: Array[String], mainClass: String, arguments: Array[String]): RichProcess
-
- /**
- * This function will clean resources for a launched process.
- * @param appId The appId of the launched executor
- * @param executorId The executorId of launched executor
- */
- def cleanProcess(appId: Int, executorId: Int): Unit
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/cluster/worker/WorkerId.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/cluster/worker/WorkerId.scala b/core/src/main/scala/io/gearpump/cluster/worker/WorkerId.scala
deleted file mode 100644
index 24c6ad2..0000000
--- a/core/src/main/scala/io/gearpump/cluster/worker/WorkerId.scala
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.worker
-
-/**
- * WorkerId is used to uniquely track a worker machine.
- *
- * @param sessionId sessionId is assigned by Master node for easy tracking. It is possible that
- * sessionId is **NOT** unique, so always use WorkerId for comparison.
- * @param registerTime the timestamp when a worker node register itself to master node
- */
-case class WorkerId(sessionId: Int, registerTime: Long)
-
-object WorkerId {
- val unspecified: WorkerId = new WorkerId(-1, 0L)
-
- def render(workerId: WorkerId): String = {
- workerId.registerTime + "_" + workerId.sessionId
- }
-
- def parse(str: String): WorkerId = {
- val pair = str.split("_")
- new WorkerId(pair(1).toInt, pair(0).toLong)
- }
-
- implicit val workerIdOrdering: Ordering[WorkerId] = {
- new Ordering[WorkerId] {
-
- /** Compare timestamp first, then id */
- override def compare(x: WorkerId, y: WorkerId): Int = {
- if (x.registerTime < y.registerTime) {
- -1
- } else if (x.registerTime == y.registerTime) {
- if (x.sessionId < y.sessionId) {
- -1
- } else if (x.sessionId == y.sessionId) {
- 0
- } else {
- 1
- }
- } else {
- 1
- }
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/cluster/worker/WorkerSummary.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/cluster/worker/WorkerSummary.scala b/core/src/main/scala/io/gearpump/cluster/worker/WorkerSummary.scala
deleted file mode 100644
index cdf2d03..0000000
--- a/core/src/main/scala/io/gearpump/cluster/worker/WorkerSummary.scala
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.worker
-import io.gearpump.util.HistoryMetricsService.HistoryMetricsConfig
-
-/**
- * Worker summary information for REST API.
- */
-case class WorkerSummary(
- workerId: WorkerId,
- state: String,
- actorPath: String,
- aliveFor: Long,
- logFile: String,
- executors: Array[ExecutorSlots],
- totalSlots: Int,
- availableSlots: Int,
- homeDirectory: String,
- jvmName: String,
- // Id used to uniquely identity this worker process in low level resource manager like YARN.
- resourceManagerContainerId: String,
- historyMetricsConfig: HistoryMetricsConfig = null)
-
-object WorkerSummary {
- def empty: WorkerSummary = {
- WorkerSummary(WorkerId.unspecified, "", "", 0L, "",
- Array.empty[ExecutorSlots], 0, 0, "", jvmName = "", resourceManagerContainerId = "")
- }
-}
-
-case class ExecutorSlots(appId: Int, executorId: Int, slots: Int)
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/jarstore/JarStoreService.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/jarstore/JarStoreService.scala b/core/src/main/scala/io/gearpump/jarstore/JarStoreService.scala
deleted file mode 100644
index 54d5431..0000000
--- a/core/src/main/scala/io/gearpump/jarstore/JarStoreService.scala
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.jarstore
-
-import java.io.File
-import java.net.URI
-import java.util.ServiceLoader
-import scala.collection.JavaConverters._
-
-import akka.actor.ActorSystem
-import com.typesafe.config.Config
-
-import io.gearpump.util.{Constants, Util}
-
-case class FilePath(path: String)
-
-/**
- * JarStoreService is used to manage the upload/download of binary files,
- * like user submitted application jar.
- */
-trait JarStoreService {
- /**
- * The scheme of the JarStoreService.
- * Like "hdfs" for HDFS file system, and "file" for a local
- * file system.
- */
- val scheme: String
-
- /**
- * Init the Jar Store.
- */
- def init(config: Config, system: ActorSystem)
-
- /**
- * This function will copy the local file to the remote JarStore, called from client side.
- * @param localFile The local file
- */
- def copyFromLocal(localFile: File): FilePath
-
- /**
- * This function will copy the remote file to local file system, called from client side.
- *
- * @param localFile The destination of file path
- * @param remotePath The remote file path from JarStore
- */
- def copyToLocalFile(localFile: File, remotePath: FilePath)
-}
-
-object JarStoreService {
-
- /**
- * Get a active JarStoreService by specifying a scheme.
- *
- * Please see config [[io.gearpump.util.Constants#GEARPUMP_APP_JAR_STORE_ROOT_PATH]] for more
- * information.
- */
- def get(config: Config): JarStoreService = {
- val jarStoreRootPath = config.getString(Constants.GEARPUMP_APP_JAR_STORE_ROOT_PATH)
- get(jarStoreRootPath)
- }
-
- private lazy val jarstoreServices: List[JarStoreService] = {
- ServiceLoader.load(classOf[JarStoreService]).asScala.toList
- }
-
- private def get(rootPath: String): JarStoreService = {
- val scheme = new URI(Util.resolvePath(rootPath)).getScheme
- jarstoreServices.find(_.scheme == scheme).get
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/metrics/AkkaReporter.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/metrics/AkkaReporter.scala b/core/src/main/scala/io/gearpump/metrics/AkkaReporter.scala
deleted file mode 100644
index 3a581fb..0000000
--- a/core/src/main/scala/io/gearpump/metrics/AkkaReporter.scala
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.metrics
-
-import scala.collection.JavaConverters._
-
-import akka.actor.{ActorRef, ActorSystem}
-
-import io.gearpump.codahale.metrics.{Gauge => CodaGauge, MetricRegistry}
-import io.gearpump.metrics.Metrics.{Counter => CounterData, Gauge => GaugeData, Histogram => HistogramData, Meter => MeterData}
-import io.gearpump.metrics.MetricsReporterService.ReportTo
-import io.gearpump.util.LogUtil
-
-/**
- * A reporter class for logging metrics values to a remote actor periodically
- */
-class AkkaReporter(
- system: ActorSystem,
- registry: MetricRegistry)
- extends ReportTo {
- private val LOG = LogUtil.getLogger(getClass)
- LOG.info("Start Metrics AkkaReporter")
-
- override def report(to: ActorRef): Unit = {
- val counters = registry.getCounters()
- val histograms = registry.getHistograms()
- val meters = registry.getMeters()
- val gauges = registry.getGauges()
-
- counters.entrySet().asScala.foreach { pair =>
- to ! CounterData(pair.getKey, pair.getValue.getCount)
- }
-
- histograms.entrySet().asScala.foreach { pair =>
- val key = pair.getKey
- val value = pair.getValue
- val s = value.getSnapshot
- to ! HistogramData(
- key, s.getMean, s.getStdDev, s.getMedian,
- s.get95thPercentile, s.get99thPercentile, s.get999thPercentile)
- }
-
- meters.entrySet().asScala.foreach { pair =>
- val key = pair.getKey
- val value = pair.getValue
- to ! MeterData(key,
- value.getCount,
- value.getMeanRate,
- value.getOneMinuteRate,
- getRateUnit)
- }
-
- gauges.entrySet().asScala.foreach { kv =>
- val value = kv.getValue.asInstanceOf[CodaGauge[Number]].getValue.longValue()
- to ! GaugeData(kv.getKey, value)
- }
- }
-
- private def getRateUnit: String = {
- "events/s"
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/metrics/Counter.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/metrics/Counter.scala b/core/src/main/scala/io/gearpump/metrics/Counter.scala
deleted file mode 100644
index 70c7bae..0000000
--- a/core/src/main/scala/io/gearpump/metrics/Counter.scala
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.metrics
-
-import io.gearpump.codahale.metrics.{Counter => CodaHaleCounter}
-
-/**
- * @see io.gearpump.codahale.metrics.Counter
- */
-class Counter(val name: String, counter: CodaHaleCounter, sampleRate: Int = 1) {
- private var sampleCount = 0L
- private var toBeIncremented = 0L
-
- def inc() {
- inc(1)
- }
-
- def inc(n: Long) {
- toBeIncremented += n
- sampleCount += 1
- if (null != counter && sampleCount % sampleRate == 0) {
- counter.inc(toBeIncremented)
- toBeIncremented = 0
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/metrics/Histogram.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/metrics/Histogram.scala b/core/src/main/scala/io/gearpump/metrics/Histogram.scala
deleted file mode 100644
index 4673050..0000000
--- a/core/src/main/scala/io/gearpump/metrics/Histogram.scala
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.metrics
-
-import io.gearpump.codahale.metrics.{Histogram => CodaHaleHistogram}
-
-/**
- * @see io.gearpump.codahale.metrics.Histogram
- */
-class Histogram(val name: String, histogram: CodaHaleHistogram, sampleRate: Int = 1) {
- private var sampleCount = 0L
-
- def update(value: Long) {
- sampleCount += 1
- if (null != histogram && sampleCount % sampleRate == 0) {
- histogram.update(value)
- }
- }
-
- def getMean(): Double = {
- histogram.getSnapshot.getMean
- }
-
- def getStdDev(): Double = {
- histogram.getSnapshot.getStdDev
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/metrics/JvmMetricsSet.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/metrics/JvmMetricsSet.scala b/core/src/main/scala/io/gearpump/metrics/JvmMetricsSet.scala
deleted file mode 100644
index 28d420a..0000000
--- a/core/src/main/scala/io/gearpump/metrics/JvmMetricsSet.scala
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.metrics
-
-import java.util
-import scala.collection.JavaConverters._
-
-import io.gearpump.codahale.metrics.jvm.{MemoryUsageGaugeSet, ThreadStatesGaugeSet}
-import io.gearpump.codahale.metrics.{Metric, MetricSet}
-
-class JvmMetricsSet(name: String) extends MetricSet {
-
- override def getMetrics: util.Map[String, Metric] = {
- val memoryMetrics = new MemoryUsageGaugeSet().getMetrics.asScala
- val threadMetrics = new ThreadStatesGaugeSet().getMetrics.asScala
- Map(
- s"$name:memory.total.used" -> memoryMetrics("total.used"),
- s"$name:memory.total.committed" -> memoryMetrics("total.committed"),
- s"$name:memory.total.max" -> memoryMetrics("total.max"),
- s"$name:memory.heap.used" -> memoryMetrics("heap.used"),
- s"$name:memory.heap.committed" -> memoryMetrics("heap.committed"),
- s"$name:memory.heap.max" -> memoryMetrics("heap.max"),
- s"$name:thread.count" -> threadMetrics("count"),
- s"$name:thread.daemon.count" -> threadMetrics("daemon.count")
- ).asJava
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/metrics/Meter.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/metrics/Meter.scala b/core/src/main/scala/io/gearpump/metrics/Meter.scala
deleted file mode 100644
index ca79a37..0000000
--- a/core/src/main/scala/io/gearpump/metrics/Meter.scala
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.metrics
-
-import io.gearpump.codahale.metrics.{Meter => CodaHaleMeter}
-
-/** See io.gearpump.codahale.metrics.Meter */
-class Meter(val name: String, meter: CodaHaleMeter, sampleRate: Int = 1) {
- private var sampleCount = 0L
- private var toBeMarked = 0L
-
- def mark() {
- meter.mark(1)
- }
-
- def mark(n: Long) {
- toBeMarked += n
- sampleCount += 1
- if (null != meter && sampleCount % sampleRate == 0) {
- meter.mark(toBeMarked)
- toBeMarked = 0
- }
- }
-
- def getOneMinuteRate(): Double = {
- meter.getOneMinuteRate
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/metrics/Metrics.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/metrics/Metrics.scala b/core/src/main/scala/io/gearpump/metrics/Metrics.scala
deleted file mode 100644
index aad1af0..0000000
--- a/core/src/main/scala/io/gearpump/metrics/Metrics.scala
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.metrics
-
-import scala.collection.JavaConverters._
-
-import akka.actor._
-import org.slf4j.Logger
-
-import io.gearpump.codahale.metrics._
-import io.gearpump.metrics
-import io.gearpump.util.LogUtil
-
-/** Metric objects registry */
-class Metrics(sampleRate: Int) extends Extension {
-
- val registry = new MetricRegistry()
-
- def meter(name: String): metrics.Meter = {
- new metrics.Meter(name, registry.meter(name), sampleRate)
- }
-
- def histogram(name: String): Histogram = {
- new Histogram(name, registry.histogram(name), sampleRate)
- }
-
- def histogram(name: String, sampleRate: Int): Histogram = {
- new Histogram(name, registry.histogram(name), sampleRate)
- }
-
- def counter(name: String): Counter = {
- new Counter(name, registry.counter(name), sampleRate)
- }
-
- def register(set: MetricSet): Unit = {
- val names = registry.getNames
- val metrics = set.getMetrics.asScala.filterKeys { key => !names.contains(key) }
- metrics.foreach { kv =>
- registry.register(kv._1, kv._2)
- }
- }
-}
-
-object Metrics extends ExtensionId[Metrics] with ExtensionIdProvider {
-
- val LOG: Logger = LogUtil.getLogger(getClass)
- import io.gearpump.util.Constants._
-
- sealed trait MetricType {
- def name: String
- }
-
- object MetricType {
- def unapply(obj: MetricType): Option[(Histogram, Counter, Meter, Timer, Gauge)] = {
- obj match {
- case x: Histogram => Some((x, null, null, null, null))
- case x: Counter => Some((null, x, null, null, null))
- case x: Meter => Some((null, null, x, null, null))
- case x: Timer => Some((null, null, null, x, null))
- case g: Gauge => Some((null, null, null, null, g))
- }
- }
-
- def apply(h: Histogram, c: Counter, m: Meter, t: Timer, g: Gauge): MetricType = {
- val result =
- if (h != null) h
- else if (c != null) c
- else if (m != null) m
- else if (t != null) t
- else if (g != null) g
- else null
- result
- }
- }
-
- case class Histogram (
- name: String, mean: Double,
- stddev: Double, median: Double,
- p95: Double, p99: Double, p999: Double)
- extends MetricType
-
- case class Counter(name: String, value: Long) extends MetricType
-
- case class Meter(
- name: String, count: Long, meanRate: Double,
- m1: Double, rateUnit: String)
- extends MetricType
-
- case class Timer(
- name: String, count: Long, min: Double, max: Double,
- mean: Double, stddev: Double, median: Double,
- p75: Double, p95: Double, p98: Double,
- p99: Double, p999: Double, meanRate: Double,
- m1: Double, m5: Double, m15: Double,
- rateUnit: String, durationUnit: String)
- extends MetricType
-
- case class Gauge(name: String, value: Long) extends MetricType
-
- case object ReportMetrics
-
- case class DemandMoreMetrics(subscriber: ActorRef)
-
- override def get(system: ActorSystem): Metrics = super.get(system)
-
- override def lookup: ExtensionId[Metrics] = Metrics
-
- override def createExtension(system: ExtendedActorSystem): Metrics = {
- val metricsEnabled = system.settings.config.getBoolean(GEARPUMP_METRIC_ENABLED)
- LOG.info(s"Metrics is enabled..., $metricsEnabled")
- val sampleRate = system.settings.config.getInt(GEARPUMP_METRIC_SAMPLE_RATE)
- if (metricsEnabled) {
- val meters = new Metrics(sampleRate)
- meters
- } else {
- new DummyMetrics
- }
- }
-
- class DummyMetrics extends Metrics(1) {
- override def register(set: MetricSet): Unit = Unit
-
- private val meter = new metrics.Meter("", null) {
- override def mark(): Unit = Unit
- override def mark(n: Long): Unit = Unit
- override def getOneMinuteRate(): Double = 0
- }
-
- private val histogram = new metrics.Histogram("", null) {
- override def update(value: Long): Unit = Unit
- override def getMean(): Double = 0
- override def getStdDev(): Double = 0
- }
-
- private val counter = new metrics.Counter("", null) {
- override def inc(): Unit = Unit
- override def inc(n: Long): Unit = Unit
- }
-
- override def meter(name: String): metrics.Meter = meter
- override def histogram(name: String): metrics.Histogram = histogram
- override def counter(name: String): metrics.Counter = counter
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/metrics/MetricsAggregator.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/metrics/MetricsAggregator.scala b/core/src/main/scala/io/gearpump/metrics/MetricsAggregator.scala
deleted file mode 100644
index f52a060..0000000
--- a/core/src/main/scala/io/gearpump/metrics/MetricsAggregator.scala
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.metrics
-
-import io.gearpump.cluster.MasterToClient.HistoryMetricsItem
-
-/**
- * Aggregates a larger set of metrics into a smaller set
- *
- * Sub Class must implement a constructor with signature like this:
- * MetricsAggregator(config: Config)
- */
-trait MetricsAggregator {
- def aggregate(options: Map[String, String], inputs: Iterator[HistoryMetricsItem])
- : List[HistoryMetricsItem]
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/metrics/MetricsReporterService.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/metrics/MetricsReporterService.scala b/core/src/main/scala/io/gearpump/metrics/MetricsReporterService.scala
deleted file mode 100644
index 05decdd..0000000
--- a/core/src/main/scala/io/gearpump/metrics/MetricsReporterService.scala
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.metrics
-
-import java.net.InetSocketAddress
-import java.util.concurrent.TimeUnit
-import scala.concurrent.duration._
-
-import akka.actor.{Actor, ActorRef}
-
-import io.gearpump.codahale.metrics.graphite.{Graphite, GraphiteReporter}
-import io.gearpump.codahale.metrics.{MetricFilter, Slf4jReporter}
-import io.gearpump.metrics.Metrics.{DemandMoreMetrics, ReportMetrics}
-import io.gearpump.metrics.MetricsReporterService.ReportTo
-import io.gearpump.util.Constants._
-import io.gearpump.util.LogUtil
-
-/**
- * Reports the metrics data to some where, like Ganglia, remote Akka actor, log files...
- *
- * @param metrics Holds a list of metrics object.
- */
-class MetricsReporterService(metrics: Metrics) extends Actor {
-
- private val LOG = LogUtil.getLogger(getClass)
- private implicit val system = context.system
-
- private val reportInterval = system.settings.config.getInt(GEARPUMP_METRIC_REPORT_INTERVAL)
- private val reporter = getReporter
- implicit val dispatcher = context.dispatcher
-
- def receive: Receive = {
- // The subscriber is demanding more messages.
- case DemandMoreMetrics(subscriber) => {
- reporter.report(subscriber)
- context.system.scheduler.scheduleOnce(reportInterval.milliseconds,
- subscriber, ReportMetrics)
- }
- }
-
- def startGraphiteReporter(): ReportTo = {
- val graphiteHost = system.settings.config.getString(GEARPUMP_METRIC_GRAPHITE_HOST)
- val graphitePort = system.settings.config.getInt(GEARPUMP_METRIC_GRAPHITE_PORT)
-
- val graphite = new Graphite(new InetSocketAddress(graphiteHost, graphitePort))
- LOG.info(s"reporting to $graphiteHost, $graphitePort")
- new ReportTo {
- private val reporter = GraphiteReporter.forRegistry(metrics.registry)
- .convertRatesTo(TimeUnit.SECONDS)
- .convertDurationsTo(TimeUnit.MILLISECONDS)
- .filter(MetricFilter.ALL)
- .build(graphite)
-
- override def report(to: ActorRef): Unit = reporter.report()
- }
- }
-
- def startSlf4jReporter(): ReportTo = {
- new ReportTo {
- val reporter = Slf4jReporter.forRegistry(metrics.registry)
- .convertRatesTo(TimeUnit.SECONDS)
- .convertDurationsTo(TimeUnit.MILLISECONDS)
- .filter(MetricFilter.ALL)
- .outputTo(LOG)
- .build()
-
- override def report(to: ActorRef): Unit = reporter.report()
- }
- }
-
- def startAkkaReporter(): ReportTo = {
- new AkkaReporter(system, metrics.registry)
- }
-
- def getReporter: ReportTo = {
- val reporterType = system.settings.config.getString(GEARPUMP_METRIC_REPORTER)
- LOG.info(s"Metrics reporter is enabled, using $reporterType reporter")
- val reporter = reporterType match {
- case "graphite" => startGraphiteReporter()
- case "logfile" => startSlf4jReporter()
- case "akka" => startAkkaReporter()
- }
- reporter
- }
-}
-
-object MetricsReporterService {
-
- /** Target where user want to report the metrics data to */
- trait ReportTo {
- def report(to: ActorRef): Unit
- }
-}
\ No newline at end of file
[36/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/org/apache/gearpump/util/FileServer.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/org/apache/gearpump/util/FileServer.scala b/daemon/src/main/scala/org/apache/gearpump/util/FileServer.scala
new file mode 100644
index 0000000..3a0faad
--- /dev/null
+++ b/daemon/src/main/scala/org/apache/gearpump/util/FileServer.scala
@@ -0,0 +1,167 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.util
+
+import java.io.File
+import scala.concurrent.{ExecutionContext, Future}
+
+import akka.actor.ActorSystem
+import akka.http.scaladsl.Http
+import akka.http.scaladsl.Http.ServerBinding
+import akka.http.scaladsl.marshalling.Marshal
+import akka.http.scaladsl.model.Uri.{Path, Query}
+import akka.http.scaladsl.model.{HttpEntity, HttpRequest, MediaTypes, Multipart, _}
+import akka.http.scaladsl.server.Directives._
+import akka.http.scaladsl.server._
+import akka.http.scaladsl.unmarshalling.Unmarshal
+import akka.stream.ActorMaterializer
+import akka.stream.scaladsl.{FileIO, Sink, Source}
+import spray.json.DefaultJsonProtocol._
+import spray.json.JsonFormat
+
+import org.apache.gearpump.jarstore.FilePath
+import org.apache.gearpump.util.FileDirective._
+import org.apache.gearpump.util.FileServer.Port
+
+/**
+ * A simple file server implemented with akka-http to store/fetch large
+ * binary files.
+ */
+class FileServer(system: ActorSystem, host: String, port: Int = 0, rootDirectory: File) {
+ import system.dispatcher
+ implicit val actorSystem = system
+ implicit val materializer = ActorMaterializer()
+ implicit def ec: ExecutionContext = system.dispatcher
+
+ val route: Route = {
+ path("upload") {
+ uploadFileTo(rootDirectory) { form =>
+ val fileName = form.fields.headOption.flatMap { pair =>
+ val (_, fileInfo) = pair
+ fileInfo match {
+ case Left(file) => Option(file.file).map(_.getName)
+ case Right(_) => None
+ }
+ }
+
+ if (fileName.isDefined) {
+ complete(fileName.get)
+ } else {
+ failWith(new Exception("File not found in the uploaded form"))
+ }
+ }
+ } ~
+ path("download") {
+ parameters("file") { file: String =>
+ downloadFile(new File(rootDirectory, file))
+ }
+ } ~
+ pathEndOrSingleSlash {
+ extractUri { uri =>
+ val upload = uri.withPath(Uri.Path("/upload")).toString()
+ val entity = HttpEntity(ContentTypes.`text/html(UTF-8)`,
+ s"""
+ |
+ |<h2>Please specify a file to upload:</h2>
+ |<form action="$upload" enctype="multipart/form-data" method="post">
+ |<input type="file" name="datafile" size="40">
+ |</p>
+ |<div>
+ |<input type="submit" value="Submit">
+ |</div>
+ |</form>
+ """.stripMargin)
+ complete(entity)
+ }
+ }
+ }
+
+ private var connection: Future[ServerBinding] = null
+
+ def start: Future[Port] = {
+ connection = Http().bindAndHandle(Route.handlerFlow(route), host, port)
+ connection.map(address => Port(address.localAddress.getPort))
+ }
+
+ def stop: Future[Unit] = {
+ connection.flatMap(_.unbind())
+ }
+}
+
+object FileServer {
+
+ implicit def filePathFormat: JsonFormat[FilePath] = jsonFormat1(FilePath.apply)
+
+ case class Port(port: Int)
+
+ /**
+ * Client of [[org.apache.gearpump.util.FileServer]]
+ */
+ class Client(system: ActorSystem, host: String, port: Int) {
+
+ def this(system: ActorSystem, url: String) = {
+ this(system, Uri(url).authority.host.address(), Uri(url).authority.port)
+ }
+
+ private implicit val actorSystem = system
+ private implicit val materializer = ActorMaterializer()
+ private implicit val ec = system.dispatcher
+
+ val server = Uri(s"http://$host:$port")
+ val httpClient = Http(system).outgoingConnection(server.authority.host.address(),
+ server.authority.port)
+
+ def upload(file: File): Future[FilePath] = {
+ val target = server.withPath(Path("/upload"))
+
+ val request = entity(file).map { entity =>
+ HttpRequest(HttpMethods.POST, uri = target, entity = entity)
+ }
+
+ val response = Source.fromFuture(request).via(httpClient).runWith(Sink.head)
+ response.flatMap { some =>
+ Unmarshal(some).to[String]
+ }.map { path =>
+ FilePath(path)
+ }
+ }
+
+ def download(remoteFile: FilePath, saveAs: File): Future[Unit] = {
+ val download = server.withPath(Path("/download")).withQuery(Query("file" -> remoteFile.path))
+ // Download file to local
+ val response = Source.single(HttpRequest(uri = download)).via(httpClient).runWith(Sink.head)
+ val downloaded = response.flatMap { response =>
+ response.entity.dataBytes.runWith(FileIO.toFile(saveAs))
+ }
+ downloaded.map(written => Unit)
+ }
+
+ private def entity(file: File)(implicit ec: ExecutionContext): Future[RequestEntity] = {
+ val entity = HttpEntity(MediaTypes.`application/octet-stream`, file.length(),
+ FileIO.fromFile(file, chunkSize = 100000))
+ val body = Source.single(
+ Multipart.FormData.BodyPart(
+ "uploadfile",
+ entity,
+ Map("filename" -> file.getName)))
+ val form = Multipart.FormData(body)
+
+ Marshal(form).to[RequestEntity]
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/test/resources/META-INF/services/io.gearpump.jarstore.JarStoreService
----------------------------------------------------------------------
diff --git a/daemon/src/test/resources/META-INF/services/io.gearpump.jarstore.JarStoreService b/daemon/src/test/resources/META-INF/services/io.gearpump.jarstore.JarStoreService
deleted file mode 100644
index d226af9..0000000
--- a/daemon/src/test/resources/META-INF/services/io.gearpump.jarstore.JarStoreService
+++ /dev/null
@@ -1,20 +0,0 @@
-#
-# 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.
-#
-
-io.gearpump.jarstore.local.LocalJarStoreService
-io.gearpump.jarstore.dfs.DFSJarStoreService
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/test/resources/META-INF/services/org.apache.gearpump.jarstore.JarStoreService
----------------------------------------------------------------------
diff --git a/daemon/src/test/resources/META-INF/services/org.apache.gearpump.jarstore.JarStoreService b/daemon/src/test/resources/META-INF/services/org.apache.gearpump.jarstore.JarStoreService
new file mode 100644
index 0000000..bf37316
--- /dev/null
+++ b/daemon/src/test/resources/META-INF/services/org.apache.gearpump.jarstore.JarStoreService
@@ -0,0 +1,20 @@
+#
+# 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.
+#
+
+org.apache.gearpump.jarstore.local.LocalJarStoreService
+org.apache.gearpump.jarstore.dfs.DFSJarStoreService
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/test/scala/io/gearpump/cluster/MiniCluster.scala
----------------------------------------------------------------------
diff --git a/daemon/src/test/scala/io/gearpump/cluster/MiniCluster.scala b/daemon/src/test/scala/io/gearpump/cluster/MiniCluster.scala
deleted file mode 100644
index c6dbbfe..0000000
--- a/daemon/src/test/scala/io/gearpump/cluster/MiniCluster.scala
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.cluster
-
-import scala.concurrent.duration.Duration
-import scala.concurrent.{Await, Future}
-
-import akka.actor.{Actor, ActorRef, ActorSystem, Props}
-import akka.pattern.ask
-import akka.testkit.TestActorRef
-import com.typesafe.config.ConfigValueFactory
-
-import io.gearpump.cluster.AppMasterToMaster.GetAllWorkers
-import io.gearpump.cluster.MasterToAppMaster.WorkerList
-import io.gearpump.cluster.master.Master
-import io.gearpump.cluster.worker.Worker
-import io.gearpump.util.Constants
-
-class MiniCluster {
- private val mockMasterIP = "127.0.0.1"
-
- implicit val system = ActorSystem("system", TestUtil.MASTER_CONFIG.
- withValue(Constants.NETTY_TCP_HOSTNAME, ConfigValueFactory.fromAnyRef(mockMasterIP)))
-
- val (mockMaster, worker) = {
- val master = system.actorOf(Props(classOf[Master]), "master")
- val worker = system.actorOf(Props(classOf[Worker], master), "worker")
-
- // Wait until worker register itself to master
- waitUtilWorkerIsRegistered(master)
- (master, worker)
- }
-
- def launchActor(props: Props): TestActorRef[Actor] = {
- TestActorRef(props)
- }
-
- private def waitUtilWorkerIsRegistered(master: ActorRef): Unit = {
- while (!isWorkerRegistered(master)) {}
- }
-
- private def isWorkerRegistered(master: ActorRef): Boolean = {
- import scala.concurrent.duration._
- implicit val dispatcher = system.dispatcher
-
- implicit val futureTimeout = Constants.FUTURE_TIMEOUT
-
- val workerListFuture = (master ? GetAllWorkers).asInstanceOf[Future[WorkerList]]
-
- // Waits until the worker is registered.
- val workers = Await.result[WorkerList](workerListFuture, 15.seconds)
- workers.workers.size > 0
- }
-
- def shutDown(): Unit = {
- system.terminate()
- Await.result(system.whenTerminated, Duration.Inf)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/test/scala/io/gearpump/cluster/main/MainSpec.scala
----------------------------------------------------------------------
diff --git a/daemon/src/test/scala/io/gearpump/cluster/main/MainSpec.scala b/daemon/src/test/scala/io/gearpump/cluster/main/MainSpec.scala
deleted file mode 100644
index 30347d2..0000000
--- a/daemon/src/test/scala/io/gearpump/cluster/main/MainSpec.scala
+++ /dev/null
@@ -1,189 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.main
-
-import scala.concurrent.Future
-import scala.util.{Success, Try}
-
-import com.typesafe.config.Config
-import org.scalatest._
-
-import io.gearpump.cluster.ClientToMaster.{ResolveAppId, ShutdownApplication}
-import io.gearpump.cluster.MasterToAppMaster.{AppMastersDataRequest, ReplayFromTimestampWindowTrailingEdge, _}
-import io.gearpump.cluster.MasterToClient.{ReplayApplicationResult, ResolveAppIdResult, ShutdownApplicationResult}
-import io.gearpump.cluster.WorkerToMaster.RegisterNewWorker
-import io.gearpump.cluster.{MasterHarness, TestUtil}
-import io.gearpump.util.Constants._
-import io.gearpump.util.{Constants, LogUtil, Util}
-
-class MainSpec extends FlatSpec with Matchers with BeforeAndAfterEach with MasterHarness {
-
- private val LOG = LogUtil.getLogger(getClass)
-
- override def config: Config = TestUtil.DEFAULT_CONFIG
-
- override def beforeEach(): Unit = {
- startActorSystem()
- }
-
- override def afterEach(): Unit = {
- shutdownActorSystem()
- }
-
- "Worker" should "register worker address to master when started." in {
-
- val masterReceiver = createMockMaster()
-
- val tempTestConf = convertTestConf(getHost, getPort)
-
- val options = Array(
- s"-D$GEARPUMP_CUSTOM_CONFIG_FILE=${tempTestConf.toString}",
- s"-D${PREFER_IPV4}=true"
- ) ++ getMasterListOption()
-
- val worker = Util.startProcess(options,
- getContextClassPath,
- getMainClassName(Worker),
- Array.empty)
-
- try {
- masterReceiver.expectMsg(PROCESS_BOOT_TIME, RegisterNewWorker)
-
- tempTestConf.delete()
- } finally {
- worker.destroy()
- }
- }
-
- // This UT fails a lot on Travis, temporarily delete it.
- // "Master" should "accept worker RegisterNewWorker when started" in {
- // val worker = TestProbe()(getActorSystem)
- //
- // val port = Util.findFreePort.get
- //
- // val masterConfig = Array(s"-D${Constants.GEARPUMP_CLUSTER_MASTERS}.0=127.0.0.1:$port",
- // s"-D${Constants.GEARPUMP_HOSTNAME}=127.0.0.1")
- //
- // val masterProcess = Util.startProcess(masterConfig,
- // getContextClassPath,
- // getMainClassName(io.gearpump.cluster.main.Master),
- // Array("-ip", "127.0.0.1", "-port", port.toString))
- //
- // //wait for master process to be started
- //
- // try {
- //
- // val masterProxy = getActorSystem.actorOf(
- // MasterProxy.props(List(HostPort("127.0.0.1", port))), "mainSpec")
- //
- // worker.send(masterProxy, RegisterNewWorker)
- // worker.expectMsgType[WorkerRegistered](PROCESS_BOOT_TIME)
- // } finally {
- // masterProcess.destroy()
- // }
- // }
-
- "Info" should "be started without exception" in {
-
- val masterReceiver = createMockMaster()
-
- Future {
- io.gearpump.cluster.main.Info.main(masterConfig, Array.empty)
- }
-
- masterReceiver.expectMsg(PROCESS_BOOT_TIME, AppMastersDataRequest)
- masterReceiver.reply(AppMastersData(List(AppMasterData(AppMasterActive, 0, "appName"))))
- }
-
- "Kill" should "be started without exception" in {
-
- val masterReceiver = createMockMaster()
-
- Future {
- Kill.main(masterConfig, Array("-appid", "0"))
- }
-
- masterReceiver.expectMsg(PROCESS_BOOT_TIME, ShutdownApplication(0))
- masterReceiver.reply(ShutdownApplicationResult(Success(0)))
- }
-
- "Replay" should "be started without exception" in {
-
- val masterReceiver = createMockMaster()
-
- Future {
- Replay.main(masterConfig, Array("-appid", "0"))
- }
-
- masterReceiver.expectMsgType[ResolveAppId](PROCESS_BOOT_TIME)
- masterReceiver.reply(ResolveAppIdResult(Success(masterReceiver.ref)))
- masterReceiver.expectMsgType[ReplayFromTimestampWindowTrailingEdge](PROCESS_BOOT_TIME)
- masterReceiver.reply(ReplayApplicationResult(Success(0)))
- }
-
- "Local" should "be started without exception" in {
- val port = Util.findFreePort().get
- val options = Array(s"-D${Constants.GEARPUMP_CLUSTER_MASTERS}.0=$getHost:$port",
- s"-D${Constants.GEARPUMP_HOSTNAME}=$getHost",
- s"-D${PREFER_IPV4}=true")
-
- val local = Util.startProcess(options,
- getContextClassPath,
- getMainClassName(Local),
- Array.empty)
-
- def retry(times: Int)(fn: => Boolean): Boolean = {
-
- LOG.info(s"Local Test: Checking whether local port is available, remain times $times ..")
-
- val result = fn
- if (result || times <= 0) {
- result
- } else {
- Thread.sleep(1000)
- retry(times - 1)(fn)
- }
- }
-
- try {
- assert(retry(10)(isPortUsed("127.0.0.1", port)),
- "local is not started successfully, as port is not used " + port)
- } finally {
- local.destroy()
- }
- }
-
- "Gear" should "support app|info|kill|shell|replay" in {
-
- val commands = Array("app", "info", "kill", "shell", "replay")
-
- assert(Try(Gear.main(Array.empty)).isSuccess, "print help, no throw")
-
- for (command <- commands) {
- assert(Try(Gear.main(Array("-noexist"))).isFailure,
- "pass unknown option, throw, command: " + command)
- }
-
- assert(Try(Gear.main(Array("unknownCommand"))).isFailure, "unknown command, throw ")
-
- val tryThis = Try(Gear.main(Array("unknownCommand", "-noexist")))
- assert(tryThis.isFailure, "unknown command, throw")
- }
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/test/scala/io/gearpump/cluster/main/MasterWatcherSpec.scala
----------------------------------------------------------------------
diff --git a/daemon/src/test/scala/io/gearpump/cluster/main/MasterWatcherSpec.scala b/daemon/src/test/scala/io/gearpump/cluster/main/MasterWatcherSpec.scala
deleted file mode 100644
index 66b9ea8..0000000
--- a/daemon/src/test/scala/io/gearpump/cluster/main/MasterWatcherSpec.scala
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.cluster.main
-
-import scala.concurrent.Await
-import scala.concurrent.duration._
-
-import akka.actor.{ActorSystem, Props}
-import akka.testkit.TestProbe
-import com.typesafe.config.Config
-import org.scalatest.{FlatSpec, Matchers}
-
-import io.gearpump.cluster.TestUtil
-
-class MasterWatcherSpec extends FlatSpec with Matchers {
- def config: Config = TestUtil.MASTER_CONFIG
-
- "MasterWatcher" should "kill itself when can not get a quorum" in {
- val system = ActorSystem("ForMasterWatcher", config)
-
- val actorWatcher = TestProbe()(system)
-
- val masterWatcher = system.actorOf(Props(classOf[MasterWatcher], "watcher"))
- actorWatcher watch masterWatcher
- actorWatcher.expectTerminated(masterWatcher, 5.seconds)
- system.terminate()
- Await.result(system.whenTerminated, Duration.Inf)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/test/scala/io/gearpump/cluster/master/AppManagerSpec.scala
----------------------------------------------------------------------
diff --git a/daemon/src/test/scala/io/gearpump/cluster/master/AppManagerSpec.scala b/daemon/src/test/scala/io/gearpump/cluster/master/AppManagerSpec.scala
deleted file mode 100644
index ee6e0e2..0000000
--- a/daemon/src/test/scala/io/gearpump/cluster/master/AppManagerSpec.scala
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.master
-
-import scala.util.Success
-
-import akka.actor.{Actor, ActorRef, Props}
-import akka.testkit.TestProbe
-import com.typesafe.config.Config
-import org.scalatest.{BeforeAndAfterEach, FlatSpec, Matchers}
-
-import io.gearpump.cluster.AppMasterToMaster.{AppDataSaved, _}
-import io.gearpump.cluster.ClientToMaster.{ResolveAppId, ShutdownApplication, SubmitApplication}
-import io.gearpump.cluster.MasterToAppMaster.{AppMasterData, AppMasterRegistered, AppMastersData, AppMastersDataRequest, _}
-import io.gearpump.cluster.MasterToClient.{ResolveAppIdResult, ShutdownApplicationResult, SubmitApplicationResult}
-import io.gearpump.cluster.appmaster.{AppMasterRuntimeInfo, ApplicationState}
-import io.gearpump.cluster.master.AppManager._
-import io.gearpump.cluster.master.InMemoryKVService.{GetKV, GetKVSuccess, PutKV, PutKVSuccess}
-import io.gearpump.cluster.{TestUtil, _}
-import io.gearpump.util.LogUtil
-
-class AppManagerSpec extends FlatSpec with Matchers with BeforeAndAfterEach with MasterHarness {
- var kvService: TestProbe = null
- var haService: TestProbe = null
- var appLauncher: TestProbe = null
- var appManager: ActorRef = null
- private val LOG = LogUtil.getLogger(getClass)
-
- override def config: Config = TestUtil.DEFAULT_CONFIG
-
- override def beforeEach(): Unit = {
- startActorSystem()
- kvService = TestProbe()(getActorSystem)
- appLauncher = TestProbe()(getActorSystem)
-
- appManager = getActorSystem.actorOf(Props(new AppManager(kvService.ref,
- new DummyAppMasterLauncherFactory(appLauncher))))
- kvService.expectMsgType[GetKV]
- kvService.reply(GetKVSuccess(MASTER_STATE, MasterState(0, Map.empty, Map.empty)))
- }
-
- override def afterEach(): Unit = {
- shutdownActorSystem()
- }
-
- "AppManager" should "handle appmaster message correctly" in {
- val appMaster = TestProbe()(getActorSystem)
- val worker = TestProbe()(getActorSystem)
-
- val register = RegisterAppMaster(appMaster.ref, AppMasterRuntimeInfo(0, "appName"))
- appMaster.send(appManager, register)
- appMaster.expectMsgType[AppMasterRegistered]
- }
-
- "DataStoreService" should "support Put and Get" in {
- val appMaster = TestProbe()(getActorSystem)
- appMaster.send(appManager, SaveAppData(0, "key", 1))
- kvService.expectMsgType[PutKV]
- kvService.reply(PutKVSuccess)
- appMaster.expectMsg(AppDataSaved)
-
- appMaster.send(appManager, GetAppData(0, "key"))
- kvService.expectMsgType[GetKV]
- kvService.reply(GetKVSuccess("key", 1))
- appMaster.expectMsg(GetAppDataResult("key", 1))
- }
-
- "AppManager" should "support application submission and shutdown" in {
- testClientSubmission(withRecover = false)
- }
-
- "AppManager" should "support application submission and recover if appmaster dies" in {
- LOG.info("=================testing recover==============")
- testClientSubmission(withRecover = true)
- }
-
- "AppManager" should "handle client message correctly" in {
- val mockClient = TestProbe()(getActorSystem)
- mockClient.send(appManager, ShutdownApplication(1))
- assert(mockClient.receiveN(1).head.asInstanceOf[ShutdownApplicationResult].appId.isFailure)
-
- mockClient.send(appManager, ResolveAppId(1))
- assert(mockClient.receiveN(1).head.asInstanceOf[ResolveAppIdResult].appMaster.isFailure)
-
- mockClient.send(appManager, AppMasterDataRequest(1))
- mockClient.expectMsg(AppMasterData(AppMasterNonExist))
- }
-
- "AppManager" should "reject the application submission if the app name already existed" in {
- val app = TestUtil.dummyApp
- val submit = SubmitApplication(app, None, "username")
- val client = TestProbe()(getActorSystem)
- val appMaster = TestProbe()(getActorSystem)
- val worker = TestProbe()(getActorSystem)
- val appId = 1
-
- client.send(appManager, submit)
-
- kvService.expectMsgType[PutKV]
- appLauncher.expectMsg(LauncherStarted(appId))
- appMaster.send(appManager, RegisterAppMaster(appMaster.ref,
- AppMasterRuntimeInfo(appId, app.name)))
- appMaster.expectMsgType[AppMasterRegistered]
-
- client.send(appManager, submit)
- assert(client.receiveN(1).head.asInstanceOf[SubmitApplicationResult].appId.isFailure)
- }
-
- def testClientSubmission(withRecover: Boolean): Unit = {
- val app = TestUtil.dummyApp
- val submit = SubmitApplication(app, None, "username")
- val client = TestProbe()(getActorSystem)
- val appMaster = TestProbe()(getActorSystem)
- val worker = TestProbe()(getActorSystem)
- val appId = 1
-
- client.send(appManager, submit)
-
- kvService.expectMsgType[PutKV]
- appLauncher.expectMsg(LauncherStarted(appId))
- appMaster.send(appManager, RegisterAppMaster(appMaster.ref,
- AppMasterRuntimeInfo(appId, app.name)))
- kvService.expectMsgType[PutKV]
- appMaster.expectMsgType[AppMasterRegistered]
-
- client.send(appManager, ResolveAppId(appId))
- client.expectMsg(ResolveAppIdResult(Success(appMaster.ref)))
-
- client.send(appManager, AppMastersDataRequest)
- client.expectMsgType[AppMastersData]
-
- client.send(appManager, AppMasterDataRequest(appId, false))
- client.expectMsgType[AppMasterData]
-
- if (!withRecover) {
- client.send(appManager, ShutdownApplication(appId))
- client.expectMsg(ShutdownApplicationResult(Success(appId)))
- } else {
- // Do recovery
- getActorSystem.stop(appMaster.ref)
- kvService.expectMsgType[GetKV]
- val appState = ApplicationState(appId, "application1", 1, app, None, "username", null)
- kvService.reply(GetKVSuccess(APP_STATE, appState))
- appLauncher.expectMsg(LauncherStarted(appId))
- }
- }
-}
-
-class DummyAppMasterLauncherFactory(test: TestProbe) extends AppMasterLauncherFactory {
-
- override def props(appId: Int, executorId: Int, app: AppDescription, jar: Option[AppJar],
- username: String, master: ActorRef, client: Option[ActorRef]): Props = {
- Props(new DummyAppMasterLauncher(test, appId))
- }
-}
-
-class DummyAppMasterLauncher(test: TestProbe, appId: Int) extends Actor {
-
- test.ref ! LauncherStarted(appId)
- override def receive: Receive = {
- case any: Any => test.ref forward any
- }
-}
-
-case class LauncherStarted(appId: Int)
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/test/scala/io/gearpump/cluster/master/InMemoryKVServiceSpec.scala
----------------------------------------------------------------------
diff --git a/daemon/src/test/scala/io/gearpump/cluster/master/InMemoryKVServiceSpec.scala b/daemon/src/test/scala/io/gearpump/cluster/master/InMemoryKVServiceSpec.scala
deleted file mode 100644
index b929349..0000000
--- a/daemon/src/test/scala/io/gearpump/cluster/master/InMemoryKVServiceSpec.scala
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.master
-
-import scala.concurrent.duration._
-
-import akka.actor.Props
-import akka.testkit.TestProbe
-import com.typesafe.config.Config
-import org.scalatest.{BeforeAndAfterEach, FlatSpec, Matchers}
-
-import io.gearpump.cluster.master.InMemoryKVService._
-import io.gearpump.cluster.{MasterHarness, TestUtil}
-
-class InMemoryKVServiceSpec
- extends FlatSpec with Matchers with BeforeAndAfterEach with MasterHarness {
-
- override def beforeEach(): Unit = {
- startActorSystem()
- }
-
- override def afterEach(): Unit = {
- shutdownActorSystem()
- }
-
- override def config: Config = TestUtil.MASTER_CONFIG
-
- "KVService" should "get, put, delete correctly" in {
- val system = getActorSystem
- val kvService = system.actorOf(Props(new InMemoryKVService()))
- val group = "group"
-
- val client = TestProbe()(system)
-
- client.send(kvService, PutKV(group, "key", 1))
- client.expectMsg(PutKVSuccess)
-
- client.send(kvService, PutKV(group, "key", 2))
- client.expectMsg(PutKVSuccess)
-
- client.send(kvService, GetKV(group, "key"))
- client.expectMsg(GetKVSuccess("key", 2))
-
- client.send(kvService, DeleteKVGroup(group))
-
- // After DeleteGroup, it no longer accept Get and Put message for this group.
- client.send(kvService, GetKV(group, "key"))
- client.expectNoMsg(3.seconds)
-
- client.send(kvService, PutKV(group, "key", 3))
- client.expectNoMsg(3.seconds)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/test/scala/io/gearpump/cluster/scheduler/PrioritySchedulerSpec.scala
----------------------------------------------------------------------
diff --git a/daemon/src/test/scala/io/gearpump/cluster/scheduler/PrioritySchedulerSpec.scala b/daemon/src/test/scala/io/gearpump/cluster/scheduler/PrioritySchedulerSpec.scala
deleted file mode 100644
index a75ade2..0000000
--- a/daemon/src/test/scala/io/gearpump/cluster/scheduler/PrioritySchedulerSpec.scala
+++ /dev/null
@@ -1,231 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.cluster.scheduler
-
-import scala.concurrent.duration._
-
-import akka.actor.{ActorSystem, Props}
-import akka.testkit.{ImplicitSender, TestKit, TestProbe}
-import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}
-
-import io.gearpump.cluster.AppMasterToMaster.RequestResource
-import io.gearpump.cluster.MasterToAppMaster.ResourceAllocated
-import io.gearpump.cluster.MasterToWorker.{UpdateResourceFailed, WorkerRegistered}
-import io.gearpump.cluster.TestUtil
-import io.gearpump.cluster.WorkerToMaster.ResourceUpdate
-import io.gearpump.cluster.master.Master.MasterInfo
-import io.gearpump.cluster.scheduler.Priority.{HIGH, LOW, NORMAL}
-import io.gearpump.cluster.scheduler.Scheduler.ApplicationFinished
-import io.gearpump.cluster.worker.WorkerId
-
-class PrioritySchedulerSpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
- with WordSpecLike with Matchers with BeforeAndAfterAll{
-
- def this() = this(ActorSystem("PrioritySchedulerSpec", TestUtil.DEFAULT_CONFIG))
- val appId = 0
- val workerId1: WorkerId = WorkerId(1, 0L)
- val workerId2: WorkerId = WorkerId(2, 0L)
- val mockAppMaster = TestProbe()
- val mockWorker1 = TestProbe()
- val mockWorker2 = TestProbe()
-
- override def afterAll {
- TestKit.shutdownActorSystem(system)
- }
-
- "The scheduler" should {
- "update resource only when the worker is registered" in {
- val scheduler = system.actorOf(Props(classOf[PriorityScheduler]))
- scheduler ! ResourceUpdate(mockWorker1.ref, workerId1, Resource(100))
- expectMsg(UpdateResourceFailed(s"ResourceUpdate failed! The worker $workerId1 has not been " +
- s"registered into master"))
- }
-
- "drop application's resource requests when the application is removed" in {
- val scheduler = system.actorOf(Props(classOf[PriorityScheduler]))
- val request1 = ResourceRequest(Resource(40), WorkerId.unspecified, HIGH, Relaxation.ANY)
- val request2 = ResourceRequest(Resource(20), WorkerId.unspecified, HIGH, Relaxation.ANY)
- scheduler.tell(RequestResource(appId, request1), mockAppMaster.ref)
- scheduler.tell(RequestResource(appId, request2), mockAppMaster.ref)
- scheduler.tell(ApplicationFinished(appId), mockAppMaster.ref)
- scheduler.tell(WorkerRegistered(workerId1, MasterInfo.empty), mockWorker1.ref)
- scheduler.tell(ResourceUpdate(mockWorker1.ref, workerId1, Resource(100)), mockWorker1.ref)
- mockAppMaster.expectNoMsg(5.seconds)
- }
- }
-
- def sameElement(left: ResourceAllocated, right: ResourceAllocated): Boolean = {
- left.allocations.sortBy(_.workerId).sameElements(right.allocations.sortBy(_.workerId))
- }
-
- "The resource request with higher priority" should {
- "be handled first" in {
- val scheduler = system.actorOf(Props(classOf[PriorityScheduler]))
- val request1 = ResourceRequest(Resource(40), WorkerId.unspecified, LOW, Relaxation.ANY)
- val request2 = ResourceRequest(Resource(20), WorkerId.unspecified, NORMAL, Relaxation.ANY)
- val request3 = ResourceRequest(Resource(30), WorkerId.unspecified, HIGH, Relaxation.ANY)
-
- scheduler.tell(RequestResource(appId, request1), mockAppMaster.ref)
- scheduler.tell(RequestResource(appId, request1), mockAppMaster.ref)
- scheduler.tell(RequestResource(appId, request2), mockAppMaster.ref)
- scheduler.tell(RequestResource(appId, request3), mockAppMaster.ref)
- scheduler.tell(WorkerRegistered(workerId1, MasterInfo.empty), mockWorker1.ref)
- scheduler.tell(ResourceUpdate(mockWorker1.ref, workerId1, Resource(100)), mockWorker1.ref)
-
- var expect = ResourceAllocated(
- Array(ResourceAllocation(Resource(30), mockWorker1.ref, workerId1)))
- mockAppMaster.expectMsgPF(5.seconds) {
- case request: ResourceAllocated if sameElement(request, expect) => Unit
- }
-
- expect = ResourceAllocated(
- Array(ResourceAllocation(Resource(20), mockWorker1.ref, workerId1)))
- mockAppMaster.expectMsgPF(5.seconds) {
- case request: ResourceAllocated if sameElement(request, expect) => Unit
- }
-
- expect = ResourceAllocated(
- Array(ResourceAllocation(Resource(40), mockWorker1.ref, workerId1)))
- mockAppMaster.expectMsgPF(5.seconds) {
- case request: ResourceAllocated if sameElement(request, expect) => Unit
- }
-
- scheduler.tell(WorkerRegistered(workerId2, MasterInfo.empty), mockWorker2.ref)
- scheduler.tell(ResourceUpdate(mockWorker1.ref, workerId1, Resource.empty), mockWorker1.ref)
- scheduler.tell(ResourceUpdate(mockWorker2.ref, workerId2, Resource(100)), mockWorker2.ref)
-
- expect = ResourceAllocated(
- Array(ResourceAllocation(Resource(40), mockWorker2.ref, workerId2)))
- mockAppMaster.expectMsgPF(5.seconds) {
- case request: ResourceAllocated if sameElement(request, expect) => Unit
- }
- }
- }
-
- "The resource request which delivered earlier" should {
- "be handled first if the priorities are the same" in {
- val scheduler = system.actorOf(Props(classOf[PriorityScheduler]))
- val request1 = ResourceRequest(Resource(40), WorkerId.unspecified, HIGH, Relaxation.ANY)
- val request2 = ResourceRequest(Resource(20), WorkerId.unspecified, HIGH, Relaxation.ANY)
- scheduler.tell(RequestResource(appId, request1), mockAppMaster.ref)
- scheduler.tell(RequestResource(appId, request2), mockAppMaster.ref)
- scheduler.tell(WorkerRegistered(workerId1, MasterInfo.empty), mockWorker1.ref)
- scheduler.tell(ResourceUpdate(mockWorker1.ref, workerId1, Resource(100)), mockWorker1.ref)
-
- var expect = ResourceAllocated(
- Array(ResourceAllocation(Resource(40), mockWorker1.ref, workerId1)))
- mockAppMaster.expectMsgPF(5.seconds) {
- case request: ResourceAllocated if sameElement(request, expect) => Unit
- }
- expect = ResourceAllocated(
- Array(ResourceAllocation(Resource(20), mockWorker1.ref, workerId1)))
- mockAppMaster.expectMsgPF(5.seconds) {
- case request: ResourceAllocated if sameElement(request, expect) => Unit
- }
- }
- }
-
- "The PriorityScheduler" should {
- "handle the resource request with different relaxation" in {
- val scheduler = system.actorOf(Props(classOf[PriorityScheduler]))
- val request1 = ResourceRequest(Resource(40), workerId2, HIGH, Relaxation.SPECIFICWORKER)
- val request2 = ResourceRequest(Resource(20), workerId1, NORMAL, Relaxation.SPECIFICWORKER)
-
- scheduler.tell(RequestResource(appId, request1), mockAppMaster.ref)
- scheduler.tell(RequestResource(appId, request2), mockAppMaster.ref)
- scheduler.tell(WorkerRegistered(workerId1, MasterInfo.empty), mockWorker1.ref)
- scheduler.tell(ResourceUpdate(mockWorker1.ref, workerId1, Resource(100)), mockWorker1.ref)
-
- var expect = ResourceAllocated(
- Array(ResourceAllocation(Resource(20), mockWorker1.ref, workerId1)))
- mockAppMaster.expectMsgPF(5.seconds) {
- case request: ResourceAllocated if sameElement(request, expect) => Unit
- }
-
- scheduler.tell(WorkerRegistered(workerId2, MasterInfo.empty), mockWorker2.ref)
- scheduler.tell(ResourceUpdate(mockWorker2.ref, workerId2, Resource(100)), mockWorker2.ref)
-
- expect = ResourceAllocated(
- Array(ResourceAllocation(Resource(40), mockWorker2.ref, workerId2)))
- mockAppMaster.expectMsgPF(5.seconds) {
- case request: ResourceAllocated if sameElement(request, expect) => Unit
- }
-
- val request3 = ResourceRequest(
- Resource(30), WorkerId.unspecified, NORMAL, Relaxation.ANY, executorNum = 2)
- scheduler.tell(RequestResource(appId, request3), mockAppMaster.ref)
-
- expect = ResourceAllocated(Array(
- ResourceAllocation(Resource(15), mockWorker1.ref, workerId1),
- ResourceAllocation(Resource(15), mockWorker2.ref, workerId2)))
- mockAppMaster.expectMsgPF(5.seconds) {
- case request: ResourceAllocated if sameElement(request, expect) => Unit
- }
-
- // We have to manually update the resource on each worker
- scheduler.tell(ResourceUpdate(mockWorker1.ref, workerId1, Resource(65)), mockWorker1.ref)
- scheduler.tell(ResourceUpdate(mockWorker2.ref, workerId2, Resource(45)), mockWorker2.ref)
- val request4 = ResourceRequest(Resource(60), WorkerId(0, 0L), NORMAL, Relaxation.ONEWORKER)
- scheduler.tell(RequestResource(appId, request4), mockAppMaster.ref)
-
- expect = ResourceAllocated(
- Array(ResourceAllocation(Resource(60), mockWorker1.ref, workerId1)))
- mockAppMaster.expectMsgPF(5.seconds) {
- case request: ResourceAllocated if sameElement(request, expect) => Unit
- }
- }
- }
-
- "The PriorityScheduler" should {
- "handle the resource request with different executor number" in {
- val scheduler = system.actorOf(Props(classOf[PriorityScheduler]))
- scheduler.tell(WorkerRegistered(workerId1, MasterInfo.empty), mockWorker1.ref)
- scheduler.tell(ResourceUpdate(mockWorker1.ref, workerId1, Resource(100)), mockWorker1.ref)
- scheduler.tell(WorkerRegistered(workerId2, MasterInfo.empty), mockWorker2.ref)
- scheduler.tell(ResourceUpdate(mockWorker2.ref, workerId2, Resource(100)), mockWorker2.ref)
-
- // By default, the request requires only one executor
- val request2 = ResourceRequest(Resource(20), WorkerId.unspecified)
- scheduler.tell(RequestResource(appId, request2), mockAppMaster.ref)
- val allocations2 = mockAppMaster.receiveN(1).head.asInstanceOf[ResourceAllocated]
- assert(allocations2.allocations.length == 1)
- assert(allocations2.allocations.head.resource == Resource(20))
-
- val request3 = ResourceRequest(Resource(24), WorkerId.unspecified, executorNum = 3)
- scheduler.tell(RequestResource(appId, request3), mockAppMaster.ref)
- val allocations3 = mockAppMaster.receiveN(1).head.asInstanceOf[ResourceAllocated]
- assert(allocations3.allocations.length == 3)
- assert(allocations3.allocations.forall(_.resource == Resource(8)))
-
- // The total available resource can not satisfy the requirements with executor number
- scheduler.tell(ResourceUpdate(mockWorker1.ref, workerId1, Resource(30)), mockWorker1.ref)
- scheduler.tell(ResourceUpdate(mockWorker2.ref, workerId2, Resource(30)), mockWorker2.ref)
- val request4 = ResourceRequest(Resource(60), WorkerId.unspecified, executorNum = 3)
- scheduler.tell(RequestResource(appId, request4), mockAppMaster.ref)
- val allocations4 = mockAppMaster.receiveN(1).head.asInstanceOf[ResourceAllocated]
- assert(allocations4.allocations.length == 2)
- assert(allocations4.allocations.forall(_.resource == Resource(20)))
-
- // When new resources are available, the remaining request will be satisfied
- scheduler.tell(ResourceUpdate(mockWorker1.ref, workerId1, Resource(40)), mockWorker1.ref)
- val allocations5 = mockAppMaster.receiveN(1).head.asInstanceOf[ResourceAllocated]
- assert(allocations5.allocations.length == 1)
- assert(allocations4.allocations.forall(_.resource == Resource(20)))
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/test/scala/io/gearpump/cluster/worker/WorkerSpec.scala
----------------------------------------------------------------------
diff --git a/daemon/src/test/scala/io/gearpump/cluster/worker/WorkerSpec.scala b/daemon/src/test/scala/io/gearpump/cluster/worker/WorkerSpec.scala
deleted file mode 100644
index 46e8d37..0000000
--- a/daemon/src/test/scala/io/gearpump/cluster/worker/WorkerSpec.scala
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.cluster.worker
-
-import scala.concurrent.Await
-import scala.concurrent.duration._
-
-import akka.actor.{ActorSystem, PoisonPill, Props}
-import akka.testkit.TestProbe
-import com.typesafe.config.{Config, ConfigFactory}
-import org.scalatest._
-
-import io.gearpump.cluster.AppMasterToWorker.{ChangeExecutorResource, LaunchExecutor, ShutdownExecutor}
-import io.gearpump.cluster.MasterToWorker.{UpdateResourceFailed, WorkerRegistered}
-import io.gearpump.cluster.WorkerToAppMaster.{ExecutorLaunchRejected, ShutdownExecutorFailed, ShutdownExecutorSucceed}
-import io.gearpump.cluster.WorkerToMaster.{RegisterNewWorker, RegisterWorker, ResourceUpdate}
-import io.gearpump.cluster.master.Master.MasterInfo
-import io.gearpump.cluster.scheduler.Resource
-import io.gearpump.cluster.{ExecutorJVMConfig, MasterHarness, TestUtil}
-import io.gearpump.util.{ActorSystemBooter, ActorUtil, Constants}
-
-class WorkerSpec extends WordSpec with Matchers with BeforeAndAfterEach with MasterHarness {
- override def config: Config = TestUtil.DEFAULT_CONFIG
-
- val appId = 1
- val workerId: WorkerId = WorkerId(1, 0L)
- val executorId = 1
- var masterProxy: TestProbe = null
- var mockMaster: TestProbe = null
- var client: TestProbe = null
- val workerSlots = 50
-
- override def beforeEach(): Unit = {
- startActorSystem()
- mockMaster = TestProbe()(getActorSystem)
- masterProxy = TestProbe()(getActorSystem)
- client = TestProbe()(getActorSystem)
- }
-
- override def afterEach(): Unit = {
- shutdownActorSystem()
- }
-
- "The new started worker" should {
- "kill itself if no response from Master after registering" in {
- val worker = getActorSystem.actorOf(Props(classOf[Worker], mockMaster.ref))
- mockMaster watch worker
- mockMaster.expectMsg(RegisterNewWorker)
- mockMaster.expectTerminated(worker, 60.seconds)
- }
- }
-
- "Worker" should {
- "init its resource from the gearpump config" in {
- val config = ConfigFactory.parseString(s"${Constants.GEARPUMP_WORKER_SLOTS} = $workerSlots").
- withFallback(TestUtil.DEFAULT_CONFIG)
- val workerSystem = ActorSystem("WorkerSystem", config)
- val worker = workerSystem.actorOf(Props(classOf[Worker], mockMaster.ref))
- mockMaster watch worker
- mockMaster.expectMsg(RegisterNewWorker)
-
- worker.tell(WorkerRegistered(workerId, MasterInfo(mockMaster.ref)), mockMaster.ref)
- mockMaster.expectMsg(ResourceUpdate(worker, workerId, Resource(workerSlots)))
-
- worker.tell(
- UpdateResourceFailed("Test resource update failed", new Exception()), mockMaster.ref)
- mockMaster.expectTerminated(worker, 5.seconds)
- workerSystem.terminate()
- Await.result(workerSystem.whenTerminated, Duration.Inf)
- }
- }
-
- "Worker" should {
- "update its remaining resource when launching and shutting down executors" in {
- val worker = getActorSystem.actorOf(Props(classOf[Worker], masterProxy.ref))
- masterProxy.expectMsg(RegisterNewWorker)
-
- worker.tell(WorkerRegistered(workerId, MasterInfo(mockMaster.ref)), mockMaster.ref)
- mockMaster.expectMsg(ResourceUpdate(worker, workerId, Resource(100)))
-
- val executorName = ActorUtil.actorNameForExecutor(appId, executorId)
- // This is an actor path which the ActorSystemBooter will report back to,
- // not needed in this test
- val reportBack = "dummy"
- val executionContext = ExecutorJVMConfig(Array.empty[String],
- getActorSystem.settings.config.getString(Constants.GEARPUMP_APPMASTER_ARGS).split(" "),
- classOf[ActorSystemBooter].getName, Array(executorName, reportBack), None,
- username = "user")
-
- // Test LaunchExecutor
- worker.tell(LaunchExecutor(appId, executorId, Resource(101), executionContext),
- mockMaster.ref)
- mockMaster.expectMsg(ExecutorLaunchRejected("There is no free resource on this machine"))
-
- worker.tell(LaunchExecutor(appId, executorId, Resource(5), executionContext), mockMaster.ref)
- mockMaster.expectMsg(ResourceUpdate(worker, workerId, Resource(95)))
-
- worker.tell(ChangeExecutorResource(appId, executorId, Resource(2)), client.ref)
- mockMaster.expectMsg(ResourceUpdate(worker, workerId, Resource(98)))
-
- // Test terminationWatch
- worker.tell(ShutdownExecutor(appId, executorId, "Test shut down executor"), client.ref)
- mockMaster.expectMsg(ResourceUpdate(worker, workerId, Resource(100)))
- client.expectMsg(ShutdownExecutorSucceed(1, 1))
-
- worker.tell(ShutdownExecutor(appId, executorId + 1, "Test shut down executor"), client.ref)
- client.expectMsg(ShutdownExecutorFailed(
- s"Can not find executor ${executorId + 1} for app $appId"))
-
- mockMaster.ref ! PoisonPill
- masterProxy.expectMsg(RegisterWorker(workerId))
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/test/scala/io/gearpump/util/FileServerSpec.scala
----------------------------------------------------------------------
diff --git a/daemon/src/test/scala/io/gearpump/util/FileServerSpec.scala b/daemon/src/test/scala/io/gearpump/util/FileServerSpec.scala
deleted file mode 100644
index 66c7c1d..0000000
--- a/daemon/src/test/scala/io/gearpump/util/FileServerSpec.scala
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.util
-
-import java.io.File
-import java.util.concurrent.TimeUnit
-import scala.concurrent.Await
-import scala.concurrent.duration.Duration
-
-import akka.actor.ActorSystem
-import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}
-
-import io.gearpump.cluster.TestUtil
-import io.gearpump.google.common.io.Files
-import io.gearpump.jarstore.FilePath
-import io.gearpump.util.FileServer._
-
-class FileServerSpec extends WordSpecLike with Matchers with BeforeAndAfterAll {
-
- implicit val timeout = akka.util.Timeout(25, TimeUnit.SECONDS)
- val host = "localhost"
- private val LOG = LogUtil.getLogger(getClass)
-
- var system: ActorSystem = null
-
- override def afterAll {
- if (null != system) {
- system.terminate()
- Await.result(system.whenTerminated, Duration.Inf)
- }
- }
-
- override def beforeAll {
- val config = TestUtil.DEFAULT_CONFIG
- system = ActorSystem("FileServerSpec", config)
- }
-
- private def save(client: Client, data: Array[Byte]): FilePath = {
- val file = File.createTempFile("fileserverspec", "test")
- FileUtils.writeByteArrayToFile(file, data)
- val future = client.upload(file)
- import scala.concurrent.duration._
- val path = Await.result(future, 30.seconds)
- file.delete()
- path
- }
-
- private def get(client: Client, remote: FilePath): Array[Byte] = {
- val file = File.createTempFile("fileserverspec", "test")
- val future = client.download(remote, file)
- import scala.concurrent.duration._
- val data = Await.result(future, 10.seconds)
-
- val bytes = FileUtils.readFileToByteArray(file)
- file.delete()
- bytes
- }
-
- "The file server" should {
- "serve the data previously stored" in {
-
- val rootDir = Files.createTempDir()
-
- val server = new FileServer(system, host, 0, rootDir)
- val port = Await.result((server.start), Duration(25, TimeUnit.SECONDS))
-
- LOG.info("start test web server on port " + port)
-
- val sizes = List(1, 100, 1000000, 50000000)
- val client = new Client(system, host, port.port)
-
- sizes.foreach { size =>
- val bytes = randomBytes(size)
- val url = s"http://$host:${port.port}/$size"
- val remote = save(client, bytes)
- val fetchedBytes = get(client, remote)
- assert(fetchedBytes sameElements bytes, s"fetch data is coruppted, $url, $rootDir")
- }
- server.stop
- rootDir.delete()
- }
- }
-
- "The file server" should {
- "handle missed file" in {
-
- val rootDir = Files.createTempDir()
-
- val server = new FileServer(system, host, 0, rootDir)
- val port = Await.result((server.start), Duration(25, TimeUnit.SECONDS))
-
- val client = new Client(system, host, port.port)
- val fetchedBytes = get(client, FilePath("noexist"))
- assert(fetchedBytes.length == 0)
- rootDir.delete()
- }
- }
-
- private def randomBytes(size: Int): Array[Byte] = {
- val bytes = new Array[Byte](size)
- (new java.util.Random()).nextBytes(bytes)
- bytes
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/test/scala/org/apache/gearpump/cluster/MiniCluster.scala
----------------------------------------------------------------------
diff --git a/daemon/src/test/scala/org/apache/gearpump/cluster/MiniCluster.scala b/daemon/src/test/scala/org/apache/gearpump/cluster/MiniCluster.scala
new file mode 100644
index 0000000..a6b75cb
--- /dev/null
+++ b/daemon/src/test/scala/org/apache/gearpump/cluster/MiniCluster.scala
@@ -0,0 +1,74 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.cluster
+
+import scala.concurrent.duration.Duration
+import scala.concurrent.{Await, Future}
+
+import akka.actor.{Actor, ActorRef, ActorSystem, Props}
+import akka.pattern.ask
+import akka.testkit.TestActorRef
+import com.typesafe.config.ConfigValueFactory
+
+import org.apache.gearpump.cluster.AppMasterToMaster.GetAllWorkers
+import org.apache.gearpump.cluster.MasterToAppMaster.WorkerList
+import org.apache.gearpump.cluster.master.Master
+import org.apache.gearpump.cluster.worker.Worker
+import org.apache.gearpump.util.Constants
+
+class MiniCluster {
+ private val mockMasterIP = "127.0.0.1"
+
+ implicit val system = ActorSystem("system", TestUtil.MASTER_CONFIG.
+ withValue(Constants.NETTY_TCP_HOSTNAME, ConfigValueFactory.fromAnyRef(mockMasterIP)))
+
+ val (mockMaster, worker) = {
+ val master = system.actorOf(Props(classOf[Master]), "master")
+ val worker = system.actorOf(Props(classOf[Worker], master), "worker")
+
+ // Wait until worker register itself to master
+ waitUtilWorkerIsRegistered(master)
+ (master, worker)
+ }
+
+ def launchActor(props: Props): TestActorRef[Actor] = {
+ TestActorRef(props)
+ }
+
+ private def waitUtilWorkerIsRegistered(master: ActorRef): Unit = {
+ while (!isWorkerRegistered(master)) {}
+ }
+
+ private def isWorkerRegistered(master: ActorRef): Boolean = {
+ import scala.concurrent.duration._
+ implicit val dispatcher = system.dispatcher
+
+ implicit val futureTimeout = Constants.FUTURE_TIMEOUT
+
+ val workerListFuture = (master ? GetAllWorkers).asInstanceOf[Future[WorkerList]]
+
+ // Waits until the worker is registered.
+ val workers = Await.result[WorkerList](workerListFuture, 15.seconds)
+ workers.workers.size > 0
+ }
+
+ def shutDown(): Unit = {
+ system.terminate()
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/test/scala/org/apache/gearpump/cluster/main/MainSpec.scala
----------------------------------------------------------------------
diff --git a/daemon/src/test/scala/org/apache/gearpump/cluster/main/MainSpec.scala b/daemon/src/test/scala/org/apache/gearpump/cluster/main/MainSpec.scala
new file mode 100644
index 0000000..205bb49
--- /dev/null
+++ b/daemon/src/test/scala/org/apache/gearpump/cluster/main/MainSpec.scala
@@ -0,0 +1,189 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.main
+
+import scala.concurrent.Future
+import scala.util.{Success, Try}
+
+import com.typesafe.config.Config
+import org.scalatest._
+
+import org.apache.gearpump.cluster.ClientToMaster.{ResolveAppId, ShutdownApplication}
+import org.apache.gearpump.cluster.MasterToAppMaster.{AppMastersDataRequest, ReplayFromTimestampWindowTrailingEdge, _}
+import org.apache.gearpump.cluster.MasterToClient.{ReplayApplicationResult, ResolveAppIdResult, ShutdownApplicationResult}
+import org.apache.gearpump.cluster.WorkerToMaster.RegisterNewWorker
+import org.apache.gearpump.cluster.{MasterHarness, TestUtil}
+import org.apache.gearpump.util.Constants._
+import org.apache.gearpump.util.{Constants, LogUtil, Util}
+
+class MainSpec extends FlatSpec with Matchers with BeforeAndAfterEach with MasterHarness {
+
+ private val LOG = LogUtil.getLogger(getClass)
+
+ override def config: Config = TestUtil.DEFAULT_CONFIG
+
+ override def beforeEach(): Unit = {
+ startActorSystem()
+ }
+
+ override def afterEach(): Unit = {
+ shutdownActorSystem()
+ }
+
+ "Worker" should "register worker address to master when started." in {
+
+ val masterReceiver = createMockMaster()
+
+ val tempTestConf = convertTestConf(getHost, getPort)
+
+ val options = Array(
+ s"-D$GEARPUMP_CUSTOM_CONFIG_FILE=${tempTestConf.toString}",
+ s"-D${PREFER_IPV4}=true"
+ ) ++ getMasterListOption()
+
+ val worker = Util.startProcess(options,
+ getContextClassPath,
+ getMainClassName(Worker),
+ Array.empty)
+
+ try {
+ masterReceiver.expectMsg(PROCESS_BOOT_TIME, RegisterNewWorker)
+
+ tempTestConf.delete()
+ } finally {
+ worker.destroy()
+ }
+ }
+
+ // This UT fails a lot on Travis, temporarily delete it.
+ // "Master" should "accept worker RegisterNewWorker when started" in {
+ // val worker = TestProbe()(getActorSystem)
+ //
+ // val port = Util.findFreePort.get
+ //
+ // val masterConfig = Array(s"-D${Constants.GEARPUMP_CLUSTER_MASTERS}.0=127.0.0.1:$port",
+ // s"-D${Constants.GEARPUMP_HOSTNAME}=127.0.0.1")
+ //
+ // val masterProcess = Util.startProcess(masterConfig,
+ // getContextClassPath,
+ // getMainClassName(org.apache.gearpump.cluster.main.Master),
+ // Array("-ip", "127.0.0.1", "-port", port.toString))
+ //
+ // //wait for master process to be started
+ //
+ // try {
+ //
+ // val masterProxy = getActorSystem.actorOf(
+ // MasterProxy.props(List(HostPort("127.0.0.1", port))), "mainSpec")
+ //
+ // worker.send(masterProxy, RegisterNewWorker)
+ // worker.expectMsgType[WorkerRegistered](PROCESS_BOOT_TIME)
+ // } finally {
+ // masterProcess.destroy()
+ // }
+ // }
+
+ "Info" should "be started without exception" in {
+
+ val masterReceiver = createMockMaster()
+
+ Future {
+ org.apache.gearpump.cluster.main.Info.main(masterConfig, Array.empty)
+ }
+
+ masterReceiver.expectMsg(PROCESS_BOOT_TIME, AppMastersDataRequest)
+ masterReceiver.reply(AppMastersData(List(AppMasterData(AppMasterActive, 0, "appName"))))
+ }
+
+ "Kill" should "be started without exception" in {
+
+ val masterReceiver = createMockMaster()
+
+ Future {
+ Kill.main(masterConfig, Array("-appid", "0"))
+ }
+
+ masterReceiver.expectMsg(PROCESS_BOOT_TIME, ShutdownApplication(0))
+ masterReceiver.reply(ShutdownApplicationResult(Success(0)))
+ }
+
+ "Replay" should "be started without exception" in {
+
+ val masterReceiver = createMockMaster()
+
+ Future {
+ Replay.main(masterConfig, Array("-appid", "0"))
+ }
+
+ masterReceiver.expectMsgType[ResolveAppId](PROCESS_BOOT_TIME)
+ masterReceiver.reply(ResolveAppIdResult(Success(masterReceiver.ref)))
+ masterReceiver.expectMsgType[ReplayFromTimestampWindowTrailingEdge](PROCESS_BOOT_TIME)
+ masterReceiver.reply(ReplayApplicationResult(Success(0)))
+ }
+
+ "Local" should "be started without exception" in {
+ val port = Util.findFreePort().get
+ val options = Array(s"-D${Constants.GEARPUMP_CLUSTER_MASTERS}.0=$getHost:$port",
+ s"-D${Constants.GEARPUMP_HOSTNAME}=$getHost",
+ s"-D${PREFER_IPV4}=true")
+
+ val local = Util.startProcess(options,
+ getContextClassPath,
+ getMainClassName(Local),
+ Array.empty)
+
+ def retry(times: Int)(fn: => Boolean): Boolean = {
+
+ LOG.info(s"Local Test: Checking whether local port is available, remain times $times ..")
+
+ val result = fn
+ if (result || times <= 0) {
+ result
+ } else {
+ Thread.sleep(1000)
+ retry(times - 1)(fn)
+ }
+ }
+
+ try {
+ assert(retry(10)(isPortUsed("127.0.0.1", port)),
+ "local is not started successfully, as port is not used " + port)
+ } finally {
+ local.destroy()
+ }
+ }
+
+ "Gear" should "support app|info|kill|shell|replay" in {
+
+ val commands = Array("app", "info", "kill", "shell", "replay")
+
+ assert(Try(Gear.main(Array.empty)).isSuccess, "print help, no throw")
+
+ for (command <- commands) {
+ assert(Try(Gear.main(Array("-noexist"))).isFailure,
+ "pass unknown option, throw, command: " + command)
+ }
+
+ assert(Try(Gear.main(Array("unknownCommand"))).isFailure, "unknown command, throw ")
+
+ val tryThis = Try(Gear.main(Array("unknownCommand", "-noexist")))
+ assert(tryThis.isFailure, "unknown command, throw")
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/test/scala/org/apache/gearpump/cluster/main/MasterWatcherSpec.scala
----------------------------------------------------------------------
diff --git a/daemon/src/test/scala/org/apache/gearpump/cluster/main/MasterWatcherSpec.scala b/daemon/src/test/scala/org/apache/gearpump/cluster/main/MasterWatcherSpec.scala
new file mode 100644
index 0000000..e1ba8f6
--- /dev/null
+++ b/daemon/src/test/scala/org/apache/gearpump/cluster/main/MasterWatcherSpec.scala
@@ -0,0 +1,44 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.cluster.main
+
+import scala.concurrent.Await
+import scala.concurrent.duration._
+
+import akka.actor.{ActorSystem, Props}
+import akka.testkit.TestProbe
+import com.typesafe.config.Config
+import org.scalatest.{FlatSpec, Matchers}
+
+import org.apache.gearpump.cluster.TestUtil
+
+class MasterWatcherSpec extends FlatSpec with Matchers {
+ def config: Config = TestUtil.MASTER_CONFIG
+
+ "MasterWatcher" should "kill itself when can not get a quorum" in {
+ val system = ActorSystem("ForMasterWatcher", config)
+
+ val actorWatcher = TestProbe()(system)
+
+ val masterWatcher = system.actorOf(Props(classOf[MasterWatcher], "watcher"))
+ actorWatcher watch masterWatcher
+ actorWatcher.expectTerminated(masterWatcher, 5.seconds)
+ system.terminate()
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/test/scala/org/apache/gearpump/cluster/master/AppManagerSpec.scala
----------------------------------------------------------------------
diff --git a/daemon/src/test/scala/org/apache/gearpump/cluster/master/AppManagerSpec.scala b/daemon/src/test/scala/org/apache/gearpump/cluster/master/AppManagerSpec.scala
new file mode 100644
index 0000000..ae0ebcd
--- /dev/null
+++ b/daemon/src/test/scala/org/apache/gearpump/cluster/master/AppManagerSpec.scala
@@ -0,0 +1,181 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.master
+
+import scala.util.Success
+
+import akka.actor.{Actor, ActorRef, Props}
+import akka.testkit.TestProbe
+import com.typesafe.config.Config
+import org.scalatest.{BeforeAndAfterEach, FlatSpec, Matchers}
+
+import org.apache.gearpump.cluster.AppMasterToMaster.{AppDataSaved, _}
+import org.apache.gearpump.cluster.ClientToMaster.{ResolveAppId, ShutdownApplication, SubmitApplication}
+import org.apache.gearpump.cluster.MasterToAppMaster.{AppMasterData, AppMasterRegistered, AppMastersData, AppMastersDataRequest, _}
+import org.apache.gearpump.cluster.MasterToClient.{ResolveAppIdResult, ShutdownApplicationResult, SubmitApplicationResult}
+import org.apache.gearpump.cluster.appmaster.{AppMasterRuntimeInfo, ApplicationState}
+import org.apache.gearpump.cluster.master.AppManager._
+import org.apache.gearpump.cluster.master.InMemoryKVService.{GetKV, GetKVSuccess, PutKV, PutKVSuccess}
+import org.apache.gearpump.cluster.{TestUtil, _}
+import org.apache.gearpump.util.LogUtil
+
+class AppManagerSpec extends FlatSpec with Matchers with BeforeAndAfterEach with MasterHarness {
+ var kvService: TestProbe = null
+ var haService: TestProbe = null
+ var appLauncher: TestProbe = null
+ var appManager: ActorRef = null
+ private val LOG = LogUtil.getLogger(getClass)
+
+ override def config: Config = TestUtil.DEFAULT_CONFIG
+
+ override def beforeEach(): Unit = {
+ startActorSystem()
+ kvService = TestProbe()(getActorSystem)
+ appLauncher = TestProbe()(getActorSystem)
+
+ appManager = getActorSystem.actorOf(Props(new AppManager(kvService.ref,
+ new DummyAppMasterLauncherFactory(appLauncher))))
+ kvService.expectMsgType[GetKV]
+ kvService.reply(GetKVSuccess(MASTER_STATE, MasterState(0, Map.empty, Map.empty)))
+ }
+
+ override def afterEach(): Unit = {
+ shutdownActorSystem()
+ }
+
+ "AppManager" should "handle appmaster message correctly" in {
+ val appMaster = TestProbe()(getActorSystem)
+ val worker = TestProbe()(getActorSystem)
+
+ val register = RegisterAppMaster(appMaster.ref, AppMasterRuntimeInfo(0, "appName"))
+ appMaster.send(appManager, register)
+ appMaster.expectMsgType[AppMasterRegistered]
+ }
+
+ "DataStoreService" should "support Put and Get" in {
+ val appMaster = TestProbe()(getActorSystem)
+ appMaster.send(appManager, SaveAppData(0, "key", 1))
+ kvService.expectMsgType[PutKV]
+ kvService.reply(PutKVSuccess)
+ appMaster.expectMsg(AppDataSaved)
+
+ appMaster.send(appManager, GetAppData(0, "key"))
+ kvService.expectMsgType[GetKV]
+ kvService.reply(GetKVSuccess("key", 1))
+ appMaster.expectMsg(GetAppDataResult("key", 1))
+ }
+
+ "AppManager" should "support application submission and shutdown" in {
+ testClientSubmission(withRecover = false)
+ }
+
+ "AppManager" should "support application submission and recover if appmaster dies" in {
+ LOG.info("=================testing recover==============")
+ testClientSubmission(withRecover = true)
+ }
+
+ "AppManager" should "handle client message correctly" in {
+ val mockClient = TestProbe()(getActorSystem)
+ mockClient.send(appManager, ShutdownApplication(1))
+ assert(mockClient.receiveN(1).head.asInstanceOf[ShutdownApplicationResult].appId.isFailure)
+
+ mockClient.send(appManager, ResolveAppId(1))
+ assert(mockClient.receiveN(1).head.asInstanceOf[ResolveAppIdResult].appMaster.isFailure)
+
+ mockClient.send(appManager, AppMasterDataRequest(1))
+ mockClient.expectMsg(AppMasterData(AppMasterNonExist))
+ }
+
+ "AppManager" should "reject the application submission if the app name already existed" in {
+ val app = TestUtil.dummyApp
+ val submit = SubmitApplication(app, None, "username")
+ val client = TestProbe()(getActorSystem)
+ val appMaster = TestProbe()(getActorSystem)
+ val worker = TestProbe()(getActorSystem)
+ val appId = 1
+
+ client.send(appManager, submit)
+
+ kvService.expectMsgType[PutKV]
+ appLauncher.expectMsg(LauncherStarted(appId))
+ appMaster.send(appManager, RegisterAppMaster(appMaster.ref,
+ AppMasterRuntimeInfo(appId, app.name)))
+ appMaster.expectMsgType[AppMasterRegistered]
+
+ client.send(appManager, submit)
+ assert(client.receiveN(1).head.asInstanceOf[SubmitApplicationResult].appId.isFailure)
+ }
+
+ def testClientSubmission(withRecover: Boolean): Unit = {
+ val app = TestUtil.dummyApp
+ val submit = SubmitApplication(app, None, "username")
+ val client = TestProbe()(getActorSystem)
+ val appMaster = TestProbe()(getActorSystem)
+ val worker = TestProbe()(getActorSystem)
+ val appId = 1
+
+ client.send(appManager, submit)
+
+ kvService.expectMsgType[PutKV]
+ appLauncher.expectMsg(LauncherStarted(appId))
+ appMaster.send(appManager, RegisterAppMaster(appMaster.ref,
+ AppMasterRuntimeInfo(appId, app.name)))
+ kvService.expectMsgType[PutKV]
+ appMaster.expectMsgType[AppMasterRegistered]
+
+ client.send(appManager, ResolveAppId(appId))
+ client.expectMsg(ResolveAppIdResult(Success(appMaster.ref)))
+
+ client.send(appManager, AppMastersDataRequest)
+ client.expectMsgType[AppMastersData]
+
+ client.send(appManager, AppMasterDataRequest(appId, false))
+ client.expectMsgType[AppMasterData]
+
+ if (!withRecover) {
+ client.send(appManager, ShutdownApplication(appId))
+ client.expectMsg(ShutdownApplicationResult(Success(appId)))
+ } else {
+ // Do recovery
+ getActorSystem.stop(appMaster.ref)
+ kvService.expectMsgType[GetKV]
+ val appState = ApplicationState(appId, "application1", 1, app, None, "username", null)
+ kvService.reply(GetKVSuccess(APP_STATE, appState))
+ appLauncher.expectMsg(LauncherStarted(appId))
+ }
+ }
+}
+
+class DummyAppMasterLauncherFactory(test: TestProbe) extends AppMasterLauncherFactory {
+
+ override def props(appId: Int, executorId: Int, app: AppDescription, jar: Option[AppJar],
+ username: String, master: ActorRef, client: Option[ActorRef]): Props = {
+ Props(new DummyAppMasterLauncher(test, appId))
+ }
+}
+
+class DummyAppMasterLauncher(test: TestProbe, appId: Int) extends Actor {
+
+ test.ref ! LauncherStarted(appId)
+ override def receive: Receive = {
+ case any: Any => test.ref forward any
+ }
+}
+
+case class LauncherStarted(appId: Int)
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/test/scala/org/apache/gearpump/cluster/master/InMemoryKVServiceSpec.scala
----------------------------------------------------------------------
diff --git a/daemon/src/test/scala/org/apache/gearpump/cluster/master/InMemoryKVServiceSpec.scala b/daemon/src/test/scala/org/apache/gearpump/cluster/master/InMemoryKVServiceSpec.scala
new file mode 100644
index 0000000..325a484
--- /dev/null
+++ b/daemon/src/test/scala/org/apache/gearpump/cluster/master/InMemoryKVServiceSpec.scala
@@ -0,0 +1,69 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.master
+
+import scala.concurrent.duration._
+
+import akka.actor.Props
+import akka.testkit.TestProbe
+import com.typesafe.config.Config
+import org.scalatest.{BeforeAndAfterEach, FlatSpec, Matchers}
+
+import org.apache.gearpump.cluster.master.InMemoryKVService._
+import org.apache.gearpump.cluster.{MasterHarness, TestUtil}
+
+class InMemoryKVServiceSpec
+ extends FlatSpec with Matchers with BeforeAndAfterEach with MasterHarness {
+
+ override def beforeEach(): Unit = {
+ startActorSystem()
+ }
+
+ override def afterEach(): Unit = {
+ shutdownActorSystem()
+ }
+
+ override def config: Config = TestUtil.MASTER_CONFIG
+
+ "KVService" should "get, put, delete correctly" in {
+ val system = getActorSystem
+ val kvService = system.actorOf(Props(new InMemoryKVService()))
+ val group = "group"
+
+ val client = TestProbe()(system)
+
+ client.send(kvService, PutKV(group, "key", 1))
+ client.expectMsg(PutKVSuccess)
+
+ client.send(kvService, PutKV(group, "key", 2))
+ client.expectMsg(PutKVSuccess)
+
+ client.send(kvService, GetKV(group, "key"))
+ client.expectMsg(GetKVSuccess("key", 2))
+
+ client.send(kvService, DeleteKVGroup(group))
+
+ // After DeleteGroup, it no longer accept Get and Put message for this group.
+ client.send(kvService, GetKV(group, "key"))
+ client.expectNoMsg(3.seconds)
+
+ client.send(kvService, PutKV(group, "key", 3))
+ client.expectNoMsg(3.seconds)
+ }
+}
[09/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/source/DataSourceTask.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/source/DataSourceTask.scala b/streaming/src/main/scala/io/gearpump/streaming/source/DataSourceTask.scala
deleted file mode 100644
index eab74aa..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/source/DataSourceTask.scala
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.source
-
-import io.gearpump._
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.task.{StartTime, Task, TaskContext}
-
-object DataSourceTask {
- val DATA_SOURCE = "data_source"
-}
-
-/**
- * Default Task container for [[io.gearpump.streaming.source.DataSource]] that
- * reads from DataSource in batch
- * See [[io.gearpump.streaming.source.DataSourceProcessor]] for its usage
- *
- * DataSourceTask calls:
- * - `DataSource.open()` in `onStart` and pass in [[io.gearpump.streaming.task.TaskContext]]
- * and application start time
- * - `DataSource.read()` in each `onNext`, which reads a batch of messages
- * - `DataSource.close()` in `onStop`
- */
-class DataSourceTask(context: TaskContext, conf: UserConfig) extends Task(context, conf) {
- import io.gearpump.streaming.source.DataSourceTask._
-
- private val source = conf.getValue[DataSource](DATA_SOURCE).get
- private val batchSize = conf.getInt(DataSourceConfig.SOURCE_READ_BATCH_SIZE).getOrElse(1000)
- private var startTime = 0L
-
- override def onStart(newStartTime: StartTime): Unit = {
- startTime = newStartTime.startTime
- LOG.info(s"opening data source at $startTime")
- source.open(context, startTime)
- self ! Message("start", System.currentTimeMillis())
- }
-
- override def onNext(message: Message): Unit = {
- 0.until(batchSize).foreach { _ =>
- Option(source.read()).foreach(context.output)
- }
- self ! Message("continue", System.currentTimeMillis())
- }
-
- override def onStop(): Unit = {
- LOG.info("closing data source...")
- source.close()
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/source/DefaultTimeStampFilter.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/source/DefaultTimeStampFilter.scala b/streaming/src/main/scala/io/gearpump/streaming/source/DefaultTimeStampFilter.scala
deleted file mode 100644
index b7d4e90..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/source/DefaultTimeStampFilter.scala
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.source
-
-import io.gearpump.streaming.transaction.api.TimeStampFilter
-import io.gearpump.{Message, TimeStamp}
-
-/**
- * TimeStampFilter filters out messages which have obsolete (smaller) timestamp.
- */
-class DefaultTimeStampFilter extends TimeStampFilter {
- override def filter(msg: Message, predicate: TimeStamp): Option[Message] = {
- Option(msg).find(_.timestamp >= predicate)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/state/api/Monoid.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/state/api/Monoid.scala b/streaming/src/main/scala/io/gearpump/streaming/state/api/Monoid.scala
deleted file mode 100644
index dfe3e93..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/state/api/Monoid.scala
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.state.api
-
-trait Monoid[T] extends java.io.Serializable {
- def plus(l: T, r: T): T
- def zero: T
-}
-
-trait Group[T] extends Monoid[T] {
- def minus(l: T, r: T): T
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/state/api/MonoidState.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/state/api/MonoidState.scala b/streaming/src/main/scala/io/gearpump/streaming/state/api/MonoidState.scala
deleted file mode 100644
index 238eab4..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/state/api/MonoidState.scala
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.state.api
-
-import io.gearpump.TimeStamp
-
-/**
- * MonoidState uses Algebird Monoid to aggregate state
- *
- * on start, state value is initialized to monoid.zero
- * on each new message, existing state value is aggregated with
- * the incoming value using monoid.plus to get a new state value
- */
-abstract class MonoidState[T](monoid: Monoid[T]) extends PersistentState[T] {
- // Left state updated by messages before checkpoint time
- private[state] var left: T = monoid.zero
- // Right state updated by message after checkpoint time
- private[state] var right: T = monoid.zero
-
- protected var checkpointTime = Long.MaxValue
-
- override def get: Option[T] = Option(monoid.plus(left, right))
-
- override def setNextCheckpointTime(nextCheckpointTime: TimeStamp): Unit = {
- checkpointTime = nextCheckpointTime
- }
-
- protected def updateState(timestamp: TimeStamp, t: T): Unit = {
- if (timestamp < checkpointTime) {
- left = monoid.plus(left, t)
- } else {
- right = monoid.plus(right, t)
- }
- }
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/state/api/PersistentState.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/state/api/PersistentState.scala b/streaming/src/main/scala/io/gearpump/streaming/state/api/PersistentState.scala
deleted file mode 100644
index f1b923a..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/state/api/PersistentState.scala
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.state.api
-
-import io.gearpump._
-
-/**
- * PersistentState is part of the transaction API
- *
- * Users could get transaction support from the framework by
- * conforming to PersistentState APIs and extending PersistentTask
- * to manage the state
- */
-trait PersistentState[T] {
-
- /**
- * Recovers state to a previous checkpoint
- * usually invoked by the framework
- */
- def recover(timestamp: TimeStamp, bytes: Array[Byte]): Unit
-
- /**
- * Updates state on a new message
- * this is invoked by user
- */
- def update(timestamp: TimeStamp, t: T): Unit
-
- /**
- * Sets next checkpoint time
- * should be invoked by the framework
- */
- def setNextCheckpointTime(timeStamp: TimeStamp): Unit
-
- /**
- * Gets a binary snapshot of state
- * usually invoked by the framework
- */
- def checkpoint(): Array[Byte]
-
- /**
- * Unwraps the raw value of state
- */
- def get: Option[T]
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/state/api/PersistentTask.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/state/api/PersistentTask.scala b/streaming/src/main/scala/io/gearpump/streaming/state/api/PersistentTask.scala
deleted file mode 100644
index a8a5d5d..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/state/api/PersistentTask.scala
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.state.api
-
-import java.util.concurrent.TimeUnit
-import scala.concurrent.duration.FiniteDuration
-
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.state.impl.{CheckpointManager, PersistentStateConfig}
-import io.gearpump.streaming.task.{ReportCheckpointClock, StartTime, Task, TaskContext}
-import io.gearpump.streaming.transaction.api.CheckpointStoreFactory
-import io.gearpump.util.LogUtil
-import io.gearpump.{Message, TimeStamp}
-
-object PersistentTask {
- val CHECKPOINT = Message("checkpoint")
- val LOG = LogUtil.getLogger(getClass)
-}
-
-/**
- * PersistentTask is part of the transaction API
- *
- * Users should extend this task if they want to get transaction support
- * from the framework
- */
-abstract class PersistentTask[T](taskContext: TaskContext, conf: UserConfig)
- extends Task(taskContext, conf) {
- import taskContext._
-
- import io.gearpump.streaming.state.api.PersistentTask._
-
- val checkpointStoreFactory = conf.getValue[CheckpointStoreFactory](
- PersistentStateConfig.STATE_CHECKPOINT_STORE_FACTORY).get
- val checkpointStore = checkpointStoreFactory.getCheckpointStore(conf, taskContext)
- val checkpointInterval = conf.getLong(PersistentStateConfig.STATE_CHECKPOINT_INTERVAL_MS).get
- val checkpointManager = new CheckpointManager(checkpointInterval, checkpointStore)
- // System time interval to attempt checkpoint
- private val checkpointAttemptInterval = 1000L
-
- /**
- * Subclass should override this method to pass in a PersistentState. the framework has already
- * offered two states:
- * - NonWindowState: state with no time or other boundary
- * - WindowState: each state is bounded by a time window
- */
- def persistentState: PersistentState[T]
-
- /**
- * Subclass should override this method to specify how a new message should update state
- */
- def processMessage(state: PersistentState[T], message: Message): Unit
-
- /** Persistent state that will be stored (by checkpointing) automatically to storage like HDFS */
- val state = persistentState
-
- final override def onStart(startTime: StartTime): Unit = {
- val timestamp = startTime.startTime
- checkpointManager
- .recover(timestamp)
- .foreach(state.recover(timestamp, _))
-
- reportCheckpointClock(timestamp)
- scheduleCheckpoint(checkpointAttemptInterval)
- }
-
- final override def onNext(message: Message): Unit = {
- message match {
- case CHECKPOINT =>
- val upstreamMinClock = taskContext.upstreamMinClock
- if (checkpointManager.shouldCheckpoint(upstreamMinClock)) {
- checkpointManager.getCheckpointTime.foreach { checkpointTime =>
- val serialized = state.checkpoint()
- checkpointManager.checkpoint(checkpointTime, serialized)
- .foreach(state.setNextCheckpointTime)
- taskContext.output(Message(serialized, checkpointTime))
- reportCheckpointClock(checkpointTime)
- }
- }
- scheduleCheckpoint(checkpointAttemptInterval)
- case _ =>
- checkpointManager.update(message.timestamp)
- .foreach(state.setNextCheckpointTime)
- processMessage(state, message)
- }
- }
-
- final override def onStop(): Unit = {
- checkpointManager.close()
- }
-
- private def scheduleCheckpoint(interval: Long): Unit = {
- scheduleOnce(new FiniteDuration(interval, TimeUnit.MILLISECONDS))(self ! CHECKPOINT)
- }
-
- private def reportCheckpointClock(timestamp: TimeStamp): Unit = {
- appMaster ! ReportCheckpointClock(taskContext.taskId, timestamp)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/state/api/Serializer.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/state/api/Serializer.scala b/streaming/src/main/scala/io/gearpump/streaming/state/api/Serializer.scala
deleted file mode 100644
index f87b224..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/state/api/Serializer.scala
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.state.api
-
-import scala.util.Try
-
-trait Serializer[T] extends java.io.Serializable {
- def serialize(t: T): Array[Byte]
- def deserialize(bytes: Array[Byte]): Try[T]
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/state/impl/CheckpointManager.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/state/impl/CheckpointManager.scala b/streaming/src/main/scala/io/gearpump/streaming/state/impl/CheckpointManager.scala
deleted file mode 100644
index 76c91c7..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/state/impl/CheckpointManager.scala
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.state.impl
-
-import io.gearpump.TimeStamp
-import io.gearpump.streaming.transaction.api.CheckpointStore
-
-/** Manage physical checkpoints to persitent storage like HDFS */
-class CheckpointManager(checkpointInterval: Long,
- checkpointStore: CheckpointStore) {
-
- private var maxMessageTime: Long = 0L
- private var checkpointTime: Option[Long] = None
-
- def recover(timestamp: TimeStamp): Option[Array[Byte]] = {
- checkpointStore.recover(timestamp)
- }
-
- def checkpoint(timestamp: TimeStamp, checkpoint: Array[Byte]): Option[TimeStamp] = {
- checkpointStore.persist(timestamp, checkpoint)
- checkpointTime = checkpointTime.collect { case time if maxMessageTime > time =>
- time + (1 + (maxMessageTime - time) / checkpointInterval) * checkpointInterval
- }
-
- checkpointTime
- }
-
- def update(messageTime: TimeStamp): Option[TimeStamp] = {
- maxMessageTime = Math.max(maxMessageTime, messageTime)
- if (checkpointTime.isEmpty) {
- checkpointTime = Some((1 + messageTime / checkpointInterval) * checkpointInterval)
- }
-
- checkpointTime
- }
-
- def shouldCheckpoint(upstreamMinClock: TimeStamp): Boolean = {
- checkpointTime.exists(time => upstreamMinClock >= time)
- }
-
- def getCheckpointTime: Option[TimeStamp] = checkpointTime
-
- def close(): Unit = {
- checkpointStore.close()
- }
-
- private[impl] def getMaxMessageTime: TimeStamp = maxMessageTime
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/state/impl/InMemoryCheckpointStore.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/state/impl/InMemoryCheckpointStore.scala b/streaming/src/main/scala/io/gearpump/streaming/state/impl/InMemoryCheckpointStore.scala
deleted file mode 100644
index 21623e3..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/state/impl/InMemoryCheckpointStore.scala
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.state.impl
-
-import io.gearpump.TimeStamp
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.task.TaskContext
-import io.gearpump.streaming.transaction.api.{CheckpointStore, CheckpointStoreFactory}
-
-/**
- * an in memory store provided for test
- * should not be used in real cases
- */
-class InMemoryCheckpointStore extends CheckpointStore {
- private var checkpoints = Map.empty[TimeStamp, Array[Byte]]
-
- override def persist(timestamp: TimeStamp, checkpoint: Array[Byte]): Unit = {
- checkpoints += timestamp -> checkpoint
- }
-
- override def recover(timestamp: TimeStamp): Option[Array[Byte]] = {
- checkpoints.get(timestamp)
- }
-
- override def close(): Unit = {
- checkpoints = Map.empty[TimeStamp, Array[Byte]]
- }
-}
-
-class InMemoryCheckpointStoreFactory extends CheckpointStoreFactory {
- override def getCheckpointStore(conf: UserConfig, taskContext: TaskContext): CheckpointStore = {
- new InMemoryCheckpointStore
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/state/impl/NonWindowState.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/state/impl/NonWindowState.scala b/streaming/src/main/scala/io/gearpump/streaming/state/impl/NonWindowState.scala
deleted file mode 100644
index dcd3918..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/state/impl/NonWindowState.scala
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.state.impl
-
-import org.slf4j.Logger
-
-import io.gearpump.TimeStamp
-import io.gearpump.streaming.state.api.{Monoid, MonoidState, Serializer}
-import io.gearpump.streaming.state.impl.NonWindowState._
-import io.gearpump.util.LogUtil
-
-object NonWindowState {
- val LOG: Logger = LogUtil.getLogger(classOf[NonWindowState[_]])
-}
-
-/**
- * a MonoidState storing non-window state
- */
-class NonWindowState[T](monoid: Monoid[T], serializer: Serializer[T])
- extends MonoidState[T](monoid) {
-
- override def recover(timestamp: TimeStamp, bytes: Array[Byte]): Unit = {
- serializer.deserialize(bytes).foreach(left = _)
- }
-
- override def update(timestamp: TimeStamp, t: T): Unit = {
- updateState(timestamp, t)
- }
-
- override def checkpoint(): Array[Byte] = {
- val serialized = serializer.serialize(left)
- LOG.debug(s"checkpoint time: $checkpointTime; checkpoint value: ($checkpointTime, $left)")
- left = monoid.plus(left, right)
- right = monoid.zero
- serialized
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/state/impl/PersistentStateConfig.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/state/impl/PersistentStateConfig.scala b/streaming/src/main/scala/io/gearpump/streaming/state/impl/PersistentStateConfig.scala
deleted file mode 100644
index d7488d7..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/state/impl/PersistentStateConfig.scala
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.state.impl
-
-object PersistentStateConfig {
-
- val STATE_CHECKPOINT_ENABLE = "state.checkpoint.enable"
- val STATE_CHECKPOINT_INTERVAL_MS = "state.checkpoint.interval.ms"
- val STATE_CHECKPOINT_STORE_FACTORY = "state.checkpoint.store.factory"
- val STATE_WINDOW_SIZE = "state.window.size"
- val STATE_WINDOW_STEP = "state.window.step"
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/state/impl/Window.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/state/impl/Window.scala b/streaming/src/main/scala/io/gearpump/streaming/state/impl/Window.scala
deleted file mode 100644
index 63cdf06..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/state/impl/Window.scala
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.state.impl
-
-import io.gearpump.TimeStamp
-
-/**
- * Used in window applications
- * it keeps the current window and slide ahead when the window expires
- */
-class Window(val windowSize: Long, val windowStep: Long) {
-
- def this(windowConfig: WindowConfig) = {
- this(windowConfig.windowSize, windowConfig.windowStep)
- }
-
- private var clock: TimeStamp = 0L
- private var startTime = 0L
-
- def update(clock: TimeStamp): Unit = {
- this.clock = clock
- }
-
- def slideOneStep(): Unit = {
- startTime += windowStep
- }
-
- def slideTo(timestamp: TimeStamp): Unit = {
- startTime = timestamp / windowStep * windowStep
- }
-
- def shouldSlide: Boolean = {
- clock >= (startTime + windowSize)
- }
-
- def range: (TimeStamp, TimeStamp) = {
- startTime -> (startTime + windowSize)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/state/impl/WindowConfig.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/state/impl/WindowConfig.scala b/streaming/src/main/scala/io/gearpump/streaming/state/impl/WindowConfig.scala
deleted file mode 100644
index d7d3776..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/state/impl/WindowConfig.scala
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.state.impl
-
-object WindowConfig {
- val NAME = "window_config"
-}
-
-case class WindowConfig(windowSize: Long, windowStep: Long)
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/state/impl/WindowState.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/state/impl/WindowState.scala b/streaming/src/main/scala/io/gearpump/streaming/state/impl/WindowState.scala
deleted file mode 100644
index 30382c0..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/state/impl/WindowState.scala
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.state.impl
-
-import scala.collection.immutable.TreeMap
-
-import org.slf4j.Logger
-
-import io.gearpump.TimeStamp
-import io.gearpump.streaming.state.api.{Group, MonoidState, Serializer}
-import io.gearpump.streaming.state.impl.WindowState._
-import io.gearpump.streaming.task.TaskContext
-import io.gearpump.util.LogUtil
-
-/**
- * an interval is a dynamic time range that is divided by window boundary and checkpoint time
- */
-case class Interval(startTime: TimeStamp, endTime: TimeStamp) extends Ordered[Interval] {
- override def compare(that: Interval): Int = {
- if (startTime < that.startTime) -1
- else if (startTime > that.startTime) 1
- else 0
- }
-}
-
-object WindowState {
- val LOG: Logger = LogUtil.getLogger(classOf[WindowState[_]])
-}
-
-/**
- * this is a list of states, each of which is bounded by a time window
- * state of each window doesn't affect each other
- *
- * WindowState requires a Algebird Group to be passed in
- * Group augments Monoid with a minus function which makes it
- * possible to undo the update by messages that have left the window
- */
-class WindowState[T](group: Group[T],
- serializer: Serializer[TreeMap[Interval, T]],
- taskContext: TaskContext,
- window: Window) extends MonoidState[T](group) {
- /**
- * each interval has a state updated by message with timestamp in
- * [interval.startTime, interval.endTime)
- */
- private var intervalStates = TreeMap.empty[Interval, T]
-
- private var lastCheckpointTime = 0L
-
- override def recover(timestamp: TimeStamp, bytes: Array[Byte]): Unit = {
- window.slideTo(timestamp)
- serializer.deserialize(bytes)
- .foreach { states =>
- intervalStates = states
- left = states.foldLeft(left) { case (accum, iter) =>
- group.plus(accum, iter._2)
- }
- }
- }
-
- override def update(timestamp: TimeStamp, t: T): Unit = {
- val (startTime, endTime) = window.range
- if (timestamp >= startTime && timestamp < endTime) {
- updateState(timestamp, t)
- }
-
- updateIntervalStates(timestamp, t, checkpointTime)
-
- val upstreamMinClock = taskContext.upstreamMinClock
- window.update(upstreamMinClock)
-
- if (window.shouldSlide) {
- window.slideOneStep()
-
- val (newStartTime, newEndTime) = window.range
- getIntervalStates(startTime, newStartTime).foreach { case (_, st) =>
- left = group.minus(left, st)
- }
- if (checkpointTime > endTime) {
- getIntervalStates(endTime, checkpointTime).foreach { case (_, st) =>
- left = group.plus(left, st)
- }
- } else {
- getIntervalStates(endTime, newEndTime).foreach { case (_, st) =>
- right = group.plus(right, st)
- }
- }
- }
- }
-
- override def checkpoint(): Array[Byte] = {
- left = group.plus(left, right)
- right = group.zero
-
- val states = getIntervalStates(window.range._1, checkpointTime)
- lastCheckpointTime = checkpointTime
- LOG.debug(s"checkpoint time: $checkpointTime; checkpoint value: ($checkpointTime, $states)")
- serializer.serialize(states)
- }
-
- /**
- * Each message will update state in corresponding Interval[StartTime, endTime),
- *
- * which is decided by the message's timestamp t where
- * {{{
- * startTime = Math.max(lowerBound1, lowerBound2, checkpointTime)
- * endTime = Math.min(upperBound1, upperBound2, checkpointTime)
- * lowerBound1 = step * Nmax1 <= t
- * lowerBound2 = step * Nmax2 + size <= t
- * upperBound1 = step * Nmin1 > t
- * upperBound2 = step * Nmin2 + size > t
- * }}}
- */
- private[impl] def getInterval(timestamp: TimeStamp, checkpointTime: TimeStamp): Interval = {
- val windowSize = window.windowSize
- val windowStep = window.windowStep
- val lowerBound1 = timestamp / windowStep * windowStep
- val lowerBound2 =
- if (timestamp < windowSize) 0L
- else (timestamp - windowSize) / windowStep * windowStep + windowSize
- val upperBound1 = (timestamp / windowStep + 1) * windowStep
- val upperBound2 =
- if (timestamp < windowSize) windowSize
- else ((timestamp - windowSize) / windowStep + 1) * windowStep + windowSize
- val lowerBound = Math.max(lowerBound1, lowerBound2)
- val upperBound = Math.min(upperBound1, upperBound2)
- if (checkpointTime > timestamp) {
- Interval(Math.max(lowerBound, lastCheckpointTime), Math.min(upperBound, checkpointTime))
- } else {
- Interval(Math.max(lowerBound, checkpointTime), upperBound)
- }
- }
-
- private[impl] def updateIntervalStates(timestamp: TimeStamp, t: T, checkpointTime: TimeStamp)
- : Unit = {
- val interval = getInterval(timestamp, checkpointTime)
- intervalStates.get(interval) match {
- case Some(st) =>
- intervalStates += interval -> group.plus(st, t)
- case None =>
- intervalStates += interval -> group.plus(group.zero, t)
- }
- }
-
- private[impl] def getIntervalStates(startTime: TimeStamp, endTime: TimeStamp)
- : TreeMap[Interval, T] = {
- intervalStates.dropWhile(_._1.endTime <= startTime).takeWhile(_._1.endTime <= endTime)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/storage/AppDataStore.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/storage/AppDataStore.scala b/streaming/src/main/scala/io/gearpump/streaming/storage/AppDataStore.scala
deleted file mode 100644
index 962f48f..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/storage/AppDataStore.scala
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.storage
-
-import scala.concurrent._
-
-/**
- * Generic storage to store KV Data.
- */
-trait AppDataStore {
- def put(key: String, value: Any): Future[Any]
-
- def get(key: String): Future[Any]
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/storage/InMemoryAppStoreOnMaster.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/storage/InMemoryAppStoreOnMaster.scala b/streaming/src/main/scala/io/gearpump/streaming/storage/InMemoryAppStoreOnMaster.scala
deleted file mode 100644
index f1a19a8..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/storage/InMemoryAppStoreOnMaster.scala
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.storage
-
-import scala.concurrent.Future
-
-import akka.actor.ActorRef
-import akka.pattern.ask
-
-import io.gearpump.cluster.AppMasterToMaster.{GetAppData, GetAppDataResult, SaveAppData}
-import io.gearpump.util.Constants
-
-/**
- * In memory application storage located on master nodes
- */
-class InMemoryAppStoreOnMaster(appId: Int, master: ActorRef) extends AppDataStore {
- implicit val timeout = Constants.FUTURE_TIMEOUT
- import scala.concurrent.ExecutionContext.Implicits.global
-
- override def put(key: String, value: Any): Future[Any] = {
- master.ask(SaveAppData(appId, key, value))
- }
-
- override def get(key: String): Future[Any] = {
- master.ask(GetAppData(appId, key)).asInstanceOf[Future[GetAppDataResult]].map { result =>
- if (result.key.equals(key)) {
- result.value
- } else {
- null
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/task/ExpressTransport.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/task/ExpressTransport.scala b/streaming/src/main/scala/io/gearpump/streaming/task/ExpressTransport.scala
deleted file mode 100644
index a3cb6e1..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/task/ExpressTransport.scala
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.task
-
-import akka.actor.{ActorRef, ExtendedActorSystem}
-
-import io.gearpump.Message
-import io.gearpump.transport.netty.TaskMessage
-import io.gearpump.transport.{Express, HostPort}
-import io.gearpump.util.AkkaHelper
-/**
- * ExpressTransport wire the networking function from default akka
- * networking to customized implementation [[io.gearpump.transport.Express]].
- *
- * See [[io.gearpump.transport.Express]] for more information.
- */
-trait ExpressTransport {
- this: TaskActor =>
-
- final val express = Express(context.system)
- implicit val system = context.system.asInstanceOf[ExtendedActorSystem]
-
- final def local: HostPort = express.localHost
- lazy val sourceId = TaskId.toLong(taskId)
-
- lazy val sessionRef: ActorRef = {
- AkkaHelper.actorFor(system, s"/session#$sessionId")
- }
-
- def transport(msg: AnyRef, remotes: TaskId*): Unit = {
- var serializedMessage: AnyRef = null
-
- remotes.foreach { remote =>
- val transportId = TaskId.toLong(remote)
- val localActor = express.lookupLocalActor(transportId)
- if (localActor.isDefined) {
- localActor.get.tell(msg, sessionRef)
- } else {
- if (null == serializedMessage) {
- msg match {
- case message: Message =>
- val bytes = serializerPool.get().serialize(message.msg)
- serializedMessage = SerializedMessage(message.timestamp, bytes)
- case _ => serializedMessage = msg
- }
- }
- val taskMessage = new TaskMessage(sessionId, transportId, sourceId, serializedMessage)
-
- val remoteAddress = express.lookupRemoteAddress(transportId)
- if (remoteAddress.isDefined) {
- express.transport(taskMessage, remoteAddress.get)
- } else {
- LOG.error(
- s"Can not find target task $remote, maybe the application is undergoing recovery")
- }
- }
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/task/SerializedMessage.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/task/SerializedMessage.scala b/streaming/src/main/scala/io/gearpump/streaming/task/SerializedMessage.scala
deleted file mode 100644
index 9f9bf1b..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/task/SerializedMessage.scala
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.task
-
-import java.io.{DataInput, DataOutput}
-
-import io.gearpump.TimeStamp
-
-case class SerializedMessage(timeStamp: TimeStamp, bytes: Array[Byte])
-
-class SerializedMessageSerializer extends TaskMessageSerializer[SerializedMessage] {
- override def getLength(obj: SerializedMessage): Int = 12 + obj.bytes.length
-
- override def write(dataOutput: DataOutput, obj: SerializedMessage): Unit = {
- dataOutput.writeLong(obj.timeStamp)
- dataOutput.writeInt(obj.bytes.length)
- dataOutput.write(obj.bytes)
- }
-
- override def read(dataInput: DataInput): SerializedMessage = {
- val timestamp = dataInput.readLong()
- val length = dataInput.readInt()
- val bytes = new Array[Byte](length)
- dataInput.readFully(bytes)
- SerializedMessage(timestamp, bytes)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/task/SerializerResolver.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/task/SerializerResolver.scala b/streaming/src/main/scala/io/gearpump/streaming/task/SerializerResolver.scala
deleted file mode 100644
index 72bc7db..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/task/SerializerResolver.scala
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.task
-
-import io.gearpump.esotericsoftware.kryo.util.{IntMap, ObjectMap}
-import io.gearpump.streaming.task.SerializerResolver.Registration
-
-private[task] class SerializerResolver {
- private var classId = 0
- private val idToRegistration = new IntMap[Registration]()
- private val classToRegistration = new ObjectMap[Class[_], Registration]()
-
- def register[T](clazz: Class[T], serializer: TaskMessageSerializer[T]): Unit = {
- val registration = new Registration(classId, clazz, serializer)
- idToRegistration.put(classId, registration)
- classToRegistration.put(clazz, registration)
- classId += 1
- }
-
- def getRegistration(clazz: Class[_]): Registration = {
- classToRegistration.get(clazz)
- }
-
- def getRegistration(clazzId: Int): Registration = {
- idToRegistration.get(clazzId)
- }
-}
-
-object SerializerResolver {
- class Registration(val id: Int, val clazz: Class[_], val serializer: TaskMessageSerializer[_])
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/task/StartTime.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/task/StartTime.scala b/streaming/src/main/scala/io/gearpump/streaming/task/StartTime.scala
deleted file mode 100644
index 6bc8b15..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/task/StartTime.scala
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.task
-
-import io.gearpump.TimeStamp
-
-/** Start time of streaming application. All message older than start time will be dropped */
-case class StartTime(startTime: TimeStamp = 0)
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/task/StreamingTransportSerializer.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/task/StreamingTransportSerializer.scala b/streaming/src/main/scala/io/gearpump/streaming/task/StreamingTransportSerializer.scala
deleted file mode 100644
index 17d0b1b..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/task/StreamingTransportSerializer.scala
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.task
-
-import java.io.{DataInput, DataOutput}
-
-import org.slf4j.Logger
-
-import io.gearpump.streaming.{AckRequestSerializer, AckSerializer, InitialAckRequestSerializer, LatencyProbeSerializer}
-import io.gearpump.transport.netty.ITransportMessageSerializer
-import io.gearpump.util.LogUtil
-
-class StreamingTransportSerializer extends ITransportMessageSerializer {
- private val log: Logger = LogUtil.getLogger(getClass)
- private val serializers = new SerializerResolver
-
- serializers.register(classOf[Ack], new AckSerializer)
- serializers.register(classOf[AckRequest], new AckRequestSerializer)
- serializers.register(classOf[InitialAckRequest], new InitialAckRequestSerializer)
- serializers.register(classOf[LatencyProbe], new LatencyProbeSerializer)
- serializers.register(classOf[SerializedMessage], new SerializedMessageSerializer)
-
- override def serialize(dataOutput: DataOutput, obj: Object): Unit = {
- val registration = serializers.getRegistration(obj.getClass)
- if (registration != null) {
- dataOutput.writeInt(registration.id)
- registration.serializer.asInstanceOf[TaskMessageSerializer[AnyRef]].write(dataOutput, obj)
- } else {
- log.error(s"Can not find serializer for class type ${obj.getClass}")
- }
- }
-
- override def deserialize(dataInput: DataInput, length: Int): Object = {
- val classID = dataInput.readInt()
- val registration = serializers.getRegistration(classID)
- if (registration != null) {
- registration.serializer.asInstanceOf[TaskMessageSerializer[AnyRef]].read(dataInput)
- } else {
- log.error(s"Can not find serializer for class id $classID")
- null
- }
- }
-
- override def getLength(obj: Object): Int = {
- val registration = serializers.getRegistration(obj.getClass)
- if (registration != null) {
- registration.serializer.asInstanceOf[TaskMessageSerializer[AnyRef]].getLength(obj) + 4
- } else {
- log.error(s"Can not find serializer for class type ${obj.getClass}")
- 0
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/task/Subscriber.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/task/Subscriber.scala b/streaming/src/main/scala/io/gearpump/streaming/task/Subscriber.scala
deleted file mode 100644
index d20074b..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/task/Subscriber.scala
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.task
-
-import io.gearpump.partitioner.PartitionerDescription
-import io.gearpump.streaming.{DAG, LifeTime}
-
-/**
- * Each processor can have multiple downstream subscribers.
- *
- * For example: When processor A subscribe to processor B, then the output of B will be
- * pushed to processor A.
- *
- * @param processorId subscriber processor Id
- * @param partitionerDescription subscriber partitioner
- */
-case class Subscriber(processorId: Int, partitionerDescription: PartitionerDescription,
- parallelism: Int, lifeTime: LifeTime)
-
-object Subscriber {
-
- /**
- *
- * List subscriptions of a processor.
- * The topology information is retrieved from dag
- *
- * @param processorId the processor to list
- * @param dag the DAG
- * @return the subscribers of this processor
- */
- def of(processorId: Int, dag: DAG): List[Subscriber] = {
- val edges = dag.graph.outgoingEdgesOf(processorId)
-
- edges.foldLeft(List.empty[Subscriber]) { (list, nodeEdgeNode) =>
- val (_, partitioner, downstreamProcessorId) = nodeEdgeNode
- val downstreamProcessor = dag.processors(downstreamProcessorId)
- list :+ Subscriber(downstreamProcessorId, partitioner,
- downstreamProcessor.parallelism, downstreamProcessor.life)
- }
- }
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/task/Subscription.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/task/Subscription.scala b/streaming/src/main/scala/io/gearpump/streaming/task/Subscription.scala
deleted file mode 100644
index 155edf4..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/task/Subscription.scala
+++ /dev/null
@@ -1,235 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.task
-
-import org.slf4j.Logger
-
-import io.gearpump.google.common.primitives.Shorts
-import io.gearpump.partitioner.{MulticastPartitioner, Partitioner, UnicastPartitioner}
-import io.gearpump.streaming.AppMasterToExecutor.MsgLostException
-import io.gearpump.streaming.LifeTime
-import io.gearpump.streaming.task.Subscription._
-import io.gearpump.util.LogUtil
-import io.gearpump.{Message, TimeStamp}
-
-/**
- * Manges the output and message clock for single downstream processor
- *
- * @param subscriber downstream processor
- * @param maxPendingMessageCount trigger flow control. Should be bigger than
- * maxPendingMessageCountPerAckRequest
- * @param ackOnceEveryMessageCount send on AckRequest to the target
- */
-class Subscription(
- appId: Int,
- executorId: Int,
- taskId: TaskId,
- subscriber: Subscriber, sessionId: Int,
- transport: ExpressTransport,
- maxPendingMessageCount: Int = MAX_PENDING_MESSAGE_COUNT,
- ackOnceEveryMessageCount: Int = ONE_ACKREQUEST_EVERY_MESSAGE_COUNT) {
-
- assert(maxPendingMessageCount >= ackOnceEveryMessageCount)
- assert(maxPendingMessageCount < Short.MaxValue / 2)
-
- private val LOG: Logger = LogUtil.getLogger(getClass, app = appId,
- executor = executorId, task = taskId)
-
- import subscriber.{parallelism, partitionerDescription, processorId}
-
- // Don't worry if this store negative number. We will wrap the Short
- private val messageCount: Array[Short] = new Array[Short](parallelism)
- private val pendingMessageCount: Array[Short] = new Array[Short](parallelism)
- private val candidateMinClockSince: Array[Short] = new Array[Short](parallelism)
-
- private val minClockValue: Array[TimeStamp] = Array.fill(parallelism)(Long.MaxValue)
- private val candidateMinClock: Array[TimeStamp] = Array.fill(parallelism)(Long.MaxValue)
-
- private var maxPendingCount: Short = 0
-
- private var life = subscriber.lifeTime
-
- private val partitioner = partitionerDescription.partitionerFactory.partitioner
- private val sendFn = partitioner match {
- case up: UnicastPartitioner =>
- (msg: Message) => {
- val partition = up.getPartition(msg, parallelism, taskId.index)
- sendMessage(msg, partition)
- }
- case mp: MulticastPartitioner =>
- (msg: Message) => {
- val partitions = mp.getPartitions(msg, parallelism, taskId.index)
- partitions.map(partition => sendMessage(msg, partition)).sum
- }
- }
-
- def changeLife(life: LifeTime): Unit = {
- this.life = life
- }
-
- def start(): Unit = {
- val ackRequest = InitialAckRequest(taskId, sessionId)
- transport.transport(ackRequest, allTasks: _*)
- }
-
- def sendMessage(msg: Message): Int = {
- sendFn(msg)
- }
-
- /**
- * Returns how many message is actually sent by this subscription
- *
- * @param msg the message to send
- * @param partition the target partition to send message to
- * @return 1 if success
- */
- def sendMessage(msg: Message, partition: Int): Int = {
-
- var count = 0
- // Only sends message whose timestamp matches the lifeTime
- if (partition != Partitioner.UNKNOWN_PARTITION_ID && life.contains(msg.timestamp)) {
-
- val targetTask = TaskId(processorId, partition)
- transport.transport(msg, targetTask)
-
- this.minClockValue(partition) = Math.min(this.minClockValue(partition), msg.timestamp)
- this.candidateMinClock(partition) = Math.min(this.candidateMinClock(partition), msg.timestamp)
-
- incrementMessageCount(partition, 1)
-
- if (messageCount(partition) % ackOnceEveryMessageCount == 0) {
- sendAckRequest(partition)
- }
-
- if (messageCount(partition) / maxPendingMessageCount !=
- (messageCount(partition) + ackOnceEveryMessageCount) / maxPendingMessageCount) {
- sendLatencyProbe(partition)
- }
- count = 1
- count
- } else {
- if (needFlush) {
- flush()
- }
- count = 0
- count
- }
- }
-
- private var lastFlushTime: Long = 0L
- private val FLUSH_INTERVAL = 5 * 1000 // ms
- private def needFlush: Boolean = {
- System.currentTimeMillis() - lastFlushTime > FLUSH_INTERVAL &&
- Shorts.max(pendingMessageCount: _*) > 0
- }
-
- private def flush(): Unit = {
- lastFlushTime = System.currentTimeMillis()
- allTasks.foreach { targetTaskId =>
- sendAckRequest(targetTaskId.index)
- }
- }
-
- private def allTasks: scala.collection.Seq[TaskId] = {
- (0 until parallelism).map { taskIndex =>
- TaskId(processorId, taskIndex)
- }
- }
-
- /**
- * Handles acknowledge message. Throw MessageLossException if required.
- *
- * @param ack acknowledge message received
- */
- def receiveAck(ack: Ack): Unit = {
-
- val index = ack.taskId.index
-
- if (ack.sessionId == sessionId) {
- if (ack.actualReceivedNum == ack.seq) {
- if ((ack.seq - candidateMinClockSince(index)).toShort >= 0) {
- if (ack.seq == messageCount(index)) {
- // All messages have been acked.
- minClockValue(index) = Long.MaxValue
- } else {
- minClockValue(index) = candidateMinClock(index)
- }
- candidateMinClock(index) = Long.MaxValue
- candidateMinClockSince(index) = messageCount(index)
- }
-
- pendingMessageCount(ack.taskId.index) = (messageCount(ack.taskId.index) - ack.seq).toShort
- updateMaxPendingCount()
- } else {
- LOG.error(s"Failed! received ack: $ack, received: ${ack.actualReceivedNum}, " +
- s"sent: ${ack.seq}, try to replay...")
- throw new MsgLostException
- }
- }
- }
-
- def minClock: TimeStamp = {
- minClockValue.min
- }
-
- def allowSendingMoreMessages(): Boolean = {
- maxPendingCount < maxPendingMessageCount
- }
-
- def sendAckRequestOnStallingTime(stallingTime: TimeStamp): Unit = {
- minClockValue.indices.foreach { i =>
- if (minClockValue(i) == stallingTime && pendingMessageCount(i) > 0
- && allowSendingMoreMessages) {
- sendAckRequest(i)
- sendLatencyProbe(i)
- }
- }
- }
-
- private def sendAckRequest(partition: Int): Unit = {
- // Increments more count for each AckRequest
- // to throttle the number of unacked AckRequest
- incrementMessageCount(partition, ackOnceEveryMessageCount)
- val targetTask = TaskId(processorId, partition)
- val ackRequest = AckRequest(taskId, messageCount(partition), sessionId)
- transport.transport(ackRequest, targetTask)
- }
-
- private def incrementMessageCount(partition: Int, count: Int): Unit = {
- messageCount(partition) = (messageCount(partition) + count).toShort
- pendingMessageCount(partition) = (pendingMessageCount(partition) + count).toShort
- updateMaxPendingCount()
- }
-
- private def updateMaxPendingCount(): Unit = {
- maxPendingCount = Shorts.max(pendingMessageCount: _*)
- }
-
- private def sendLatencyProbe(partition: Int): Unit = {
- val probeLatency = LatencyProbe(System.currentTimeMillis())
- val targetTask = TaskId(processorId, partition)
- transport.transport(probeLatency, targetTask)
- }
-}
-
-object Subscription {
- // Makes sure it is smaller than MAX_PENDING_MESSAGE_COUNT
- final val ONE_ACKREQUEST_EVERY_MESSAGE_COUNT = 100
- final val MAX_PENDING_MESSAGE_COUNT = 1000
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/task/Task.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/task/Task.scala b/streaming/src/main/scala/io/gearpump/streaming/task/Task.scala
deleted file mode 100644
index 212a659..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/task/Task.scala
+++ /dev/null
@@ -1,189 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.task
-
-import scala.concurrent.duration.FiniteDuration
-
-import akka.actor.Actor.Receive
-import akka.actor.{ActorRef, ActorSystem, Cancellable, Props}
-import org.slf4j.Logger
-
-import io.gearpump.cluster.UserConfig
-import io.gearpump.util.LogUtil
-import io.gearpump.{Message, TimeStamp}
-
-/**
- * This provides context information for a task.
- */
-trait TaskContext {
-
- def taskId: TaskId
-
- def executorId: Int
-
- def appId: Int
-
- def appName: String
-
- /**
- * The actorRef of AppMaster
- * @return application master's actor reference
- */
- def appMaster: ActorRef
-
- /**
- * The task parallelism
- *
- * For example, we can create 3 source tasks, and 3 sink tasks,
- * the task parallelism is 3 for each.
- *
- * This can be useful when reading from partitioned data source.
- * For example, for kafka, there may be 10 partitions, if we have
- * parallelism of 2 for this task, then each task will be responsible
- * to read data from 5 partitions.
- *
- * @return the parallelism level
- */
- def parallelism: Int
-
- /**
- * Please don't use this if possible.
- * @return self actor ref
- */
- // TODO: We should remove the self from TaskContext
- def self: ActorRef
-
- /**
- * Please don't use this if possible
- * @return the actor system
- */
- // TODO: we should remove this in future
- def system: ActorSystem
-
- /**
- * This can be used to output messages to downstream tasks. The data shuffling rule
- * can be decided by Partitioner.
- *
- * @param msg message to output
- */
- def output(msg: Message): Unit
-
- def actorOf(props: Props): ActorRef
-
- def actorOf(props: Props, name: String): ActorRef
-
- def schedule(initialDelay: FiniteDuration, interval: FiniteDuration)(f: => Unit): Cancellable
-
- /**
- * akka.actor.ActorRefProvider.scheduleOnce
- *
- * @param initialDelay the initial delay
- * @param f the function to execute after initial delay
- * @return the executable
- */
- def scheduleOnce(initialDelay: FiniteDuration)(f: => Unit): Cancellable
-
- /**
- * For managed message(type of Message), the sender only serve as a unique Id,
- * It's address is not something meaningful, you should not use this directly
- *
- * For unmanaged message, the sender represent the sender ActorRef
- * @return sender
- */
- def sender: ActorRef
-
- /**
- * Retrieves upstream min clock from TaskActor
- *
- * @return the min clock
- */
- def upstreamMinClock: TimeStamp
-
- /**
- * Logger is environment dependant, it should be provided by
- * containing environment.
- */
- def logger: Logger
-}
-
-/**
- * Streaming Task interface
- */
-trait TaskInterface {
-
- /**
- * Method called with the task is initialized.
- * @param startTime startTime that can be used to decide from when a source producer task should
- * replay the data source, or from when a processor task should recover its
- * checkpoint data in to in-memory state.
- */
- def onStart(startTime: StartTime): Unit
-
- /**
- * Method called for each message received.
- *
- * @param msg Message send by upstream tasks
- */
- def onNext(msg: Message): Unit
-
- /**
- * Method called when task is under clean up.
- *
- * This can be used to cleanup resource when the application finished.
- */
- def onStop(): Unit
-
- /**
- * Handlers unmanaged messages
- *
- * @return the handler
- */
- def receiveUnManagedMessage: Receive = null
-}
-
-abstract class Task(taskContext: TaskContext, userConf: UserConfig) extends TaskInterface {
-
- import taskContext.{appId, executorId, taskId}
-
- val LOG: Logger = LogUtil.getLogger(getClass, app = appId, executor = executorId, task = taskId)
-
- protected implicit val system = taskContext.system
-
- implicit val self = taskContext.self
-
- /**
- * For managed message(type of Message), the sender mean nothing,
- * you should not use this directory
- *
- * For unmanaged message, the sender represent the sender actor
- * @return the sender
- */
- protected def sender: ActorRef = taskContext.sender
-
- def onStart(startTime: StartTime): Unit = {}
-
- def onNext(msg: Message): Unit = {}
-
- def onStop(): Unit = {}
-
- override def receiveUnManagedMessage: Receive = {
- case msg =>
- LOG.error("Failed! Received unknown message " + "taskId: " + taskId + ", " + msg.toString)
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/task/TaskActor.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/task/TaskActor.scala b/streaming/src/main/scala/io/gearpump/streaming/task/TaskActor.scala
deleted file mode 100644
index b9b8829..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/task/TaskActor.scala
+++ /dev/null
@@ -1,397 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.task
-
-import java.util
-import java.util.concurrent.TimeUnit
-
-import akka.actor._
-import org.slf4j.Logger
-
-import io.gearpump.cluster.UserConfig
-import io.gearpump.gs.collections.impl.map.mutable.primitive.IntShortHashMap
-import io.gearpump.metrics.Metrics
-import io.gearpump.serializer.SerializationFramework
-import io.gearpump.streaming.AppMasterToExecutor._
-import io.gearpump.streaming.ExecutorToAppMaster._
-import io.gearpump.streaming.{Constants, ProcessorId}
-import io.gearpump.util.{LogUtil, TimeOutScheduler}
-import io.gearpump.{Message, TimeStamp}
-
-/**
- *
- * All tasks of Gearpump runs inside a Actor. TaskActor is the Actor container for a task.
- */
-class TaskActor(
- val taskId: TaskId,
- val taskContextData: TaskContextData,
- userConf: UserConfig,
- val task: TaskWrapper,
- inputSerializerPool: SerializationFramework)
- extends Actor with ExpressTransport with TimeOutScheduler {
- var upstreamMinClock: TimeStamp = 0L
- private var _minClock: TimeStamp = 0L
-
- def serializerPool: SerializationFramework = inputSerializerPool
-
- import taskContextData._
-
- import io.gearpump.streaming.Constants._
- import io.gearpump.streaming.task.TaskActor._
- val config = context.system.settings.config
-
- val LOG: Logger = LogUtil.getLogger(getClass, app = appId, executor = executorId, task = taskId)
-
- // Metrics
- private val metricName = s"app${appId}.processor${taskId.processorId}.task${taskId.index}"
- private val receiveLatency = Metrics(context.system).histogram(
- s"$metricName:receiveLatency", sampleRate = 1)
- private val processTime = Metrics(context.system).histogram(s"$metricName:processTime")
- private val sendThroughput = Metrics(context.system).meter(s"$metricName:sendThroughput")
- private val receiveThroughput = Metrics(context.system).meter(s"$metricName:receiveThroughput")
-
- private val maxPendingMessageCount = config.getInt(GEARPUMP_STREAMING_MAX_PENDING_MESSAGE_COUNT)
- private val ackOnceEveryMessageCount = config.getInt(
- GEARPUMP_STREAMING_ACK_ONCE_EVERY_MESSAGE_COUNT)
-
- private val executor = context.parent
- private var life = taskContextData.life
-
- // Latency probe
- import scala.concurrent.duration._
-
- import context.dispatcher
- final val LATENCY_PROBE_INTERVAL = FiniteDuration(1, TimeUnit.SECONDS)
-
- // Clock report interval
- final val CLOCK_REPORT_INTERVAL = FiniteDuration(1, TimeUnit.SECONDS)
-
- // Flush interval
- final val FLUSH_INTERVAL = FiniteDuration(100, TimeUnit.MILLISECONDS)
-
- private val queue = new util.LinkedList[AnyRef]()
-
- private var subscriptions = List.empty[(Int, Subscription)]
-
- // SecurityChecker will be responsible of dropping messages from
- // unknown sources
- private val securityChecker = new SecurityChecker(taskId, self)
- private[task] var sessionId = NONE_SESSION
-
- // Reports to appMaster with my address
- express.registerLocalActor(TaskId.toLong(taskId), self)
-
- final def receive: Receive = null
-
- task.setTaskActor(this)
-
- def onStart(startTime: StartTime): Unit = {
- task.onStart(startTime)
- }
-
- def onNext(msg: Message): Unit = task.onNext(msg)
-
- def onUnManagedMessage(msg: Any): Unit = task.receiveUnManagedMessage.apply(msg)
-
- def onStop(): Unit = task.onStop()
-
- /**
- * output to a downstream by specifying a arrayIndex
- * @param arrayIndex this is not same as ProcessorId
- */
- def output(arrayIndex: Int, msg: Message): Unit = {
- var count = 0
- count += this.subscriptions(arrayIndex)._2.sendMessage(msg)
- sendThroughput.mark(count)
- }
-
- def output(msg: Message): Unit = {
- var count = 0
- this.subscriptions.foreach { subscription =>
- count += subscription._2.sendMessage(msg)
- }
- sendThroughput.mark(count)
- }
-
- final override def postStop(): Unit = {
- onStop()
- }
-
- final override def preStart(): Unit = {
- val register = RegisterTask(taskId, executorId, local)
- LOG.info(s"$register")
- executor ! register
- context.become(waitForTaskRegistered)
- }
-
- private def allowSendingMoreMessages(): Boolean = {
- subscriptions.forall(_._2.allowSendingMoreMessages())
- }
-
- private def doHandleMessage(): Unit = {
- var done = false
-
- var count = 0
- val start = System.currentTimeMillis()
-
- while (allowSendingMoreMessages() && !done) {
- val msg = queue.poll()
- if (msg != null) {
- msg match {
- case SendAck(ack, targetTask) =>
- transport(ack, targetTask)
- case m: Message =>
- count += 1
- onNext(m)
- case other =>
- // un-managed message
- onUnManagedMessage(other)
- }
- } else {
- done = true
- }
- }
-
- receiveThroughput.mark(count)
- if (count > 0) {
- processTime.update((System.currentTimeMillis() - start) / count)
- }
- }
-
- private def onStartClock(): Unit = {
- LOG.info(s"received start, clock: $upstreamMinClock, sessionId: $sessionId")
- subscriptions = subscribers.map { subscriber =>
- (subscriber.processorId,
- new Subscription(appId, executorId, taskId, subscriber, sessionId, this,
- maxPendingMessageCount, ackOnceEveryMessageCount))
- }.sortBy(_._1)
-
- subscriptions.foreach(_._2.start())
-
- import scala.collection.JavaConverters._
- stashQueue.asScala.foreach { item =>
- handleMessages(item.sender).apply(item.msg)
- }
- stashQueue.clear()
-
- // Put this as the last step so that the subscription is already initialized.
- // Message sending in current Task before onStart will not be delivered to
- // target
- onStart(new StartTime(upstreamMinClock))
-
- appMaster ! GetUpstreamMinClock(taskId)
- context.become(handleMessages(sender))
- }
-
- def waitForTaskRegistered: Receive = {
- case start@TaskRegistered(_, sessionId, startClock) =>
- this.sessionId = sessionId
- this.upstreamMinClock = startClock
- context.become(waitForStartClock)
- }
-
- private val stashQueue = new util.LinkedList[MessageAndSender]()
-
- def waitForStartClock: Receive = {
- case start: StartTask =>
- onStartClock()
- case other: AnyRef =>
- stashQueue.add(MessageAndSender(other, sender()))
- }
-
- def handleMessages(sender: => ActorRef): Receive = {
- case ackRequest: InitialAckRequest =>
- val ackResponse = securityChecker.handleInitialAckRequest(ackRequest)
- if (null != ackResponse) {
- queue.add(SendAck(ackResponse, ackRequest.taskId))
- doHandleMessage()
- }
- case ackRequest: AckRequest =>
- // Enqueue to handle the ackRequest and send back ack later
- val ackResponse = securityChecker.generateAckResponse(ackRequest, sender,
- ackOnceEveryMessageCount)
- if (null != ackResponse) {
- queue.add(SendAck(ackResponse, ackRequest.taskId))
- doHandleMessage()
- }
- case ack: Ack =>
- subscriptions.find(_._1 == ack.taskId.processorId).foreach(_._2.receiveAck(ack))
- doHandleMessage()
- case inputMessage: SerializedMessage =>
- val message = Message(serializerPool.get().deserialize(inputMessage.bytes),
- inputMessage.timeStamp)
- receiveMessage(message, sender)
- case inputMessage: Message =>
- receiveMessage(inputMessage, sender)
- case upstream@UpstreamMinClock(upstreamClock) =>
- this.upstreamMinClock = upstreamClock
-
- val subMinClock = subscriptions.foldLeft(Long.MaxValue) { (min, sub) =>
- val subMin = sub._2.minClock
- // A subscription is holding back the _minClock;
- // we send AckRequest to its tasks to push _minClock forward
- if (subMin == _minClock) {
- sub._2.sendAckRequestOnStallingTime(_minClock)
- }
- Math.min(min, subMin)
- }
-
- _minClock = Math.max(life.birth, Math.min(upstreamMinClock, subMinClock))
-
- val update = UpdateClock(taskId, _minClock)
- context.system.scheduler.scheduleOnce(CLOCK_REPORT_INTERVAL) {
- appMaster ! update
- }
-
- // Checks whether current task is dead.
- if (_minClock > life.death) {
- // There will be no more message received...
- val unRegister = UnRegisterTask(taskId, executorId)
- executor ! unRegister
-
- LOG.info(s"Sending $unRegister, current minclock: ${_minClock}, life: $life")
- }
-
- case ChangeTask(_, dagVersion, life, subscribers) =>
- this.life = life
- subscribers.foreach { subscriber =>
- val processorId = subscriber.processorId
- val subscription = getSubscription(processorId)
- subscription match {
- case Some(subscription) =>
- subscription.changeLife(subscriber.lifeTime cross this.life)
- case None =>
- val subscription = new Subscription(appId, executorId, taskId, subscriber,
- sessionId, this, maxPendingMessageCount, ackOnceEveryMessageCount)
- subscription.start()
- subscriptions :+=(subscriber.processorId, subscription)
- // Sorting, keep the order
- subscriptions = subscriptions.sortBy(_._1)
- }
- }
- sender ! TaskChanged(taskId, dagVersion)
- case LatencyProbe(timeStamp) =>
- receiveLatency.update(System.currentTimeMillis() - timeStamp)
- case send: SendMessageLoss =>
- LOG.info("received SendMessageLoss")
- throw new MsgLostException
- case other: AnyRef =>
- queue.add(other)
- doHandleMessage()
- }
-
- /**
- * Returns min clock of this task
- */
- def minClock: TimeStamp = _minClock
-
- /**
- * Returns min clock of upstream task
- */
- def getUpstreamMinClock: TimeStamp = upstreamMinClock
-
- private def receiveMessage(msg: Message, sender: ActorRef): Unit = {
- val messageAfterCheck = securityChecker.checkMessage(msg, sender)
- messageAfterCheck match {
- case Some(msg) =>
- queue.add(msg)
- doHandleMessage()
- case None =>
- // TODO: Indicate the error and avoid the LOG flood
- // LOG.error(s"Task $taskId drop message $msg")
- }
- }
-
- private def getSubscription(processorId: ProcessorId): Option[Subscription] = {
- subscriptions.find(_._1 == processorId).map(_._2)
- }
-}
-
-object TaskActor {
- // 3 seconds
- val CLOCK_SYNC_TIMEOUT_INTERVAL = 3 * 1000
-
- // If the message comes from an unknown source, securityChecker will drop it
- class SecurityChecker(task_id: TaskId, self: ActorRef) {
-
- private val LOG: Logger = LogUtil.getLogger(getClass, task = task_id)
-
- // Uses mutable HashMap for performance optimization
- private val receivedMsgCount = new IntShortHashMap()
-
- // Tricky performance optimization to save memory.
- // We store the session Id in the uid of ActorPath
- // ActorPath.hashCode is same as uid.
- private def getSessionId(actor: ActorRef): Int = {
- // TODO: As method uid is protected in [akka] package. We
- // are using hashCode instead of uid.
- actor.hashCode()
- }
-
- def handleInitialAckRequest(ackRequest: InitialAckRequest): Ack = {
- LOG.debug(s"Handle InitialAckRequest for session $ackRequest")
- val sessionId = ackRequest.sessionId
- if (sessionId == NONE_SESSION) {
- LOG.error(s"SessionId is not initialized, ackRequest: $ackRequest")
- null
- } else {
- receivedMsgCount.put(sessionId, 0)
- Ack(task_id, 0, 0, sessionId)
- }
- }
-
- def generateAckResponse(ackRequest: AckRequest, sender: ActorRef, incrementCount: Int): Ack = {
- val sessionId = ackRequest.sessionId
- if (receivedMsgCount.containsKey(sessionId)) {
- // Increments more count for each AckRequest
- // to throttle the number of unacked AckRequest
- receivedMsgCount.put(sessionId, (receivedMsgCount.get(sessionId) + incrementCount).toShort)
- Ack(task_id, ackRequest.seq, receivedMsgCount.get(sessionId), ackRequest.sessionId)
- } else {
- LOG.error(s"get unknown AckRequest $ackRequest from ${sender.toString()}")
- null
- }
- }
-
- // If the message comes from an unknown source, then drop it
- def checkMessage(message: Message, sender: ActorRef): Option[Message] = {
- if (sender.equals(self)) {
- Some(message)
- } else {
- val sessionId = getSessionId(sender)
- if (receivedMsgCount.containsKey(sessionId)) {
- receivedMsgCount.put(sessionId, (receivedMsgCount.get(sessionId) + 1).toShort)
- Some(message)
- } else {
- // This is an illegal message,
- LOG.debug(s"received message before receive the first AckRequest, session $sessionId")
- None
- }
- }
- }
- }
-
- case class SendAck(ack: Ack, targetTask: TaskId)
-
- case object FLUSH
-
- val NONE_SESSION = -1
-
- case class MessageAndSender(msg: AnyRef, sender: ActorRef)
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/task/TaskContextData.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/task/TaskContextData.scala b/streaming/src/main/scala/io/gearpump/streaming/task/TaskContextData.scala
deleted file mode 100644
index 28605cf..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/task/TaskContextData.scala
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.task
-
-import akka.actor.ActorRef
-
-import io.gearpump.streaming.LifeTime
-
-case class TaskContextData(
- executorId: Int,
- appId: Int,
- appName: String,
- appMaster: ActorRef,
- parallelism: Int,
- life: LifeTime,
- subscribers: List[Subscriber])
[20/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/test/scala/org/apache/gearpump/experiments/yarn/client/LaunchClusterSpec.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/test/scala/org/apache/gearpump/experiments/yarn/client/LaunchClusterSpec.scala b/experiments/yarn/src/test/scala/org/apache/gearpump/experiments/yarn/client/LaunchClusterSpec.scala
new file mode 100644
index 0000000..c0a4ee2
--- /dev/null
+++ b/experiments/yarn/src/test/scala/org/apache/gearpump/experiments/yarn/client/LaunchClusterSpec.scala
@@ -0,0 +1,232 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.yarn.client
+
+import java.io.{ByteArrayInputStream, ByteArrayOutputStream, InputStream, OutputStream}
+import java.util.Random
+import java.util.zip.{ZipEntry, ZipOutputStream}
+
+import akka.actor.ActorSystem
+import akka.testkit.TestProbe
+import com.typesafe.config.ConfigFactory
+import org.apache.gearpump.cluster.TestUtil
+import org.apache.gearpump.experiments.yarn.appmaster.YarnAppMaster.{ActiveConfig, GetActiveConfig}
+import org.apache.gearpump.experiments.yarn.glue.Records._
+import org.apache.gearpump.experiments.yarn.glue.{FileSystem, YarnClient, YarnConfig}
+import org.apache.gearpump.util.FileUtils
+import org.mockito.Matchers._
+import org.mockito.Mockito._
+import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
+
+import scala.concurrent.Await
+import scala.concurrent.duration.Duration
+import scala.util.Try
+class LaunchClusterSpec extends FlatSpec with Matchers with BeforeAndAfterAll {
+ implicit var system: ActorSystem = null
+
+ val rand = new Random()
+
+ private def randomArray(size: Int): Array[Byte] = {
+ val array = new Array[Byte](size)
+ rand.nextBytes(array)
+ array
+ }
+ val appId = ApplicationId.newInstance(0L, 0)
+
+ val akka = ConfigFactory.parseString(
+
+ """
+ |gearpump {
+ | yarn {
+ | client {
+ | package -path = "/user/gearpump/gearpump.zip"
+ | }
+ |
+ | applicationmaster {
+ | ## Memory of YarnAppMaster
+ | command = "$JAVA_HOME/bin/java -Xmx512m"
+ | memory = "512"
+ | vcores = "1"
+ | queue = "default"
+ | }
+ |
+ | master {
+ | ## Memory of master daemon
+ | command = "$JAVA_HOME/bin/java -Xmx512m"
+ | containers = "2"
+ | memory = "512"
+ | vcores = "1"
+ | }
+ |
+ | worker {
+ | ## memory of worker daemon
+ | command = "$JAVA_HOME/bin/java -Xmx512m"
+ | containers = "4"
+ | ## This also contains all memory for child executors.
+ | memory = "4096"
+ | vcores = "1"
+ | }
+ | services {
+ | enabled = true
+ | }
+ | }
+ |}
+ """.stripMargin).withFallback(TestUtil.DEFAULT_CONFIG)
+
+ override def beforeAll(): Unit = {
+ system = ActorSystem(getClass.getSimpleName, akka)
+ }
+
+ override def afterAll(): Unit = {
+ system.terminate()
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+
+ it should "reject non-zip files" in {
+ val yarnConfig = mock(classOf[YarnConfig])
+ val yarnClient = mock(classOf[YarnClient])
+ val fs = mock(classOf[FileSystem])
+ val appMasterResolver = mock(classOf[AppMasterResolver])
+
+ val launcher = new LaunchCluster(akka, yarnConfig, yarnClient, fs, system, appMasterResolver)
+ val packagePath = "gearpump.zip2"
+ assert(Try(launcher.submit("gearpump", packagePath)).isFailure)
+ }
+
+ it should "reject if we cannot find the package file on HDFS" in {
+ val yarnConfig = mock(classOf[YarnConfig])
+ val yarnClient = mock(classOf[YarnClient])
+ val fs = mock(classOf[FileSystem])
+ val appMasterResolver = mock(classOf[AppMasterResolver])
+
+ val launcher = new LaunchCluster(akka, yarnConfig, yarnClient, fs, system, appMasterResolver)
+ val packagePath = "gearpump.zip"
+ when(fs.exists(anyString)).thenReturn(false)
+ assert(Try(launcher.submit("gearpump", packagePath)).isFailure)
+ }
+
+ it should "throw when package exists on HDFS, but the file is corrupted" in {
+ val yarnConfig = mock(classOf[YarnConfig])
+ val yarnClient = mock(classOf[YarnClient])
+ val fs = mock(classOf[FileSystem])
+ val appMasterResolver = mock(classOf[AppMasterResolver])
+
+ val launcher = new LaunchCluster(akka, yarnConfig, yarnClient, fs, system, appMasterResolver)
+ val packagePath = "gearpump.zip"
+ when(fs.exists(anyString)).thenReturn(true)
+
+ val content = new ByteArrayInputStream(randomArray(10))
+ when(fs.open(anyString)).thenReturn(content)
+ assert(Try(launcher.submit("gearpump", packagePath)).isFailure)
+ content.close()
+ }
+
+ it should "throw when the HDFS package version is not consistent with local version" in {
+ val yarnConfig = mock(classOf[YarnConfig])
+ val yarnClient = mock(classOf[YarnClient])
+ val fs = mock(classOf[FileSystem])
+ val appMasterResolver = mock(classOf[AppMasterResolver])
+
+ val version = "gearpump-0.2"
+ val launcher = new LaunchCluster(akka, yarnConfig, yarnClient, fs, system,
+ appMasterResolver, version)
+ val packagePath = "gearpump.zip"
+ when(fs.exists(anyString)).thenReturn(true)
+
+ val oldVesion = "gearpump-0.1"
+ when(fs.open(anyString)).thenReturn(zipInputStream(oldVesion))
+ assert(Try(launcher.submit("gearpump", packagePath)).isFailure)
+ }
+
+ it should "upload config file to HDFS when submitting" in {
+ val yarnConfig = mock(classOf[YarnConfig])
+ val yarnClient = mock(classOf[YarnClient])
+ val fs = mock(classOf[FileSystem])
+ val appMasterResolver = mock(classOf[AppMasterResolver])
+
+ val version = "gearpump-0.2"
+ val launcher = new LaunchCluster(akka, yarnConfig, yarnClient,
+ fs, system, appMasterResolver, version)
+ val packagePath = "gearpump.zip"
+
+ val out = mock(classOf[OutputStream])
+ when(fs.exists(anyString)).thenReturn(true)
+ when(fs.create(anyString)).thenReturn(out)
+ when(fs.getHomeDirectory).thenReturn("/root")
+
+ when(fs.open(anyString)).thenReturn(zipInputStream(version))
+
+ val report = mock(classOf[ApplicationReport])
+ when(yarnClient.awaitApplication(any[ApplicationId], anyLong())).thenReturn(report)
+
+ when(report.getApplicationId).thenReturn(appId)
+ when(yarnClient.createApplication).thenReturn(appId)
+ assert(appId == launcher.submit("gearpump", packagePath))
+
+ // 3 Config files are uploaded to HDFS, one is akka.conf,
+ // one is yarn-site.xml, one is log4j.properties.
+ verify(fs, times(3)).create(anyString)
+ verify(out, times(3)).close()
+
+ // val workerResources = ArgumentCaptor.forClass(classOf[List[Resource]])
+ // scalastyle:off line.size.limit
+ val expectedCommand = "$JAVA_HOME/bin/java -Xmx512m -cp conf:pack/gearpump-0.2/conf:pack/gearpump-0.2/dashboard:pack/gearpump-0.2/lib/*:pack/gearpump-0.2/lib/daemon/*:pack/gearpump-0.2/lib/services/*:pack/gearpump-0.2/lib/yarn/*:$CLASSPATH -Dgearpump.home={{LOCAL_DIRS}}/{{CONTAINER_ID}}/pack/gearpump-0.2 -Dgearpump.binary-version-with-scala-version=gearpump-0.2 -Dgearpump.log.daemon.dir=<LOG_DIR> -Dgearpump.log.application.dir=<LOG_DIR> -Dgearpump.hostname={{NM_HOST}} org.apache.gearpump.experiments.yarn.appmaster.YarnAppMaster -conf /root/.gearpump_application_0_0000/conf/ -package gearpump.zip 2>&1 | /usr/bin/tee -a <LOG_DIR>/stderr"
+ // scalastyle:on line.size.limit
+ verify(yarnClient).submit("gearpump", appId, expectedCommand,
+ Resource.newInstance(512, 1), "default",
+ "gearpump.zip", "/root/.gearpump_application_0_0000/conf/")
+ }
+
+ it should "save active config from Gearpump cluster" in {
+ val yarnConfig = mock(classOf[YarnConfig])
+ val yarnClient = mock(classOf[YarnClient])
+ val fs = mock(classOf[FileSystem])
+ val appMasterResolver = mock(classOf[AppMasterResolver])
+ val appMaster = TestProbe()
+
+ val version = "gearpump-0.2"
+ val launcher = new LaunchCluster(akka, yarnConfig, yarnClient, fs, system,
+ appMasterResolver, version)
+ val outputPath = java.io.File.createTempFile("LaunchClusterSpec", ".conf")
+
+ when(appMasterResolver.resolve(any[ApplicationId], anyInt)).thenReturn(appMaster.ref)
+ val fileFuture = launcher.saveConfig(appId, outputPath.getPath)
+ appMaster.expectMsgType[GetActiveConfig]
+ appMaster.reply(ActiveConfig(ConfigFactory.empty()))
+
+ import scala.concurrent.duration._
+ val file = Await.result(fileFuture, 30.seconds).asInstanceOf[java.io.File]
+
+ assert(!FileUtils.read(file).isEmpty)
+ file.delete()
+ }
+
+ private def zipInputStream(version: String): InputStream = {
+ val bytes = new ByteArrayOutputStream(1000)
+ val zipOut = new ZipOutputStream(bytes)
+
+ // Not available on BufferedOutputStream
+ zipOut.putNextEntry(new ZipEntry(s"$version/README.md"))
+ zipOut.write("README".getBytes())
+ // Not available on BufferedOutputStream
+ zipOut.closeEntry()
+ zipOut.close()
+ new ByteArrayInputStream(bytes.toByteArray)
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/test/scala/org/apache/gearpump/experiments/yarn/client/ManageClusterSpec.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/test/scala/org/apache/gearpump/experiments/yarn/client/ManageClusterSpec.scala b/experiments/yarn/src/test/scala/org/apache/gearpump/experiments/yarn/client/ManageClusterSpec.scala
new file mode 100644
index 0000000..01960ad
--- /dev/null
+++ b/experiments/yarn/src/test/scala/org/apache/gearpump/experiments/yarn/client/ManageClusterSpec.scala
@@ -0,0 +1,141 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.yarn.client
+
+import akka.actor.ActorSystem
+import akka.testkit.TestProbe
+import com.typesafe.config.ConfigFactory
+import org.apache.gearpump.cluster.ClientToMaster.{AddWorker, CommandResult, RemoveWorker}
+import org.apache.gearpump.cluster.TestUtil
+import org.apache.gearpump.cluster.main.ParseResult
+import org.apache.gearpump.experiments.yarn.appmaster.YarnAppMaster.{ActiveConfig, ClusterInfo, GetActiveConfig, Kill, QueryClusterInfo, QueryVersion, Version}
+import org.apache.gearpump.experiments.yarn.client.ManageCluster._
+import org.apache.gearpump.experiments.yarn.glue.Records.ApplicationId
+import org.apache.gearpump.util.FileUtils
+import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
+
+import scala.concurrent.Await
+import scala.concurrent.duration.Duration
+
+class ManageClusterSpec extends FlatSpec with Matchers with BeforeAndAfterAll {
+
+ implicit var system: ActorSystem = null
+
+ override def beforeAll(): Unit = {
+ system = ActorSystem("test", TestUtil.DEFAULT_CONFIG)
+ }
+
+ override def afterAll(): Unit = {
+ system.terminate()
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+
+ it should "getConfig from remote Gearpump" in {
+ val appId = ApplicationId.newInstance(0L, 0)
+ val appMaster = TestProbe()
+ val manager = new ManageCluster(appId, appMaster.ref, system)
+
+ val output = java.io.File.createTempFile("managerClusterSpec", ".conf")
+
+ val future = manager.command(GET_CONFIG, new ParseResult(Map("output" -> output.toString),
+ Array.empty[String]))
+ appMaster.expectMsgType[GetActiveConfig]
+ appMaster.reply(ActiveConfig(ConfigFactory.empty()))
+ import scala.concurrent.duration._
+ Await.result(future, 30.seconds)
+
+ val content = FileUtils.read(output)
+ assert(content.length > 0)
+ output.delete()
+ }
+
+ it should "addworker" in {
+ val appId = ApplicationId.newInstance(0L, 0)
+ val appMaster = TestProbe()
+ val manager = new ManageCluster(appId, appMaster.ref, system)
+
+ val future = manager.command(ADD_WORKER, new ParseResult(Map("count" -> 1.toString),
+ Array.empty[String]))
+ appMaster.expectMsg(AddWorker(1))
+ appMaster.reply(CommandResult(true))
+ import scala.concurrent.duration._
+ val result = Await.result(future, 30.seconds).asInstanceOf[CommandResult]
+ assert(result.success)
+ }
+
+ it should "removeworker" in {
+ val appId = ApplicationId.newInstance(0L, 0)
+ val appMaster = TestProbe()
+ val manager = new ManageCluster(appId, appMaster.ref, system)
+
+ val future = manager.command(REMOVE_WORKER, new ParseResult(Map("container" -> "1"),
+ Array.empty[String]))
+ appMaster.expectMsg(RemoveWorker("1"))
+ appMaster.reply(CommandResult(true))
+ import scala.concurrent.duration._
+ val result = Await.result(future, 30.seconds).asInstanceOf[CommandResult]
+ assert(result.success)
+ }
+
+ it should "get version" in {
+ val appId = ApplicationId.newInstance(0L, 0)
+ val appMaster = TestProbe()
+ val manager = new ManageCluster(appId, appMaster.ref, system)
+ val future = manager.command(VERSION, new ParseResult(Map("container" -> "1"),
+ Array.empty[String]))
+ appMaster.expectMsg(QueryVersion)
+ appMaster.reply(Version("version 0.1"))
+ import scala.concurrent.duration._
+ val result = Await.result(future, 30.seconds).asInstanceOf[Version]
+ assert(result.version == "version 0.1")
+ }
+
+ it should "get cluster info" in {
+ val appId = ApplicationId.newInstance(0L, 0)
+ val appMaster = TestProbe()
+ val manager = new ManageCluster(appId, appMaster.ref, system)
+
+ val output = java.io.File.createTempFile("managerClusterSpec", ".conf")
+
+ val future = manager.command(QUERY, new ParseResult(Map.empty[String, String],
+ Array.empty[String]))
+ appMaster.expectMsg(QueryClusterInfo)
+ appMaster.reply(ClusterInfo(List("master"), List("worker")))
+ import scala.concurrent.duration._
+ val result = Await.result(future, 30.seconds).asInstanceOf[ClusterInfo]
+ assert(result.masters.sameElements(List("master")))
+ assert(result.workers.sameElements(List("worker")))
+ }
+
+ it should "kill the cluster" in {
+ val appId = ApplicationId.newInstance(0L, 0)
+ val appMaster = TestProbe()
+ val manager = new ManageCluster(appId, appMaster.ref, system)
+
+ val output = java.io.File.createTempFile("managerClusterSpec", ".conf")
+
+ val future = manager.command(KILL, new ParseResult(Map("container" -> "1"),
+ Array.empty[String]))
+ appMaster.expectMsg(Kill)
+ appMaster.reply(CommandResult(true))
+ import scala.concurrent.duration._
+ val result = Await.result(future, 30.seconds).asInstanceOf[CommandResult]
+ assert(result.success)
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/HadoopCheckpointStore.scala
----------------------------------------------------------------------
diff --git a/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/HadoopCheckpointStore.scala b/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/HadoopCheckpointStore.scala
deleted file mode 100644
index 194c9a5..0000000
--- a/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/HadoopCheckpointStore.scala
+++ /dev/null
@@ -1,164 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.hadoop
-
-import org.apache.hadoop.conf.Configuration
-import org.apache.hadoop.fs.{FileSystem, Path}
-import org.slf4j.Logger
-
-import io.gearpump.TimeStamp
-import io.gearpump.streaming.hadoop.lib.rotation.Rotation
-import io.gearpump.streaming.hadoop.lib.{HadoopCheckpointStoreReader, HadoopCheckpointStoreWriter}
-import io.gearpump.streaming.transaction.api.CheckpointStore
-import io.gearpump.util.LogUtil
-
-object HadoopCheckpointStore {
- val LOG: Logger = LogUtil.getLogger(classOf[HadoopCheckpointStore])
-}
-
-/**
- * Stores timestamp-checkpoint mapping to Hadoop-compatible filesystem.
- *
- * Store file layout:
- * {{{
- * timestamp1, index1,
- * timestamp2, index2,
- * ...
- * timestampN, indexN
- * }}}
- */
-class HadoopCheckpointStore(
- dir: Path,
- fs: FileSystem,
- hadoopConfig: Configuration,
- rotation: Rotation)
- extends CheckpointStore {
-
- private[hadoop] var curTime = 0L
- private[hadoop] var curStartTime = curTime
- private[hadoop] var curFile: Option[String] = None
- private[hadoop] var curWriter: Option[HadoopCheckpointStoreWriter] = None
- // regex (checkpoints-$startTime-$endTime.store) for complete checkpoint file,
- private val compRegex =
- """checkpoints-(\d+)-(\d+).store""".r
- // regex (checkpoints-$startTime.store) for temporary checkpoint file
- private val tempRegex =
- """checkpoints-(\d+).store""".r
-
- /**
- * Persists a pair of timestamp and checkpoint, which:
- *
- * 1. creates a temporary checkpoint file, checkpoints-\$startTime.store, if not exist
- * 2. writes out (timestamp, checkpoint) and marks rotation
- * 3. rotates checkpoint file if needed
- * a. renames temporary checkpoint file to checkpoints-\$startTime-\$endTime.store
- * b. closes current writer and reset
- * c. rotation rotates
- */
- override def persist(timestamp: TimeStamp, checkpoint: Array[Byte]): Unit = {
- curTime = timestamp
- if (curWriter.isEmpty) {
- curStartTime = curTime
- curFile = Some(s"checkpoints-$curStartTime.store")
- curWriter = curFile.map(file =>
- new HadoopCheckpointStoreWriter(new Path(dir, file), hadoopConfig))
- }
-
- curWriter.foreach { w =>
- val offset = w.write(timestamp, checkpoint)
- rotation.mark(timestamp, offset)
- }
-
- if (rotation.shouldRotate) {
- curFile.foreach { f =>
- fs.rename(new Path(dir, f), new Path(dir, s"checkpoints-$curStartTime-$curTime.store"))
- curWriter.foreach(_.close())
- curWriter = None
- }
- rotation.rotate
- }
- }
-
- /**
- * Recovers checkpoint given timestamp, which
- * {{{
- * 1. returns None if no store exists
- * 2. searches checkpoint stores for
- * a. complete store checkpoints-\$startTime-\$endTime.store
- * where startTime <= timestamp <= endTime
- * b. temporary store checkpoints-\$startTime.store
- * where startTime <= timestamp
- * 3. renames store to checkpoints-\$startTime-\$endTime.store
- * 4. deletes all stores whose name has a startTime larger than timestamp
- * 5. looks for the checkpoint in the found store
- * }}}
- */
- override def recover(timestamp: TimeStamp): Option[Array[Byte]] = {
- var checkpoint: Option[Array[Byte]] = None
-
- if (fs.exists(dir)) {
- var checkpointFile: Option[Path] = None
- fs.listStatus(dir).map(_.getPath).foreach { file =>
- val fileName = file.getName
- fileName match {
- case compRegex(start, end) =>
- val startTime = start.toLong
- val endTime = end.toLong
- if (timestamp >= startTime && timestamp <= endTime) {
- checkpointFile = Some(new Path(dir, fileName))
- } else if (timestamp < startTime) {
- fs.delete(file, true)
- }
- case tempRegex(start) =>
- val startTime = start.toLong
- if (timestamp >= startTime) {
- val newFile = new Path(dir, s"checkpoints-$startTime-$timestamp.store")
- fs.rename(new Path(dir, fileName), newFile)
- checkpointFile = Some(newFile)
- }
- }
- }
-
- checkpointFile.foreach { file =>
- val reader = new HadoopCheckpointStoreReader(file, hadoopConfig)
-
- @annotation.tailrec
- def read: Option[Array[Byte]] = {
- if (reader.hasNext) {
- val (time, bytes) = reader.next()
- if (time == timestamp) {
- Some(bytes)
- } else {
- read
- }
- } else {
- None
- }
- }
- checkpoint = read
- reader.close()
- }
- }
- checkpoint
- }
-
- override def close(): Unit = {
- curWriter.foreach(_.close())
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/HadoopCheckpointStoreFactory.scala
----------------------------------------------------------------------
diff --git a/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/HadoopCheckpointStoreFactory.scala b/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/HadoopCheckpointStoreFactory.scala
deleted file mode 100644
index 5a81ecd..0000000
--- a/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/HadoopCheckpointStoreFactory.scala
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.hadoop
-
-import java.io.{ObjectInputStream, ObjectOutputStream}
-
-import org.apache.hadoop.conf.Configuration
-import org.apache.hadoop.fs.Path
-
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.hadoop.lib.HadoopUtil
-import io.gearpump.streaming.hadoop.lib.rotation.{FileSizeRotation, Rotation}
-import io.gearpump.streaming.task.TaskContext
-import io.gearpump.streaming.transaction.api.{CheckpointStore, CheckpointStoreFactory}
-
-object HadoopCheckpointStoreFactory {
- val VERSION = 1
-}
-
-class HadoopCheckpointStoreFactory(
- dir: String,
- @transient private var hadoopConfig: Configuration,
- rotation: Rotation = new FileSizeRotation(128 * Math.pow(2, 20).toLong))
- extends CheckpointStoreFactory {
- import io.gearpump.streaming.hadoop.HadoopCheckpointStoreFactory._
-
- private def writeObject(out: ObjectOutputStream): Unit = {
- out.defaultWriteObject()
- hadoopConfig.write(out)
- }
-
- private def readObject(in: ObjectInputStream): Unit = {
- in.defaultReadObject()
- hadoopConfig = new Configuration(false)
- hadoopConfig.readFields(in)
- }
-
- override def getCheckpointStore(conf: UserConfig, taskContext: TaskContext): CheckpointStore = {
- import taskContext.{appId, taskId}
- val dirPath = new Path(dir + Path.SEPARATOR + s"v$VERSION",
- s"app$appId-task${taskId.processorId}_${taskId.index}")
- val fs = HadoopUtil.getFileSystemForPath(dirPath, hadoopConfig)
- new HadoopCheckpointStore(dirPath, fs, hadoopConfig, rotation)
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/SequenceFileSink.scala
----------------------------------------------------------------------
diff --git a/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/SequenceFileSink.scala b/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/SequenceFileSink.scala
deleted file mode 100644
index a07dbbc..0000000
--- a/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/SequenceFileSink.scala
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.hadoop
-
-import java.text.SimpleDateFormat
-
-import org.apache.hadoop.fs.Path
-import org.apache.hadoop.hdfs.HdfsConfiguration
-import org.apache.hadoop.io.SequenceFile
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.hadoop.lib.HadoopUtil
-import io.gearpump.streaming.hadoop.lib.format.{DefaultSequenceFormatter, OutputFormatter}
-import io.gearpump.streaming.hadoop.lib.rotation.{FileSizeRotation, Rotation}
-import io.gearpump.streaming.sink.DataSink
-import io.gearpump.streaming.task.{TaskContext, TaskId}
-
-class SequenceFileSink(
- userConfig: UserConfig,
- basePath: String,
- rotation: Rotation = new FileSizeRotation(128 * Math.pow(2, 20).toLong),
- sequenceFormat: OutputFormatter = new DefaultSequenceFormatter)
- extends DataSink{
- @transient private lazy val configuration = new HdfsConfiguration()
- private val dateFormat = new SimpleDateFormat("yyyy_MM_dd-HH-mm-ss")
- private var writer: SequenceFile.Writer = null
- private var taskId: TaskId = null
- private var appName: String = null
-
- /**
- * Starts connection to data sink
- *
- * Invoked at onStart() method of [[io.gearpump.streaming.task.Task]]
- *
- * @param context is the task context at runtime
- */
- override def open(context: TaskContext): Unit = {
- HadoopUtil.login(userConfig, configuration)
- this.appName = context.appName
- this.taskId = context.taskId
- this.writer = getNextWriter
- }
-
- /**
- * Writes message into data sink
- *
- * Invoked at onNext() method of [[io.gearpump.streaming.task.Task]]
- * @param message wraps data to be written out
- */
- override def write(message: Message): Unit = {
- val key = sequenceFormat.getKey(message)
- val value = sequenceFormat.getValue(message)
- if (writer == null) {
- writer = getNextWriter
- }
- writer.append(key, value)
- rotation.mark(message.timestamp, writer.getLength)
- if (rotation.shouldRotate) {
- closeWriter
- this.writer = getNextWriter
- rotation.rotate
- }
- }
-
- /**
- * Closes connection to data sink
- *
- * Invoked at onClose() method of [[io.gearpump.streaming.task.Task]]
- */
- override def close(): Unit = {
- closeWriter()
- }
-
- private def closeWriter(): Unit = {
- Option(writer).foreach { w =>
- w.hflush()
- w.close()
- }
- }
-
- private def getNextWriter: SequenceFile.Writer = {
- SequenceFile.createWriter(
- configuration,
- SequenceFile.Writer.file(getNextFilePath),
- SequenceFile.Writer.keyClass(sequenceFormat.getKeyClass),
- SequenceFile.Writer.valueClass(sequenceFormat.getValueClass)
- )
- }
-
- private def getNextFilePath: Path = {
- val base = new Path(basePath, s"$appName-task${taskId.processorId}_${taskId.index}")
- new Path(base, dateFormat.format(new java.util.Date))
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/lib/HadoopCheckpointStoreReader.scala
----------------------------------------------------------------------
diff --git a/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/lib/HadoopCheckpointStoreReader.scala b/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/lib/HadoopCheckpointStoreReader.scala
deleted file mode 100644
index 52acbac..0000000
--- a/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/lib/HadoopCheckpointStoreReader.scala
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.hadoop.lib
-
-import java.io.EOFException
-
-import org.apache.hadoop.conf.Configuration
-import org.apache.hadoop.fs.Path
-
-import io.gearpump.TimeStamp
-
-class HadoopCheckpointStoreReader(
- path: Path,
- hadoopConfig: Configuration)
- extends Iterator[(TimeStamp, Array[Byte])] {
-
- private val stream = HadoopUtil.getInputStream(path, hadoopConfig)
- private var nextTimeStamp: Option[TimeStamp] = None
- private var nextData: Option[Array[Byte]] = None
-
- override def hasNext: Boolean = {
- if (nextTimeStamp.isDefined) {
- true
- } else {
- try {
- nextTimeStamp = Some(stream.readLong())
- val length = stream.readInt()
- val buffer = new Array[Byte](length)
- stream.readFully(buffer)
- nextData = Some(buffer)
- true
- } catch {
- case e: EOFException =>
- close()
- false
- case e: Exception =>
- close()
- throw e
- }
- }
- }
-
- override def next(): (TimeStamp, Array[Byte]) = {
- val timeAndData = for {
- time <- nextTimeStamp
- data <- nextData
- } yield (time, data)
- nextTimeStamp = None
- nextData = None
- timeAndData.get
- }
-
- def close(): Unit = {
- stream.close()
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/lib/HadoopCheckpointStoreWriter.scala
----------------------------------------------------------------------
diff --git a/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/lib/HadoopCheckpointStoreWriter.scala b/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/lib/HadoopCheckpointStoreWriter.scala
deleted file mode 100644
index 35f2f51..0000000
--- a/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/lib/HadoopCheckpointStoreWriter.scala
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.hadoop.lib
-
-import org.apache.hadoop.conf.Configuration
-import org.apache.hadoop.fs.Path
-
-import io.gearpump.TimeStamp
-
-class HadoopCheckpointStoreWriter(path: Path, hadoopConfig: Configuration) {
- private lazy val stream = HadoopUtil.getOutputStream(path, hadoopConfig)
-
- def write(timestamp: TimeStamp, data: Array[Byte]): Long = {
- stream.writeLong(timestamp)
- stream.writeInt(data.length)
- stream.write(data)
- stream.hflush()
- stream.getPos()
- }
-
- def close(): Unit = {
- stream.close()
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/lib/HadoopUtil.scala
----------------------------------------------------------------------
diff --git a/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/lib/HadoopUtil.scala b/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/lib/HadoopUtil.scala
deleted file mode 100644
index eb579e4..0000000
--- a/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/lib/HadoopUtil.scala
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.hadoop.lib
-
-import java.io.File
-
-import org.apache.hadoop.conf.Configuration
-import org.apache.hadoop.fs._
-import org.apache.hadoop.security.UserGroupInformation
-
-import io.gearpump.cluster.UserConfig
-import io.gearpump.util.{Constants, FileUtils}
-
-private[hadoop] object HadoopUtil {
-
- def getOutputStream(path: Path, hadoopConfig: Configuration): FSDataOutputStream = {
- val dfs = getFileSystemForPath(path, hadoopConfig)
- val stream: FSDataOutputStream = {
- if (dfs.isFile(path)) {
- dfs.append(path)
- } else {
- dfs.create(path)
- }
- }
- stream
- }
-
- def getInputStream(path: Path, hadoopConfig: Configuration): FSDataInputStream = {
- val dfs = getFileSystemForPath(path, hadoopConfig)
- val stream = dfs.open(path)
- stream
- }
-
- def getFileSystemForPath(path: Path, hadoopConfig: Configuration): FileSystem = {
- // For local file systems, return the raw local file system, such calls to flush()
- // actually flushes the stream.
- val fs = path.getFileSystem(hadoopConfig)
- fs match {
- case localFs: LocalFileSystem => localFs.getRawFileSystem
- case _ => fs
- }
- }
-
- def login(userConfig: UserConfig, configuration: Configuration): Unit = {
- if (UserGroupInformation.isSecurityEnabled) {
- val principal = userConfig.getString(Constants.GEARPUMP_KERBEROS_PRINCIPAL)
- val keytabContent = userConfig.getBytes(Constants.GEARPUMP_KEYTAB_FILE)
- if (principal.isEmpty || keytabContent.isEmpty) {
- val errorMsg = s"HDFS is security enabled, user should provide kerberos principal in " +
- s"${Constants.GEARPUMP_KERBEROS_PRINCIPAL} " +
- s"and keytab file in ${Constants.GEARPUMP_KEYTAB_FILE}"
- throw new Exception(errorMsg)
- }
- val keytabFile = File.createTempFile("login", ".keytab")
- FileUtils.writeByteArrayToFile(keytabFile, keytabContent.get)
- keytabFile.setExecutable(false)
- keytabFile.setWritable(false)
- keytabFile.setReadable(true, true)
-
- UserGroupInformation.setConfiguration(configuration)
- UserGroupInformation.loginUserFromKeytab(principal.get, keytabFile.getAbsolutePath)
- keytabFile.delete()
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/lib/format/DefaultSequenceFormatter.scala
----------------------------------------------------------------------
diff --git a/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/lib/format/DefaultSequenceFormatter.scala b/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/lib/format/DefaultSequenceFormatter.scala
deleted file mode 100644
index d19e71f..0000000
--- a/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/lib/format/DefaultSequenceFormatter.scala
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.hadoop.lib.format
-
-import org.apache.hadoop.io.{LongWritable, Text, Writable}
-
-import io.gearpump.Message
-
-class DefaultSequenceFormatter extends OutputFormatter {
- override def getKey(message: Message): Writable = new LongWritable(message.timestamp)
-
- override def getValue(message: Message): Writable = new Text(message.msg.asInstanceOf[String])
-
- override def getKeyClass: Class[_ <: Writable] = classOf[LongWritable]
-
- override def getValueClass: Class[_ <: Writable] = classOf[Text]
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/lib/format/OutputFormatter.scala
----------------------------------------------------------------------
diff --git a/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/lib/format/OutputFormatter.scala b/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/lib/format/OutputFormatter.scala
deleted file mode 100644
index fe8e52e..0000000
--- a/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/lib/format/OutputFormatter.scala
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.hadoop.lib.format
-
-import org.apache.hadoop.io.Writable
-
-import io.gearpump.Message
-
-trait OutputFormatter extends Serializable {
- def getKeyClass: Class[_ <: Writable]
-
- def getValueClass: Class[_ <: Writable]
-
- def getKey(message: Message): Writable
-
- def getValue(message: Message): Writable
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/lib/rotation/FileSizeRotation.scala
----------------------------------------------------------------------
diff --git a/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/lib/rotation/FileSizeRotation.scala b/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/lib/rotation/FileSizeRotation.scala
deleted file mode 100644
index cd83ea5..0000000
--- a/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/lib/rotation/FileSizeRotation.scala
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.hadoop.lib.rotation
-
-import io.gearpump.TimeStamp
-
-case class FileSizeRotation(maxBytes: Long) extends Rotation {
-
- private var bytesWritten = 0L
-
- override def mark(timestamp: TimeStamp, offset: Long): Unit = {
- bytesWritten = offset
- }
-
- override def shouldRotate: Boolean = bytesWritten >= maxBytes
-
- override def rotate(): Unit = {
- bytesWritten = 0L
- }
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/lib/rotation/Rotation.scala
----------------------------------------------------------------------
diff --git a/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/lib/rotation/Rotation.scala b/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/lib/rotation/Rotation.scala
deleted file mode 100644
index e28b222..0000000
--- a/external/hadoopfs/src/main/scala/io/gearpump/streaming/hadoop/lib/rotation/Rotation.scala
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.hadoop.lib.rotation
-
-import io.gearpump.TimeStamp
-
-trait Rotation extends Serializable {
- def mark(timestamp: TimeStamp, offset: Long): Unit
- def shouldRotate: Boolean
- def rotate(): Unit
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/HadoopCheckpointStore.scala
----------------------------------------------------------------------
diff --git a/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/HadoopCheckpointStore.scala b/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/HadoopCheckpointStore.scala
new file mode 100644
index 0000000..a18cce6
--- /dev/null
+++ b/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/HadoopCheckpointStore.scala
@@ -0,0 +1,164 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.hadoop
+
+import org.apache.hadoop.conf.Configuration
+import org.apache.hadoop.fs.{FileSystem, Path}
+import org.slf4j.Logger
+
+import org.apache.gearpump.TimeStamp
+import org.apache.gearpump.streaming.hadoop.lib.rotation.Rotation
+import org.apache.gearpump.streaming.hadoop.lib.{HadoopCheckpointStoreReader, HadoopCheckpointStoreWriter}
+import org.apache.gearpump.streaming.transaction.api.CheckpointStore
+import org.apache.gearpump.util.LogUtil
+
+object HadoopCheckpointStore {
+ val LOG: Logger = LogUtil.getLogger(classOf[HadoopCheckpointStore])
+}
+
+/**
+ * Stores timestamp-checkpoint mapping to Hadoop-compatible filesystem.
+ *
+ * Store file layout:
+ * {{{
+ * timestamp1, index1,
+ * timestamp2, index2,
+ * ...
+ * timestampN, indexN
+ * }}}
+ */
+class HadoopCheckpointStore(
+ dir: Path,
+ fs: FileSystem,
+ hadoopConfig: Configuration,
+ rotation: Rotation)
+ extends CheckpointStore {
+
+ private[hadoop] var curTime = 0L
+ private[hadoop] var curStartTime = curTime
+ private[hadoop] var curFile: Option[String] = None
+ private[hadoop] var curWriter: Option[HadoopCheckpointStoreWriter] = None
+ // regex (checkpoints-$startTime-$endTime.store) for complete checkpoint file,
+ private val compRegex =
+ """checkpoints-(\d+)-(\d+).store""".r
+ // regex (checkpoints-$startTime.store) for temporary checkpoint file
+ private val tempRegex =
+ """checkpoints-(\d+).store""".r
+
+ /**
+ * Persists a pair of timestamp and checkpoint, which:
+ *
+ * 1. creates a temporary checkpoint file, checkpoints-\$startTime.store, if not exist
+ * 2. writes out (timestamp, checkpoint) and marks rotation
+ * 3. rotates checkpoint file if needed
+ * a. renames temporary checkpoint file to checkpoints-\$startTime-\$endTime.store
+ * b. closes current writer and reset
+ * c. rotation rotates
+ */
+ override def persist(timestamp: TimeStamp, checkpoint: Array[Byte]): Unit = {
+ curTime = timestamp
+ if (curWriter.isEmpty) {
+ curStartTime = curTime
+ curFile = Some(s"checkpoints-$curStartTime.store")
+ curWriter = curFile.map(file =>
+ new HadoopCheckpointStoreWriter(new Path(dir, file), hadoopConfig))
+ }
+
+ curWriter.foreach { w =>
+ val offset = w.write(timestamp, checkpoint)
+ rotation.mark(timestamp, offset)
+ }
+
+ if (rotation.shouldRotate) {
+ curFile.foreach { f =>
+ fs.rename(new Path(dir, f), new Path(dir, s"checkpoints-$curStartTime-$curTime.store"))
+ curWriter.foreach(_.close())
+ curWriter = None
+ }
+ rotation.rotate
+ }
+ }
+
+ /**
+ * Recovers checkpoint given timestamp, which
+ * {{{
+ * 1. returns None if no store exists
+ * 2. searches checkpoint stores for
+ * a. complete store checkpoints-\$startTime-\$endTime.store
+ * where startTime <= timestamp <= endTime
+ * b. temporary store checkpoints-\$startTime.store
+ * where startTime <= timestamp
+ * 3. renames store to checkpoints-\$startTime-\$endTime.store
+ * 4. deletes all stores whose name has a startTime larger than timestamp
+ * 5. looks for the checkpoint in the found store
+ * }}}
+ */
+ override def recover(timestamp: TimeStamp): Option[Array[Byte]] = {
+ var checkpoint: Option[Array[Byte]] = None
+
+ if (fs.exists(dir)) {
+ var checkpointFile: Option[Path] = None
+ fs.listStatus(dir).map(_.getPath).foreach { file =>
+ val fileName = file.getName
+ fileName match {
+ case compRegex(start, end) =>
+ val startTime = start.toLong
+ val endTime = end.toLong
+ if (timestamp >= startTime && timestamp <= endTime) {
+ checkpointFile = Some(new Path(dir, fileName))
+ } else if (timestamp < startTime) {
+ fs.delete(file, true)
+ }
+ case tempRegex(start) =>
+ val startTime = start.toLong
+ if (timestamp >= startTime) {
+ val newFile = new Path(dir, s"checkpoints-$startTime-$timestamp.store")
+ fs.rename(new Path(dir, fileName), newFile)
+ checkpointFile = Some(newFile)
+ }
+ }
+ }
+
+ checkpointFile.foreach { file =>
+ val reader = new HadoopCheckpointStoreReader(file, hadoopConfig)
+
+ @annotation.tailrec
+ def read: Option[Array[Byte]] = {
+ if (reader.hasNext) {
+ val (time, bytes) = reader.next()
+ if (time == timestamp) {
+ Some(bytes)
+ } else {
+ read
+ }
+ } else {
+ None
+ }
+ }
+ checkpoint = read
+ reader.close()
+ }
+ }
+ checkpoint
+ }
+
+ override def close(): Unit = {
+ curWriter.foreach(_.close())
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/HadoopCheckpointStoreFactory.scala
----------------------------------------------------------------------
diff --git a/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/HadoopCheckpointStoreFactory.scala b/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/HadoopCheckpointStoreFactory.scala
new file mode 100644
index 0000000..e5e0f13
--- /dev/null
+++ b/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/HadoopCheckpointStoreFactory.scala
@@ -0,0 +1,61 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.hadoop
+
+import java.io.{ObjectInputStream, ObjectOutputStream}
+
+import org.apache.hadoop.conf.Configuration
+import org.apache.hadoop.fs.Path
+
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.hadoop.lib.HadoopUtil
+import org.apache.gearpump.streaming.hadoop.lib.rotation.{FileSizeRotation, Rotation}
+import org.apache.gearpump.streaming.task.TaskContext
+import org.apache.gearpump.streaming.transaction.api.{CheckpointStore, CheckpointStoreFactory}
+
+object HadoopCheckpointStoreFactory {
+ val VERSION = 1
+}
+
+class HadoopCheckpointStoreFactory(
+ dir: String,
+ @transient private var hadoopConfig: Configuration,
+ rotation: Rotation = new FileSizeRotation(128 * Math.pow(2, 20).toLong))
+ extends CheckpointStoreFactory {
+ import org.apache.gearpump.streaming.hadoop.HadoopCheckpointStoreFactory._
+
+ private def writeObject(out: ObjectOutputStream): Unit = {
+ out.defaultWriteObject()
+ hadoopConfig.write(out)
+ }
+
+ private def readObject(in: ObjectInputStream): Unit = {
+ in.defaultReadObject()
+ hadoopConfig = new Configuration(false)
+ hadoopConfig.readFields(in)
+ }
+
+ override def getCheckpointStore(conf: UserConfig, taskContext: TaskContext): CheckpointStore = {
+ import taskContext.{appId, taskId}
+ val dirPath = new Path(dir + Path.SEPARATOR + s"v$VERSION",
+ s"app$appId-task${taskId.processorId}_${taskId.index}")
+ val fs = HadoopUtil.getFileSystemForPath(dirPath, hadoopConfig)
+ new HadoopCheckpointStore(dirPath, fs, hadoopConfig, rotation)
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/SequenceFileSink.scala
----------------------------------------------------------------------
diff --git a/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/SequenceFileSink.scala b/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/SequenceFileSink.scala
new file mode 100644
index 0000000..bb56003
--- /dev/null
+++ b/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/SequenceFileSink.scala
@@ -0,0 +1,110 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.hadoop
+
+import java.text.SimpleDateFormat
+
+import org.apache.hadoop.fs.Path
+import org.apache.hadoop.hdfs.HdfsConfiguration
+import org.apache.hadoop.io.SequenceFile
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.hadoop.lib.HadoopUtil
+import org.apache.gearpump.streaming.hadoop.lib.format.{DefaultSequenceFormatter, OutputFormatter}
+import org.apache.gearpump.streaming.hadoop.lib.rotation.{FileSizeRotation, Rotation}
+import org.apache.gearpump.streaming.sink.DataSink
+import org.apache.gearpump.streaming.task.{TaskContext, TaskId}
+
+class SequenceFileSink(
+ userConfig: UserConfig,
+ basePath: String,
+ rotation: Rotation = new FileSizeRotation(128 * Math.pow(2, 20).toLong),
+ sequenceFormat: OutputFormatter = new DefaultSequenceFormatter)
+ extends DataSink{
+ @transient private lazy val configuration = new HdfsConfiguration()
+ private val dateFormat = new SimpleDateFormat("yyyy_MM_dd-HH-mm-ss")
+ private var writer: SequenceFile.Writer = null
+ private var taskId: TaskId = null
+ private var appName: String = null
+
+ /**
+ * Starts connection to data sink
+ *
+ * Invoked at onStart() method of [[org.apache.gearpump.streaming.task.Task]]
+ *
+ * @param context is the task context at runtime
+ */
+ override def open(context: TaskContext): Unit = {
+ HadoopUtil.login(userConfig, configuration)
+ this.appName = context.appName
+ this.taskId = context.taskId
+ this.writer = getNextWriter
+ }
+
+ /**
+ * Writes message into data sink
+ *
+ * Invoked at onNext() method of [[org.apache.gearpump.streaming.task.Task]]
+ * @param message wraps data to be written out
+ */
+ override def write(message: Message): Unit = {
+ val key = sequenceFormat.getKey(message)
+ val value = sequenceFormat.getValue(message)
+ if (writer == null) {
+ writer = getNextWriter
+ }
+ writer.append(key, value)
+ rotation.mark(message.timestamp, writer.getLength)
+ if (rotation.shouldRotate) {
+ closeWriter
+ this.writer = getNextWriter
+ rotation.rotate
+ }
+ }
+
+ /**
+ * Closes connection to data sink
+ *
+ * Invoked at onClose() method of [[org.apache.gearpump.streaming.task.Task]]
+ */
+ override def close(): Unit = {
+ closeWriter()
+ }
+
+ private def closeWriter(): Unit = {
+ Option(writer).foreach { w =>
+ w.hflush()
+ w.close()
+ }
+ }
+
+ private def getNextWriter: SequenceFile.Writer = {
+ SequenceFile.createWriter(
+ configuration,
+ SequenceFile.Writer.file(getNextFilePath),
+ SequenceFile.Writer.keyClass(sequenceFormat.getKeyClass),
+ SequenceFile.Writer.valueClass(sequenceFormat.getValueClass)
+ )
+ }
+
+ private def getNextFilePath: Path = {
+ val base = new Path(basePath, s"$appName-task${taskId.processorId}_${taskId.index}")
+ new Path(base, dateFormat.format(new java.util.Date))
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/lib/HadoopCheckpointStoreReader.scala
----------------------------------------------------------------------
diff --git a/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/lib/HadoopCheckpointStoreReader.scala b/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/lib/HadoopCheckpointStoreReader.scala
new file mode 100644
index 0000000..082e963
--- /dev/null
+++ b/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/lib/HadoopCheckpointStoreReader.scala
@@ -0,0 +1,72 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.hadoop.lib
+
+import java.io.EOFException
+
+import org.apache.hadoop.conf.Configuration
+import org.apache.hadoop.fs.Path
+
+import org.apache.gearpump.TimeStamp
+
+class HadoopCheckpointStoreReader(
+ path: Path,
+ hadoopConfig: Configuration)
+ extends Iterator[(TimeStamp, Array[Byte])] {
+
+ private val stream = HadoopUtil.getInputStream(path, hadoopConfig)
+ private var nextTimeStamp: Option[TimeStamp] = None
+ private var nextData: Option[Array[Byte]] = None
+
+ override def hasNext: Boolean = {
+ if (nextTimeStamp.isDefined) {
+ true
+ } else {
+ try {
+ nextTimeStamp = Some(stream.readLong())
+ val length = stream.readInt()
+ val buffer = new Array[Byte](length)
+ stream.readFully(buffer)
+ nextData = Some(buffer)
+ true
+ } catch {
+ case e: EOFException =>
+ close()
+ false
+ case e: Exception =>
+ close()
+ throw e
+ }
+ }
+ }
+
+ override def next(): (TimeStamp, Array[Byte]) = {
+ val timeAndData = for {
+ time <- nextTimeStamp
+ data <- nextData
+ } yield (time, data)
+ nextTimeStamp = None
+ nextData = None
+ timeAndData.get
+ }
+
+ def close(): Unit = {
+ stream.close()
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/lib/HadoopCheckpointStoreWriter.scala
----------------------------------------------------------------------
diff --git a/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/lib/HadoopCheckpointStoreWriter.scala b/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/lib/HadoopCheckpointStoreWriter.scala
new file mode 100644
index 0000000..11c12c4
--- /dev/null
+++ b/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/lib/HadoopCheckpointStoreWriter.scala
@@ -0,0 +1,40 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.hadoop.lib
+
+import org.apache.hadoop.conf.Configuration
+import org.apache.hadoop.fs.Path
+
+import org.apache.gearpump.TimeStamp
+
+class HadoopCheckpointStoreWriter(path: Path, hadoopConfig: Configuration) {
+ private lazy val stream = HadoopUtil.getOutputStream(path, hadoopConfig)
+
+ def write(timestamp: TimeStamp, data: Array[Byte]): Long = {
+ stream.writeLong(timestamp)
+ stream.writeInt(data.length)
+ stream.write(data)
+ stream.hflush()
+ stream.getPos()
+ }
+
+ def close(): Unit = {
+ stream.close()
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/lib/HadoopUtil.scala
----------------------------------------------------------------------
diff --git a/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/lib/HadoopUtil.scala b/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/lib/HadoopUtil.scala
new file mode 100644
index 0000000..935b52c
--- /dev/null
+++ b/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/lib/HadoopUtil.scala
@@ -0,0 +1,80 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.hadoop.lib
+
+import java.io.File
+
+import org.apache.hadoop.conf.Configuration
+import org.apache.hadoop.fs._
+import org.apache.hadoop.security.UserGroupInformation
+
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.util.{Constants, FileUtils}
+
+private[hadoop] object HadoopUtil {
+
+ def getOutputStream(path: Path, hadoopConfig: Configuration): FSDataOutputStream = {
+ val dfs = getFileSystemForPath(path, hadoopConfig)
+ val stream: FSDataOutputStream = {
+ if (dfs.isFile(path)) {
+ dfs.append(path)
+ } else {
+ dfs.create(path)
+ }
+ }
+ stream
+ }
+
+ def getInputStream(path: Path, hadoopConfig: Configuration): FSDataInputStream = {
+ val dfs = getFileSystemForPath(path, hadoopConfig)
+ val stream = dfs.open(path)
+ stream
+ }
+
+ def getFileSystemForPath(path: Path, hadoopConfig: Configuration): FileSystem = {
+ // For local file systems, return the raw local file system, such calls to flush()
+ // actually flushes the stream.
+ val fs = path.getFileSystem(hadoopConfig)
+ fs match {
+ case localFs: LocalFileSystem => localFs.getRawFileSystem
+ case _ => fs
+ }
+ }
+
+ def login(userConfig: UserConfig, configuration: Configuration): Unit = {
+ if (UserGroupInformation.isSecurityEnabled) {
+ val principal = userConfig.getString(Constants.GEARPUMP_KERBEROS_PRINCIPAL)
+ val keytabContent = userConfig.getBytes(Constants.GEARPUMP_KEYTAB_FILE)
+ if (principal.isEmpty || keytabContent.isEmpty) {
+ val errorMsg = s"HDFS is security enabled, user should provide kerberos principal in " +
+ s"${Constants.GEARPUMP_KERBEROS_PRINCIPAL} " +
+ s"and keytab file in ${Constants.GEARPUMP_KEYTAB_FILE}"
+ throw new Exception(errorMsg)
+ }
+ val keytabFile = File.createTempFile("login", ".keytab")
+ FileUtils.writeByteArrayToFile(keytabFile, keytabContent.get)
+ keytabFile.setExecutable(false)
+ keytabFile.setWritable(false)
+ keytabFile.setReadable(true, true)
+
+ UserGroupInformation.setConfiguration(configuration)
+ UserGroupInformation.loginUserFromKeytab(principal.get, keytabFile.getAbsolutePath)
+ keytabFile.delete()
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/lib/format/DefaultSequenceFormatter.scala
----------------------------------------------------------------------
diff --git a/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/lib/format/DefaultSequenceFormatter.scala b/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/lib/format/DefaultSequenceFormatter.scala
new file mode 100644
index 0000000..318c071
--- /dev/null
+++ b/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/lib/format/DefaultSequenceFormatter.scala
@@ -0,0 +1,32 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.hadoop.lib.format
+
+import org.apache.hadoop.io.{LongWritable, Text, Writable}
+
+import org.apache.gearpump.Message
+
+class DefaultSequenceFormatter extends OutputFormatter {
+ override def getKey(message: Message): Writable = new LongWritable(message.timestamp)
+
+ override def getValue(message: Message): Writable = new Text(message.msg.asInstanceOf[String])
+
+ override def getKeyClass: Class[_ <: Writable] = classOf[LongWritable]
+
+ override def getValueClass: Class[_ <: Writable] = classOf[Text]
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/lib/format/OutputFormatter.scala
----------------------------------------------------------------------
diff --git a/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/lib/format/OutputFormatter.scala b/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/lib/format/OutputFormatter.scala
new file mode 100644
index 0000000..435d0fc
--- /dev/null
+++ b/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/lib/format/OutputFormatter.scala
@@ -0,0 +1,32 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.hadoop.lib.format
+
+import org.apache.hadoop.io.Writable
+
+import org.apache.gearpump.Message
+
+trait OutputFormatter extends Serializable {
+ def getKeyClass: Class[_ <: Writable]
+
+ def getValueClass: Class[_ <: Writable]
+
+ def getKey(message: Message): Writable
+
+ def getValue(message: Message): Writable
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/lib/rotation/FileSizeRotation.scala
----------------------------------------------------------------------
diff --git a/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/lib/rotation/FileSizeRotation.scala b/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/lib/rotation/FileSizeRotation.scala
new file mode 100644
index 0000000..72be9c3
--- /dev/null
+++ b/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/lib/rotation/FileSizeRotation.scala
@@ -0,0 +1,37 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.hadoop.lib.rotation
+
+import org.apache.gearpump.TimeStamp
+
+case class FileSizeRotation(maxBytes: Long) extends Rotation {
+
+ private var bytesWritten = 0L
+
+ override def mark(timestamp: TimeStamp, offset: Long): Unit = {
+ bytesWritten = offset
+ }
+
+ override def shouldRotate: Boolean = bytesWritten >= maxBytes
+
+ override def rotate(): Unit = {
+ bytesWritten = 0L
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/lib/rotation/Rotation.scala
----------------------------------------------------------------------
diff --git a/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/lib/rotation/Rotation.scala b/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/lib/rotation/Rotation.scala
new file mode 100644
index 0000000..cd8c04a
--- /dev/null
+++ b/external/hadoopfs/src/main/scala/org/apache/gearpump/streaming/hadoop/lib/rotation/Rotation.scala
@@ -0,0 +1,27 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.hadoop.lib.rotation
+
+import org.apache.gearpump.TimeStamp
+
+trait Rotation extends Serializable {
+ def mark(timestamp: TimeStamp, offset: Long): Unit
+ def shouldRotate: Boolean
+ def rotate(): Unit
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/hadoopfs/src/test/scala/io/gearpump/streaming/hadoop/HadoopCheckpointStoreIntegrationSpec.scala
----------------------------------------------------------------------
diff --git a/external/hadoopfs/src/test/scala/io/gearpump/streaming/hadoop/HadoopCheckpointStoreIntegrationSpec.scala b/external/hadoopfs/src/test/scala/io/gearpump/streaming/hadoop/HadoopCheckpointStoreIntegrationSpec.scala
deleted file mode 100644
index cc8a5f0..0000000
--- a/external/hadoopfs/src/test/scala/io/gearpump/streaming/hadoop/HadoopCheckpointStoreIntegrationSpec.scala
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.hadoop
-
-import org.apache.hadoop.conf.Configuration
-import org.apache.hadoop.fs.Path
-import org.mockito.Mockito._
-import org.scalacheck.Gen
-import org.scalatest.mock.MockitoSugar
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{Matchers, PropSpec}
-
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.MockUtil
-import io.gearpump.streaming.hadoop.lib.HadoopUtil
-import io.gearpump.streaming.hadoop.lib.rotation.FileSizeRotation
-import io.gearpump.streaming.task.TaskId
-
-class HadoopCheckpointStoreIntegrationSpec
- extends PropSpec with PropertyChecks with MockitoSugar with Matchers {
-
- property("HadoopCheckpointStore should persist and recover checkpoints") {
- val fileSizeGen = Gen.chooseNum[Int](100, 1000)
- forAll(fileSizeGen) { (fileSize: Int) =>
- val userConfig = UserConfig.empty
- val taskContext = MockUtil.mockTaskContext
- val hadoopConfig = new Configuration()
-
- when(taskContext.appId).thenReturn(0)
- when(taskContext.taskId).thenReturn(TaskId(0, 0))
-
- val rootDirName = "test"
- val rootDir = new Path(rootDirName + Path.SEPARATOR +
- s"v${HadoopCheckpointStoreFactory.VERSION}")
- val subDir = new Path(rootDir, "app0-task0_0")
-
- val fs = HadoopUtil.getFileSystemForPath(rootDir, hadoopConfig)
- fs.delete(rootDir, true)
- fs.exists(rootDir) shouldBe false
-
- val checkpointStoreFactory = new HadoopCheckpointStoreFactory(
- rootDirName, hadoopConfig, new FileSizeRotation(fileSize))
- val checkpointStore = checkpointStoreFactory.getCheckpointStore(userConfig, taskContext)
-
- checkpointStore.persist(0L, Array(0.toByte))
-
- val tempFile = new Path(subDir, "checkpoints-0.store")
- fs.exists(tempFile) shouldBe true
-
- checkpointStore.persist(1L, Array.fill(fileSize)(0.toByte))
- fs.exists(tempFile) shouldBe false
- fs.exists(new Path(subDir, "checkpoints-0-1.store")) shouldBe true
-
- checkpointStore.persist(2L, Array(0.toByte))
- val newTempFile = new Path(subDir, "checkpoints-2.store")
- fs.exists(newTempFile) shouldBe true
-
- for (i <- 0 to 2) {
- val optCp = checkpointStore.recover(i)
- optCp should not be empty
- }
- fs.exists(newTempFile) shouldBe false
- fs.exists(new Path(subDir, "checkpoints-2-2.store")) shouldBe true
-
- checkpointStore.close()
- fs.delete(rootDir, true)
- fs.close()
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/hadoopfs/src/test/scala/io/gearpump/streaming/hadoop/lib/rotation/FileSizeRotationSpec.scala
----------------------------------------------------------------------
diff --git a/external/hadoopfs/src/test/scala/io/gearpump/streaming/hadoop/lib/rotation/FileSizeRotationSpec.scala b/external/hadoopfs/src/test/scala/io/gearpump/streaming/hadoop/lib/rotation/FileSizeRotationSpec.scala
deleted file mode 100644
index 9b4057c..0000000
--- a/external/hadoopfs/src/test/scala/io/gearpump/streaming/hadoop/lib/rotation/FileSizeRotationSpec.scala
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.hadoop.lib.rotation
-
-import org.scalacheck.Gen
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{Matchers, PropSpec}
-
-import io.gearpump.TimeStamp
-
-class FileSizeRotationSpec extends PropSpec with PropertyChecks with Matchers {
-
- val timestampGen = Gen.chooseNum[Long](0L, 1000L)
- val fileSizeGen = Gen.chooseNum[Long](1, Long.MaxValue)
-
- property("FileSize rotation rotates on file size") {
- forAll(timestampGen, fileSizeGen) { (timestamp: TimeStamp, fileSize: Long) =>
- val rotation = new FileSizeRotation(fileSize)
- rotation.shouldRotate shouldBe false
- rotation.mark(timestamp, rotation.maxBytes / 2)
- rotation.shouldRotate shouldBe false
- rotation.mark(timestamp, rotation.maxBytes)
- rotation.shouldRotate shouldBe true
- rotation.rotate
- rotation.shouldRotate shouldBe false
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/hadoopfs/src/test/scala/org/apache/gearpump/streaming/hadoop/HadoopCheckpointStoreIntegrationSpec.scala
----------------------------------------------------------------------
diff --git a/external/hadoopfs/src/test/scala/org/apache/gearpump/streaming/hadoop/HadoopCheckpointStoreIntegrationSpec.scala b/external/hadoopfs/src/test/scala/org/apache/gearpump/streaming/hadoop/HadoopCheckpointStoreIntegrationSpec.scala
new file mode 100644
index 0000000..4fd8dc1
--- /dev/null
+++ b/external/hadoopfs/src/test/scala/org/apache/gearpump/streaming/hadoop/HadoopCheckpointStoreIntegrationSpec.scala
@@ -0,0 +1,86 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.hadoop
+
+import org.apache.hadoop.conf.Configuration
+import org.apache.hadoop.fs.Path
+import org.mockito.Mockito._
+import org.scalacheck.Gen
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{Matchers, PropSpec}
+
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.MockUtil
+import org.apache.gearpump.streaming.hadoop.lib.HadoopUtil
+import org.apache.gearpump.streaming.hadoop.lib.rotation.FileSizeRotation
+import org.apache.gearpump.streaming.task.TaskId
+
+class HadoopCheckpointStoreIntegrationSpec
+ extends PropSpec with PropertyChecks with MockitoSugar with Matchers {
+
+ property("HadoopCheckpointStore should persist and recover checkpoints") {
+ val fileSizeGen = Gen.chooseNum[Int](100, 1000)
+ forAll(fileSizeGen) { (fileSize: Int) =>
+ val userConfig = UserConfig.empty
+ val taskContext = MockUtil.mockTaskContext
+ val hadoopConfig = new Configuration()
+
+ when(taskContext.appId).thenReturn(0)
+ when(taskContext.taskId).thenReturn(TaskId(0, 0))
+
+ val rootDirName = "test"
+ val rootDir = new Path(rootDirName + Path.SEPARATOR +
+ s"v${HadoopCheckpointStoreFactory.VERSION}")
+ val subDir = new Path(rootDir, "app0-task0_0")
+
+ val fs = HadoopUtil.getFileSystemForPath(rootDir, hadoopConfig)
+ fs.delete(rootDir, true)
+ fs.exists(rootDir) shouldBe false
+
+ val checkpointStoreFactory = new HadoopCheckpointStoreFactory(
+ rootDirName, hadoopConfig, new FileSizeRotation(fileSize))
+ val checkpointStore = checkpointStoreFactory.getCheckpointStore(userConfig, taskContext)
+
+ checkpointStore.persist(0L, Array(0.toByte))
+
+ val tempFile = new Path(subDir, "checkpoints-0.store")
+ fs.exists(tempFile) shouldBe true
+
+ checkpointStore.persist(1L, Array.fill(fileSize)(0.toByte))
+ fs.exists(tempFile) shouldBe false
+ fs.exists(new Path(subDir, "checkpoints-0-1.store")) shouldBe true
+
+ checkpointStore.persist(2L, Array(0.toByte))
+ val newTempFile = new Path(subDir, "checkpoints-2.store")
+ fs.exists(newTempFile) shouldBe true
+
+ for (i <- 0 to 2) {
+ val optCp = checkpointStore.recover(i)
+ optCp should not be empty
+ }
+ fs.exists(newTempFile) shouldBe false
+ fs.exists(new Path(subDir, "checkpoints-2-2.store")) shouldBe true
+
+ checkpointStore.close()
+ fs.delete(rootDir, true)
+ fs.close()
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/hadoopfs/src/test/scala/org/apache/gearpump/streaming/hadoop/lib/rotation/FileSizeRotationSpec.scala
----------------------------------------------------------------------
diff --git a/external/hadoopfs/src/test/scala/org/apache/gearpump/streaming/hadoop/lib/rotation/FileSizeRotationSpec.scala b/external/hadoopfs/src/test/scala/org/apache/gearpump/streaming/hadoop/lib/rotation/FileSizeRotationSpec.scala
new file mode 100644
index 0000000..4eab3c9
--- /dev/null
+++ b/external/hadoopfs/src/test/scala/org/apache/gearpump/streaming/hadoop/lib/rotation/FileSizeRotationSpec.scala
@@ -0,0 +1,44 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.hadoop.lib.rotation
+
+import org.scalacheck.Gen
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{Matchers, PropSpec}
+
+import org.apache.gearpump.TimeStamp
+
+class FileSizeRotationSpec extends PropSpec with PropertyChecks with Matchers {
+
+ val timestampGen = Gen.chooseNum[Long](0L, 1000L)
+ val fileSizeGen = Gen.chooseNum[Long](1, Long.MaxValue)
+
+ property("FileSize rotation rotates on file size") {
+ forAll(timestampGen, fileSizeGen) { (timestamp: TimeStamp, fileSize: Long) =>
+ val rotation = new FileSizeRotation(fileSize)
+ rotation.shouldRotate shouldBe false
+ rotation.mark(timestamp, rotation.maxBytes / 2)
+ rotation.shouldRotate shouldBe false
+ rotation.mark(timestamp, rotation.maxBytes)
+ rotation.shouldRotate shouldBe true
+ rotation.rotate
+ rotation.shouldRotate shouldBe false
+ }
+ }
+}
[46/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/package.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/package.scala b/core/src/main/scala/io/gearpump/package.scala
deleted file mode 100644
index 1877651..0000000
--- a/core/src/main/scala/io/gearpump/package.scala
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * 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.
- */
-
-package io
-
-package object gearpump {
- type TimeStamp = Long
- val LatestTime = -1
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/partitioner/BroadcastPartitioner.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/partitioner/BroadcastPartitioner.scala b/core/src/main/scala/io/gearpump/partitioner/BroadcastPartitioner.scala
deleted file mode 100644
index 0b9c57e..0000000
--- a/core/src/main/scala/io/gearpump/partitioner/BroadcastPartitioner.scala
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.partitioner
-
-import io.gearpump.Message
-
-/** Used by storm module to broadcast message to all downstream tasks */
-class BroadcastPartitioner extends MulticastPartitioner {
- private var lastPartitionNum = -1
- private var partitions = Array.empty[Int]
-
- override def getPartitions(
- msg: Message, partitionNum: Int, currentPartitionId: Int): Array[Int] = {
- if (partitionNum != lastPartitionNum) {
- partitions = (0 until partitionNum).toArray
- lastPartitionNum = partitionNum
- }
- partitions
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/partitioner/CoLocationPartitioner.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/partitioner/CoLocationPartitioner.scala b/core/src/main/scala/io/gearpump/partitioner/CoLocationPartitioner.scala
deleted file mode 100644
index 062fc10..0000000
--- a/core/src/main/scala/io/gearpump/partitioner/CoLocationPartitioner.scala
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.partitioner
-
-import io.gearpump.Message
-
-/**
- * Will have the same parallelism with last processor
- * And each task in current processor will co-locate with task of last processor
- */
-class CoLocationPartitioner extends UnicastPartitioner {
- override def getPartition(msg: Message, partitionNum: Int, currentPartitionId: Int): Int = {
- currentPartitionId
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/partitioner/HashPartitioner.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/partitioner/HashPartitioner.scala b/core/src/main/scala/io/gearpump/partitioner/HashPartitioner.scala
deleted file mode 100644
index 6ba0cd6..0000000
--- a/core/src/main/scala/io/gearpump/partitioner/HashPartitioner.scala
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.partitioner
-
-import io.gearpump.Message
-
-/**
- * Only make sense when the message has implemented the hashCode()
- * Otherwise, it will use Object.hashCode(), which will not return
- * same hash code after serialization and deserialization.
- */
-class HashPartitioner extends UnicastPartitioner {
- override def getPartition(msg: Message, partitionNum: Int, currentPartitionId: Int): Int = {
- (msg.msg.hashCode() & Integer.MAX_VALUE) % partitionNum
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/partitioner/Partitioner.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/partitioner/Partitioner.scala b/core/src/main/scala/io/gearpump/partitioner/Partitioner.scala
deleted file mode 100644
index 69104c7..0000000
--- a/core/src/main/scala/io/gearpump/partitioner/Partitioner.scala
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.partitioner
-
-import scala.reflect.ClassTag
-
-import org.apache.commons.lang.SerializationUtils
-
-import io.gearpump.Message
-
-/**
- * For processor chain: A (3 tasks) {@literal ->} B (3 tasks), partitioner decide how ONE task
- * of upstream processor A send to several tasks of downstream processor B.
- */
-sealed trait Partitioner extends Serializable
-
-/**
- * For processor chain: A (3 tasks) {@literal ->} B (3 tasks), UnicastPartitioner does
- * ONE-task {@literal ->} ONE-task mapping.
- */
-trait UnicastPartitioner extends Partitioner {
-
- /**
- * Gets the SINGLE downstream processor task index to send message to.
- *
- * @param msg Message you want to send
- * @param partitionNum How many tasks does the downstream processor have.
- * @param upstreamTaskIndex Upstream task's task index who trigger the getPartition() call.
- *
- * @return ONE task index of downstream processor.
- */
- def getPartition(msg: Message, partitionNum: Int, upstreamTaskIndex: Int): Int
-
- def getPartition(msg: Message, partitionNum: Int): Int = {
- getPartition(msg, partitionNum, Partitioner.UNKNOWN_PARTITION_ID)
- }
-}
-
-trait MulticastPartitioner extends Partitioner {
-
- /**
- * Gets a list of downstream processor task indexes to send message to.
- *
- * @param upstreamTaskIndex Current sender task's task index.
- *
- */
- def getPartitions(msg: Message, partitionNum: Int, upstreamTaskIndex: Int): Array[Int]
-
- def getPartitions(msg: Message, partitionNum: Int): Array[Int] = {
- getPartitions(msg, partitionNum, Partitioner.UNKNOWN_PARTITION_ID)
- }
-}
-
-sealed trait PartitionerFactory {
-
- def name: String
-
- def partitioner: Partitioner
-}
-
-/** Stores the Partitioner in an object. To use it, user need to deserialize the object */
-class PartitionerObject(private[this] val _partitioner: Partitioner)
- extends PartitionerFactory with Serializable {
-
- override def name: String = partitioner.getClass.getName
-
- override def partitioner: Partitioner = {
- SerializationUtils.clone(_partitioner).asInstanceOf[Partitioner]
- }
-}
-
-/** Store the partitioner in class Name, the user need to instantiate a new class */
-class PartitionerByClassName(partitionerClass: String)
- extends PartitionerFactory with Serializable {
-
- override def name: String = partitionerClass
- override def partitioner: Partitioner = {
- Class.forName(partitionerClass).newInstance().asInstanceOf[Partitioner]
- }
-}
-
-/**
- * @param partitionerFactory How we construct a Partitioner.
- */
-case class PartitionerDescription(partitionerFactory: PartitionerFactory)
-
-object Partitioner {
- val UNKNOWN_PARTITION_ID = -1
-
- def apply[T <: Partitioner](implicit clazz: ClassTag[T]): PartitionerDescription = {
- PartitionerDescription(new PartitionerByClassName(clazz.runtimeClass.getName))
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/partitioner/ShuffleGroupingPartitioner.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/partitioner/ShuffleGroupingPartitioner.scala b/core/src/main/scala/io/gearpump/partitioner/ShuffleGroupingPartitioner.scala
deleted file mode 100644
index ff962fa..0000000
--- a/core/src/main/scala/io/gearpump/partitioner/ShuffleGroupingPartitioner.scala
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.partitioner
-
-import scala.util.Random
-
-import io.gearpump.Message
-
-/**
- * The idea of ShuffleGroupingPartitioner is derived from Storm.
- * Messages are randomly distributed across the downstream's tasks in a way such that
- * each task is guaranteed to get an equal number of messages.
- */
-class ShuffleGroupingPartitioner extends UnicastPartitioner {
- private val random = new Random
- private var index = -1
- private var partitions = List.empty[Int]
- override def getPartition(msg: Message, partitionNum: Int, currentPartitionId: Int): Int = {
- index += 1
- if (partitions.isEmpty) {
- partitions = 0.until(partitionNum).toList
- partitions = random.shuffle(partitions)
- } else if (index >= partitionNum) {
- index = 0
- partitions = random.shuffle(partitions)
- }
- partitions(index)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/partitioner/ShufflePartitioner.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/partitioner/ShufflePartitioner.scala b/core/src/main/scala/io/gearpump/partitioner/ShufflePartitioner.scala
deleted file mode 100644
index 6b3c26e..0000000
--- a/core/src/main/scala/io/gearpump/partitioner/ShufflePartitioner.scala
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.partitioner
-
-import java.util.Random
-
-import io.gearpump.Message
-
-/**
- * Round Robin partition the data to downstream processor tasks.
- */
-class ShufflePartitioner extends UnicastPartitioner {
- private var seed = 0
- private var count = 0
-
- override def getPartition(msg: Message, partitionNum: Int, currentPartitionId: Int): Int = {
-
- if (seed == 0) {
- seed = newSeed()
- }
-
- val result = ((count + seed) & Integer.MAX_VALUE) % partitionNum
- count = count + 1
- result
- }
-
- private def newSeed(): Int = new Random().nextInt()
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/security/Authenticator.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/security/Authenticator.scala b/core/src/main/scala/io/gearpump/security/Authenticator.scala
deleted file mode 100644
index 73bc8e1..0000000
--- a/core/src/main/scala/io/gearpump/security/Authenticator.scala
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.security
-import scala.concurrent.{ExecutionContext, Future}
-
-import io.gearpump.security.Authenticator.AuthenticationResult
-
-/**
- * Authenticator for UI dashboard.
- *
- * Sub Class must implement a constructor with signature like this:
- * this(config: Config)
- */
-trait Authenticator {
-
- // TODO: Change the signature to return more attributes of user credentials...
- def authenticate(
- user: String, password: String, ec: ExecutionContext): Future[AuthenticationResult]
-}
-
-object Authenticator {
-
- trait AuthenticationResult {
-
- def authenticated: Boolean
-
- def permissionLevel: Int
- }
-
- val UnAuthenticated = new AuthenticationResult {
- override val authenticated = false
- override val permissionLevel = -1
- }
-
- /** Guest can view but have no permission to submit app or write */
- val Guest = new AuthenticationResult {
- override val authenticated = true
- override val permissionLevel = 1000
- }
-
- /** User can submit app, kill app, but have no permission to add or remote machines */
- val User = new AuthenticationResult {
- override val authenticated = true
- override val permissionLevel = 1000 + Guest.permissionLevel
- }
-
- /** Super user */
- val Admin = new AuthenticationResult {
- override val authenticated = true
- override val permissionLevel = 1000 + User.permissionLevel
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/security/ConfigFileBasedAuthenticator.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/security/ConfigFileBasedAuthenticator.scala b/core/src/main/scala/io/gearpump/security/ConfigFileBasedAuthenticator.scala
deleted file mode 100644
index 0743a3f..0000000
--- a/core/src/main/scala/io/gearpump/security/ConfigFileBasedAuthenticator.scala
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.security
-
-import scala.concurrent.{ExecutionContext, Future}
-
-import com.typesafe.config.Config
-
-import io.gearpump.security.Authenticator.AuthenticationResult
-import io.gearpump.security.ConfigFileBasedAuthenticator._
-
-object ConfigFileBasedAuthenticator {
-
- private val ROOT = "gearpump.ui-security.config-file-based-authenticator"
- private val ADMINS = ROOT + "." + "admins"
- private val USERS = ROOT + "." + "users"
- private val GUESTS = ROOT + "." + "guests"
-
- private case class Credentials(
- admins: Map[String, String], users: Map[String, String], guests: Map[String, String]) {
-
- def verify(user: String, password: String): AuthenticationResult = {
- if (admins.contains(user)) {
- if (verify(user, password, admins)) {
- Authenticator.Admin
- } else {
- Authenticator.UnAuthenticated
- }
- } else if (users.contains(user)) {
- if (verify(user, password, users)) {
- Authenticator.User
- } else {
- Authenticator.UnAuthenticated
- }
- } else if (guests.contains(user)) {
- if (verify(user, password, guests)) {
- Authenticator.Guest
- } else {
- Authenticator.UnAuthenticated
- }
- } else {
- Authenticator.UnAuthenticated
- }
- }
-
- private def verify(user: String, password: String, map: Map[String, String]): Boolean = {
- val storedPass = map(user)
- PasswordUtil.verify(password, storedPass)
- }
- }
-}
-
-/**
- * UI dashboard authenticator based on configuration file.
- *
- * It has three categories of users: admins, users, and guests.
- * admins have unlimited permission, like shutdown a cluster, add/remove machines.
- * users have limited permission to submit an application and etc..
- * guests can not submit/kill applications, but can view the application status.
- *
- * see conf/gear.conf section gearpump.ui-security.config-file-based-authenticator to find
- * information about how to configure this authenticator.
- *
- * [Security consideration]
- * It will keep one-way sha1 digest of password instead of password itself. The original password is
- * NOT kept in any way, so generally it is safe.
- *
- *
- * digesting flow (from original password to digest):
- * {{{
- * random salt byte array of length 8 -> byte array of (salt + sha1(salt, password)) ->
- * base64Encode.
- * }}}
- *
- * Verification user input password with stored digest:
- * {{{
- * base64Decode -> extract salt -> do sha1(salt, password) -> generate digest:
- * salt + sha1 -> compare the generated digest with the stored digest.
- * }}}
- */
-class ConfigFileBasedAuthenticator(config: Config) extends Authenticator {
-
- private val credentials = loadCredentials(config)
-
- override def authenticate(user: String, password: String, ec: ExecutionContext)
- : Future[AuthenticationResult] = {
- implicit val ctx = ec
- Future {
- credentials.verify(user, password)
- }
- }
-
- private def loadCredentials(config: Config): Credentials = {
- val admins = configToMap(config, ADMINS)
- val users = configToMap(config, USERS)
- val guests = configToMap(config, GUESTS)
- new Credentials(admins, users, guests)
- }
-
- private def configToMap(config: Config, path: String) = {
- import scala.collection.JavaConverters._
- config.getConfig(path).root.unwrapped.asScala.toMap map { case (k, v) => k -> v.toString }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/security/PasswordUtil.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/security/PasswordUtil.scala b/core/src/main/scala/io/gearpump/security/PasswordUtil.scala
deleted file mode 100644
index 9bf40d2..0000000
--- a/core/src/main/scala/io/gearpump/security/PasswordUtil.scala
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.security
-
-import java.security.MessageDigest
-import scala.util.Try
-
-import sun.misc.{BASE64Decoder, BASE64Encoder}
-
-/**
- * Util to verify whether user input password is valid or not.
- * It use sha1 to do the digesting.
- */
-object PasswordUtil {
- private val SALT_LENGTH = 8
-
- /**
- * Verifies user input password with stored digest:
- * {{{
- * base64Decode -> extract salt -> do sha1(salt, password) ->
- * generate digest: salt + sha1 -> compare the generated digest with the stored digest.
- * }}}
- */
- def verify(password: String, stored: String): Boolean = {
- Try {
- val decoded = base64Decode(stored)
- val salt = new Array[Byte](SALT_LENGTH)
- Array.copy(decoded, 0, salt, 0, SALT_LENGTH)
-
- hash(password, salt) == stored
- }.getOrElse(false)
- }
- /**
- * digesting flow (from original password to digest):
- * {{{
- * random salt byte array of length 8 ->
- * byte array of (salt + sha1(salt, password)) -> base64Encode
- * }}}
- */
- def hash(password: String): String = {
- // Salt generation 64 bits long
- val salt = new Array[Byte](SALT_LENGTH)
- new java.util.Random().nextBytes(salt)
- hash(password, salt)
- }
-
- private def hash(password: String, salt: Array[Byte]): String = {
- val digest = MessageDigest.getInstance("SHA-1")
- digest.reset()
- digest.update(salt)
- var input = digest.digest(password.getBytes("UTF-8"))
- digest.reset()
- input = digest.digest(input)
- val withSalt = salt ++ input
- base64Encode(withSalt)
- }
-
- private def base64Encode(data: Array[Byte]): String = {
- val endecoder = new BASE64Encoder()
- endecoder.encode(data)
- }
-
- private def base64Decode(data: String): Array[Byte] = {
- val decoder = new BASE64Decoder()
- decoder.decodeBuffer(data)
- }
-
- // scalastyle:off println
- private def help() = {
- Console.println("usage: gear io.gearpump.security.PasswordUtil -password <your password>")
- }
-
- def main(args: Array[String]): Unit = {
- if (args.length != 2 || args(0) != "-password") {
- help()
- } else {
- val pass = args(1)
- val result = hash(pass)
- Console.println("Here is the hashed password")
- Console.println("==============================")
- Console.println(result)
- }
- }
- // scalastyle:on println
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/serializer/FastKryoSerializationFramework.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/serializer/FastKryoSerializationFramework.scala b/core/src/main/scala/io/gearpump/serializer/FastKryoSerializationFramework.scala
deleted file mode 100644
index cb9d563..0000000
--- a/core/src/main/scala/io/gearpump/serializer/FastKryoSerializationFramework.scala
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.serializer
-
-import akka.actor.ExtendedActorSystem
-
-import io.gearpump.cluster.UserConfig
-
-/**
- * A build-in serializer framework using kryo
- *
- * NOTE: The Kryo here is a shaded version by Gearpump
- */
-class FastKryoSerializationFramework extends SerializationFramework {
- private var system: ExtendedActorSystem = null
-
- private lazy val pool = new ThreadLocal[Serializer]() {
- override def initialValue(): Serializer = {
- new FastKryoSerializer(system)
- }
- }
-
- override def init(system: ExtendedActorSystem, config: UserConfig): Unit = {
- this.system = system
- }
-
- override def get(): Serializer = {
- pool.get()
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/serializer/FastKryoSerializer.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/serializer/FastKryoSerializer.scala b/core/src/main/scala/io/gearpump/serializer/FastKryoSerializer.scala
deleted file mode 100644
index 57b7b5e..0000000
--- a/core/src/main/scala/io/gearpump/serializer/FastKryoSerializer.scala
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.serializer
-
-import akka.actor.ExtendedActorSystem
-
-import io.gearpump.esotericsoftware.kryo.Kryo.DefaultInstantiatorStrategy
-import io.gearpump.objenesis.strategy.StdInstantiatorStrategy
-import io.gearpump.romix.serialization.kryo.KryoSerializerWrapper
-import io.gearpump.serializer.FastKryoSerializer.KryoSerializationException
-import io.gearpump.util.LogUtil
-
-class FastKryoSerializer(system: ExtendedActorSystem) extends Serializer {
-
- private val LOG = LogUtil.getLogger(getClass)
- private val config = system.settings.config
-
- private val kryoSerializer = new KryoSerializerWrapper(system)
- private val kryo = kryoSerializer.kryo
- val strategy = new DefaultInstantiatorStrategy
- strategy.setFallbackInstantiatorStrategy(new StdInstantiatorStrategy)
- kryo.setInstantiatorStrategy(strategy)
- private val kryoClazz = new GearpumpSerialization(config).customize(kryo)
-
- override def serialize(message: Any): Array[Byte] = {
- try {
- kryoSerializer.toBinary(message)
- } catch {
- case ex: java.lang.IllegalArgumentException =>
- val clazz = message.getClass
- val error = s"""
- | ${ex.getMessage}
- |You can also register the class by providing a configuration with serializer
- |defined,
- |
- |gearpump{
- | serializers {
- | ## Follow this format when adding new serializer for new message types
- | # "yourpackage.YourClass" = "yourpackage.YourSerializerForThisClass"
- |
- | ## If you intend to use default serializer for this class, then you can write this
- | # "yourpackage.YourClass" = ""
- | }
- |}
- |
- |If you want to register the serializer globally, you need to change
- |gear.conf on every worker in the cluster; if you only want to register
- |the serializer for a single streaming application, you need to create
- |a file under conf/ named application.conf, and add the above configuration
- |into application.conf. To verify whether the configuration is effective,
- |you can browser your UI http://{UI Server Host}:8090/api/v1.0/app/{appId}/config,
- |and check whether your custom serializer is added.
- """.stripMargin
-
- LOG.error(error, ex)
- throw new KryoSerializationException(error, ex)
- }
- }
-
- override def deserialize(msg: Array[Byte]): Any = {
- kryoSerializer.fromBinary(msg)
- }
-}
-
-object FastKryoSerializer {
- class KryoSerializationException(msg: String, ex: Throwable = null) extends Exception(msg, ex)
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/serializer/GearpumpSerialization.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/serializer/GearpumpSerialization.scala b/core/src/main/scala/io/gearpump/serializer/GearpumpSerialization.scala
deleted file mode 100644
index a7eb6cf..0000000
--- a/core/src/main/scala/io/gearpump/serializer/GearpumpSerialization.scala
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.serializer
-
-import com.typesafe.config.Config
-import org.slf4j.Logger
-
-import io.gearpump.esotericsoftware.kryo.{Kryo, Serializer => KryoSerializer}
-import io.gearpump.util.{Constants, LogUtil}
-
-class GearpumpSerialization(config: Config) {
-
- private val LOG: Logger = LogUtil.getLogger(getClass)
-
- def customize(kryo: Kryo): Unit = {
-
- val serializationMap = configToMap(config, Constants.GEARPUMP_SERIALIZERS)
-
- serializationMap.foreach { kv =>
- val (key, value) = kv
- val keyClass = Class.forName(key)
-
- if (value == null || value.isEmpty) {
-
- // Use default serializer for this class type
- kryo.register(keyClass)
- } else {
- val valueClass = Class.forName(value)
- val register = kryo.register(keyClass,
- valueClass.newInstance().asInstanceOf[KryoSerializer[_]])
- LOG.debug(s"Registering ${keyClass}, id: ${register.getId}")
- }
- }
- kryo.setReferences(false)
-
- // Requires the user to register the class first before using
- kryo.setRegistrationRequired(true)
- }
-
- private final def configToMap(config: Config, path: String) = {
- import scala.collection.JavaConverters._
- config.getConfig(path).root.unwrapped.asScala.toMap map { case (k, v) => k -> v.toString }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/serializer/SerializationFramework.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/serializer/SerializationFramework.scala b/core/src/main/scala/io/gearpump/serializer/SerializationFramework.scala
deleted file mode 100644
index 4947dcc..0000000
--- a/core/src/main/scala/io/gearpump/serializer/SerializationFramework.scala
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.serializer
-
-import akka.actor.ExtendedActorSystem
-
-import io.gearpump.cluster.UserConfig
-
-/**
- * User are allowed to use a customized serialization framework by extending this
- * interface.
- */
-trait SerializationFramework {
- def init(system: ExtendedActorSystem, config: UserConfig)
-
- /**
- *
- * Need to be thread safe
- *
- * Get a serializer to use.
- * Note: this method can be called in a multi-thread environment. It's the
- * responsibility of SerializationFramework Developer to assure this method
- * is thread safe.
- *
- * To be thread-safe, one recommendation would be using a thread local pool
- * to maintain reference to Serializer of same thread.
- *
- * @return
- */
- def get(): Serializer
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/serializer/Serializer.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/serializer/Serializer.scala b/core/src/main/scala/io/gearpump/serializer/Serializer.scala
deleted file mode 100644
index ff8b147..0000000
--- a/core/src/main/scala/io/gearpump/serializer/Serializer.scala
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.serializer
-
-/**
- * User defined message serializer
- */
-trait Serializer {
- def serialize(message: Any): Array[Byte]
-
- def deserialize(msg: Array[Byte]): Any
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/transport/Express.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/transport/Express.scala b/core/src/main/scala/io/gearpump/transport/Express.scala
deleted file mode 100644
index 101b841..0000000
--- a/core/src/main/scala/io/gearpump/transport/Express.scala
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.transport
-
-import scala.collection.immutable.LongMap
-import scala.concurrent._
-
-import akka.actor._
-import akka.agent.Agent
-import org.slf4j.Logger
-
-import io.gearpump.transport.netty.Client.Close
-import io.gearpump.transport.netty.{Context, TaskMessage}
-import io.gearpump.util.LogUtil
-
-trait ActorLookupById {
-
- /** Lookup actor ref for local task actor by providing a TaskId (TaskId.toLong) */
- def lookupLocalActor(id: Long): Option[ActorRef]
-}
-
-/**
- * Custom networking layer.
- *
- * It will translate long sender/receiver address to shorter ones to reduce
- * the network overhead.
- */
-class Express(val system: ExtendedActorSystem) extends Extension with ActorLookupById {
-
- import system.dispatcher
-
- import io.gearpump.transport.Express._
- val localActorMap = Agent(LongMap.empty[ActorRef])
- val remoteAddressMap = Agent(Map.empty[Long, HostPort])
-
- val remoteClientMap = Agent(Map.empty[HostPort, ActorRef])
-
- val conf = system.settings.config
-
- lazy val (context, serverPort, localHost) = init
-
- lazy val init = {
- LOG.info(s"Start Express init ...${system.name}")
- val context = new Context(system, conf)
- val serverPort = context.bind("netty-server", this)
- val localHost = HostPort(system.provider.getDefaultAddress.host.get, serverPort)
- LOG.info(s"binding to netty server $localHost")
-
- system.registerOnTermination(new Runnable {
- override def run(): Unit = context.close()
- })
- (context, serverPort, localHost)
- }
-
- def unregisterLocalActor(id: Long): Unit = {
- localActorMap.sendOff(_ - id)
- }
-
- /** Start Netty client actors to connect to remote machines */
- def startClients(hostPorts: Set[HostPort]): Future[Map[HostPort, ActorRef]] = {
- val clientsToClose = remoteClientMap.get().filterKeys(!hostPorts.contains(_)).keySet
- closeClients(clientsToClose)
- hostPorts.toList.foldLeft(Future(Map.empty[HostPort, ActorRef])) { (future, hostPort) =>
- remoteClientMap.alter { map =>
- if (!map.contains(hostPort)) {
- val actor = context.connect(hostPort)
- map + (hostPort -> actor)
- } else {
- map
- }
- }
- }
- }
-
- def closeClients(hostPorts: Set[HostPort]): Future[Map[HostPort, ActorRef]] = {
- remoteClientMap.alter { map =>
- map.filterKeys(hostPorts.contains).foreach { hostAndClient =>
- val (_, client) = hostAndClient
- client ! Close
- }
- map -- hostPorts
- }
- }
-
- def registerLocalActor(id: Long, actor: ActorRef): Unit = {
- LOG.info(s"RegisterLocalActor: $id, actor: ${actor.path.name}")
- init
- localActorMap.sendOff(_ + (id -> actor))
- }
-
- def lookupLocalActor(id: Long): Option[ActorRef] = localActorMap.get().get(id)
-
- def lookupRemoteAddress(id: Long): Option[HostPort] = remoteAddressMap.get().get(id)
-
- /** Send message to remote task */
- def transport(taskMessage: TaskMessage, remote: HostPort): Unit = {
-
- val remoteClient = remoteClientMap.get.get(remote)
- if (remoteClient.isDefined) {
- remoteClient.get.tell(taskMessage, Actor.noSender)
- } else {
- val errorMsg = s"Clients has not been launched properly before transporting messages, " +
- s"the destination is $remote"
- LOG.error(errorMsg)
- throw new Exception(errorMsg)
- }
- }
-}
-
-/** A customized transport layer by using Akka extension */
-object Express extends ExtensionId[Express] with ExtensionIdProvider {
- val LOG: Logger = LogUtil.getLogger(getClass)
-
- override def get(system: ActorSystem): Express = super.get(system)
-
- override def lookup: ExtensionId[Express] = Express
-
- override def createExtension(system: ExtendedActorSystem): Express = new Express(system)
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/transport/HostPort.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/transport/HostPort.scala b/core/src/main/scala/io/gearpump/transport/HostPort.scala
deleted file mode 100644
index 40c4342..0000000
--- a/core/src/main/scala/io/gearpump/transport/HostPort.scala
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.transport
-
-case class HostPort(host: String, port: Int) {
- def toTuple: (String, Int) = {
- (host, port)
- }
-}
-
-object HostPort {
- def apply(address: String): HostPort = {
- val hostAndPort = address.split(":")
- new HostPort(hostAndPort(0), hostAndPort(1).toInt)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/transport/netty/Client.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/transport/netty/Client.scala b/core/src/main/scala/io/gearpump/transport/netty/Client.scala
deleted file mode 100644
index d5960ad..0000000
--- a/core/src/main/scala/io/gearpump/transport/netty/Client.scala
+++ /dev/null
@@ -1,248 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.transport.netty
-
-import java.net.{ConnectException, InetSocketAddress}
-import java.nio.channels.ClosedChannelException
-import java.util
-import java.util.Random
-import java.util.concurrent.TimeUnit
-import scala.concurrent.duration.FiniteDuration
-import scala.language.implicitConversions
-
-import akka.actor.Actor
-import org.jboss.netty.bootstrap.ClientBootstrap
-import org.jboss.netty.channel._
-import org.slf4j.Logger
-
-import io.gearpump.transport.HostPort
-import io.gearpump.util.LogUtil
-
-/**
- * Netty Client implemented as an actor, on the other side, there is a netty server Actor.
- * All messages sent to this actor will be forwarded to remote machine.
- */
-class Client(conf: NettyConfig, factory: ChannelFactory, hostPort: HostPort) extends Actor {
- import io.gearpump.transport.netty.Client._
-
- val name = s"netty-client-$hostPort"
-
- private final var bootstrap: ClientBootstrap = null
- private final val random: Random = new Random
- private val serializer = conf.newTransportSerializer
- private var channel: Channel = null
-
- var batch = new util.ArrayList[TaskMessage]
-
- private val init = {
- bootstrap = NettyUtil.createClientBootStrap(factory,
- new ClientPipelineFactory(name, conf), conf.buffer_size)
- self ! Connect(0)
- }
-
- def receive: Receive = messageHandler orElse connectionHandler
-
- def messageHandler: Receive = {
- case msg: TaskMessage =>
- batch.add(msg)
- case flush@Flush(flushChannel) =>
- if (channel != flushChannel) {
- Unit // Drop, as it belong to old channel flush message
- } else if (batch.size > 0 && flushChannel.isWritable) {
- send(flushChannel, batch.iterator)
- batch.clear()
- self ! flush
- } else {
- import context.dispatcher
- context.system.scheduler.scheduleOnce(
- new FiniteDuration(conf.flushCheckInterval, TimeUnit.MILLISECONDS), self, flush)
- }
- }
-
- def connectionHandler: Receive = {
- case ChannelReady(channel) =>
- this.channel = channel
- self ! Flush(channel)
- case Connect(tries) =>
- if (null == channel) {
- connect(tries)
- } else {
- LOG.error("there already exist a channel, will not establish a new one...")
- }
- case CompareAndReconnectIfEqual(oldChannel) =>
- if (oldChannel == channel) {
- channel = null
- self ! Connect(0)
- }
- case Close =>
- close()
- context.become(closed)
- }
-
- def closed: Receive = {
- case msg: AnyRef =>
- LOG.error(s"This client $name is closed, drop any message ${msg.getClass.getSimpleName}...")
- }
-
- private def connect(tries: Int): Unit = {
- LOG.info(s"netty client try to connect to $name, tries: $tries")
- if (tries <= conf.max_retries) {
- val remote_addr = new InetSocketAddress(hostPort.host, hostPort.port)
- val future = bootstrap.connect(remote_addr)
- future success { current =>
- LOG.info(s"netty client successfully connectted to $name, tries: $tries")
- self ! ChannelReady(current)
- } fail { (current, ex) =>
- LOG.error(s"failed to connect to $name, reason: ${ex.getMessage}, class: ${ex.getClass}")
- current.close()
- import context.dispatcher
- context.system.scheduler.scheduleOnce(
- new FiniteDuration(
- getSleepTimeMs(tries), TimeUnit.MILLISECONDS), self, Connect(tries + 1))
- }
- } else {
- LOG.error(s"fail to connect to a remote host $name after retied $tries ...")
- self ! Close
- }
- }
-
- private def send(flushChannel: Channel, msgs: util.Iterator[TaskMessage]) {
- var messageBatch: MessageBatch = null
-
- while (msgs.hasNext) {
- val message: TaskMessage = msgs.next()
- if (null == messageBatch) {
- messageBatch = new MessageBatch(conf.messageBatchSize, serializer)
- }
- messageBatch.add(message)
- if (messageBatch.isFull) {
- val toBeFlushed: MessageBatch = messageBatch
- flushRequest(flushChannel, toBeFlushed)
- messageBatch = null
- }
- }
- if (null != messageBatch && !messageBatch.isEmpty) {
- flushRequest(flushChannel, messageBatch)
- }
- }
-
- private def close() {
- LOG.info(s"closing netty client $name...")
- if (null != channel) {
- channel.close()
- channel = null
- }
- batch = null
- }
-
- override def postStop(): Unit = {
- close()
- }
-
- private def flushRequest(channel: Channel, requests: MessageBatch) {
- val future: ChannelFuture = channel.write(requests)
- future.fail { (channel, ex) =>
- if (channel.isOpen) {
- channel.close
- }
- LOG.error(s"failed to send requests " +
- s"to ${channel.getRemoteAddress} ${ex.getClass.getSimpleName}")
- if (!ex.isInstanceOf[ClosedChannelException]) {
- LOG.error(ex.getMessage, ex)
- }
- self ! CompareAndReconnectIfEqual(channel)
- }
- }
-
- private def getSleepTimeMs(retries: Int): Long = {
- if (retries > 30) {
- conf.max_sleep_ms
- } else {
- val backoff = 1 << retries
- val sleepMs = conf.base_sleep_ms * Math.max(1, random.nextInt(backoff))
- if (sleepMs < conf.max_sleep_ms) sleepMs else conf.max_sleep_ms
- }
- }
-
- private def isChannelWritable = (null != channel) && channel.isWritable
-}
-
-object Client {
- val LOG: Logger = LogUtil.getLogger(getClass)
-
- // Reconnect if current channel equals channel
- case class CompareAndReconnectIfEqual(channel: Channel)
-
- case class Connect(tries: Int)
- case class ChannelReady(chanel: Channel)
- case object Close
-
- case class Flush(channel: Channel)
-
- class ClientErrorHandler(name: String) extends SimpleChannelUpstreamHandler {
-
- override def exceptionCaught(ctx: ChannelHandlerContext, event: ExceptionEvent) {
- event.getCause match {
- case ex: ConnectException => Unit
- case ex: ClosedChannelException =>
- LOG.warn("exception found when trying to close netty connection", ex.getMessage)
- case ex => LOG.error("Connection failed " + name, ex)
- }
- }
- }
-
- class ClientPipelineFactory(name: String, conf: NettyConfig) extends ChannelPipelineFactory {
- def getPipeline: ChannelPipeline = {
- val pipeline: ChannelPipeline = Channels.pipeline
- pipeline.addLast("decoder", new MessageDecoder(conf.newTransportSerializer))
- pipeline.addLast("encoder", new MessageEncoder)
- pipeline.addLast("handler", new ClientErrorHandler(name))
- pipeline
- }
- }
-
- implicit def channelFutureToChannelFutureOps(channel: ChannelFuture): ChannelFutureOps = {
- new ChannelFutureOps(channel)
- }
-
- class ChannelFutureOps(channelFuture: ChannelFuture) {
-
- def success(handler: (Channel => Unit)): ChannelFuture = {
- channelFuture.addListener(new ChannelFutureListener {
- def operationComplete(future: ChannelFuture) {
- if (future.isSuccess) {
- handler(future.getChannel)
- }
- }
- })
- channelFuture
- }
-
- def fail(handler: ((Channel, Throwable) => Unit)): ChannelFuture = {
- channelFuture.addListener(new ChannelFutureListener {
- def operationComplete(future: ChannelFuture) {
- if (!future.isSuccess) {
- handler(future.getChannel, future.getCause)
- }
- }
- })
- channelFuture
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/transport/netty/Context.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/transport/netty/Context.scala b/core/src/main/scala/io/gearpump/transport/netty/Context.scala
deleted file mode 100644
index 9a9ee29..0000000
--- a/core/src/main/scala/io/gearpump/transport/netty/Context.scala
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.transport.netty
-
-import java.io.Closeable
-import java.util.concurrent._
-import scala.collection.JavaConverters._
-
-import akka.actor.{ActorRef, ActorSystem, Props}
-import com.typesafe.config.Config
-import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory
-import org.slf4j.Logger
-
-import io.gearpump.transport.netty.Server.ServerPipelineFactory
-import io.gearpump.transport.{ActorLookupById, HostPort}
-import io.gearpump.util.{Constants, LogUtil}
-
-object Context {
- private final val LOG: Logger = LogUtil.getLogger(getClass)
-}
-
-/** Netty Context */
-class Context(system: ActorSystem, conf: NettyConfig) extends IContext {
- import io.gearpump.transport.netty.Context._
-
- def this(system: ActorSystem, conf: Config) {
- this(system, new NettyConfig(conf))
- }
-
- private val closeHandler = new ConcurrentLinkedQueue[Closeable]()
- private val nettyDispatcher = system.settings.config.getString(Constants.NETTY_DISPATCHER)
- val maxWorkers: Int = 1
-
- private lazy val clientChannelFactory: NioClientSocketChannelFactory = {
- val bossFactory: ThreadFactory = new NettyRenameThreadFactory("client" + "-boss")
- val workerFactory: ThreadFactory = new NettyRenameThreadFactory("client" + "-worker")
- val channelFactory =
- new NioClientSocketChannelFactory(
- Executors.newCachedThreadPool(bossFactory),
- Executors.newCachedThreadPool(workerFactory), maxWorkers)
-
- closeHandler.add(new Closeable {
- override def close(): Unit = {
- LOG.info("Closing all client resources....")
- channelFactory.releaseExternalResources
- }
- })
- channelFactory
- }
-
- def bind(
- name: String, lookupActor : ActorLookupById, deserializeFlag : Boolean = true,
- inputPort: Int = 0): Int = {
- // TODO: whether we should expose it as application config?
- val server = system.actorOf(Props(classOf[Server], name, conf, lookupActor,
- deserializeFlag).withDispatcher(nettyDispatcher), name)
- val (port, channel) = NettyUtil.newNettyServer(name,
- new ServerPipelineFactory(server, conf), 5242880, inputPort)
- val factory = channel.getFactory
- closeHandler.add(new Closeable {
- override def close(): Unit = {
- system.stop(server)
- channel.close()
- LOG.info("Closing all server resources....")
- factory.releaseExternalResources
- }
- })
- port
- }
-
- def connect(hostPort: HostPort): ActorRef = {
- val client = system.actorOf(Props(classOf[Client], conf, clientChannelFactory, hostPort)
- .withDispatcher(nettyDispatcher))
- closeHandler.add(new Closeable {
- override def close(): Unit = {
- LOG.info("closing Client actor....")
- system.stop(client)
- }
- })
-
- client
- }
-
- /**
- * terminate this context
- */
- def close(): Unit = {
-
- LOG.info(s"Context.term, cleanup resources...., " +
- s"we have ${closeHandler.size()} items to close...")
-
- // Cleans up resource in reverse order so that client actor can be cleaned
- // before clientChannelFactory
- closeHandler.iterator().asScala.toList.reverse.foreach(_.close())
- }
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/transport/netty/IContext.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/transport/netty/IContext.scala b/core/src/main/scala/io/gearpump/transport/netty/IContext.scala
deleted file mode 100644
index 56b2f7c..0000000
--- a/core/src/main/scala/io/gearpump/transport/netty/IContext.scala
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.transport.netty
-
-import akka.actor.ActorRef
-
-import io.gearpump.transport.{ActorLookupById, HostPort}
-
-trait IContext {
-
- /**
- * Create a Netty server connection.
- */
- def bind(name: String, lookupActor: ActorLookupById, deserializeFlag: Boolean, port: Int): Int
-
- /**
- * Create a Netty client actor
- */
- def connect(hostPort: HostPort): ActorRef
-
- /**
- * Close resource for this context
- */
- def close()
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/transport/netty/NettyConfig.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/transport/netty/NettyConfig.scala b/core/src/main/scala/io/gearpump/transport/netty/NettyConfig.scala
deleted file mode 100644
index a62eff5..0000000
--- a/core/src/main/scala/io/gearpump/transport/netty/NettyConfig.scala
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.transport.netty
-
-import com.typesafe.config.Config
-
-import io.gearpump.util.Constants
-
-class NettyConfig(conf: Config) {
-
- val buffer_size = conf.getInt(Constants.NETTY_BUFFER_SIZE)
- val max_retries = conf.getInt(Constants.NETTY_MAX_RETRIES)
- val base_sleep_ms = conf.getInt(Constants.NETTY_BASE_SLEEP_MS)
- val max_sleep_ms = conf.getInt(Constants.NETTY_MAX_SLEEP_MS)
- val messageBatchSize = conf.getInt(Constants.NETTY_MESSAGE_BATCH_SIZE)
- val flushCheckInterval = conf.getInt(Constants.NETTY_FLUSH_CHECK_INTERVAL)
-
- def newTransportSerializer: ITransportMessageSerializer = {
- Class.forName(
- conf.getString(Constants.GEARPUMP_TRANSPORT_SERIALIZER))
- .newInstance().asInstanceOf[ITransportMessageSerializer]
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/transport/netty/NettyUtil.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/transport/netty/NettyUtil.scala b/core/src/main/scala/io/gearpump/transport/netty/NettyUtil.scala
deleted file mode 100644
index 3e746af..0000000
--- a/core/src/main/scala/io/gearpump/transport/netty/NettyUtil.scala
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.transport.netty
-
-import java.net.InetSocketAddress
-import java.util.concurrent.{Executors, ThreadFactory}
-
-import org.jboss.netty.bootstrap.{ClientBootstrap, ServerBootstrap}
-import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory
-import org.jboss.netty.channel.{Channel, ChannelFactory, ChannelPipelineFactory}
-
-object NettyUtil {
-
- def newNettyServer(
- name: String,
- pipelineFactory: ChannelPipelineFactory,
- buffer_size: Int,
- inputPort: Int = 0): (Int, Channel) = {
- val bossFactory: ThreadFactory = new NettyRenameThreadFactory(name + "-boss")
- val workerFactory: ThreadFactory = new NettyRenameThreadFactory(name + "-worker")
- val factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(bossFactory),
- Executors.newCachedThreadPool(workerFactory), 1)
-
- val bootstrap = createServerBootStrap(factory, pipelineFactory, buffer_size)
- val channel: Channel = bootstrap.bind(new InetSocketAddress(inputPort))
- val port = channel.getLocalAddress().asInstanceOf[InetSocketAddress].getPort()
- (port, channel)
- }
-
- def createServerBootStrap(
- factory: ChannelFactory, pipelineFactory: ChannelPipelineFactory, buffer_size: Int)
- : ServerBootstrap = {
- val bootstrap = new ServerBootstrap(factory)
- bootstrap.setOption("child.tcpNoDelay", true)
- bootstrap.setOption("child.receiveBufferSize", buffer_size)
- bootstrap.setOption("child.keepAlive", true)
- bootstrap.setPipelineFactory(pipelineFactory)
- bootstrap
- }
-
- def createClientBootStrap(
- factory: ChannelFactory, pipelineFactory: ChannelPipelineFactory, buffer_size: Int)
- : ClientBootstrap = {
- val bootstrap = new ClientBootstrap(factory)
- bootstrap.setOption("tcpNoDelay", true)
- bootstrap.setOption("sendBufferSize", buffer_size)
- bootstrap.setOption("keepAlive", true)
- bootstrap.setPipelineFactory(pipelineFactory)
- bootstrap
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/transport/netty/Server.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/transport/netty/Server.scala b/core/src/main/scala/io/gearpump/transport/netty/Server.scala
deleted file mode 100644
index 9a9d79b..0000000
--- a/core/src/main/scala/io/gearpump/transport/netty/Server.scala
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.transport.netty
-
-import java.util
-import scala.collection.JavaConverters._
-import scala.collection.immutable.IntMap
-import scala.concurrent.Future
-
-import akka.actor.{Actor, ActorContext, ActorRef, ExtendedActorSystem}
-import org.jboss.netty.channel._
-import org.jboss.netty.channel.group.{ChannelGroup, DefaultChannelGroup}
-import org.slf4j.Logger
-
-import io.gearpump.transport.ActorLookupById
-import io.gearpump.util.{AkkaHelper, LogUtil}
-
-/** Netty server actor, message received will be forward to the target on the address line. */
-class Server(
- name: String, conf: NettyConfig, lookupActor: ActorLookupById, deserializeFlag: Boolean)
- extends Actor {
-
- private[netty] final val LOG: Logger = LogUtil.getLogger(getClass, context = name)
- import io.gearpump.transport.netty.Server._
-
- val allChannels: ChannelGroup = new DefaultChannelGroup("gearpump-server")
-
- val system = context.system.asInstanceOf[ExtendedActorSystem]
-
- def receive: Receive = msgHandler orElse channelManager
- // As we will only transfer TaskId on the wire,
- // this object will translate taskId to or from ActorRef
- private val taskIdActorRefTranslation = new TaskIdActorRefTranslation(context)
-
- def channelManager: Receive = {
- case AddChannel(channel) => allChannels.add(channel)
- case CloseChannel(channel) =>
- import context.dispatcher
- Future {
- channel.close.awaitUninterruptibly
- allChannels.remove(channel)
- }
- }
-
- def msgHandler: Receive = {
- case MsgBatch(msgs) =>
- msgs.asScala.groupBy(_.targetTask()).foreach { taskBatch =>
- val (taskId, taskMessages) = taskBatch
- val actor = lookupActor.lookupLocalActor(taskId)
-
- if (actor.isEmpty) {
- LOG.error(s"Cannot find actor for id: $taskId...")
- } else taskMessages.foreach { taskMessage =>
- actor.get.tell(taskMessage.message(),
- taskIdActorRefTranslation.translateToActorRef(taskMessage.sessionId()))
- }
- }
- }
-
- override def postStop(): Unit = {
- allChannels.close.awaitUninterruptibly
- }
-}
-
-object Server {
-
- class ServerPipelineFactory(server: ActorRef, conf: NettyConfig) extends ChannelPipelineFactory {
- def getPipeline: ChannelPipeline = {
- val pipeline: ChannelPipeline = Channels.pipeline
- pipeline.addLast("decoder", new MessageDecoder(conf.newTransportSerializer))
- pipeline.addLast("encoder", new MessageEncoder)
- pipeline.addLast("handler", new ServerHandler(server))
- pipeline
- }
- }
-
- class ServerHandler(server: ActorRef) extends SimpleChannelUpstreamHandler {
- private[netty] final val LOG: Logger = LogUtil.getLogger(getClass, context = server.path.name)
-
- override def channelConnected(ctx: ChannelHandlerContext, e: ChannelStateEvent) {
- server ! AddChannel(e.getChannel)
- }
-
- override def messageReceived(ctx: ChannelHandlerContext, e: MessageEvent) {
- val msgs: util.List[TaskMessage] = e.getMessage.asInstanceOf[util.List[TaskMessage]]
- if (msgs != null) {
- server ! MsgBatch(msgs)
- }
- }
-
- override def exceptionCaught(ctx: ChannelHandlerContext, e: ExceptionEvent) {
- LOG.error("server errors in handling the request", e.getCause)
- server ! CloseChannel(e.getChannel)
- }
- }
-
- class TaskIdActorRefTranslation(context: ActorContext) {
- private var taskIdtoActorRef = IntMap.empty[ActorRef]
-
- /** 1-1 mapping from session id to fake ActorRef */
- def translateToActorRef(sessionId: Int): ActorRef = {
- if (!taskIdtoActorRef.contains(sessionId)) {
-
- // A fake ActorRef for performance optimization.
- val actorRef = AkkaHelper.actorFor(context.system, s"/session#$sessionId")
- taskIdtoActorRef += sessionId -> actorRef
- }
- taskIdtoActorRef.get(sessionId).get
- }
- }
-
- case class AddChannel(channel: Channel)
-
- case class CloseChannel(channel: Channel)
-
- case class MsgBatch(messages: java.lang.Iterable[TaskMessage])
-
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/util/ActorSystemBooter.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/util/ActorSystemBooter.scala b/core/src/main/scala/io/gearpump/util/ActorSystemBooter.scala
deleted file mode 100644
index 25a34d9..0000000
--- a/core/src/main/scala/io/gearpump/util/ActorSystemBooter.scala
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.util
-
-import java.util.concurrent.{TimeUnit, TimeoutException}
-import scala.concurrent.Await
-import scala.concurrent.duration.Duration
-import scala.util.{Failure, Success, Try}
-
-import akka.actor._
-import com.typesafe.config.Config
-import org.slf4j.Logger
-
-import io.gearpump.cluster.ClusterConfig
-import io.gearpump.util.LogUtil.ProcessType
-
-/**
- * ActorSystemBooter start a new JVM process to boot an actor system.
- * All executors are started by ActorSystemBooter
- *
- * It send the system address to "report back actor"
- */
-class ActorSystemBooter(config: Config) {
- import io.gearpump.util.ActorSystemBooter._
-
- def boot(name: String, reportBackActor: String): ActorSystem = {
- val system = ActorSystem(name, config)
- // Daemon path: http://{system}@{ip}:{port}/daemon
- system.actorOf(Props(classOf[Daemon], name, reportBackActor), "daemon")
- system
- }
-}
-
-object ActorSystemBooter {
-
- def apply(config: Config): ActorSystemBooter = new ActorSystemBooter(config)
-
- def main(args: Array[String]) {
- val name = args(0)
- val reportBack = args(1)
- val config = ClusterConfig.default()
-
- LogUtil.loadConfiguration(config, ProcessType.APPLICATION)
-
- val debugPort = Option(System.getProperty(Constants.GEARPUMP_REMOTE_DEBUG_PORT))
- debugPort.foreach { port =>
- val LOG: Logger = LogUtil.getLogger(ActorSystemBooter.getClass)
- LOG.info("==========================================")
- LOG.info("Remote debug port: " + port)
- LOG.info("==========================================")
- }
-
- val system = apply(config).boot(name, reportBack)
-
- Runtime.getRuntime().addShutdownHook(new Thread() {
- override def run(): Unit = {
- val LOG: Logger = LogUtil.getLogger(ActorSystemBooter.getClass)
- LOG.info("Maybe we have received a SIGINT signal from parent process, " +
- "start to cleanup resources....")
- system.terminate()
- }
- })
-
- Await.result(system.whenTerminated, Duration.Inf)
- }
-
- case class BindLifeCycle(actor: ActorRef)
- case class CreateActor(prop: Props, name: String)
- case class ActorCreated(actor: ActorRef, name: String)
- case class CreateActorFailed(name: String, reason: Throwable)
-
- case class RegisterActorSystem(systemPath: String)
-
- /**
- * This actor system will watch for parent,
- * If parent dies, this will also die
- */
- case class ActorSystemRegistered(bindLifeWith: ActorRef)
- case class RegisterActorSystemFailed(reason: Throwable)
-
- object RegisterActorSystemTimeOut
-
- class Daemon(val name: String, reportBack: String) extends Actor {
- val LOG: Logger = LogUtil.getLogger(getClass, context = name)
-
- val username = Option(System.getProperty(Constants.GEARPUMP_USERNAME)).getOrElse("not_defined")
- LOG.info(s"RegisterActorSystem to ${reportBack}, current user: $username")
-
- val reportBackActor = context.actorSelection(reportBack)
- reportBackActor ! RegisterActorSystem(ActorUtil.getSystemAddress(context.system).toString)
-
- implicit val executionContext = context.dispatcher
- val timeout = context.system.scheduler.scheduleOnce(Duration(25, TimeUnit.SECONDS),
- self, RegisterActorSystemFailed(new TimeoutException))
-
- context.become(waitForRegisterResult)
-
- def receive: Receive = null
-
- def waitForRegisterResult: Receive = {
- case ActorSystemRegistered(parent) =>
- timeout.cancel()
- context.watch(parent)
- context.become(waitCommand)
- case RegisterActorSystemFailed(ex) =>
- LOG.error("RegisterActorSystemFailed", ex)
- timeout.cancel()
- context.stop(self)
- }
-
- def waitCommand: Receive = {
- case BindLifeCycle(actor) =>
- LOG.info(s"ActorSystem $name Binding life cycle with actor: $actor")
- context.watch(actor)
- case create@CreateActor(props: Props, name: String) =>
- LOG.info(s"creating actor $name")
- val actor = Try(context.actorOf(props, name))
- actor match {
- case Success(actor) =>
- sender ! ActorCreated(actor, name)
- case Failure(e) =>
- sender ! CreateActorFailed(props.clazz.getName, e)
- }
- case PoisonPill =>
- context.stop(self)
- case Terminated(actor) =>
- LOG.info(s"System $name Watched actor is terminated $actor")
- context.stop(self)
- }
-
- override def postStop(): Unit = {
- LOG.info(s"ActorSystem $name is shutting down...")
- context.system.terminate()
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/util/ActorUtil.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/util/ActorUtil.scala b/core/src/main/scala/io/gearpump/util/ActorUtil.scala
deleted file mode 100644
index d5f48a7..0000000
--- a/core/src/main/scala/io/gearpump/util/ActorUtil.scala
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.util
-
-import scala.concurrent.{ExecutionContext, Future}
-
-import akka.actor.Actor.Receive
-import akka.actor._
-import akka.pattern.ask
-import org.slf4j.Logger
-
-import io.gearpump.cluster.AppMasterToMaster.GetAllWorkers
-import io.gearpump.cluster.ClientToMaster.{ResolveAppId, ResolveWorkerId}
-import io.gearpump.cluster.MasterToAppMaster.WorkerList
-import io.gearpump.cluster.MasterToClient.{ResolveAppIdResult, ResolveWorkerIdResult}
-import io.gearpump.cluster.appmaster.ExecutorSystemScheduler.{ExecutorSystemJvmConfig, StartExecutorSystems}
-import io.gearpump.cluster.scheduler.{Relaxation, Resource, ResourceRequest}
-import io.gearpump.cluster.worker.WorkerId
-import io.gearpump.transport.HostPort
-
-object ActorUtil {
- private val LOG: Logger = LogUtil.getLogger(getClass)
-
- def getSystemAddress(system: ActorSystem): Address = {
- system.asInstanceOf[ExtendedActorSystem].provider.getDefaultAddress
- }
-
- def getFullPath(system: ActorSystem, path: ActorPath): String = {
- path.toStringWithAddress(getSystemAddress(system))
- }
-
- def getHostname(actor: ActorRef): String = {
- val path = actor.path
- path.address.host.getOrElse("localhost")
- }
-
- def defaultMsgHandler(actor: ActorRef): Receive = {
- case msg: Any =>
- LOG.error(s"Cannot find a matching message, ${msg.getClass.toString}, forwarded from $actor")
- }
-
- def printActorSystemTree(system: ActorSystem): Unit = {
- val extendedSystem = system.asInstanceOf[ExtendedActorSystem]
- val clazz = system.getClass
- val m = clazz.getDeclaredMethod("printTree")
- m.setAccessible(true)
- LOG.info(m.invoke(system).asInstanceOf[String])
- }
-
- /** Checks whether a actor is child actor by simply examining name */
- // TODO: fix this, we should also check the path to root besides name
- def isChildActorPath(parent: ActorRef, child: ActorRef): Boolean = {
- if (null != child) {
- parent.path.name == child.path.parent.name
- } else {
- false
- }
- }
-
- def actorNameForExecutor(appId: Int, executorId: Int): String = "app" + appId + "-executor" +
- executorId
-
- // TODO: Currently we explicitly require the master contacts to be started with this path pattern
- // akka.tcp://$MASTER@${master.host}:${master.port}/user/$MASTER
- def getMasterActorPath(master: HostPort): ActorPath = {
- import io.gearpump.util.Constants.MASTER
- ActorPath.fromString(s"akka.tcp://$MASTER@${master.host}:${master.port}/user/$MASTER")
- }
-
- def launchExecutorOnEachWorker(master: ActorRef, executorJvmConfig: ExecutorSystemJvmConfig,
- sender: ActorRef)(implicit executor: scala.concurrent.ExecutionContext): Unit = {
- implicit val timeout = Constants.FUTURE_TIMEOUT
-
- (master ? GetAllWorkers).asInstanceOf[Future[WorkerList]].map { list =>
- val resources = list.workers.map {
- workerId => ResourceRequest(Resource(1), workerId, relaxation = Relaxation.SPECIFICWORKER)
- }.toArray
-
- master.tell(StartExecutorSystems(resources, executorJvmConfig), sender)
- }
- }
-
- def askAppMaster[T](master: ActorRef, appId: Int, msg: Any)(implicit ex: ExecutionContext)
- : Future[T] = {
- implicit val timeout = Constants.FUTURE_TIMEOUT
- val appmaster = askActor[ResolveAppIdResult](master, ResolveAppId(appId)).flatMap { result =>
- if (result.appMaster.isSuccess) {
- Future.successful(result.appMaster.get)
- } else {
- Future.failed(result.appMaster.failed.get)
- }
- }
- appmaster.flatMap(askActor[T](_, msg))
- }
-
- def askWorker[T](master: ActorRef, workerId: WorkerId, msg: Any)(implicit ex: ExecutionContext)
- : Future[T] = {
- implicit val timeout = Constants.FUTURE_TIMEOUT
- val worker = askActor[ResolveWorkerIdResult](master, ResolveWorkerId(workerId))
- .flatMap { result =>
- if (result.worker.isSuccess) {
- Future.successful(result.worker.get)
- } else {
- Future.failed(result.worker.failed.get)
- }
- }
- worker.flatMap(askActor[T](_, msg))
- }
-
- def askActor[T](actor: ActorRef, msg: Any)(implicit ex: ExecutionContext): Future[T] = {
- implicit val timeout = Constants.FUTURE_TIMEOUT
- (actor ? msg).asInstanceOf[Future[T]]
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/util/AkkaApp.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/util/AkkaApp.scala b/core/src/main/scala/io/gearpump/util/AkkaApp.scala
deleted file mode 100644
index 2b0bf61..0000000
--- a/core/src/main/scala/io/gearpump/util/AkkaApp.scala
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.util
-
-import scala.util.Try
-
-import io.gearpump.cluster.ClusterConfig
-
-/**
- * A Main class helper to load Akka configuration automatically.
- */
-trait AkkaApp {
-
- type Config = com.typesafe.config.Config
-
- def main(akkaConf: Config, args: Array[String]): Unit
-
- def help(): Unit
-
- protected def akkaConfig: Config = {
- ClusterConfig.default()
- }
-
- def main(args: Array[String]): Unit = {
- Try {
- main(akkaConfig, args)
- }.failed.foreach { ex => help(); throw ex }
- }
-}
[03/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/io/gearpump/streaming/appmaster/TaskSchedulerSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/io/gearpump/streaming/appmaster/TaskSchedulerSpec.scala b/streaming/src/test/scala/io/gearpump/streaming/appmaster/TaskSchedulerSpec.scala
deleted file mode 100644
index 2c64133..0000000
--- a/streaming/src/test/scala/io/gearpump/streaming/appmaster/TaskSchedulerSpec.scala
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.appmaster
-
-import scala.collection.mutable.ArrayBuffer
-
-import com.typesafe.config.ConfigFactory
-import org.scalatest.{Matchers, WordSpec}
-
-import io.gearpump.Message
-import io.gearpump.cluster.scheduler.{Relaxation, Resource, ResourceRequest}
-import io.gearpump.cluster.worker.WorkerId
-import io.gearpump.cluster.{TestUtil, UserConfig}
-import io.gearpump.partitioner.{HashPartitioner, Partitioner}
-import io.gearpump.streaming.appmaster.TaskLocator.Localities
-import io.gearpump.streaming.appmaster.TaskSchedulerSpec.{TestTask1, TestTask2}
-import io.gearpump.streaming.task.{StartTime, Task, TaskContext, TaskId}
-import io.gearpump.streaming.{Constants, DAG, ProcessorDescription}
-import io.gearpump.util.Graph
-import io.gearpump.util.Graph._
-
-class TaskSchedulerSpec extends WordSpec with Matchers {
- val task1 = ProcessorDescription(id = 0, taskClass = classOf[TestTask1].getName, parallelism = 4)
- val task2 = ProcessorDescription(id = 1, taskClass = classOf[TestTask2].getName, parallelism = 2)
-
- val dag = DAG(Graph(task1 ~ Partitioner[HashPartitioner] ~> task2))
-
- val config = TestUtil.DEFAULT_CONFIG
-
- "TaskScheduler" should {
- "schedule tasks on different workers properly according user's configuration" in {
-
- val localities = Localities(
- Map(WorkerId(1, 0L) -> Array(TaskId(0, 0), TaskId(0, 1), TaskId(1, 0), TaskId(1, 1)),
- WorkerId(2, 0L) -> Array(TaskId(0, 2), TaskId(0, 3))
- ))
-
- val localityConfig = ConfigFactory.parseString(Localities.toJson(localities))
-
- import io.gearpump.streaming.Constants.GEARPUMP_STREAMING_LOCALITIES
- val appName = "app"
- val taskScheduler = new TaskSchedulerImpl(appId = 0, appName,
- config.withValue(s"$GEARPUMP_STREAMING_LOCALITIES.$appName", localityConfig.root))
-
- val expectedRequests =
- Array(ResourceRequest(Resource(4), WorkerId(1, 0L), relaxation = Relaxation.SPECIFICWORKER),
- ResourceRequest(Resource(2), WorkerId(2, 0L), relaxation = Relaxation.SPECIFICWORKER))
-
- taskScheduler.setDAG(dag)
- val resourceRequests = taskScheduler.getResourceRequests()
-
- val acturalRequests = resourceRequests.sortBy(_.resource.slots)
- assert(acturalRequests.sameElements(expectedRequests.sortBy(_.resource.slots)))
-
- val tasksOnWorker1 = ArrayBuffer[Int]()
- val tasksOnWorker2 = ArrayBuffer[Int]()
- for (i <- 0 until 4) {
- tasksOnWorker1.append(taskScheduler.schedule(WorkerId(1, 0L),
- executorId = 0, Resource(1)).head.processorId)
- }
- for (i <- 0 until 2) {
- tasksOnWorker2.append(taskScheduler.schedule(WorkerId(2, 0L), executorId = 1,
- Resource(1)).head.processorId)
- }
-
- // Allocates more resource, and no tasks to launch
- assert(taskScheduler.schedule(WorkerId(3, 0L), executorId = 3,
- Resource(1)) == List.empty[TaskId])
-
- // On worker1, executor 0
- assert(tasksOnWorker1.sorted.sameElements(Array(0, 0, 1, 1)))
-
- // On worker2, executor 1, Task(0, 0), Task(0, 1)
- assert(tasksOnWorker2.sorted.sameElements(Array(0, 0)))
-
- val rescheduledResources = taskScheduler.executorFailed(executorId = 1)
-
- assert(rescheduledResources.sameElements(Array(ResourceRequest(Resource(2),
- WorkerId.unspecified, relaxation = Relaxation.ONEWORKER))))
-
- val launchedTask = taskScheduler.schedule(WorkerId(3, 0L), executorId = 3, Resource(2))
-
- // Starts the failed 2 tasks Task(0, 0) and Task(0, 1)
- assert(launchedTask.length == 2)
- }
-
- "schedule task fairly" in {
- val appName = "app"
- val taskScheduler = new TaskSchedulerImpl(appId = 0, appName, config)
-
- val expectedRequests =
- Array(ResourceRequest(Resource(4), WorkerId(1, 0L), relaxation = Relaxation.SPECIFICWORKER),
- ResourceRequest(Resource(2), WorkerId(2, 0L), relaxation = Relaxation.SPECIFICWORKER))
-
- taskScheduler.setDAG(dag)
- val tasks = taskScheduler.schedule(WorkerId(1, 0L), executorId = 0, Resource(4))
- assert(tasks.filter(_.processorId == 0).length == 2)
- assert(tasks.filter(_.processorId == 1).length == 2)
- }
- }
-}
-
-object TaskSchedulerSpec {
- class TestTask1(taskContext: TaskContext, userConf: UserConfig)
- extends Task(taskContext, userConf) {
- override def onStart(startTime: StartTime): Unit = Unit
- override def onNext(msg: Message): Unit = Unit
- }
-
- class TestTask2(taskContext: TaskContext, userConf: UserConfig)
- extends Task(taskContext, userConf) {
- override def onStart(startTime: StartTime): Unit = Unit
- override def onNext(msg: Message): Unit = Unit
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/io/gearpump/streaming/dsl/StreamAppSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/io/gearpump/streaming/dsl/StreamAppSpec.scala b/streaming/src/test/scala/io/gearpump/streaming/dsl/StreamAppSpec.scala
deleted file mode 100644
index 132d46c..0000000
--- a/streaming/src/test/scala/io/gearpump/streaming/dsl/StreamAppSpec.scala
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.dsl
-
-import scala.concurrent.Await
-import scala.concurrent.duration.Duration
-
-import akka.actor.ActorSystem
-import org.mockito.Mockito.when
-import org.scalatest._
-import org.scalatest.mock.MockitoSugar
-
-import io.gearpump.cluster.TestUtil
-import io.gearpump.cluster.client.ClientContext
-import io.gearpump.streaming.dsl.plan.OpTranslator.SourceTask
-class StreamAppSpec extends FlatSpec with Matchers with BeforeAndAfterAll with MockitoSugar {
-
- implicit var system: ActorSystem = null
-
- override def beforeAll(): Unit = {
- system = ActorSystem("test", TestUtil.DEFAULT_CONFIG)
- }
-
- override def afterAll(): Unit = {
- system.terminate()
- Await.result(system.whenTerminated, Duration.Inf)
- }
-
- it should "be able to generate multiple new streams" in {
- val context: ClientContext = mock[ClientContext]
- when(context.system).thenReturn(system)
-
- val app = StreamApp("dsl", context)
- app.source(List("A"), 1, "")
- app.source(List("B"), 1, "")
-
- assert(app.graph.vertices.size == 2)
- }
-
- it should "plan the dsl to Processsor(TaskDescription) DAG" in {
- val context: ClientContext = mock[ClientContext]
- when(context.system).thenReturn(system)
-
- val app = StreamApp("dsl", context)
- val parallism = 3
- app.source(List("A", "B", "C"), parallism, "").flatMap(Array(_)).reduce(_ + _)
- val task = app.plan.dag.vertices.iterator.next()
- assert(task.taskClass == classOf[SourceTask[_, _]].getName)
- assert(task.parallelism == parallism)
- }
-
- it should "produce 3 messages" in {
- val context: ClientContext = mock[ClientContext]
- when(context.system).thenReturn(system)
- val app = StreamApp("dsl", context)
- val list = List[String](
- "0",
- "1",
- "2"
- )
- val producer = app.source(list, 1, "producer").flatMap(Array(_)).reduce(_ + _)
- val task = app.plan.dag.vertices.iterator.next()
- /*
- val task = app.plan.dag.vertices.iterator.map(desc => {
- LOG.info(s"${desc.taskClass}")
- })
- val sum = producer.flatMap(msg => {
- LOG.info("in flatMap")
- assert(msg.msg.isInstanceOf[String])
- val num = msg.msg.asInstanceOf[String].toInt
- Array(num)
- }).reduce(_+_)
- val task = app.plan.dag.vertices.iterator.map(desc => {
- LOG.info(s"${desc.taskClass}")
- })
- */
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/io/gearpump/streaming/dsl/StreamSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/io/gearpump/streaming/dsl/StreamSpec.scala b/streaming/src/test/scala/io/gearpump/streaming/dsl/StreamSpec.scala
deleted file mode 100644
index c8a44f6..0000000
--- a/streaming/src/test/scala/io/gearpump/streaming/dsl/StreamSpec.scala
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.dsl
-
-import scala.concurrent.Await
-import scala.concurrent.duration.Duration
-import scala.util.{Either, Left, Right}
-
-import akka.actor._
-import org.mockito.Mockito.when
-import org.scalatest._
-import org.scalatest.mock.MockitoSugar
-
-import io.gearpump.Message
-import io.gearpump.cluster.client.ClientContext
-import io.gearpump.cluster.{TestUtil, UserConfig}
-import io.gearpump.partitioner.{CoLocationPartitioner, HashPartitioner}
-import io.gearpump.streaming.dsl.StreamSpec.Join
-import io.gearpump.streaming.dsl.partitioner.GroupByPartitioner
-import io.gearpump.streaming.dsl.plan.OpTranslator._
-import io.gearpump.streaming.task.{StartTime, Task, TaskContext}
-import io.gearpump.util.Graph
-import io.gearpump.util.Graph._
-
-class StreamSpec extends FlatSpec with Matchers with BeforeAndAfterAll with MockitoSugar {
-
- implicit var system: ActorSystem = null
-
- override def beforeAll(): Unit = {
- system = ActorSystem("test", TestUtil.DEFAULT_CONFIG)
- }
-
- override def afterAll(): Unit = {
- system.terminate()
- Await.result(system.whenTerminated, Duration.Inf)
- }
-
- it should "translate the DSL to a DAG" in {
- val context: ClientContext = mock[ClientContext]
- when(context.system).thenReturn(system)
-
- val app = StreamApp("dsl", context)
-
- val data =
- """
- five four three two one
- five four three two
- five four three
- five four
- five
- """
- val stream = app.source(data.lines.toList, 1, "").
- flatMap(line => line.split("[\\s]+")).filter(_.nonEmpty).
- map(word => (word, 1)).
- groupBy(_._1, parallelism = 2).
- reduce((left, right) => (left._1, left._2 + right._2)).
- map[Either[(String, Int), String]](Left(_))
-
- val query = app.source(List("two"), 1, "").map[Either[(String, Int), String]](Right(_))
- stream.merge(query).process[(String, Int)](classOf[Join], 1)
-
- val appDescription = app.plan
-
- val dagTopology = appDescription.dag.mapVertex(_.taskClass).mapEdge { (node1, edge, node2) =>
- edge.partitionerFactory.partitioner.getClass.getName
- }
- val expectedDagTopology = getExpectedDagTopology
-
- assert(dagTopology.vertices.toSet.equals(expectedDagTopology.vertices.toSet))
- assert(dagTopology.edges.toSet.equals(expectedDagTopology.edges.toSet))
- }
-
- private def getExpectedDagTopology: Graph[String, String] = {
- val source = classOf[SourceTask[_, _]].getName
- val group = classOf[GroupByTask[_, _, _]].getName
- val merge = classOf[TransformTask[_, _]].getName
- val join = classOf[Join].getName
-
- val hash = classOf[HashPartitioner].getName
- val groupBy = classOf[GroupByPartitioner[_, _]].getName
- val colocation = classOf[CoLocationPartitioner].getName
-
- val expectedDagTopology = Graph(
- source ~ groupBy ~> group ~ colocation ~> merge ~ hash ~> join,
- source ~ hash ~> merge
- )
- expectedDagTopology
- }
-}
-
-object StreamSpec {
-
- class Join(taskContext: TaskContext, userConf: UserConfig) extends Task(taskContext, userConf) {
-
- var query: String = null
- override def onStart(startTime: StartTime): Unit = {}
-
- override def onNext(msg: Message): Unit = {
- msg.msg match {
- case Left(wordCount: (String @unchecked, Int @unchecked)) =>
- if (query != null && wordCount._1 == query) {
- taskContext.output(new Message(wordCount))
- }
-
- case Right(query: String) =>
- this.query = query
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/io/gearpump/streaming/dsl/partitioner/GroupByPartitionerSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/io/gearpump/streaming/dsl/partitioner/GroupByPartitionerSpec.scala b/streaming/src/test/scala/io/gearpump/streaming/dsl/partitioner/GroupByPartitionerSpec.scala
deleted file mode 100644
index 03dd242..0000000
--- a/streaming/src/test/scala/io/gearpump/streaming/dsl/partitioner/GroupByPartitionerSpec.scala
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.dsl.partitioner
-
-import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
-
-import io.gearpump.Message
-import io.gearpump.streaming.dsl.partitioner.GroupByPartitionerSpec.People
-
-class GroupByPartitionerSpec extends FlatSpec with Matchers with BeforeAndAfterAll {
- it should "use the outpout of groupBy function to do partition" in {
- val mark = People("Mark", "male")
- val tom = People("Tom", "male")
- val michelle = People("Michelle", "female")
-
- val partitionNum = 10
- val groupBy = new GroupByPartitioner[People, String](_.gender)
- assert(groupBy.getPartition(Message(mark), partitionNum)
- == groupBy.getPartition(Message(tom), partitionNum))
-
- assert(groupBy.getPartition(Message(mark), partitionNum)
- != groupBy.getPartition(Message(michelle), partitionNum))
- }
-}
-
-object GroupByPartitionerSpec {
- case class People(name: String, gender: String)
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/io/gearpump/streaming/dsl/plan/OpTranslatorSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/io/gearpump/streaming/dsl/plan/OpTranslatorSpec.scala b/streaming/src/test/scala/io/gearpump/streaming/dsl/plan/OpTranslatorSpec.scala
deleted file mode 100644
index 62a0f95..0000000
--- a/streaming/src/test/scala/io/gearpump/streaming/dsl/plan/OpTranslatorSpec.scala
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.dsl.plan
-
-import scala.concurrent.Await
-import scala.concurrent.duration.Duration
-
-import akka.actor.ActorSystem
-import org.mockito.ArgumentCaptor
-import org.mockito.Matchers._
-import org.mockito.Mockito._
-import org.scalatest._
-
-import io.gearpump.Message
-import io.gearpump.cluster.{TestUtil, UserConfig}
-import io.gearpump.streaming.Constants._
-import io.gearpump.streaming.MockUtil
-import io.gearpump.streaming.dsl.CollectionDataSource
-import io.gearpump.streaming.dsl.plan.OpTranslator._
-import io.gearpump.streaming.task.StartTime
-
-class OpTranslatorSpec extends FlatSpec with Matchers with BeforeAndAfterAll {
-
- "andThen" should "chain multiple single input function" in {
- val dummy = new DummyInputFunction[String]
- val split = new FlatMapFunction[String, String](line => line.split("\\s"), "split")
-
- val filter = new FlatMapFunction[String, String](word =>
- if (word.isEmpty) None else Some(word), "filter")
-
- val map = new FlatMapFunction[String, Int](word => Some(1), "map")
-
- val sum = new ReduceFunction[Int]({ (left, right) => left + right }, "sum")
-
- val all = dummy.andThen(split).andThen(filter).andThen(map).andThen(sum)
-
- assert(all.description == "split.filter.map.sum")
-
- val data =
- """
- five four three two one
- five four three two
- five four three
- five four
- five
- """
- val count = all.process(data).toList.last
- assert(count == 15)
- }
-
- "Source" should "iterate over input source and apply attached operator" in {
-
- val taskContext = MockUtil.mockTaskContext
-
- val conf = UserConfig.empty
- val data = "one two three".split("\\s")
-
- // Source with no transformer
- val source = new SourceTask[String, String](new CollectionDataSource[String](data), None,
- taskContext, conf)
- source.onStart(StartTime(0))
- source.onNext(Message("next"))
- verify(taskContext, times(1)).output(anyObject())
-
- // Source with transformer
- val anotherTaskContext = MockUtil.mockTaskContext
- val double = new FlatMapFunction[String, String](word => List(word, word), "double")
- val another = new SourceTask(new CollectionDataSource[String](data), Some(double),
- anotherTaskContext, conf)
- another.onStart(StartTime(0))
- another.onNext(Message("next"))
- verify(anotherTaskContext, times(2)).output(anyObject())
- }
-
- "GroupByTask" should "group input by groupBy Function and " +
- "apply attached operator for each group" in {
-
- val data = "1 2 2 3 3 3"
-
- var map = Map.empty[String, Int]
-
- val concat = new ReduceFunction[String]({ (left, right) =>
- left + right
- }, "concat")
-
- implicit val system = ActorSystem("test", TestUtil.DEFAULT_CONFIG)
- val config = UserConfig.empty.withValue[SingleInputFunction[String, String]](
- GEARPUMP_STREAMING_OPERATOR, concat)
-
- val taskContext = MockUtil.mockTaskContext
-
- val task = new GroupByTask[String, String, String](input => input, taskContext, config)
- task.onStart(StartTime(0))
-
- val peopleCaptor = ArgumentCaptor.forClass(classOf[Message])
-
- data.split("\\s+").foreach { word =>
- task.onNext(Message(word))
- }
- verify(taskContext, times(6)).output(peopleCaptor.capture())
-
- import scala.collection.JavaConverters._
-
- val values = peopleCaptor.getAllValues().asScala.map(input => input.msg.asInstanceOf[String])
- assert(values.mkString(",") == "1,2,22,3,33,333")
- system.terminate()
- Await.result(system.whenTerminated, Duration.Inf)
- }
-
- "MergeTask" should "accept two stream and apply the attached operator" in {
-
- // Source with transformer
- val taskContext = MockUtil.mockTaskContext
- val conf = UserConfig.empty
- val double = new FlatMapFunction[String, String](word => List(word, word), "double")
- val task = new TransformTask[String, String](Some(double), taskContext, conf)
- task.onStart(StartTime(0))
-
- val data = "1 2 2 3 3 3".split("\\s+")
-
- data.foreach { input =>
- task.onNext(Message(input))
- }
-
- verify(taskContext, times(data.length * 2)).output(anyObject())
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/io/gearpump/streaming/executor/ExecutorSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/io/gearpump/streaming/executor/ExecutorSpec.scala b/streaming/src/test/scala/io/gearpump/streaming/executor/ExecutorSpec.scala
deleted file mode 100644
index 1d94776..0000000
--- a/streaming/src/test/scala/io/gearpump/streaming/executor/ExecutorSpec.scala
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.executor
-
-import scala.concurrent.Await
-import scala.concurrent.duration.Duration
-
-import akka.actor.{ActorSystem, Props}
-import akka.testkit.TestProbe
-import org.mockito.Matchers._
-import org.mockito.Mockito.{times, _}
-import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
-
-import io.gearpump.cluster.appmaster.WorkerInfo
-import io.gearpump.cluster.scheduler.Resource
-import io.gearpump.cluster.worker.WorkerId
-import io.gearpump.cluster.{ExecutorContext, TestUtil, UserConfig}
-import io.gearpump.streaming.AppMasterToExecutor._
-import io.gearpump.streaming.ExecutorToAppMaster.RegisterTask
-import io.gearpump.streaming.appmaster.TaskRegistry.TaskLocations
-import io.gearpump.streaming.executor.TaskLauncherSpec.MockTask
-import io.gearpump.streaming.task.{Subscriber, TaskId}
-import io.gearpump.streaming.{LifeTime, ProcessorDescription}
-import io.gearpump.transport.HostPort
-
-class ExecutorSpec extends FlatSpec with Matchers with BeforeAndAfterAll {
- val appId = 0
- val executorId = 0
- val workerId = WorkerId(0, 0L)
- var appMaster: TestProbe = null
- implicit var system: ActorSystem = null
- val userConf = UserConfig.empty
-
- override def beforeAll(): Unit = {
- system = ActorSystem("TaskLauncherSpec", TestUtil.DEFAULT_CONFIG)
- appMaster = TestProbe()
- }
-
- override def afterAll(): Unit = {
- system.terminate()
- Await.result(system.whenTerminated, Duration.Inf)
- }
-
- it should "call launcher to launch task" in {
- val worker = TestProbe()
- val workerInfo = WorkerInfo(workerId, worker.ref)
- val executorContext = ExecutorContext(executorId, workerInfo, appId, "app",
- appMaster.ref, Resource(2))
- val taskLauncher = mock(classOf[ITaskLauncher])
- val executor = system.actorOf(Props(new Executor(executorContext, userConf, taskLauncher)))
- val processor = ProcessorDescription(id = 0, taskClass = classOf[MockTask].getName,
- parallelism = 2)
- val taskIds = List(TaskId(0, 0), TaskId(0, 1))
- val launchTasks = LaunchTasks(taskIds, dagVersion = 0, processor, List.empty[Subscriber])
-
- val task = TestProbe()
- when(taskLauncher.launch(any(), any(), any(), any(), any()))
- .thenReturn(taskIds.map((_, task.ref)).toMap)
-
- val client = TestProbe()
- client.send(executor, launchTasks)
- client.expectMsg(TasksLaunched)
-
- verify(taskLauncher, times(1)).launch(any(), any(), any(), any(), any())
-
- executor ! RegisterTask(TaskId(0, 0), executorId, HostPort("localhost:80"))
- executor ! RegisterTask(TaskId(0, 1), executorId, HostPort("localhost:80"))
-
- executor ! TaskRegistered(TaskId(0, 0), 0, 0)
-
- task.expectMsgType[TaskRegistered]
-
- executor ! TaskRegistered(TaskId(0, 1), 0, 0)
-
- task.expectMsgType[TaskRegistered]
-
- executor ! TaskLocationsReady(TaskLocations(Map.empty), dagVersion = 0)
- executor ! StartAllTasks(dagVersion = 0)
-
- task.expectMsgType[StartTask]
- task.expectMsgType[StartTask]
-
- val changeTasks = ChangeTasks(taskIds, dagVersion = 1, life = LifeTime(0, Long.MaxValue),
- List.empty[Subscriber])
-
- client.send(executor, changeTasks)
- client.expectMsgType[TasksChanged]
-
- executor ! TaskLocationsReady(TaskLocations(Map.empty), 1)
- executor ! StartAllTasks(dagVersion = 1)
-
- task.expectMsgType[ChangeTask]
- task.expectMsgType[ChangeTask]
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/io/gearpump/streaming/executor/TaskArgumentStoreSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/io/gearpump/streaming/executor/TaskArgumentStoreSpec.scala b/streaming/src/test/scala/io/gearpump/streaming/executor/TaskArgumentStoreSpec.scala
deleted file mode 100644
index c97ae4c..0000000
--- a/streaming/src/test/scala/io/gearpump/streaming/executor/TaskArgumentStoreSpec.scala
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.executor
-
-import org.scalatest._
-
-import io.gearpump.streaming.executor.Executor.TaskArgumentStore
-import io.gearpump.streaming.executor.TaskLauncher.TaskArgument
-import io.gearpump.streaming.task.TaskId
-
-class TaskArgumentStoreSpec extends FlatSpec with Matchers with BeforeAndAfterEach {
- it should "retain all history of taskArgument" in {
- val version0 = TaskArgument(0, null, null)
- val version2 = version0.copy(dagVersion = 2)
- val store = new TaskArgumentStore
- val task = TaskId(0, 0)
- store.add(task, version0)
- store.add(task, version2)
-
- // Should return a version which is same or older than expected version
- assert(store.get(dagVersion = 1, task) == Some(version0))
- assert(store.get(dagVersion = 0, task) == Some(version0))
- assert(store.get(dagVersion = 2, task) == Some(version2))
-
- store.removeObsoleteVersion()
- assert(store.get(dagVersion = 1, task) == None)
- assert(store.get(dagVersion = 0, task) == None)
- assert(store.get(dagVersion = 2, task) == Some(version2))
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/io/gearpump/streaming/executor/TaskLauncherSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/io/gearpump/streaming/executor/TaskLauncherSpec.scala b/streaming/src/test/scala/io/gearpump/streaming/executor/TaskLauncherSpec.scala
deleted file mode 100644
index c135c5b..0000000
--- a/streaming/src/test/scala/io/gearpump/streaming/executor/TaskLauncherSpec.scala
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.executor
-
-import scala.concurrent.Await
-import scala.concurrent.duration.Duration
-
-import akka.actor.{Actor, ActorSystem}
-import akka.testkit.TestProbe
-import org.scalatest._
-
-import io.gearpump.cluster.{TestUtil, UserConfig}
-import io.gearpump.serializer.SerializationFramework
-import io.gearpump.streaming.ProcessorDescription
-import io.gearpump.streaming.executor.TaskLauncher.TaskArgument
-import io.gearpump.streaming.executor.TaskLauncherSpec.{MockTask, MockTaskActor}
-import io.gearpump.streaming.task.{Task, TaskContext, TaskContextData, TaskId, TaskWrapper}
-
-class TaskLauncherSpec extends FlatSpec with Matchers with BeforeAndAfterAll {
- val appId = 0
- val executorId = 0
- var appMaster: TestProbe = null
- implicit var system: ActorSystem = null
- val userConf = UserConfig.empty
-
- override def beforeAll(): Unit = {
- system = ActorSystem("TaskLauncherSpec", TestUtil.DEFAULT_CONFIG)
- appMaster = TestProbe()
- }
-
- override def afterAll(): Unit = {
- system.terminate()
- Await.result(system.whenTerminated, Duration.Inf)
- }
-
- it should "able to launch tasks" in {
- val launcher = new TaskLauncher(appId, "app", executorId, appMaster.ref,
- userConf, classOf[MockTaskActor])
- val taskIds = List(TaskId(0, 0), TaskId(0, 1))
- val processor = ProcessorDescription(id = 0, taskClass = classOf[MockTask].getName,
- parallelism = 2)
- val argument = TaskArgument(0, processor, null)
-
- val tasks = launcher.launch(taskIds, argument, system, null,
- "gearpump.shared-thread-pool-dispatcher")
- tasks.keys.toSet shouldBe taskIds.toSet
- }
-}
-
-object TaskLauncherSpec {
- class MockTaskActor(
- val taskId: TaskId,
- val taskContextData : TaskContextData,
- userConf : UserConfig,
- val task: TaskWrapper,
- serializer: SerializationFramework) extends Actor {
- def receive: Receive = null
- }
-
- class MockTask(taskContext: TaskContext, userConf: UserConfig)
- extends Task(taskContext, userConf) {
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/io/gearpump/streaming/metrics/ProcessorAggregatorSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/io/gearpump/streaming/metrics/ProcessorAggregatorSpec.scala b/streaming/src/test/scala/io/gearpump/streaming/metrics/ProcessorAggregatorSpec.scala
deleted file mode 100644
index da1ca9f..0000000
--- a/streaming/src/test/scala/io/gearpump/streaming/metrics/ProcessorAggregatorSpec.scala
+++ /dev/null
@@ -1,261 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.metrics
-
-import scala.collection.JavaConverters._
-import scala.util.Random
-
-import org.scalatest.{FlatSpec, Matchers}
-
-import io.gearpump.cluster.ClientToMaster.ReadOption
-import io.gearpump.cluster.MasterToClient.HistoryMetricsItem
-import io.gearpump.metrics.Metrics.{Gauge, Histogram, Meter}
-import io.gearpump.streaming.metrics.ProcessorAggregator.{AggregatorFactory, HistogramAggregator, MeterAggregator, MultiLayerMap}
-import io.gearpump.streaming.task.TaskId
-import io.gearpump.util.HistoryMetricsService.HistoryMetricsConfig
-
-class ProcessorAggregatorSpec extends FlatSpec with Matchers {
-
- "MultiLayerMap" should "maintain multiple layers HashMap" in {
- val layers = 3
- val map = new MultiLayerMap[String](layers)
-
- assert(map.get(layer = 0, "key") == null)
-
- // Illegal, handle safely
- assert(map.get(layer = 10, "key") == null)
-
- map.put(layer = 0, "key", "value")
- assert(map.get(layer = 0, "key") == "value")
-
- map.put(layer = 1, "key2", "value2")
- map.put(layer = 2, "key3", "value3")
- map.put(layer = 2, "key4", "value4")
-
- // Illegal, should be ignored
- map.put(layer = 4, "key5", "value5")
-
- assert(map.size == 4)
- assert(map.valueIterator.asScala.toSet == Set("value", "value2", "value3", "value4"))
- }
-
- "HistogramAggregator" should "aggregate by calculating average" in {
- val aggregator = new HistogramAggregator("processor")
-
- val a = Histogram("processor.task1", 1, 2, 3, 4, 5, 6)
- val b = Histogram("processor.task2", 5, 6, 7, 8, 9, 10)
- val expect = Histogram("processor.task2", 3, 4, 5, 6, 7, 8)
-
- val olderTime = 100
- val newerTime = 200
-
- aggregator.aggregate(HistoryMetricsItem(time = newerTime, a))
- aggregator.aggregate(HistoryMetricsItem(time = olderTime, b))
-
- val result = aggregator.result
-
- // Picks old time as aggregated time
- assert(result.time == olderTime)
-
- // Does average
- val check = result.value.asInstanceOf[Histogram]
-
- assert(check.mean - expect.mean < 0.01)
- assert(check.stddev - expect.stddev < 0.01)
- assert(check.median - expect.median < 0.01)
- assert(check.p95 - expect.p95 < 0.01)
- assert(check.p99 - expect.p99 < 0.01)
- assert(check.p999 - expect.p999 < 0.01)
- }
-
- "MeterAggregator" should "aggregate by summing" in {
- val aggregator = new MeterAggregator("processor")
-
- val a = Meter("processor.task1", count = 1, 1, 3, "s")
- val b = Meter("processor.task2", count = 2, 5, 7, "s")
- val expect = Meter("processor.task2", count = 3, 6, 10, "s")
-
- val olderTime = 100
- val newerTime = 200
-
- aggregator.aggregate(HistoryMetricsItem(time = newerTime, a))
- aggregator.aggregate(HistoryMetricsItem(time = olderTime, b))
-
- val result = aggregator.result
-
- // Picks old time
- assert(result.time == olderTime)
-
- // Does summing
- val check = result.value.asInstanceOf[Meter]
-
- assert(check.count == expect.count)
- assert(check.m1 - expect.m1 < 0.01)
- assert(check.meanRate - expect.meanRate < 0.01)
- assert(check.rateUnit == expect.rateUnit)
- }
-
- "AggregatorFactory" should "create aggregator" in {
- val factory = new AggregatorFactory()
-
- val a = Meter("processor.task1", count = 1, 1, 3, "s")
- val b = Histogram("processor.task1", 1, 2, 3, 4, 5, 6)
-
- val aggegator1 = factory.create(HistoryMetricsItem(time = 0, a), "name1")
- assert(aggegator1.isInstanceOf[MeterAggregator])
-
- val aggegator2 = factory.create(HistoryMetricsItem(time = 0, b), "name2")
- assert(aggegator2.isInstanceOf[HistogramAggregator])
- }
-
- "ProcessorAggregator" should "aggregate on different read options" in {
- val hours = 2 // Maintains 2 hours history
- val seconds = 2 // Maintains 2 seconds recent data
- val taskCount = 5 // For each processor
- val metricCount = 100 // For each task, have metricCount metrics
- val range = new HistoryMetricsConfig(hours, hours / 2 * 3600 * 1000,
- seconds, seconds / 2 * 1000)
-
- val aggregator = new ProcessorAggregator(range)
-
- def count(value: Int): Int = value
-
- def inputs(timeRange: Long): List[HistoryMetricsItem] = {
- (0 until taskCount).map(TaskId(processorId = 0, _))
- .flatMap(histogram(_, "receiveLatency", timeRange, metricCount)).toList ++
- (0 until taskCount).map(TaskId(processorId = 0, _))
- .flatMap(histogram(_, "processTime", timeRange, metricCount)).toList ++
- (0 until taskCount).map(TaskId(processorId = 1, _))
- .flatMap(histogram(_, "receiveLatency", timeRange, metricCount)).toList ++
- (0 until taskCount).map(TaskId(processorId = 1, _))
- .flatMap(histogram(_, "processTime", timeRange, metricCount)).toList ++
- (0 until taskCount).map(TaskId(processorId = 0, _))
- .flatMap(meter(_, "sendThroughput", timeRange, metricCount)).toList ++
- (0 until taskCount).map(TaskId(processorId = 0, _))
- .flatMap(meter(_, "receiveThroughput", timeRange, metricCount)).toList ++
- (0 until taskCount).map(TaskId(processorId = 1, _))
- .flatMap(meter(_, "sendThroughput", timeRange, metricCount)).toList ++
- (0 until taskCount).map(TaskId(processorId = 1, _))
- .flatMap(meter(_, "receiveThroughput", timeRange, metricCount)).toList
- }
-
- def check(list: List[HistoryMetricsItem], countMap: Map[String, Int]): Boolean = {
- val nameCount = list.map(_.value.name).groupBy(key => key).mapValues(_.size).toList.toMap
- nameCount sameElements countMap
- }
-
- // Aggregates on processor and meterNames,
- val input = inputs(Long.MaxValue)
- val readLatest = aggregator.aggregate(ReadOption.ReadLatest,
- input.iterator, now = Long.MaxValue)
- assert(readLatest.size == 8) // 2 processor * 4 metrics type
- assert(check(readLatest, Map(
- "app0.processor0:receiveLatency" -> count(1),
- "app0.processor0:processTime" -> count(1),
- "app0.processor0:sendThroughput" -> count(1),
- "app0.processor0:receiveThroughput" -> count(1),
- "app0.processor1:receiveLatency" -> count(1),
- "app0.processor1:processTime" -> count(1),
- "app0.processor1:sendThroughput" -> count(1),
- "app0.processor1:receiveThroughput" -> count(1)
- )))
-
- // Aggregates on processor and meterNames and time range,
- val readRecent = aggregator.aggregate(ReadOption.ReadRecent,
- inputs(seconds * 1000).iterator, now = seconds * 1000)
- assert(readRecent.size == 16) // 2 processor * 4 metrics type * 2 time range
- assert(check(readRecent, Map(
- "app0.processor0:receiveLatency" -> count(2),
- "app0.processor0:processTime" -> count(2),
- "app0.processor0:sendThroughput" -> count(2),
- "app0.processor0:receiveThroughput" -> count(2),
- "app0.processor1:receiveLatency" -> count(2),
- "app0.processor1:processTime" -> count(2),
- "app0.processor1:sendThroughput" -> count(2),
- "app0.processor1:receiveThroughput" -> count(2)
- )))
-
- // Aggregates on processor and meterNames and time range,
- val readHistory = aggregator.aggregate(ReadOption.ReadHistory,
- inputs(hours * 3600 * 1000).iterator, now = hours * 3600 * 1000)
- assert(readHistory.size == 16) // 2 processor * 4 metrics type * 2 time ranges
- assert(check(readHistory, Map(
- "app0.processor0:receiveLatency" -> count(2),
- "app0.processor0:processTime" -> count(2),
- "app0.processor0:sendThroughput" -> count(2),
- "app0.processor0:receiveThroughput" -> count(2),
- "app0.processor1:receiveLatency" -> count(2),
- "app0.processor1:processTime" -> count(2),
- "app0.processor1:sendThroughput" -> count(2),
- "app0.processor1:receiveThroughput" -> count(2)
- )))
- }
-
- private def histogram(
- taskId: TaskId, metricName: String = "latency", timeRange: Long = Long.MaxValue,
- repeat: Int = 1): List[HistoryMetricsItem] = {
- val random = new Random()
- (0 until repeat).map { _ =>
- new HistoryMetricsItem(Math.abs(random.nextLong() % timeRange),
- new Histogram(s"app0.processor${taskId.processorId}.task${taskId.index}:$metricName",
- Math.abs(random.nextDouble()),
- Math.abs(random.nextDouble()),
- Math.abs(random.nextDouble()),
- Math.abs(random.nextDouble()),
- Math.abs(random.nextDouble()),
- Math.abs(random.nextDouble())
- ))
- }.toList
- }
-
- private def meter(taskId: TaskId, metricName: String, timeRange: Long, repeat: Int)
- : List[HistoryMetricsItem] = {
- val random = new Random()
- (0 until repeat).map { _ =>
- new HistoryMetricsItem(Math.abs(random.nextLong() % timeRange),
- new Meter(s"app0.processor${taskId.processorId}.task${taskId.index}:$metricName",
- Math.abs(random.nextInt()),
- Math.abs(random.nextDouble()),
- Math.abs(random.nextDouble()),
- "event/s")
- )
- }.toList
- }
-
- "ProcessorAggregator" should "handle smoothly for unsupported metric type and " +
- "error formatted metric name" in {
- val invalid = List(
- // Unsupported metric type
- HistoryMetricsItem(0, new Gauge("app0.processor0.task0:gauge", 100)),
-
- // Wrong format: should be app0.processor0.task0:throughput
- HistoryMetricsItem(0, new Meter("app0.processor0.task0/throughput", 100, 0, 0, ""))
- )
-
- val valid = histogram(TaskId(0, 0), repeat = 10)
-
- val aggregator = new ProcessorAggregator(new HistoryMetricsConfig(0, 0, 0, 0))
- val result = aggregator.aggregate(ReadOption.ReadLatest, (valid ++ invalid).toIterator,
- now = Long.MaxValue)
-
- // For one taskId, will only use one data point.
- assert(result.size == 1)
- assert(result.head.value.name == "app0.processor0:latency")
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/io/gearpump/streaming/metrics/TaskFilterAggregatorSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/io/gearpump/streaming/metrics/TaskFilterAggregatorSpec.scala b/streaming/src/test/scala/io/gearpump/streaming/metrics/TaskFilterAggregatorSpec.scala
deleted file mode 100644
index f654eb9..0000000
--- a/streaming/src/test/scala/io/gearpump/streaming/metrics/TaskFilterAggregatorSpec.scala
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.metrics
-
-import scala.util.Random
-
-import org.scalatest.{FlatSpec, Matchers}
-
-import io.gearpump.cluster.MasterToClient.HistoryMetricsItem
-import io.gearpump.metrics.Metrics.{Histogram, Meter}
-import io.gearpump.streaming.metrics.TaskFilterAggregator.Options
-import io.gearpump.streaming.task.TaskId
-
-class TaskFilterAggregatorSpec extends FlatSpec with Matchers {
-
- def metric(taskId: TaskId): HistoryMetricsItem = {
- val random = new Random()
- new HistoryMetricsItem(Math.abs(random.nextLong()),
- new Histogram(s"app0.processor${taskId.processorId}.task${taskId.index}:latency",
- 0, 0, 0, 0, 0, 0))
- }
-
- it should "filter data on processor range, task range combination" in {
- val inputs = (0 until 10).flatMap { processor =>
- (0 until 10).map { task =>
- metric(TaskId(processor, task))
- }
- }.toList
-
- val globalLimit = 10
- val aggregator = new TaskFilterAggregator(globalLimit)
-
- // Limit not met, return all matches in this matrix
- var options = new Options(limit = 20, startTask = 3, endTask = 6,
- startProcessor = 3, endProcessor = 6)
- assert(aggregator.aggregate(options, inputs.iterator).size == 9)
-
- // User limit reached
- options = new Options(limit = 3, startTask = 3, endTask = 5,
- startProcessor = 3, endProcessor = 5)
- assert(aggregator.aggregate(options, inputs.iterator).size == 3)
-
- // Global limit reached
- options = new Options(limit = 20, startTask = 3, endTask = 8,
- startProcessor = 3, endProcessor = 8)
- assert(aggregator.aggregate(options, inputs.iterator).size == globalLimit)
- }
-
- it should "reject wrong format options" in {
- val options = Map(TaskFilterAggregator.StartTask -> "not a number")
- assert(Options.parse(options) == null)
- }
-
- it should "skip wrong format metrics" in {
- val invalid = List {
- // Wrong format: should be app0.processor0.task0:throughput
- HistoryMetricsItem(0, new Meter("app0.processor0.task0/throughput", 100, 0, 0, ""))
- }
- val options = Options.acceptAll
-
- val aggregator = new TaskFilterAggregator(Int.MaxValue)
- assert(aggregator.aggregate(options, invalid.iterator).size == 0)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/io/gearpump/streaming/source/DefaultTimeStampFilterSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/io/gearpump/streaming/source/DefaultTimeStampFilterSpec.scala b/streaming/src/test/scala/io/gearpump/streaming/source/DefaultTimeStampFilterSpec.scala
deleted file mode 100644
index 752a8f4..0000000
--- a/streaming/src/test/scala/io/gearpump/streaming/source/DefaultTimeStampFilterSpec.scala
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.source
-
-import org.scalacheck.Gen
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{Matchers, PropSpec}
-
-import io.gearpump.{Message, TimeStamp}
-
-class DefaultTimeStampFilterSpec extends PropSpec with PropertyChecks with Matchers {
- property("DefaultTimeStampFilter should filter message against give timestamp") {
- val timestampGen = Gen.chooseNum[Long](0L, 1000L)
- val messageGen = for {
- msg <- Gen.alphaStr
- time <- timestampGen
- } yield Message(msg, time)
-
- val filter = new DefaultTimeStampFilter()
-
- forAll(timestampGen, messageGen) {
- (predicate: TimeStamp, message: Message) =>
- if (message.timestamp >= predicate) {
- filter.filter(message, predicate) shouldBe Some(message)
- } else {
- filter.filter(message, predicate) shouldBe None
- }
-
- filter.filter(null, predicate) shouldBe None
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/io/gearpump/streaming/state/impl/CheckpointManagerSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/io/gearpump/streaming/state/impl/CheckpointManagerSpec.scala b/streaming/src/test/scala/io/gearpump/streaming/state/impl/CheckpointManagerSpec.scala
deleted file mode 100644
index ea670f6..0000000
--- a/streaming/src/test/scala/io/gearpump/streaming/state/impl/CheckpointManagerSpec.scala
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.state.impl
-
-import org.mockito.Mockito._
-import org.mockito.{Matchers => MockitoMatchers}
-import org.scalacheck.Gen
-import org.scalatest.mock.MockitoSugar
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{Matchers, PropSpec}
-
-import io.gearpump.TimeStamp
-import io.gearpump.streaming.transaction.api.CheckpointStore
-
-class CheckpointManagerSpec extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
-
- val timestampGen = Gen.chooseNum[Long](0L, 1000L)
- val checkpointIntervalGen = Gen.chooseNum[Long](100L, 10000L)
- property("CheckpointManager should recover from CheckpointStore") {
- forAll(timestampGen, checkpointIntervalGen) {
- (timestamp: TimeStamp, checkpointInterval: Long) =>
- val checkpointStore = mock[CheckpointStore]
- val checkpointManager =
- new CheckpointManager(checkpointInterval, checkpointStore)
- checkpointManager.recover(timestamp)
-
- verify(checkpointStore).recover(timestamp)
- }
- }
-
- property("CheckpointManager should write checkpoint to CheckpointStore") {
- val checkpointGen = Gen.alphaStr.map(_.getBytes("UTF-8"))
- forAll(timestampGen, checkpointIntervalGen, checkpointGen) {
- (timestamp: TimeStamp, checkpointInterval: Long, checkpoint: Array[Byte]) =>
- val checkpointStore = mock[CheckpointStore]
- val checkpointManager =
- new CheckpointManager(checkpointInterval, checkpointStore)
- checkpointManager.checkpoint(timestamp, checkpoint)
-
- verify(checkpointStore).persist(timestamp, checkpoint)
- }
- }
-
- property("CheckpointManager should close CheckpointStore") {
- forAll(checkpointIntervalGen) {
- (checkpointInterval: Long) =>
- val checkpointStore = mock[CheckpointStore]
- val checkpointManager =
- new CheckpointManager(checkpointInterval, checkpointStore)
- checkpointManager.close()
- verify(checkpointStore).close()
- }
- }
-
- property("CheckpointManager should update checkpoint time according to max message timestamp") {
- forAll(timestampGen, checkpointIntervalGen) {
- (timestamp: TimeStamp, checkpointInterval: Long) =>
- val checkpointStore = mock[CheckpointStore]
- val checkpointManager =
- new CheckpointManager(checkpointInterval, checkpointStore)
- checkpointManager.update(timestamp)
- checkpointManager.getMaxMessageTime shouldBe timestamp
-
- val checkpointTime = checkpointManager.getCheckpointTime.get
- timestamp should (be < checkpointTime and be >= (checkpointTime - checkpointInterval))
-
- checkpointManager.checkpoint(checkpointTime, Array.empty[Byte])
- verify(checkpointStore).persist(MockitoMatchers.eq(checkpointTime),
- MockitoMatchers.anyObject[Array[Byte]]())
- checkpointManager.getCheckpointTime shouldBe empty
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/io/gearpump/streaming/state/impl/InMemoryCheckpointStoreSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/io/gearpump/streaming/state/impl/InMemoryCheckpointStoreSpec.scala b/streaming/src/test/scala/io/gearpump/streaming/state/impl/InMemoryCheckpointStoreSpec.scala
deleted file mode 100644
index 4bbad3b..0000000
--- a/streaming/src/test/scala/io/gearpump/streaming/state/impl/InMemoryCheckpointStoreSpec.scala
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.state.impl
-
-import org.scalacheck.Gen
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{Matchers, PropSpec}
-
-class InMemoryCheckpointStoreSpec extends PropSpec with PropertyChecks with Matchers {
-
- property("InMemoryCheckpointStore should provide read / write checkpoint") {
- val timestampGen = Gen.chooseNum[Long](1, 1000)
- val checkpointGen = Gen.alphaStr.map(_.getBytes("UTF-8"))
- forAll(timestampGen, checkpointGen) { (timestamp: Long, checkpoint: Array[Byte]) =>
- val store = new InMemoryCheckpointStore
- store.recover(timestamp) shouldBe None
- store.persist(timestamp, checkpoint)
- store.recover(timestamp) shouldBe Some(checkpoint)
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/io/gearpump/streaming/state/impl/NonWindowStateSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/io/gearpump/streaming/state/impl/NonWindowStateSpec.scala b/streaming/src/test/scala/io/gearpump/streaming/state/impl/NonWindowStateSpec.scala
deleted file mode 100644
index b20b666..0000000
--- a/streaming/src/test/scala/io/gearpump/streaming/state/impl/NonWindowStateSpec.scala
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.state.impl
-
-import scala.util.Success
-
-import org.mockito.Mockito._
-import org.scalacheck.Gen
-import org.scalatest.mock.MockitoSugar
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{Matchers, PropSpec}
-
-import io.gearpump.TimeStamp
-import io.gearpump.streaming.state.api.{Monoid, Serializer}
-
-class NonWindowStateSpec extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
-
- val longGen = Gen.chooseNum[Long](100L, System.currentTimeMillis())
-
- property("NonWindowState should recover checkpointed state at given timestamp") {
- forAll(longGen) {
- (timestamp: TimeStamp) =>
- val monoid = mock[Monoid[AnyRef]]
- val serializer = mock[Serializer[AnyRef]]
- val bytes = Array.empty[Byte]
- val checkpoint = mock[AnyRef]
- val zero = mock[AnyRef]
- when(monoid.zero).thenReturn(zero, zero)
- when(monoid.plus(zero, zero)).thenReturn(zero, Nil: _*)
- when(monoid.plus(checkpoint, zero)).thenReturn(checkpoint, Nil: _*)
-
- val state = new NonWindowState[AnyRef](monoid, serializer)
- state.left shouldBe zero
- state.right shouldBe zero
- state.get shouldBe Some(zero)
-
- when(serializer.deserialize(bytes)).thenReturn(Success(checkpoint))
- state.recover(timestamp, bytes)
-
- state.left shouldBe checkpoint
- state.right shouldBe zero
- state.get shouldBe Some(checkpoint)
- }
- }
-
- property("NonWindowState checkpoints state") {
- forAll(longGen) {
- (checkpointTime: TimeStamp) =>
- val monoid = mock[Monoid[AnyRef]]
- val serializer = mock[Serializer[AnyRef]]
-
- val left = mock[AnyRef]
- val right = mock[AnyRef]
- val zero = mock[AnyRef]
- val plus = mock[AnyRef]
-
- when(monoid.zero).thenReturn(zero, zero)
- when(monoid.plus(zero, zero)).thenReturn(zero, Nil: _*)
-
- val state = new NonWindowState[AnyRef](monoid, serializer)
- state.left shouldBe zero
- state.right shouldBe zero
- state.get shouldBe Some(zero)
-
- state.left = left
- state.right = right
-
- when(monoid.zero).thenReturn(zero, Nil: _*)
- when(monoid.plus(left, right)).thenReturn(plus, Nil: _*)
- when(monoid.plus(plus, zero)).thenReturn(plus, Nil: _*)
- state.checkpoint()
-
- verify(serializer).serialize(left)
- state.left shouldBe plus
- state.right shouldBe zero
- state.get shouldBe Some(plus)
- }
- }
-
- property("NonWindowState updates state") {
- forAll(longGen) {
- (checkpointTime: TimeStamp) =>
- val monoid = mock[Monoid[AnyRef]]
- val serializer = mock[Serializer[AnyRef]]
-
- val left = mock[AnyRef]
- val right = mock[AnyRef]
- val zero = mock[AnyRef]
- val plus = mock[AnyRef]
-
- when(monoid.zero).thenReturn(zero, zero)
- when(monoid.plus(zero, zero)).thenReturn(zero, Nil: _*)
-
- val state = new NonWindowState[AnyRef](monoid, serializer)
- state.left shouldBe zero
- state.right shouldBe zero
- state.get shouldBe Some(zero)
-
- when(monoid.plus(zero, left)).thenReturn(left, Nil: _*)
- when(monoid.plus(left, zero)).thenReturn(left, Nil: _*)
- state.setNextCheckpointTime(checkpointTime)
- state.update(checkpointTime - 1, left)
- state.left shouldBe left
- state.right shouldBe zero
- state.get shouldBe Some(left)
-
- when(monoid.plus(zero, right)).thenReturn(right, Nil: _*)
- when(monoid.plus(left, right)).thenReturn(plus, Nil: _*)
- state.setNextCheckpointTime(checkpointTime)
- state.update(checkpointTime + 1, right)
- state.left shouldBe left
- state.right shouldBe right
- state.get shouldBe Some(plus)
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/io/gearpump/streaming/state/impl/WindowSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/io/gearpump/streaming/state/impl/WindowSpec.scala b/streaming/src/test/scala/io/gearpump/streaming/state/impl/WindowSpec.scala
deleted file mode 100644
index e12ec9b..0000000
--- a/streaming/src/test/scala/io/gearpump/streaming/state/impl/WindowSpec.scala
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.state.impl
-
-import org.scalacheck.Gen
-import org.scalatest.mock.MockitoSugar
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{Matchers, PropSpec}
-
-import io.gearpump.TimeStamp
-
-class WindowSpec extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
-
- val windowSizeGen = Gen.chooseNum[Long](1L, 1000L)
- val windowStepGen = Gen.chooseNum[Long](1L, 1000L)
- val timestampGen = Gen.chooseNum[Long](0L, 1000L)
- property("Window should only slide when time passes window end") {
- forAll(timestampGen, windowSizeGen, windowStepGen) {
- (timestamp: TimeStamp, windowSize: Long, windowStep: Long) =>
- val window = new Window(windowSize, windowStep)
- window.shouldSlide shouldBe false
- window.update(timestamp)
- window.shouldSlide shouldBe timestamp >= windowSize
- }
- }
-
- property("Window should slide by one or to given timestamp") {
- forAll(timestampGen, windowSizeGen, windowStepGen) {
- (timestamp: TimeStamp, windowSize: Long, windowStep: Long) =>
- val window = new Window(windowSize, windowStep)
- window.range shouldBe(0L, windowSize)
-
- window.slideOneStep()
- window.range shouldBe(windowStep, windowSize + windowStep)
-
- window.slideTo(timestamp)
- val (startTime, endTime) = window.range
- if (windowStep > windowSize) {
- timestamp should (be >= startTime and be < (startTime + windowStep))
- } else {
- timestamp should (be >= startTime and be < endTime)
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/io/gearpump/streaming/state/impl/WindowStateSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/io/gearpump/streaming/state/impl/WindowStateSpec.scala b/streaming/src/test/scala/io/gearpump/streaming/state/impl/WindowStateSpec.scala
deleted file mode 100644
index bc79ff6..0000000
--- a/streaming/src/test/scala/io/gearpump/streaming/state/impl/WindowStateSpec.scala
+++ /dev/null
@@ -1,239 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.state.impl
-
-import scala.collection.immutable.TreeMap
-import scala.util.Success
-
-import org.mockito.Mockito._
-import org.scalacheck.Gen
-import org.scalatest.mock.MockitoSugar
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{Matchers, PropSpec}
-
-import io.gearpump._
-import io.gearpump.streaming.MockUtil
-import io.gearpump.streaming.state.api.{Group, Serializer}
-
-class WindowStateSpec extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
-
- val longGen = Gen.chooseNum[Long](100L, 10000L)
-
- val intervalGen = for {
- st <- longGen
- et <- Gen.chooseNum[Long](st + 1, 100000L)
- } yield Interval(st, et)
-
- property("WindowState init should recover checkpointed state") {
- forAll(intervalGen) {
- (interval: Interval) =>
- val window = mock[Window]
- val taskContext = MockUtil.mockTaskContext
- val group = mock[Group[AnyRef]]
- val serializer = mock[Serializer[TreeMap[Interval, AnyRef]]]
-
- val timestamp = interval.startTime
- val zero = mock[AnyRef]
- val bytes = Array.empty[Byte]
- val data = mock[AnyRef]
- val checkpoint = TreeMap(interval -> data)
- when(group.zero).thenReturn(zero, zero)
- when(group.plus(zero, data)).thenReturn(data, Nil: _*)
- when(group.plus(data, zero)).thenReturn(data, Nil: _*)
- when(group.plus(zero, zero)).thenReturn(zero, Nil: _*)
- when(serializer.deserialize(bytes)).thenReturn(Success(checkpoint))
-
- val state = new WindowState[AnyRef](group, serializer, taskContext, window)
- state.left shouldBe zero
- state.right shouldBe zero
- state.get shouldBe Some(zero)
-
- state.recover(timestamp, bytes)
-
- state.left shouldBe data
- state.right shouldBe zero
- state.get shouldBe Some(data)
- state.getIntervalStates(interval.startTime, interval.endTime) shouldBe checkpoint
- }
- }
-
- property("WindowState checkpoints") {
- forAll(longGen) { (checkpointTime: TimeStamp) =>
- val window = mock[Window]
- val taskContext = MockUtil.mockTaskContext
- val group = mock[Group[AnyRef]]
- val serializer = mock[Serializer[TreeMap[Interval, AnyRef]]]
-
- val zero = mock[AnyRef]
- val left = mock[AnyRef]
- val right = mock[AnyRef]
- val plus = mock[AnyRef]
-
- when(group.zero).thenReturn(zero, zero)
- when(group.plus(zero, zero)).thenReturn(zero, Nil: _*)
- val state = new WindowState[AnyRef](group, serializer, taskContext, window)
- state.left shouldBe zero
- state.right shouldBe zero
- state.get shouldBe Some(zero)
-
- val start = checkpointTime - 1
- val end = checkpointTime + 1
- val size = end - start
- val step = 1L
-
- when(window.range).thenReturn((start, end))
- when(window.windowSize).thenReturn(size)
- when(window.windowStep).thenReturn(step)
- when(group.zero).thenReturn(zero, zero)
- when(group.plus(zero, left)).thenReturn(left, Nil: _*)
- when(group.plus(zero, right)).thenReturn(right, Nil: _*)
- when(group.plus(left, right)).thenReturn(plus, Nil: _*)
-
- state.left = left
- state.updateIntervalStates(start, left, checkpointTime)
- state.right = right
- state.updateIntervalStates(checkpointTime, right, checkpointTime)
-
- state.setNextCheckpointTime(checkpointTime)
- state.checkpoint()
-
- state.left shouldBe plus
- state.right shouldBe zero
- verify(serializer).serialize(TreeMap(Interval(start, checkpointTime) -> left))
- }
- }
-
- property("WindowState updates state") {
- forAll(longGen) { (checkpointTime: TimeStamp) =>
- val window = mock[Window]
- val taskContext = MockUtil.mockTaskContext
- val group = mock[Group[AnyRef]]
- val serializer = mock[Serializer[TreeMap[Interval, AnyRef]]]
-
- val zero = mock[AnyRef]
- val left = mock[AnyRef]
- val right = mock[AnyRef]
- val plus = mock[AnyRef]
-
- when(group.zero).thenReturn(zero, zero)
- val state = new WindowState[AnyRef](group, serializer, taskContext, window)
-
- val start = checkpointTime - 1
- val end = checkpointTime + 1
- val size = end - start
- val step = 1L
-
- when(window.range).thenReturn((start, end))
- when(window.windowSize).thenReturn(size)
- when(window.windowStep).thenReturn(step)
- when(window.shouldSlide).thenReturn(false)
- when(group.plus(zero, left)).thenReturn(left, left)
- when(group.plus(left, zero)).thenReturn(left, Nil: _*)
- when(taskContext.upstreamMinClock).thenReturn(0L)
-
- // Time < checkpointTime
- // Update left in current window
- state.setNextCheckpointTime(checkpointTime)
- state.update(start, left)
-
- verify(window).update(0L)
- state.left shouldBe left
- state.right shouldBe zero
- state.get shouldBe Some(left)
- state.getIntervalStates(start, end) shouldBe TreeMap(Interval(start, checkpointTime) -> left)
-
- when(window.range).thenReturn((start, end))
- when(window.windowSize).thenReturn(size)
- when(window.windowStep).thenReturn(step)
- when(window.shouldSlide).thenReturn(false)
- when(group.plus(zero, right)).thenReturn(right, right)
- when(group.plus(left, right)).thenReturn(plus, Nil: _*)
- when(taskContext.upstreamMinClock).thenReturn(0L)
-
- // Time >= checkpointTime
- // Update right in current window
- state.setNextCheckpointTime(checkpointTime)
- state.update(checkpointTime, right)
-
- verify(window, times(2)).update(0L)
- state.left shouldBe left
- state.right shouldBe right
- state.get shouldBe Some(plus)
- state.getIntervalStates(start, end) shouldBe
- TreeMap(Interval(start, start + step) -> left, Interval(start + step, end) -> right)
-
- // Slides window forward
- when(window.range).thenReturn((start, end), (start + step, end + step))
- when(window.shouldSlide).thenReturn(true)
- when(taskContext.upstreamMinClock).thenReturn(checkpointTime)
- when(group.minus(left, left)).thenReturn(zero, Nil: _*)
- when(group.plus(zero, right)).thenReturn(right, Nil: _*)
- when(group.plus(right, right)).thenReturn(plus, Nil: _*)
- when(group.plus(zero, plus)).thenReturn(plus, Nil: _*)
-
- state.setNextCheckpointTime(checkpointTime)
- state.update(end, right)
-
- verify(window).slideOneStep()
- verify(window).update(checkpointTime)
- state.left shouldBe zero
- state.right shouldBe plus
- state.get shouldBe Some(plus)
- state.getIntervalStates(start, end + step) shouldBe
- TreeMap(
- Interval(start, start + step) -> left,
- Interval(start + step, end) -> right,
- Interval(end, end + step) -> right)
- }
- }
-
- property("WindowState gets interval for timestamp") {
- forAll(longGen, longGen, longGen, longGen) {
- (timestamp: TimeStamp, checkpointTime: TimeStamp, windowSize: Long, windowStep: Long) =>
- val windowManager = new Window(windowSize, windowStep)
- val taskContext = MockUtil.mockTaskContext
- val group = mock[Group[AnyRef]]
- val serializer = mock[Serializer[TreeMap[Interval, AnyRef]]]
-
- val zero = mock[AnyRef]
- when(group.zero).thenReturn(zero, zero)
- val state = new WindowState[AnyRef](group, serializer, taskContext, windowManager)
-
- val interval = state.getInterval(timestamp, checkpointTime)
- intervalSpec(interval, timestamp, checkpointTime, windowSize, windowStep)
-
- val nextTimeStamp = interval.endTime
- val nextInterval = state.getInterval(nextTimeStamp, checkpointTime)
- intervalSpec(nextInterval, nextTimeStamp, checkpointTime, windowSize, windowStep)
-
- interval.endTime shouldBe nextInterval.startTime
- }
-
- def intervalSpec(interval: Interval, timestamp: TimeStamp,
- checkpointTime: TimeStamp, windowSize: Long, windowStep: Long): Unit = {
- interval.startTime should be <= interval.endTime
- timestamp / windowStep * windowStep should (be <= interval.startTime)
- (timestamp - windowSize) / windowStep * windowStep should (be <= interval.startTime)
- (timestamp / windowStep + 1) * windowStep should (be >= interval.endTime)
- ((timestamp - windowSize) / windowStep + 1) * windowStep + windowSize should
- (be >= interval.endTime)
- checkpointTime should (be <= interval.startTime or be >= interval.endTime)
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/io/gearpump/streaming/storage/InMemoryAppStoreOnMasterSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/io/gearpump/streaming/storage/InMemoryAppStoreOnMasterSpec.scala b/streaming/src/test/scala/io/gearpump/streaming/storage/InMemoryAppStoreOnMasterSpec.scala
deleted file mode 100644
index 60baa74..0000000
--- a/streaming/src/test/scala/io/gearpump/streaming/storage/InMemoryAppStoreOnMasterSpec.scala
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.storage
-
-import scala.concurrent.Await
-import scala.concurrent.duration._
-
-import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpec}
-
-import io.gearpump.cluster.{MasterHarness, MiniCluster}
-import io.gearpump.streaming.StreamingTestUtil
-import io.gearpump.util.Constants
-
-class InMemoryAppStoreOnMasterSpec extends WordSpec with Matchers with BeforeAndAfterAll {
- implicit val timeout = Constants.FUTURE_TIMEOUT
- implicit val dispatcher = MasterHarness.cachedPool
-
- "InMemoryAppStoreOnMaster" should {
- "save and return the data properly" in {
- val appId = 0
- val miniCluster = new MiniCluster
- val master = miniCluster.mockMaster
- StreamingTestUtil.startAppMaster(miniCluster, appId)
- val store = new InMemoryAppStoreOnMaster(appId, master)
-
- Thread.sleep(500)
-
- store.put("String_type", "this is a string")
- store.put("Int_type", 1024)
- store.put("Tuple2_type", ("element1", 1024))
-
- val future1 = store.get("String_type").map { value =>
- value.asInstanceOf[String] should be("this is a string")
- }
- val future2 = store.get("Int_type").map { value => value.asInstanceOf[Int] should be(1024) }
- val future3 = store.get("Tuple2_type").map { value =>
- value.asInstanceOf[(String, Int)] should be(("element1", 1024))
- }
- val future4 = store.get("key").map { value => value.asInstanceOf[Object] should be(null) }
- Await.result(future1, 15.seconds)
- Await.result(future2, 15.seconds)
- Await.result(future3, 15.seconds)
- Await.result(future4, 15.seconds)
- miniCluster.shutDown
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/io/gearpump/streaming/task/SubscriberSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/io/gearpump/streaming/task/SubscriberSpec.scala b/streaming/src/test/scala/io/gearpump/streaming/task/SubscriberSpec.scala
deleted file mode 100644
index ffb343e..0000000
--- a/streaming/src/test/scala/io/gearpump/streaming/task/SubscriberSpec.scala
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.task
-
-import org.scalatest.{FlatSpec, Matchers}
-
-import io.gearpump.partitioner.{HashPartitioner, Partitioner}
-import io.gearpump.streaming.task.SubscriberSpec.TestTask
-import io.gearpump.streaming.{DAG, ProcessorDescription}
-import io.gearpump.util.Graph
-import io.gearpump.util.Graph._
-
-class SubscriberSpec extends FlatSpec with Matchers {
- "Subscriber.of" should "return all subscriber for a processor" in {
-
- val sourceProcessorId = 0
- val task1 = ProcessorDescription(id = sourceProcessorId, taskClass =
- classOf[TestTask].getName, parallelism = 1)
- val task2 = ProcessorDescription(id = 1, taskClass = classOf[TestTask].getName, parallelism = 1)
- val task3 = ProcessorDescription(id = 2, taskClass = classOf[TestTask].getName, parallelism = 1)
- val partitioner = Partitioner[HashPartitioner]
- val dag = DAG(Graph(task1 ~ partitioner ~> task2, task1 ~ partitioner ~> task3,
- task2 ~ partitioner ~> task3))
-
- val subscribers = Subscriber.of(sourceProcessorId, dag)
- assert(subscribers.size == 2)
-
- assert(subscribers.toSet ==
- Set(Subscriber(1, partitioner, task2.parallelism, task2.life), Subscriber(2, partitioner,
- task3.parallelism, task3.life)))
- }
-}
-
-object SubscriberSpec {
- class TestTask
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/io/gearpump/streaming/task/SubscriptionSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/io/gearpump/streaming/task/SubscriptionSpec.scala b/streaming/src/test/scala/io/gearpump/streaming/task/SubscriptionSpec.scala
deleted file mode 100644
index 57f4b8c..0000000
--- a/streaming/src/test/scala/io/gearpump/streaming/task/SubscriptionSpec.scala
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.task
-
-import java.util.Random
-
-import org.mockito.Mockito._
-import org.scalatest.mock.MockitoSugar
-import org.scalatest.{FlatSpec, Matchers}
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.partitioner.{HashPartitioner, Partitioner}
-import io.gearpump.streaming.task.SubscriptionSpec.NextTask
-import io.gearpump.streaming.{LifeTime, ProcessorDescription}
-
-class SubscriptionSpec extends FlatSpec with Matchers with MockitoSugar {
- val appId = 0
- val executorId = 0
- val taskId = TaskId(0, 0)
- val session = new Random().nextInt()
-
- val downstreamProcessorId = 1
- val partitioner = Partitioner[HashPartitioner]
-
- val parallism = 2
- val downstreamProcessor = ProcessorDescription(downstreamProcessorId, classOf[NextTask].getName,
- parallism)
- val subscriber = Subscriber(downstreamProcessorId, partitioner, downstreamProcessor.parallelism,
- downstreamProcessor.life)
-
- private def prepare: (Subscription, ExpressTransport) = {
- val transport = mock[ExpressTransport]
- val subscription = new Subscription(appId, executorId, taskId, subscriber, session, transport)
- subscription.start()
-
- val expectedAckRequest = InitialAckRequest(taskId, session)
- verify(transport, times(1)).transport(expectedAckRequest, TaskId(1, 0), TaskId(1, 1))
-
- (subscription, transport)
- }
-
- it should "not send any more message when its life ends" in {
- val (subscription, transport) = prepare
- subscription.changeLife(LifeTime(0, 0))
- val count = subscription.sendMessage(Message("some"))
- assert(count == 0)
- }
-
- it should "send message and handle ack correctly" in {
- val (subscription, transport) = prepare
- val msg1 = new Message("1", timestamp = 70)
- subscription.sendMessage(msg1)
-
- verify(transport, times(1)).transport(msg1, TaskId(1, 1))
- assert(subscription.minClock == 70)
-
- val msg2 = new Message("0", timestamp = 50)
- subscription.sendMessage(msg2)
- verify(transport, times(1)).transport(msg2, TaskId(1, 0))
-
- // minClock has been set to smaller one
- assert(subscription.minClock == 50)
-
- val initialMinClock = subscription.minClock
-
- // Acks initial AckRequest(0)
- subscription.receiveAck(Ack(TaskId(1, 1), 0, 0, session))
- subscription.receiveAck(Ack(TaskId(1, 0), 0, 0, session))
-
- // Sends 100 messages
- 100 until 200 foreach { clock =>
- subscription.sendMessage(Message("1", clock))
- subscription.sendMessage(Message("2", clock))
- }
-
- // Ack not received, minClock no change
- assert(subscription.minClock == initialMinClock)
-
- subscription.receiveAck(Ack(TaskId(1, 1), 100, 100, session))
- subscription.receiveAck(Ack(TaskId(1, 0), 100, 100, session))
-
- // Ack received, minClock changed
- assert(subscription.minClock > initialMinClock)
-
- // Expects to receive two ackRequest for two downstream tasks
- val ackRequestForTask0 = AckRequest(taskId, 200, session)
- verify(transport, times(1)).transport(ackRequestForTask0, TaskId(1, 0))
-
- val ackRequestForTask1 = AckRequest(taskId, 200, session)
- verify(transport, times(1)).transport(ackRequestForTask1, TaskId(1, 1))
- }
-
- it should "disallow more message sending if there is no ack back" in {
- val (subscription, transport) = prepare
- // send 100 messages
- 0 until (Subscription.MAX_PENDING_MESSAGE_COUNT * 2 + 1) foreach { clock =>
- subscription.sendMessage(Message(randomMessage, clock))
- }
-
- assert(subscription.allowSendingMoreMessages() == false)
- }
-
- it should "report minClock as Long.MaxValue when there is no pending message" in {
- val (subscription, transport) = prepare
- val msg1 = new Message("1", timestamp = 70)
- subscription.sendMessage(msg1)
- assert(subscription.minClock == 70)
- subscription.receiveAck(Ack(TaskId(1, 1), 1, 1, session))
- assert(subscription.minClock == Long.MaxValue)
- }
-
- private def randomMessage: String = new Random().nextInt.toString
-}
-
-object SubscriptionSpec {
-
- class NextTask(taskContext: TaskContext, conf: UserConfig) extends Task(taskContext, conf) {
-
- override def onStart(startTime: StartTime): Unit = {
- }
-
- override def onNext(msg: Message): Unit = {
- }
- }
-}
\ No newline at end of file
[26/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/scala/io/gearpump/experiments/storm/main/GearpumpNimbus.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/scala/io/gearpump/experiments/storm/main/GearpumpNimbus.scala b/experiments/storm/src/main/scala/io/gearpump/experiments/storm/main/GearpumpNimbus.scala
deleted file mode 100644
index aca2736..0000000
--- a/experiments/storm/src/main/scala/io/gearpump/experiments/storm/main/GearpumpNimbus.scala
+++ /dev/null
@@ -1,289 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.storm.main
-
-import java.io.{File, FileOutputStream, FileWriter}
-import java.nio.ByteBuffer
-import java.nio.channels.{Channels, WritableByteChannel}
-import java.util.{HashMap => JHashMap, Map => JMap, UUID}
-import scala.collection.JavaConverters._
-import scala.concurrent.duration.Duration
-import scala.concurrent.{Await, Future}
-
-import akka.actor.ActorSystem
-import com.typesafe.config.ConfigValueFactory
-import backtype.storm.Config
-import backtype.storm.generated._
-import backtype.storm.security.auth.{ThriftConnectionType, ThriftServer}
-import backtype.storm.utils.Utils
-import org.apache.storm.shade.org.json.simple.JSONValue
-import org.apache.storm.shade.org.yaml.snakeyaml.Yaml
-import org.slf4j.Logger
-
-import io.gearpump.cluster.client.ClientContext
-import io.gearpump.cluster.main.{ArgumentsParser, CLIOption}
-import io.gearpump.cluster.{MasterToAppMaster, UserConfig}
-import io.gearpump.experiments.storm.topology.GearpumpStormTopology
-import io.gearpump.experiments.storm.util.TimeCacheMapWrapper.Callback
-import io.gearpump.experiments.storm.util.{GraphBuilder, StormConstants, StormUtil, TimeCacheMapWrapper}
-import io.gearpump.streaming.StreamApplication
-import io.gearpump.util.{AkkaApp, Constants, LogUtil}
-
-object GearpumpNimbus extends AkkaApp with ArgumentsParser {
- private val THRIFT_PORT = StormUtil.getThriftPort()
- private val OUTPUT = "output"
- private val LOG: Logger = LogUtil.getLogger(classOf[GearpumpNimbus])
-
- override val options: Array[(String, CLIOption[Any])] = Array(
- OUTPUT -> CLIOption[String]("<output path for configuration file>",
- required = false, defaultValue = Some("app.yaml"))
- )
-
- override def main(inputAkkaConf: Config, args: Array[String]): Unit = {
- val parsed = parse(args)
- val output = parsed.getString(OUTPUT)
- val akkaConf = updateClientConfig(inputAkkaConf)
- val system = ActorSystem("storm", akkaConf)
-
- val clientContext = new ClientContext(akkaConf, system, null)
- val stormConf = Utils.readStormConfig().asInstanceOf[JMap[AnyRef, AnyRef]]
- val thriftConf: JMap[AnyRef, AnyRef] = Map(
- Config.NIMBUS_HOST -> akkaConf.getString(Constants.GEARPUMP_HOSTNAME),
- Config.NIMBUS_THRIFT_PORT -> s"$THRIFT_PORT").asJava.asInstanceOf[JMap[AnyRef, AnyRef]]
- updateStormConfig(thriftConf, output)
- stormConf.putAll(thriftConf)
-
- import scala.concurrent.ExecutionContext.Implicits.global
- Future {
- val thriftServer = createServer(clientContext, stormConf)
- thriftServer.serve()
- }
- Await.result(system.whenTerminated, Duration.Inf)
- }
-
- private def createServer(
- clientContext: ClientContext, stormConf: JMap[AnyRef, AnyRef]): ThriftServer = {
- val processor = new Nimbus.Processor[GearpumpNimbus](new GearpumpNimbus(clientContext,
- stormConf))
- val connectionType = ThriftConnectionType.NIMBUS
- new ThriftServer(stormConf, processor, connectionType)
- }
-
- private def updateStormConfig(thriftConfig: JMap[AnyRef, AnyRef], output: String): Unit = {
- val updatedConfig: JMap[AnyRef, AnyRef] = new JHashMap[AnyRef, AnyRef]
- val outputConfig = Utils.findAndReadConfigFile(output, false).asInstanceOf[JMap[AnyRef, AnyRef]]
- updatedConfig.putAll(outputConfig)
- updatedConfig.putAll(thriftConfig)
- val yaml = new Yaml
- val serialized = yaml.dumpAsMap(updatedConfig)
- val writer = new FileWriter(new File(output))
- try {
- writer.write(serialized)
- } catch {
- case e: Exception => throw e
- } finally {
- writer.close()
- }
- }
-
- import io.gearpump.util.Constants._
- private def updateClientConfig(config: Config): Config = {
- val storm = s"<${GEARPUMP_HOME}>/lib/storm/*"
- val appClassPath = s"$storm${File.pathSeparator}" +
- config.getString(GEARPUMP_APPMASTER_EXTRA_CLASSPATH)
- val executorClassPath = s"$storm${File.pathSeparator}" +
- config.getString(Constants.GEARPUMP_EXECUTOR_EXTRA_CLASSPATH)
-
- val updated = config
- .withValue(GEARPUMP_APPMASTER_EXTRA_CLASSPATH, ConfigValueFactory.fromAnyRef(appClassPath))
- .withValue(GEARPUMP_EXECUTOR_EXTRA_CLASSPATH,
- ConfigValueFactory.fromAnyRef(executorClassPath))
-
- if (config.hasPath(StormConstants.STORM_SERIALIZATION_FRAMEWORK)) {
- val serializerConfig = ConfigValueFactory.fromAnyRef(
- config.getString(StormConstants.STORM_SERIALIZATION_FRAMEWORK))
- updated.withValue(GEARPUMP_SERIALIZER_POOL, serializerConfig)
- } else {
- updated
- }
- }
-}
-
-class GearpumpNimbus(clientContext: ClientContext, stormConf: JMap[AnyRef, AnyRef])
- extends Nimbus.Iface {
-
- import io.gearpump.experiments.storm.main.GearpumpNimbus._
-
- private var applications = Map.empty[String, Int]
- private var topologies = Map.empty[String, TopologyData]
- private val expireSeconds = StormUtil.getInt(stormConf,
- Config.NIMBUS_FILE_COPY_EXPIRATION_SECS).get
- private val expiredCallback = new Callback[String, WritableByteChannel] {
- override def expire(k: String, v: WritableByteChannel): Unit = {
- v.close()
- }
- }
- private val fileCacheMap = new TimeCacheMapWrapper[String, WritableByteChannel](expireSeconds,
- expiredCallback)
-
- override def submitTopology(
- name: String, uploadedJarLocation: String, jsonConf: String, topology: StormTopology)
- : Unit = {
- submitTopologyWithOpts(name, uploadedJarLocation, jsonConf, topology,
- new SubmitOptions(TopologyInitialStatus.ACTIVE))
- }
-
- override def submitTopologyWithOpts(
- name: String, uploadedJarLocation: String,
- jsonConf: String, topology: StormTopology, options: SubmitOptions): Unit = {
- LOG.info(s"Submitted topology $name")
- implicit val system = clientContext.system
- val gearpumpStormTopology = GearpumpStormTopology(name, topology, jsonConf)
- val stormConfig = gearpumpStormTopology.getStormConfig
- val workerNum = StormUtil.getInt(stormConfig, Config.TOPOLOGY_WORKERS).getOrElse(1)
- val processorGraph = GraphBuilder.build(gearpumpStormTopology)
- val config = UserConfig.empty
- .withValue[StormTopology](StormConstants.STORM_TOPOLOGY, topology)
- .withValue[JMap[AnyRef, AnyRef]](StormConstants.STORM_CONFIG, stormConfig)
- val app = StreamApplication(name, processorGraph, config)
- LOG.info(s"jar file uploaded to $uploadedJarLocation")
- val appId = clientContext.submit(app, uploadedJarLocation, workerNum)
- applications += name -> appId
- topologies += name -> TopologyData(topology, stormConfig, uploadedJarLocation)
- LOG.info(s"Storm Application $appId submitted")
- }
-
- override def killTopologyWithOpts(name: String, options: KillOptions): Unit = {
- if (applications.contains(name)) {
- clientContext.shutdown(applications(name))
- removeTopology(name)
- LOG.info(s"Killed topology $name")
- } else {
- throw new RuntimeException(s"topology $name not found")
- }
- }
-
- override def getNimbusConf: String = {
- JSONValue.toJSONString(stormConf)
- }
-
- override def getTopology(name: String): StormTopology = {
- updateApps()
- topologies.getOrElse(name,
- throw new RuntimeException(s"topology $name not found")).topology
- }
-
- override def getTopologyConf(name: String): String = {
- updateApps()
- JSONValue.toJSONString(topologies.getOrElse(name,
- throw new RuntimeException(s"topology $name not found")).config)
- }
-
- override def getUserTopology(id: String): StormTopology = getTopology(id)
-
- override def beginFileUpload(): String = {
- val file = File.createTempFile(s"storm-jar-${UUID.randomUUID()}", ".jar")
- val location = file.getAbsolutePath
- val channel = Channels.newChannel(new FileOutputStream(location))
- fileCacheMap.put(location, channel)
- LOG.info(s"Uploading file from client to $location")
- location
- }
-
- override def uploadChunk(location: String, chunk: ByteBuffer): Unit = {
- if (!fileCacheMap.containsKey(location)) {
- throw new RuntimeException(s"File for $location does not exist (or timed out)")
- } else {
- val channel = fileCacheMap.get(location)
- channel.write(chunk)
- fileCacheMap.put(location, channel)
- }
- }
-
- override def finishFileUpload(location: String): Unit = {
- if (!fileCacheMap.containsKey(location)) {
- throw new RuntimeException(s"File for $location does not exist (or timed out)")
- } else {
- val channel = fileCacheMap.get(location)
- channel.close()
- fileCacheMap.remove(location)
- }
- }
-
- override def getClusterInfo: ClusterSummary = {
- updateApps()
- val topologySummaryList = topologies.map { case (name, _) =>
- new TopologySummary(name, name, 0, 0, 0, 0, "")
- }.toSeq
- new ClusterSummary(List[SupervisorSummary]().asJava, 0, topologySummaryList.asJava)
- }
-
- override def beginFileDownload(file: String): String = {
- throw new UnsupportedOperationException
- }
-
- override def uploadNewCredentials(s: String, credentials: Credentials): Unit = {
- throw new UnsupportedOperationException
- }
- override def activate(name: String): Unit = {
- throw new UnsupportedOperationException
- }
-
- override def rebalance(name: String, options: RebalanceOptions): Unit = {
- throw new UnsupportedOperationException
- }
-
- override def deactivate(name: String): Unit = {
- throw new UnsupportedOperationException
- }
-
- override def getTopologyInfo(name: String): TopologyInfo = {
- throw new UnsupportedOperationException
- }
-
- override def getTopologyInfoWithOpts(s: String, getInfoOptions: GetInfoOptions): TopologyInfo = {
- throw new UnsupportedOperationException
- }
-
- override def killTopology(name: String): Unit = killTopologyWithOpts(name, new KillOptions())
-
- override def downloadChunk(name: String): ByteBuffer = {
- throw new UnsupportedOperationException
- }
-
- private def updateApps(): Unit = {
- clientContext.listApps.appMasters.foreach { app =>
- val name = app.appName
- if (applications.contains(name)) {
- if (app.status != MasterToAppMaster.AppMasterActive) {
- removeTopology(name)
- }
- }
- }
- }
-
- private def removeTopology(name: String): Unit = {
- applications -= name
- val jar = topologies(name).jar
- new File(jar).delete()
- topologies -= name
- }
-}
-
-case class TopologyData(topology: StormTopology, config: JMap[AnyRef, AnyRef], jar: String)
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/scala/io/gearpump/experiments/storm/main/GearpumpStormClient.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/scala/io/gearpump/experiments/storm/main/GearpumpStormClient.scala b/experiments/storm/src/main/scala/io/gearpump/experiments/storm/main/GearpumpStormClient.scala
deleted file mode 100644
index fbdd579..0000000
--- a/experiments/storm/src/main/scala/io/gearpump/experiments/storm/main/GearpumpStormClient.scala
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.storm.main
-
-import backtype.storm.Config
-import backtype.storm.utils.Utils
-
-import io.gearpump.cluster.main.{ArgumentsParser, CLIOption}
-import io.gearpump.util.Constants._
-import io.gearpump.util.{AkkaApp, LogUtil, Util}
-
-object GearpumpStormClient extends AkkaApp with ArgumentsParser {
-
- override val options: Array[(String, CLIOption[Any])] = Array(
- "jar" -> CLIOption[String]("<storm jar>", required = true),
- "config" -> CLIOption[Int]("<storm config file>", required = true),
- "verbose" -> CLIOption("<print verbose log on console>", required = false,
- defaultValue = Some(false)))
-
- override def main(inputAkkaConf: Config, args: Array[String]): Unit = {
- val config = parse(args)
-
- val verbose = config.getBoolean("verbose")
- if (verbose) {
- LogUtil.verboseLogToConsole()
- }
-
- val jar = config.getString("jar")
- val stormConfig = config.getString("config")
- val topology = config.remainArgs(0)
- val stormArgs = config.remainArgs.drop(1)
- val stormOptions = Array(
- s"-Dstorm.options=${getThriftOptions(stormConfig)}",
- s"-Dstorm.jar=$jar",
- s"-Dstorm.conf.file=$stormConfig",
- s"-D${PREFER_IPV4}=true"
- )
-
- val gearpumpHome = System.getProperty(GEARPUMP_HOME)
- val classPath = Array(s"$gearpumpHome/lib/*", s"$gearpumpHome/lib/storm/*", jar)
- val process = Util.startProcess(stormOptions, classPath, topology, stormArgs)
-
- // Waits till the process exit
- val exit = process.exitValue()
-
- if (exit != 0) {
- throw new Exception(s"failed to submit jar, exit code $exit, " +
- s"error summary: ${process.logger.error}")
- }
- }
-
- private def getThriftOptions(stormConfig: String): String = {
- val config = Utils.findAndReadConfigFile(stormConfig, true)
- val host = config.get(Config.NIMBUS_HOST)
- val thriftPort = config.get(Config.NIMBUS_THRIFT_PORT)
- s"${Config.NIMBUS_HOST}=$host,${Config.NIMBUS_THRIFT_PORT}=$thriftPort"
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/scala/io/gearpump/experiments/storm/partitioner/StormPartitioner.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/scala/io/gearpump/experiments/storm/partitioner/StormPartitioner.scala b/experiments/storm/src/main/scala/io/gearpump/experiments/storm/partitioner/StormPartitioner.scala
deleted file mode 100644
index e47e11d..0000000
--- a/experiments/storm/src/main/scala/io/gearpump/experiments/storm/partitioner/StormPartitioner.scala
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.storm.partitioner
-
-import io.gearpump.Message
-import io.gearpump.experiments.storm.topology.GearpumpTuple
-import io.gearpump.partitioner.{MulticastPartitioner, Partitioner}
-
-/**
- * Partitioner bound to a target Storm component
- *
- * Partitioning is already done in [[io.gearpump.experiments.storm.util.StormOutputCollector]] and
- * kept in "targetPartitions" of [[io.gearpump.experiments.storm.topology.GearpumpTuple]]
- * the partitioner just returns the partitions of the target
- *
- * In Gearpump, a message is sent from a task to all the subscribers.
- * In Storm, however, a message is sent to one or more of the subscribers.
- * Hence, we have to do the partitioning in
- * [[io.gearpump.experiments.storm.util.StormOutputCollector]] till the Storm way is supported
- * in Gearpump
- *
- * @param target target storm component id
- */
-private[storm] class StormPartitioner(target: String) extends MulticastPartitioner {
-
- override def getPartitions(msg: Message, partitionNum: Int, currentPartitionId: Int)
- : Array[Int] = {
- val stormTuple = msg.msg.asInstanceOf[GearpumpTuple]
- stormTuple.targetPartitions.getOrElse(target, Array(Partitioner.UNKNOWN_PARTITION_ID))
- }
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/scala/io/gearpump/experiments/storm/processor/StormBoltOutputCollector.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/scala/io/gearpump/experiments/storm/processor/StormBoltOutputCollector.scala b/experiments/storm/src/main/scala/io/gearpump/experiments/storm/processor/StormBoltOutputCollector.scala
deleted file mode 100644
index 5920bf8..0000000
--- a/experiments/storm/src/main/scala/io/gearpump/experiments/storm/processor/StormBoltOutputCollector.scala
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.storm.processor
-
-import java.util.{Collection => JCollection, List => JList}
-
-import backtype.storm.task.IOutputCollector
-import backtype.storm.tuple.Tuple
-
-import io.gearpump.experiments.storm.topology.TimedTuple
-import io.gearpump.experiments.storm.util.StormConstants._
-import io.gearpump.experiments.storm.util.StormOutputCollector
-import io.gearpump.streaming.task.ReportCheckpointClock
-
-/**
- * this is used by Storm bolt to emit messages
- */
-private[storm] class StormBoltOutputCollector(collector: StormOutputCollector,
- ackEnabled: Boolean = false) extends IOutputCollector {
- private var reportTime = 0L
- private var maxAckTime = 0L
-
- override def emit(
- streamId: String, anchors: JCollection[Tuple], tuple: JList[AnyRef]): JList[Integer] = {
- collector.emit(streamId, tuple)
- }
-
- override def emitDirect(
- taskId: Int, streamId: String, anchors: JCollection[Tuple], tuple: JList[AnyRef]): Unit = {
- collector.emitDirect(taskId, streamId, tuple)
- }
-
- override def fail(tuple: Tuple): Unit = {
- // application failure, throw exception such that the tuple can be replayed
- // Note: do not print the tuple which will trigger NPE since its messageId is null
- throw new Exception("Storm Bolt.execute failed")
- }
-
- override def ack(tuple: Tuple): Unit = {
- if (ackEnabled) {
- tuple match {
- case timedTuple: TimedTuple =>
- maxAckTime = Math.max(maxAckTime, timedTuple.timestamp)
- val taskContext = collector.taskContext
- val upstreamMinClock = taskContext.upstreamMinClock
- if (reportTime <= upstreamMinClock && upstreamMinClock <= maxAckTime) {
- reportTime = upstreamMinClock / CHECKPOINT_INTERVAL_MILLIS * CHECKPOINT_INTERVAL_MILLIS
- taskContext.appMaster ! ReportCheckpointClock(taskContext.taskId, reportTime)
- reportTime += CHECKPOINT_INTERVAL_MILLIS
- }
- case _ =>
- // ignore other tuples
- }
- }
- }
-
- override def reportError(throwable: Throwable): Unit = {
- throw throwable
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/scala/io/gearpump/experiments/storm/processor/StormProcessor.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/scala/io/gearpump/experiments/storm/processor/StormProcessor.scala b/experiments/storm/src/main/scala/io/gearpump/experiments/storm/processor/StormProcessor.scala
deleted file mode 100644
index 67548b3..0000000
--- a/experiments/storm/src/main/scala/io/gearpump/experiments/storm/processor/StormProcessor.scala
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.storm.processor
-
-import java.util.concurrent.TimeUnit
-import scala.concurrent.duration.Duration
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.experiments.storm.topology.GearpumpStormComponent.GearpumpBolt
-import io.gearpump.experiments.storm.util._
-import io.gearpump.streaming.task._
-
-object StormProcessor {
- private[storm] val TICK = Message("tick")
-}
-
-/**
- * this is runtime container for Storm bolt
- */
-private[storm] class StormProcessor(gearpumpBolt: GearpumpBolt,
- taskContext: TaskContext, conf: UserConfig)
- extends Task(taskContext, conf) {
- import io.gearpump.experiments.storm.processor.StormProcessor._
-
- def this(taskContext: TaskContext, conf: UserConfig) = {
- this(StormUtil.getGearpumpStormComponent(taskContext, conf)(taskContext.system)
- .asInstanceOf[GearpumpBolt], taskContext, conf)
- }
-
- private val freqOpt = gearpumpBolt.getTickFrequency
-
- override def onStart(startTime: StartTime): Unit = {
- gearpumpBolt.start(startTime)
- freqOpt.foreach(scheduleTick)
- }
-
- override def onNext(message: Message): Unit = {
- message match {
- case TICK =>
- freqOpt.foreach { freq =>
- gearpumpBolt.tick(freq)
- scheduleTick(freq)
- }
- case _ =>
- gearpumpBolt.next(message)
- }
- }
-
- private def scheduleTick(freq: Int): Unit = {
- taskContext.scheduleOnce(Duration(freq, TimeUnit.SECONDS)) {
- self ! TICK
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/scala/io/gearpump/experiments/storm/producer/StormProducer.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/scala/io/gearpump/experiments/storm/producer/StormProducer.scala b/experiments/storm/src/main/scala/io/gearpump/experiments/storm/producer/StormProducer.scala
deleted file mode 100644
index 39882c4..0000000
--- a/experiments/storm/src/main/scala/io/gearpump/experiments/storm/producer/StormProducer.scala
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.storm.producer
-
-import java.util.concurrent.TimeUnit
-import scala.concurrent.duration.Duration
-
-import akka.actor.Actor.Receive
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.experiments.storm.topology.GearpumpStormComponent.GearpumpSpout
-import io.gearpump.experiments.storm.util._
-import io.gearpump.streaming.task._
-
-object StormProducer {
- private[storm] val TIMEOUT = Message("timeout")
-}
-
-/**
- * this is runtime container for Storm spout
- */
-private[storm] class StormProducer(gearpumpSpout: GearpumpSpout,
- taskContext: TaskContext, conf: UserConfig)
- extends Task(taskContext, conf) {
- import io.gearpump.experiments.storm.producer.StormProducer._
-
- def this(taskContext: TaskContext, conf: UserConfig) = {
- this(StormUtil.getGearpumpStormComponent(taskContext, conf)(taskContext.system)
- .asInstanceOf[GearpumpSpout], taskContext, conf)
- }
-
- private val timeoutMillis = gearpumpSpout.getMessageTimeout
-
- override def onStart(startTime: StartTime): Unit = {
- gearpumpSpout.start(startTime)
- if (gearpumpSpout.ackEnabled) {
- getCheckpointClock
- }
- timeoutMillis.foreach(scheduleTimeout)
- self ! Message("start")
- }
-
- override def onNext(msg: Message): Unit = {
- msg match {
- case TIMEOUT =>
- timeoutMillis.foreach { timeout =>
- gearpumpSpout.timeout(timeout)
- scheduleTimeout(timeout)
- }
- case _ =>
- gearpumpSpout.next(msg)
- }
- self ! Message("continue")
- }
-
- override def receiveUnManagedMessage: Receive = {
- case CheckpointClock(optClock) =>
- optClock.foreach { clock =>
- gearpumpSpout.checkpoint(clock)
- }
- getCheckpointClock()
- }
-
- def getCheckpointClock(): Unit = {
- taskContext.scheduleOnce(Duration(StormConstants.CHECKPOINT_INTERVAL_MILLIS,
- TimeUnit.MILLISECONDS))(taskContext.appMaster ! GetCheckpointClock)
- }
-
- private def scheduleTimeout(timeout: Long): Unit = {
- taskContext.scheduleOnce(Duration(timeout, TimeUnit.MILLISECONDS)) {
- self ! TIMEOUT
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/scala/io/gearpump/experiments/storm/producer/StormSpoutOutputCollector.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/scala/io/gearpump/experiments/storm/producer/StormSpoutOutputCollector.scala b/experiments/storm/src/main/scala/io/gearpump/experiments/storm/producer/StormSpoutOutputCollector.scala
deleted file mode 100644
index 83532dc..0000000
--- a/experiments/storm/src/main/scala/io/gearpump/experiments/storm/producer/StormSpoutOutputCollector.scala
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.storm.producer
-
-import java.util.{List => JList}
-
-import backtype.storm.spout.{ISpout, ISpoutOutputCollector}
-
-import io.gearpump.TimeStamp
-import io.gearpump.experiments.storm.util.StormOutputCollector
-
-case class PendingMessage(id: Object, messageTime: TimeStamp, startTime: TimeStamp)
-
-/**
- * this is used by Storm Spout to emit messages
- */
-private[storm] class StormSpoutOutputCollector(
- collector: StormOutputCollector, spout: ISpout, ackEnabled: Boolean)
- extends ISpoutOutputCollector {
-
- private var checkpointClock = 0L
- private var pendingMessage: Option[PendingMessage] = None
- private var nextPendingMessage: Option[PendingMessage] = None
-
- override def emit(streamId: String, values: JList[AnyRef], messageId: Object): JList[Integer] = {
- val curTime = System.currentTimeMillis()
- collector.setTimestamp(curTime)
- val outTasks = collector.emit(streamId, values)
- setPendingOrAck(messageId, curTime, curTime)
- outTasks
- }
-
- override def reportError(throwable: Throwable): Unit = {
- throw throwable
- }
-
- override def emitDirect(taskId: Int, streamId: String, values: JList[AnyRef], messageId: Object)
- : Unit = {
- val curTime = System.currentTimeMillis()
- collector.setTimestamp(curTime)
- collector.emitDirect(taskId, streamId, values)
- setPendingOrAck(messageId, curTime, curTime)
- }
-
- def ackPendingMessage(checkpointClock: TimeStamp): Unit = {
- this.checkpointClock = checkpointClock
- nextPendingMessage.foreach { case PendingMessage(_, messageTime, _) =>
- if (messageTime <= this.checkpointClock) {
- pendingMessage.foreach { case PendingMessage(id, _, _) =>
- spout.ack(id)
- reset()
- }
- }
- }
- }
-
- def failPendingMessage(timeoutMillis: Long): Unit = {
- pendingMessage.foreach { case PendingMessage(id, _, startTime) =>
- if (System.currentTimeMillis() - startTime >= timeoutMillis) {
- spout.fail(id)
- reset()
- }
- }
- }
-
- private def reset(): Unit = {
- pendingMessage = nextPendingMessage
- nextPendingMessage = None
- }
-
- private def setPendingOrAck(messageId: Object, startTime: TimeStamp, messageTime: TimeStamp)
- : Unit = {
- if (ackEnabled) {
- val newPendingMessage = PendingMessage(messageId, messageTime, startTime)
- pendingMessage match {
- case Some(msg) =>
- if (nextPendingMessage.isEmpty && msg.messageTime <= this.checkpointClock) {
- nextPendingMessage = Some(newPendingMessage)
- } else {
- spout.ack(messageId)
- }
- case None =>
- pendingMessage = Some(newPendingMessage)
- }
- } else {
- spout.ack(messageId)
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/scala/io/gearpump/experiments/storm/topology/GearpumpStormComponent.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/scala/io/gearpump/experiments/storm/topology/GearpumpStormComponent.scala b/experiments/storm/src/main/scala/io/gearpump/experiments/storm/topology/GearpumpStormComponent.scala
deleted file mode 100644
index 42dce5f..0000000
--- a/experiments/storm/src/main/scala/io/gearpump/experiments/storm/topology/GearpumpStormComponent.scala
+++ /dev/null
@@ -1,388 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.storm.topology
-
-import java.io.{File, FileOutputStream, IOException}
-import java.util
-import java.util.jar.JarFile
-import java.util.{HashMap => JHashMap, List => JList, Map => JMap}
-import scala.collection.JavaConverters._
-import scala.concurrent.{Await, Future}
-
-import akka.actor.ActorRef
-import akka.pattern.ask
-import backtype.storm.Config
-import backtype.storm.generated.{Bolt, ComponentCommon, SpoutSpec, StormTopology}
-import backtype.storm.metric.api.IMetric
-import backtype.storm.spout.{ISpout, SpoutOutputCollector}
-import backtype.storm.task.{GeneralTopologyContext, IBolt, OutputCollector, TopologyContext}
-import backtype.storm.tuple.{Fields, Tuple, TupleImpl}
-import backtype.storm.utils.Utils
-import clojure.lang.Atom
-import org.apache.commons.io.{FileUtils, IOUtils}
-import org.slf4j.Logger
-
-import io.gearpump.experiments.storm.processor.StormBoltOutputCollector
-import io.gearpump.experiments.storm.producer.StormSpoutOutputCollector
-import io.gearpump.experiments.storm.util.StormConstants._
-import io.gearpump.experiments.storm.util.StormUtil._
-import io.gearpump.experiments.storm.util.{StormOutputCollector, StormUtil}
-import io.gearpump.streaming.DAG
-import io.gearpump.streaming.task._
-import io.gearpump.util.{Constants, LogUtil}
-import io.gearpump.{Message, TimeStamp}
-
-/**
- * subclass wraps Storm Spout and Bolt, and their lifecycles
- * hides the complexity from Gearpump applications
- */
-trait GearpumpStormComponent {
- /**
- * invoked at Task.onStart
- * @param startTime task start time
- */
- def start(startTime: StartTime): Unit
-
- /**
- * invoked at Task.onNext
- * @param message incoming message
- */
- def next(message: Message): Unit
-
- /**
- * invoked at Task.onStop
- */
- def stop(): Unit = {}
-}
-
-object GearpumpStormComponent {
- private val LOG: Logger = LogUtil.getLogger(classOf[GearpumpStormComponent])
-
- object GearpumpSpout {
- def apply(topology: StormTopology, config: JMap[AnyRef, AnyRef],
- spoutSpec: SpoutSpec, taskContext: TaskContext): GearpumpSpout = {
- val componentCommon = spoutSpec.get_common()
- val scalaMap = config.asScala.toMap // Convert to scala immutable map
- val normalizedConfig = normalizeConfig(scalaMap, componentCommon)
- val getTopologyContext = (dag: DAG, taskId: TaskId) => {
- val stormTaskId = gearpumpTaskIdToStorm(taskId)
- buildTopologyContext(dag, topology, normalizedConfig, stormTaskId)
- }
- val spout = Utils.getSetComponentObject(spoutSpec.get_spout_object()).asInstanceOf[ISpout]
- val ackEnabled = StormUtil.ackEnabled(config)
- if (ackEnabled) {
- val className = spout.getClass.getName
- if (!isSequentiallyReplayableSpout(className)) {
- LOG.warn(s"at least once is not supported for $className")
- }
- }
- val getOutputCollector = (taskContext: TaskContext, topologyContext: TopologyContext) => {
- new StormSpoutOutputCollector(
- StormOutputCollector(taskContext, topologyContext), spout, ackEnabled)
- }
- GearpumpSpout(
- normalizedConfig,
- spout,
- askAppMasterForDAG,
- getTopologyContext,
- getOutputCollector,
- ackEnabled,
- taskContext)
- }
-
- private def isSequentiallyReplayableSpout(className: String): Boolean = {
- className.equals("storm.kafka.KafkaSpout")
- }
- }
-
- case class GearpumpSpout(
- config: JMap[AnyRef, AnyRef],
- spout: ISpout,
- getDAG: ActorRef => DAG,
- getTopologyContext: (DAG, TaskId) => TopologyContext,
- getOutputCollector: (TaskContext, TopologyContext) => StormSpoutOutputCollector,
- ackEnabled: Boolean,
- taskContext: TaskContext)
- extends GearpumpStormComponent {
-
- private var collector: StormSpoutOutputCollector = null
-
- override def start(startTime: StartTime): Unit = {
- import taskContext.{appMaster, taskId}
-
- val dag = getDAG(appMaster)
- val topologyContext = getTopologyContext(dag, taskId)
- collector = getOutputCollector(taskContext, topologyContext)
- spout.open(config, topologyContext, new SpoutOutputCollector(collector))
- }
-
- override def next(message: Message): Unit = {
- spout.nextTuple()
- }
-
- /**
- * @return timeout in milliseconds if enabled
- */
- def getMessageTimeout: Option[Long] = {
- StormUtil.getBoolean(config, Config.TOPOLOGY_ENABLE_MESSAGE_TIMEOUTS).flatMap {
- timeoutEnabled =>
- if (timeoutEnabled) {
- StormUtil.getInt(config, Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS).map(_ * 1000L)
- } else {
- None
- }
- }
- }
-
- def checkpoint(clock: TimeStamp): Unit = {
- collector.ackPendingMessage(clock)
- }
-
- def timeout(timeoutMillis: Long): Unit = {
- collector.failPendingMessage(timeoutMillis)
- }
- }
-
- object GearpumpBolt {
- def apply(topology: StormTopology, config: JMap[AnyRef, AnyRef],
- boltSpec: Bolt, taskContext: TaskContext): GearpumpBolt = {
- val configAsScalaMap = config.asScala.toMap // Convert to scala immutable map
- val normalizedConfig = normalizeConfig(configAsScalaMap, boltSpec.get_common())
- val getTopologyContext = (dag: DAG, taskId: TaskId) => {
- val stormTaskId = gearpumpTaskIdToStorm(taskId)
- buildTopologyContext(dag, topology, normalizedConfig, stormTaskId)
- }
- val getGeneralTopologyContext = (dag: DAG) => {
- buildGeneralTopologyContext(dag, topology, normalizedConfig)
- }
- val getOutputCollector = (taskContext: TaskContext, topologyContext: TopologyContext) => {
- StormOutputCollector(taskContext, topologyContext)
- }
- val getTickTuple = (topologyContext: GeneralTopologyContext, freq: Int) => {
-
- val values = new util.ArrayList[Object] // To be compatible with Java interface
- values.add(freq.asInstanceOf[java.lang.Integer])
- new TupleImpl(topologyContext, values, SYSTEM_TASK_ID, SYSTEM_TICK_STREAM_ID, null)
- }
- GearpumpBolt(
- normalizedConfig,
- Utils.getSetComponentObject(boltSpec.get_bolt_object()).asInstanceOf[IBolt],
- askAppMasterForDAG,
- getTopologyContext,
- getGeneralTopologyContext,
- getOutputCollector,
- getTickTuple,
- taskContext)
- }
- }
-
- case class GearpumpBolt(
- config: JMap[AnyRef, AnyRef],
- bolt: IBolt,
- getDAG: ActorRef => DAG,
- getTopologyContext: (DAG, TaskId) => TopologyContext,
- getGeneralTopologyContext: DAG => GeneralTopologyContext,
- getOutputCollector: (TaskContext, TopologyContext) => StormOutputCollector,
- getTickTuple: (GeneralTopologyContext, Int) => Tuple,
- taskContext: TaskContext)
- extends GearpumpStormComponent {
- import taskContext.{appMaster, taskId}
-
- private var collector: StormOutputCollector = null
- private var topologyContext: TopologyContext = null
- private var generalTopologyContext: GeneralTopologyContext = null
- private var tickTuple: Tuple = null
-
- override def start(startTime: StartTime): Unit = {
- val dag = getDAG(appMaster)
- topologyContext = getTopologyContext(dag, taskId)
- generalTopologyContext = getGeneralTopologyContext(dag)
- collector = getOutputCollector(taskContext, topologyContext)
- val delegate = new StormBoltOutputCollector(collector, StormUtil.ackEnabled(config))
- bolt.prepare(config, topologyContext, new OutputCollector(delegate))
- }
-
- override def next(message: Message): Unit = {
- val timestamp = message.timestamp
- collector.setTimestamp(timestamp)
- bolt.execute(message.msg.asInstanceOf[GearpumpTuple].toTuple(generalTopologyContext,
- timestamp))
- }
-
- def getTickFrequency: Option[Int] = {
- StormUtil.getInt(config, Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS)
- }
-
- /**
- * invoked at TICK message when "topology.tick.tuple.freq.secs" is configured
- * @param freq tick frequency
- */
- def tick(freq: Int): Unit = {
- if (null == tickTuple) {
- tickTuple = getTickTuple(generalTopologyContext, freq)
- }
- bolt.execute(tickTuple)
- }
- }
-
- /**
- * normalize general config with per component configs
- * "topology.transactional.id" and "topology.tick.tuple.freq.secs"
- * @param stormConfig general config for all components
- * @param componentCommon common component parts
- */
- private def normalizeConfig(stormConfig: Map[AnyRef, AnyRef],
- componentCommon: ComponentCommon): JMap[AnyRef, AnyRef] = {
- val config: JMap[AnyRef, AnyRef] = new JHashMap[AnyRef, AnyRef]
- config.putAll(stormConfig.asJava)
- val componentConfig = parseJsonStringToMap(componentCommon.get_json_conf())
- Option(componentConfig.get(Config.TOPOLOGY_TRANSACTIONAL_ID))
- .foreach(config.put(Config.TOPOLOGY_TRANSACTIONAL_ID, _))
- Option(componentConfig.get(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS))
- .foreach(config.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, _))
- config
- }
-
- private def askAppMasterForDAG(appMaster: ActorRef): DAG = {
- implicit val timeout = Constants.FUTURE_TIMEOUT
- val dagFuture = (appMaster ? GetDAG).asInstanceOf[Future[DAG]]
- Await.result(dagFuture, timeout.duration)
- }
-
- private def buildGeneralTopologyContext(dag: DAG, topology: StormTopology, stormConf: JMap[_, _])
- : GeneralTopologyContext = {
- val taskToComponent = getTaskToComponent(dag)
- val componentToSortedTasks: JMap[String, JList[Integer]] =
- getComponentToSortedTasks(taskToComponent)
- val componentToStreamFields: JMap[String, JMap[String, Fields]] =
- getComponentToStreamFields(topology)
- new GeneralTopologyContext(
- topology, stormConf, taskToComponent.asJava, componentToSortedTasks,
- componentToStreamFields, null)
- }
-
- private def buildTopologyContext(
- dag: DAG, topology: StormTopology, stormConf: JMap[_, _], stormTaskId: Integer)
- : TopologyContext = {
- val taskToComponent = getTaskToComponent(dag)
- val componentToSortedTasks: JMap[String, JList[Integer]] =
- getComponentToSortedTasks(taskToComponent)
- val componentToStreamFields: JMap[String, JMap[String, Fields]] =
- getComponentToStreamFields(topology)
- val codeDir = mkCodeDir
- val pidDir = mkPidDir
-
- new TopologyContext(topology, stormConf, taskToComponent.asJava, componentToSortedTasks,
- componentToStreamFields, null, codeDir, pidDir, stormTaskId, null, null, null, null,
- new JHashMap[String, AnyRef], new JHashMap[Integer, JMap[Integer, JMap[String, IMetric]]],
- new Atom(false))
- }
-
- private def getComponentToStreamFields(topology: StormTopology)
- : JMap[String, JMap[String, Fields]] = {
- val spouts = topology.get_spouts().asScala
- val bolts = topology.get_bolts().asScala
-
- val spoutFields = spouts.map {
- case (id, component) => id -> getComponentToFields(component.get_common())
- }
-
- val boltFields = bolts.map {
- case (id, component) => id -> getComponentToFields(component.get_common())
- }
-
- val systemFields = Map(SYSTEM_COMPONENT_ID ->
- Map(SYSTEM_TICK_STREAM_ID -> new Fields(SYSTEM_COMPONENT_OUTPUT_FIELDS)).asJava)
-
- (spoutFields ++ boltFields ++ systemFields).asJava
- }
-
- private def getComponentToFields(common: ComponentCommon): JMap[String, Fields] = {
- val streams = common.get_streams.asScala
- streams.map { case (sid, stream) =>
- sid -> new Fields(stream.get_output_fields())
- }.asJava
- }
-
- private def getComponentToSortedTasks(
- taskToComponent: Map[Integer, String]): JMap[String, JList[Integer]] = {
- taskToComponent.groupBy(_._2).map { case (component, map) =>
- val sortedTasks = map.keys.toList.sorted.asJava
- component -> sortedTasks
- }.asJava
- }
-
- private def getTaskToComponent(dag: DAG): Map[Integer, String] = {
- val taskToComponent = dag.processors.flatMap { case (processorId, processorDescription) =>
- val parallelism = processorDescription.parallelism
- val component = processorDescription.taskConf.getString(STORM_COMPONENT).get
- (0 until parallelism).map(index =>
- gearpumpTaskIdToStorm(TaskId(processorId, index)) -> component)
- }
- taskToComponent
- }
-
- // Workarounds to support storm ShellBolt
- private def mkPidDir: String = {
- val pidDir = FileUtils.getTempDirectoryPath + File.separator + "pid"
- try {
- FileUtils.forceMkdir(new File(pidDir))
- } catch {
- case ex: IOException =>
- LOG.error(s"failed to create pid directory $pidDir")
- }
- pidDir
- }
-
- // a workaround to support storm ShellBolt
- private def mkCodeDir: String = {
- val jarPath = System.getProperty("java.class.path").split(":").last
- val destDir = FileUtils.getTempDirectoryPath + File.separator + "storm"
-
- try {
- FileUtils.forceMkdir(new File(destDir))
-
- val jar = new JarFile(jarPath)
- val enumEntries = jar.entries().asScala
- enumEntries.foreach { entry =>
- val file = new File(destDir + File.separator + entry.getName)
- if (!entry.isDirectory) {
- file.getParentFile.mkdirs()
-
- val is = jar.getInputStream(entry)
- val fos = new FileOutputStream(file)
- try {
- IOUtils.copy(is, fos)
- } catch {
- case ex: IOException =>
- LOG.error(s"failed to copy data from ${entry.getName} to ${file.getName}")
- } finally {
- fos.close()
- is.close()
- }
- }
- }
- } catch {
- case ex: IOException =>
- LOG.error(s"could not extract $destDir from $jarPath")
- }
-
- destDir + File.separator + "resources"
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/scala/io/gearpump/experiments/storm/topology/GearpumpStormTopology.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/scala/io/gearpump/experiments/storm/topology/GearpumpStormTopology.scala b/experiments/storm/src/main/scala/io/gearpump/experiments/storm/topology/GearpumpStormTopology.scala
deleted file mode 100644
index 5c3fc3e..0000000
--- a/experiments/storm/src/main/scala/io/gearpump/experiments/storm/topology/GearpumpStormTopology.scala
+++ /dev/null
@@ -1,321 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.storm.topology
-
-import java.lang.{Iterable => JIterable}
-import java.util.{ArrayList => JArrayList, HashMap => JHashMap, List => JList, Map => JMap}
-
-import akka.actor.ActorSystem
-import backtype.storm.Config
-import backtype.storm.generated._
-import backtype.storm.utils.{ThriftTopologyUtils, Utils}
-import org.slf4j.Logger
-
-import io.gearpump.cluster.UserConfig
-import io.gearpump.experiments.storm.processor.StormProcessor
-import io.gearpump.experiments.storm.producer.StormProducer
-import io.gearpump.experiments.storm.util.StormConstants._
-import io.gearpump.experiments.storm.util.StormUtil
-import io.gearpump.experiments.storm.util.StormUtil._
-import io.gearpump.streaming.Processor
-import io.gearpump.streaming.task.Task
-import io.gearpump.util.LogUtil
-
-// TODO: Refactor this file, we should disable using of JavaConversions
-// scalastyle:off javaconversions
-import scala.collection.JavaConversions._
-// scalastyle:on javaconversions
-
-object GearpumpStormTopology {
- private val LOG: Logger = LogUtil.getLogger(classOf[GearpumpStormTopology])
-
- def apply(
- name: String,
- topology: StormTopology,
- appConfigInJson: String)(implicit system: ActorSystem): GearpumpStormTopology = {
- new GearpumpStormTopology(
- name,
- topology,
- Utils.readStormConfig().asInstanceOf[JMap[AnyRef, AnyRef]],
- parseJsonStringToMap(appConfigInJson)
- )
- }
-}
-
-/**
- * this is a wrapper over Storm topology which
- * 1. merges Storm and Gearpump configs
- * 2. creates Gearpump processors
- * 3. provides interface for Gearpump applications to use Storm topology
- *
- * an implicit ActorSystem is required to create Gearpump processors
- * @param name topology name
- * @param topology Storm topology
- * @param sysConfig configs from "defaults.yaml" and custom config file
- * @param appConfig config submitted from user application
- */
-private[storm] class GearpumpStormTopology(
- name: String,
- topology: StormTopology,
- sysConfig: JMap[AnyRef, AnyRef],
- appConfig: JMap[AnyRef, AnyRef])(implicit system: ActorSystem) {
-
- private val spouts = topology.get_spouts()
- private val bolts = topology.get_bolts()
- private val stormConfig = mergeConfigs(sysConfig, appConfig, getComponentConfigs(spouts, bolts))
- private val spoutProcessors = spouts.map { case (id, spout) =>
- id -> spoutToProcessor(id, spout, stormConfig.toMap)
- }.toMap
- private val boltProcessors = bolts.map { case (id, bolt) =>
- id -> boltToProcessor(id, bolt, stormConfig.toMap)
- }.toMap
- private val allProcessors = spoutProcessors ++ boltProcessors
-
- /**
- * @return merged Storm config with priority
- * defaults.yaml < custom file config < application config < component config
- */
- def getStormConfig: JMap[AnyRef, AnyRef] = stormConfig
-
- /**
- * @return Storm components to Gearpump processors
- */
- def getProcessors: Map[String, Processor[Task]] = allProcessors
-
- /**
- * @param sourceId source component id
- * @return target Storm components and Gearpump processors
- */
- def getTargets(sourceId: String): Map[String, Processor[Task]] = {
- getTargets(sourceId, topology).map { case (targetId, _) =>
- targetId -> boltProcessors(targetId)
- }
- }
-
- /**
- * merge configs from application, custom config file and component
- */
- private def mergeConfigs(
- sysConfig: JMap[AnyRef, AnyRef],
- appConfig: JMap[AnyRef, AnyRef],
- componentConfigs: Iterable[JMap[AnyRef, AnyRef]]): JMap[AnyRef, AnyRef] = {
- val allConfig = new JHashMap[AnyRef, AnyRef]
- allConfig.putAll(sysConfig)
- allConfig.putAll(appConfig)
- allConfig.putAll(getMergedComponentConfig(componentConfigs, allConfig.toMap))
- allConfig.put(Config.TOPOLOGY_NAME, name)
- allConfig
- }
-
- /**
- * creates Gearpump processor from Storm spout
- * @param spoutId spout id
- * @param spoutSpec spout spec
- * @param stormConfig merged storm config
- * @param system actor system
- * @return a Processor[StormProducer]
- */
- private def spoutToProcessor(spoutId: String, spoutSpec: SpoutSpec,
- stormConfig: Map[AnyRef, AnyRef])(implicit system: ActorSystem): Processor[Task] = {
- val componentCommon = spoutSpec.get_common()
- val taskConf = UserConfig.empty
- .withString(STORM_COMPONENT, spoutId)
- val parallelism = getParallelism(stormConfig, componentCommon)
- Processor[StormProducer](parallelism, spoutId, taskConf)
- }
-
- /**
- * creates Gearpump processor from Storm bolt
- * @param boltId bolt id
- * @param boltSpec bolt spec
- * @param stormConfig merged storm config
- * @param system actor system
- * @return a Processor[StormProcessor]
- */
- private def boltToProcessor(boltId: String, boltSpec: Bolt,
- stormConfig: Map[AnyRef, AnyRef])(implicit system: ActorSystem): Processor[Task] = {
- val componentCommon = boltSpec.get_common()
- val taskConf = UserConfig.empty
- .withString(STORM_COMPONENT, boltId)
- .withBoolean("state.checkpoint.enable", StormUtil.ackEnabled(stormConfig))
- val parallelism = getParallelism(stormConfig, componentCommon)
- Processor[StormProcessor](parallelism, boltId, taskConf)
- }
-
- /**
- * @return target components and streams
- */
- private def getTargets(componentId: String, topology: StormTopology)
- : Map[String, Map[String, Grouping]] = {
- val componentIds = ThriftTopologyUtils.getComponentIds(topology)
- componentIds.flatMap { otherComponentId =>
- getInputs(otherComponentId, topology).toList.map(otherComponentId -> _)
- }.foldLeft(Map.empty[String, Map[String, Grouping]]) {
- (allTargets, componentAndInput) =>
- val (otherComponentId, (globalStreamId, grouping)) = componentAndInput
- val inputStreamId = globalStreamId.get_streamId()
- val inputComponentId = globalStreamId.get_componentId
- if (inputComponentId.equals(componentId)) {
- val curr = allTargets.getOrElse(otherComponentId, Map.empty[String, Grouping])
- allTargets + (otherComponentId -> (curr + (inputStreamId -> grouping)))
- } else {
- allTargets
- }
- }
- }
-
- /**
- * @return input stream and grouping for a Storm component
- */
- private def getInputs(componentId: String, topology: StormTopology)
- : JMap[GlobalStreamId, Grouping] = {
- ThriftTopologyUtils.getComponentCommon(topology, componentId).get_inputs
- }
-
- /**
- * get Storm component parallelism according to the following rule,
- * 1. use "topology.tasks" if defined; otherwise use parallelism_hint
- * 2. parallelism should not be larger than "topology.max.task.parallelism" if defined
- * 3. component config overrides system config
- * @param stormConfig System configs without merging "topology.tasks" and
- * "topology.max.task.parallelism" of component
- * @return number of task instances for a component
- */
- private def getParallelism(stormConfig: Map[AnyRef, AnyRef], component: ComponentCommon): Int = {
- val parallelismHint: Int = if (component.is_set_parallelism_hint()) {
- component.get_parallelism_hint()
- } else {
- 1
- }
- val mergedConfig = new JHashMap[AnyRef, AnyRef]
- val componentConfig = parseJsonStringToMap(component.get_json_conf)
- mergedConfig.putAll(stormConfig)
- mergedConfig.putAll(componentConfig)
- val numTasks: Int = getInt(mergedConfig, Config.TOPOLOGY_TASKS).getOrElse(parallelismHint)
- val parallelism: Int = getInt(mergedConfig, Config.TOPOLOGY_MAX_TASK_PARALLELISM)
- .fold(numTasks)(p => math.min(p, numTasks))
- parallelism
- }
-
- private def getComponentConfigs(spouts: JMap[String, SpoutSpec],
- bolts: JMap[String, Bolt]): Iterable[JMap[AnyRef, AnyRef]] = {
- spouts.map { case (id, spoutSpec) =>
- parseJsonStringToMap(spoutSpec.get_common().get_json_conf())
- } ++ bolts.map { case (id, boltSpec) =>
- parseJsonStringToMap(boltSpec.get_common().get_json_conf())
- }
- }
-
- /**
- * merge component configs "topology.kryo.decorators" and "topology.kryo.register"
- * @param componentConfigs list of component configs
- * @param allConfig existing configs without merging component configs
- * @return the two configs merged from all the component configs and existing configs
- */
- private def getMergedComponentConfig(componentConfigs: Iterable[JMap[AnyRef, AnyRef]],
- allConfig: Map[AnyRef, AnyRef]): JMap[AnyRef, AnyRef] = {
- val mergedConfig: JMap[AnyRef, AnyRef] = new JHashMap[AnyRef, AnyRef]
- mergedConfig.putAll(getMergedKryoDecorators(componentConfigs, allConfig))
- mergedConfig.putAll(getMergedKryoRegister(componentConfigs, allConfig))
- mergedConfig
- }
-
- /**
- * @param componentConfigs list of component configs
- * @param allConfig existing configs without merging component configs
- * @return a merged config with a list of distinct kryo decorators from component and
- * existing configs
- */
- private def getMergedKryoDecorators(componentConfigs: Iterable[JMap[AnyRef, AnyRef]],
- allConfig: Map[AnyRef, AnyRef]): JMap[AnyRef, AnyRef] = {
- val mergedConfig: JMap[AnyRef, AnyRef] = new JHashMap[AnyRef, AnyRef](1)
- val key = Config.TOPOLOGY_KRYO_DECORATORS
- val configs = getConfigValues(componentConfigs, allConfig, key)
- val distincts = configs.foldLeft(Set.empty[String]) {
- case (accum, config: JIterable[_]) =>
- accum ++ config.map {
- case s: String => s
- case illegal =>
- throw new IllegalArgumentException(s"$key must be a List of Strings; actually $illegal")
- }
- case (accum, null) =>
- accum
- case illegal =>
- throw new IllegalArgumentException(s"$key must be a List of Strings; actually $illegal")
- }
- if (distincts.nonEmpty) {
- val decorators: JList[String] = new JArrayList(distincts.size)
- decorators.addAll(distincts)
- mergedConfig.put(key, decorators)
- }
- mergedConfig
- }
-
- /**
- * @param componentConfigs list of component configs
- * @param allConfig existing configs without merging component configs
- * @return a merged config with component config overriding existing configs
- */
- private def getMergedKryoRegister(componentConfigs: Iterable[JMap[AnyRef, AnyRef]],
- allConfig: Map[AnyRef, AnyRef]): JMap[AnyRef, AnyRef] = {
- val mergedConfig: JMap[AnyRef, AnyRef] = new JHashMap[AnyRef, AnyRef](1)
- val key = Config.TOPOLOGY_KRYO_REGISTER
- val configs = getConfigValues(componentConfigs, allConfig, key)
- val merged = configs.foldLeft(Map.empty[String, String]) {
- case (accum, config: JIterable[_]) =>
- accum ++ config.map {
- case m: JMap[_, _] =>
- m.map {
- case (k: String, v: String) => k -> v
- case illegal =>
- throw new IllegalArgumentException(
- s"each element of $key must be a String or a Map of Strings; actually $illegal")
- }
- case s: String =>
- Map(s -> null)
- case illegal =>
- throw new IllegalArgumentException(s"each element of $key must be a String or " +
- s"a Map of Strings; actually $illegal")
- }.reduce(_ ++ _)
- case (accum, null) =>
- accum
- case (accum, illegal) =>
- throw new IllegalArgumentException(
- s"$key must be an Iterable containing only Strings or Maps of Strings; actually $illegal")
- }
- if (merged.nonEmpty) {
- val registers: JMap[String, String] = new JHashMap[String, String](merged.size)
- registers.putAll(merged)
- mergedConfig.put(key, registers)
- }
- mergedConfig
- }
-
- /**
- * @param componentConfigs list of raw component configs
- * @param allConfig existing configs without merging component configs
- * @param key config key
- * @return a list of values for a config from both component configs and existing configs
- */
- private def getConfigValues(componentConfigs: Iterable[JMap[AnyRef, AnyRef]],
- allConfig: Map[AnyRef, AnyRef], key: String): Iterable[AnyRef] = {
- componentConfigs.map(config => config.get(key)) ++ allConfig.get(key).toList
- }
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/scala/io/gearpump/experiments/storm/topology/GearpumpTuple.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/scala/io/gearpump/experiments/storm/topology/GearpumpTuple.scala b/experiments/storm/src/main/scala/io/gearpump/experiments/storm/topology/GearpumpTuple.scala
deleted file mode 100644
index ee54add..0000000
--- a/experiments/storm/src/main/scala/io/gearpump/experiments/storm/topology/GearpumpTuple.scala
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.storm.topology
-
-import java.util.{List => JList}
-
-import backtype.storm.task.GeneralTopologyContext
-import backtype.storm.tuple.{Tuple, TupleImpl}
-
-import io.gearpump.TimeStamp
-
-/**
- * this carries Storm tuple values in the Gearpump world
- * the targetPartitions field dictate which tasks a GearpumpTuple should be sent to
- * see [[io.gearpump.experiments.storm.partitioner.StormPartitioner]] for more info
- */
-private[storm] class GearpumpTuple(
- val values: JList[AnyRef],
- val sourceTaskId: Integer,
- val sourceStreamId: String,
- @transient val targetPartitions: Map[String, Array[Int]]) extends Serializable {
- /**
- * creates a Storm [[backtype.storm.tuple.Tuple]] to be passed to a Storm component
- * this is needed for each incoming message
- * because we cannot get [[backtype.storm.task.GeneralTopologyContext]] at deserialization
- * @param topologyContext topology context used for all tasks
- * @return a Tuple
- */
- def toTuple(topologyContext: GeneralTopologyContext, timestamp: TimeStamp): Tuple = {
- TimedTuple(topologyContext, values, sourceTaskId, sourceStreamId, timestamp)
- }
-
- def canEqual(other: Any): Boolean = other.isInstanceOf[GearpumpTuple]
-
- override def equals(other: Any): Boolean = other match {
- case that: GearpumpTuple =>
- (that canEqual this) &&
- values == that.values &&
- sourceTaskId == that.sourceTaskId &&
- sourceStreamId == that.sourceStreamId
- case _ => false
- }
-
- override def hashCode(): Int = {
- val state = Seq(values, sourceTaskId, sourceStreamId)
- state.map(_.hashCode()).foldLeft(0)((a, b) => 31 * a + b)
- }
-}
-
-case class TimedTuple(topologyContext: GeneralTopologyContext, tuple: JList[AnyRef],
- sourceTaskId: Integer, sourceStreamId: String, timestamp: TimeStamp)
- extends TupleImpl(topologyContext, tuple, sourceTaskId, sourceStreamId, null)
-
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/scala/io/gearpump/experiments/storm/util/GraphBuilder.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/scala/io/gearpump/experiments/storm/util/GraphBuilder.scala b/experiments/storm/src/main/scala/io/gearpump/experiments/storm/util/GraphBuilder.scala
deleted file mode 100644
index 041a90c..0000000
--- a/experiments/storm/src/main/scala/io/gearpump/experiments/storm/util/GraphBuilder.scala
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.storm.util
-
-import io.gearpump.experiments.storm.partitioner.StormPartitioner
-import io.gearpump.experiments.storm.topology.GearpumpStormTopology
-import io.gearpump.partitioner.Partitioner
-import io.gearpump.streaming.Processor
-import io.gearpump.streaming.task.Task
-import io.gearpump.util.Graph
-
-object GraphBuilder {
-
- /**
- * build a Gearpump DAG from a Storm topology
- * @param topology a wrapper over Storm topology
- * @return a DAG
- */
- def build(topology: GearpumpStormTopology): Graph[Processor[_ <: Task], _ <: Partitioner] = {
- val processorGraph = Graph.empty[Processor[Task], Partitioner]
-
- topology.getProcessors.foreach { case (sourceId, sourceProcessor) =>
- topology.getTargets(sourceId).foreach { case (targetId, targetProcessor) =>
- processorGraph.addEdge(sourceProcessor, new StormPartitioner(targetId), targetProcessor)
- }
- }
-
- processorGraph
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/scala/io/gearpump/experiments/storm/util/Grouper.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/scala/io/gearpump/experiments/storm/util/Grouper.scala b/experiments/storm/src/main/scala/io/gearpump/experiments/storm/util/Grouper.scala
deleted file mode 100644
index 91277cd..0000000
--- a/experiments/storm/src/main/scala/io/gearpump/experiments/storm/util/Grouper.scala
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.storm.util
-
-import java.util.{List => JList}
-import scala.util.Random
-
-import backtype.storm.generated.GlobalStreamId
-import backtype.storm.grouping.CustomStreamGrouping
-import backtype.storm.task.TopologyContext
-import backtype.storm.tuple.Fields
-
-/**
- * Grouper is identical to that in storm but return gearpump partitions for storm tuple values
- */
-sealed trait Grouper {
- /**
- * @param taskId storm task id of source task
- * @param values storm tuple values
- * @return a list of gearpump partitions
- */
- def getPartitions(taskId: Int, values: JList[AnyRef]): Array[Int]
-}
-
-/**
- * GlobalGrouper always returns partition 0
- */
-class GlobalGrouper extends Grouper {
- override def getPartitions(taskId: Int, values: JList[AnyRef]): Array[Int] = Array(0)
-}
-
-/**
- * NoneGrouper randomly returns partition
- *
- * @param numTasks number of target tasks
- */
-class NoneGrouper(numTasks: Int) extends Grouper {
- private val random = new Random
-
- override def getPartitions(taskId: Int, values: JList[AnyRef]): Array[Int] = {
- val partition = StormUtil.mod(random.nextInt, numTasks)
- Array(partition)
- }
-}
-
-/**
- * ShuffleGrouper shuffles partitions and returns them sequentially, and then shuffles again
- *
- * @param numTasks number of target tasks
- */
-class ShuffleGrouper(numTasks: Int) extends Grouper {
- private val random = new Random
- private var index = -1
- private var partitions = List.empty[Int]
-
- override def getPartitions(taskId: Int, values: JList[AnyRef]): Array[Int] = {
- index += 1
- if (partitions.isEmpty) {
- partitions = 0.until(numTasks).toList
- partitions = random.shuffle(partitions)
- } else if (index >= numTasks) {
- index = 0
- partitions = random.shuffle(partitions)
- }
- Array(partitions(index))
- }
-}
-
-/**
- * FieldsGrouper returns partition based on value of groupFields
- *
- * @param outFields declared output fields of source task
- * @param groupFields grouping fields of target tasks
- * @param numTasks number of target tasks
- */
-class FieldsGrouper(outFields: Fields, groupFields: Fields, numTasks: Int) extends Grouper {
-
- override def getPartitions(taskId: Int, values: JList[AnyRef]): Array[Int] = {
- val hash = outFields.select(groupFields, values).hashCode()
- val partition = StormUtil.mod(hash, numTasks)
- Array(partition)
- }
-}
-
-/**
- * AllGrouper returns all partitions
- *
- * @param numTasks number of target tasks
- */
-class AllGrouper(numTasks: Int) extends Grouper {
- val partitions = (0 until numTasks).toArray
-
- override def getPartitions(taskId: Int, values: JList[AnyRef]): Array[Int] = {
- partitions
- }
-}
-
-/**
- * CustomGrouper allows users to specify grouping strategy
- *
- * @param grouping see [[backtype.storm.grouping.CustomStreamGrouping]]
- */
-class CustomGrouper(grouping: CustomStreamGrouping) extends Grouper {
-
- def prepare(
- topologyContext: TopologyContext, globalStreamId: GlobalStreamId, targetTasks: JList[Integer])
- : Unit = {
- grouping.prepare(topologyContext, globalStreamId, targetTasks)
- }
-
- override def getPartitions(taskId: Int, values: JList[AnyRef]): Array[Int] = {
- val tasks = grouping.chooseTasks(taskId, values)
- val result = new Array[Int](tasks.size())
-
- val iter = tasks.iterator()
-
- var index = 0
- while (iter.hasNext()) {
- val value = iter.next()
- result(index) = StormUtil.stormTaskIdToGearpump(value).index
- index += 1
- }
- result
- }
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/scala/io/gearpump/experiments/storm/util/StormConstants.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/scala/io/gearpump/experiments/storm/util/StormConstants.scala b/experiments/storm/src/main/scala/io/gearpump/experiments/storm/util/StormConstants.scala
deleted file mode 100644
index 928d07b..0000000
--- a/experiments/storm/src/main/scala/io/gearpump/experiments/storm/util/StormConstants.scala
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.storm.util
-
-object StormConstants {
- val STORM_COMPONENT = "storm_component"
- val STORM_TOPOLOGY = "storm_topology"
- val STORM_CONFIG = "storm_config"
- val SYSTEM_COMPONENT_ID = "__system"
- val SYSTEM_COMPONENT_OUTPUT_FIELDS = "rate_secs"
- val SYSTEM_TASK_ID: Integer = -1
- val SYSTEM_TICK_STREAM_ID = "__tick"
-
- val CHECKPOINT_INTERVAL_MILLIS = 2000 // 2 seconds
-
- val STORM_SERIALIZATION_FRAMEWORK = "gearpump.storm.serialization-framework"
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/scala/io/gearpump/experiments/storm/util/StormOutputCollector.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/scala/io/gearpump/experiments/storm/util/StormOutputCollector.scala b/experiments/storm/src/main/scala/io/gearpump/experiments/storm/util/StormOutputCollector.scala
deleted file mode 100644
index 74d1b2b..0000000
--- a/experiments/storm/src/main/scala/io/gearpump/experiments/storm/util/StormOutputCollector.scala
+++ /dev/null
@@ -1,221 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.storm.util
-
-import java.util.{ArrayList => JArrayList, Iterator => JIterator, List => JList, Map => JMap}
-import scala.collection.JavaConverters._
-
-import backtype.storm.generated.{GlobalStreamId, Grouping, JavaObject}
-import backtype.storm.grouping.CustomStreamGrouping
-import backtype.storm.task.TopologyContext
-import backtype.storm.tuple.Fields
-import backtype.storm.utils.Utils
-import org.slf4j.Logger
-
-import io.gearpump._
-import io.gearpump.experiments.storm.topology.GearpumpTuple
-import io.gearpump.experiments.storm.util.StormUtil._
-import io.gearpump.streaming.ProcessorId
-import io.gearpump.streaming.task.{TaskContext, TaskId}
-import io.gearpump.util.LogUtil
-
-object StormOutputCollector {
- private val LOG: Logger = LogUtil.getLogger(classOf[StormOutputCollector])
- private[storm] val EMPTY_LIST: JList[Integer] = new JArrayList[Integer](0)
-
- def apply(taskContext: TaskContext, topologyContext: TopologyContext): StormOutputCollector = {
- val stormTaskId = topologyContext.getThisTaskId
- val componentId = topologyContext.getThisComponentId
- val taskToComponent = topologyContext.getTaskToComponent
- val componentToProcessorId = getComponentToProcessorId(taskToComponent.asScala.toMap)
- val targets = topologyContext.getTargets(componentId)
- val streamGroupers: Map[String, Grouper] =
- targets.asScala.flatMap { case (streamId, targetGrouping) =>
- targetGrouping.asScala.collect { case (target, grouping) if !grouping.is_set_direct() =>
- streamId -> getGrouper(topologyContext, grouping, componentId, streamId, target)
- }
- }.toMap
- val getTargetPartitionsFn = (streamId: String, values: JList[AnyRef]) => {
- getTargetPartitions(stormTaskId, streamId, targets,
- streamGroupers, componentToProcessorId, values)
- }
- new StormOutputCollector(stormTaskId, taskToComponent, targets, getTargetPartitionsFn,
- taskContext, LatestTime)
- }
-
- /**
- * get target Gearpump partitions and Storm task ids
- */
- private def getTargetPartitions(
- stormTaskId: Int,
- streamId: String,
- targets: JMap[String, JMap[String, Grouping]],
- streamGroupers: Map[String, Grouper],
- componentToProcessorId: Map[String, ProcessorId],
- values: JList[AnyRef]): (Map[String, Array[Int]], JList[Integer]) = {
- val ret: JList[Integer] = new JArrayList[Integer](targets.size)
-
- @annotation.tailrec
- def getRecur(iter: JIterator[String],
- accum: Map[String, Array[Int]]): Map[String, Array[Int]] = {
- if (iter.hasNext) {
- val target = iter.next
- val grouper = streamGroupers(streamId)
- val partitions = grouper.getPartitions(stormTaskId, values)
- partitions.foreach { p =>
- val stormTaskId = gearpumpTaskIdToStorm(TaskId(componentToProcessorId(target), p))
- ret.add(stormTaskId)
- }
- getRecur(iter, accum + (target -> partitions))
- } else {
- accum
- }
- }
- val targetPartitions = getRecur(targets.get(streamId).keySet().iterator,
- Map.empty[String, Array[Int]])
- (targetPartitions, ret)
- }
-
- private def getComponentToProcessorId(taskToComponent: Map[Integer, String])
- : Map[String, ProcessorId] = {
- taskToComponent.map { case (id, component) =>
- component -> stormTaskIdToGearpump(id).processorId
- }
- }
-
- private def getGrouper(topologyContext: TopologyContext, grouping: Grouping,
- source: String, streamId: String, target: String): Grouper = {
- val outFields = topologyContext.getComponentOutputFields(source, streamId)
- val targetTasks = topologyContext.getComponentTasks(target)
- val targetTaskNum = targetTasks.size
- val globalStreamId = new GlobalStreamId(source, streamId)
-
- grouping.getSetField match {
- case Grouping._Fields.FIELDS =>
- if (isGlobalGrouping(grouping)) {
- new GlobalGrouper
- } else {
- new FieldsGrouper(outFields, new Fields(grouping.get_fields()), targetTaskNum)
- }
- case Grouping._Fields.SHUFFLE =>
- new ShuffleGrouper(targetTaskNum)
- case Grouping._Fields.NONE =>
- new NoneGrouper(targetTaskNum)
- case Grouping._Fields.ALL =>
- new AllGrouper(targetTaskNum)
- case Grouping._Fields.CUSTOM_SERIALIZED =>
- val customGrouping = Utils.javaDeserialize(grouping.get_custom_serialized,
- classOf[Serializable]).asInstanceOf[CustomStreamGrouping]
- val grouper = new CustomGrouper(customGrouping)
- grouper.prepare(topologyContext, globalStreamId, targetTasks)
- grouper
- case Grouping._Fields.CUSTOM_OBJECT =>
- val customObject = grouping.get_custom_object()
- val customGrouping = instantiateJavaObject(customObject)
- val grouper = new CustomGrouper(customGrouping)
- grouper.prepare(topologyContext, globalStreamId, targetTasks)
- grouper
- case Grouping._Fields.LOCAL_OR_SHUFFLE =>
- // Gearpump has built-in support for sending messages to local actor
- new ShuffleGrouper(targetTaskNum)
- case Grouping._Fields.DIRECT =>
- throw new Exception("direct grouping should not be called here")
- }
- }
-
- private def isGlobalGrouping(grouping: Grouping): Boolean = {
- grouping.getSetField == Grouping._Fields.FIELDS &&
- grouping.get_fields.isEmpty
- }
-
- private def instantiateJavaObject(javaObject: JavaObject): CustomStreamGrouping = {
- val className = javaObject.get_full_class_name()
- val args = javaObject.get_args_list().asScala.map(_.getFieldValue)
- val customGrouping = Class.forName(className).getConstructor(args.map(_.getClass): _*)
- .newInstance(args).asInstanceOf[CustomStreamGrouping]
- customGrouping
- }
-}
-
-/**
- * Provides common functionality for
- * [[io.gearpump.experiments.storm.producer.StormSpoutOutputCollector]]
- * and [[io.gearpump.experiments.storm.processor.StormBoltOutputCollector]]
- */
-class StormOutputCollector(
- stormTaskId: Int,
- taskToComponent: JMap[Integer, String],
- targets: JMap[String, JMap[String, Grouping]],
- getTargetPartitionsFn: (String, JList[AnyRef]) => (Map[String, Array[Int]], JList[Integer]),
- val taskContext: TaskContext,
- private var timestamp: TimeStamp) {
- import io.gearpump.experiments.storm.util.StormOutputCollector._
-
- /**
- * Emits tuple values into a stream (invoked by a Storm output collector).
- *
- * wrapS the values into a message of [[GearpumpTuple]] along with the target partitions
- * to tell [[io.gearpump.experiments.storm.partitioner.StormPartitioner]] where to send the
- * message. We also return the corresponding target Storm task ids back to the collector
- *
- * @param streamId Storm stream id
- * @param values Storm tuple values
- * @return Target Storm task ids
- */
- def emit(streamId: String, values: JList[AnyRef]): JList[Integer] = {
- if (targets.containsKey(streamId)) {
- val (targetPartitions, targetStormTaskIds) = getTargetPartitionsFn(streamId, values)
- val tuple = new GearpumpTuple(values, stormTaskId, streamId, targetPartitions)
- taskContext.output(Message(tuple, timestamp))
- targetStormTaskIds
- } else {
- EMPTY_LIST
- }
- }
-
- /**
- * Emit tuple values to a specific Storm task (invoked by Storm output collector).
- *
- * We translate the Storm task id into Gearpump TaskId and tell
- * [[io.gearpump.experiments.storm.partitioner.StormPartitioner]] through the targetPartitions
- * field of [[io.gearpump.experiments.storm.topology.GearpumpTuple]]
- *
- * @param id Storm task id
- * @param streamId Storm stream id
- * @param values Storm tuple values
- */
- def emitDirect(id: Int, streamId: String, values: JList[AnyRef]): Unit = {
- if (targets.containsKey(streamId)) {
- val target = taskToComponent.get(id)
- val partition = stormTaskIdToGearpump(id).index
- val targetPartitions = Map(target -> Array(partition))
- val tuple = new GearpumpTuple(values, stormTaskId, streamId, targetPartitions)
- taskContext.output(Message(tuple, timestamp))
- }
- }
-
- /**
- * set timestamp from each incoming Message if not attached.
- */
- def setTimestamp(timestamp: TimeStamp): Unit = {
- this.timestamp = timestamp
- }
-
- def getTimestamp: Long = timestamp
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/scala/io/gearpump/experiments/storm/util/StormSerializationFramework.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/scala/io/gearpump/experiments/storm/util/StormSerializationFramework.scala b/experiments/storm/src/main/scala/io/gearpump/experiments/storm/util/StormSerializationFramework.scala
deleted file mode 100644
index f1c7bab..0000000
--- a/experiments/storm/src/main/scala/io/gearpump/experiments/storm/util/StormSerializationFramework.scala
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.experiments.storm.util
-
-import java.lang.{Integer => JInteger}
-import java.util.{Map => JMap}
-
-import akka.actor.ExtendedActorSystem
-import backtype.storm.serialization.SerializationFactory
-import backtype.storm.utils.ListDelegate
-import com.esotericsoftware.kryo.Kryo
-import com.esotericsoftware.kryo.io.{Input, Output}
-
-import io.gearpump.cluster.UserConfig
-import io.gearpump.experiments.storm.topology.GearpumpTuple
-import io.gearpump.experiments.storm.util.StormConstants._
-import io.gearpump.serializer.{SerializationFramework, Serializer}
-
-class StormSerializationFramework extends SerializationFramework {
- private var stormConfig: JMap[AnyRef, AnyRef] = null
- private var pool: ThreadLocal[Serializer] = null
-
- override def init(system: ExtendedActorSystem, config: UserConfig): Unit = {
- implicit val actorSystem = system
- stormConfig = config.getValue[JMap[AnyRef, AnyRef]](STORM_CONFIG).get
- pool = new ThreadLocal[Serializer]() {
- override def initialValue(): Serializer = {
- val kryo = SerializationFactory.getKryo(stormConfig)
- new StormSerializer(kryo)
- }
- }
- }
-
- override def get(): Serializer = {
- pool.get()
- }
-}
-
-/**
- * serializes / deserializes [[io.gearpump.experiments.storm.topology.GearpumpTuple]]
- *
- * @param kryo created by Storm [[backtype.storm.serialization.SerializationFactory]]
- */
-class StormSerializer(kryo: Kryo) extends Serializer {
- // -1 means the max buffer size is 2147483647
- private val output = new Output(4096, -1)
- private val input = new Input
-
- override def serialize(message: Any): Array[Byte] = {
- val tuple = message.asInstanceOf[GearpumpTuple]
- output.clear()
- output.writeInt(tuple.sourceTaskId)
- output.writeString(tuple.sourceStreamId)
- val listDelegate = new ListDelegate
- listDelegate.setDelegate(tuple.values)
- kryo.writeObject(output, listDelegate)
- output.toBytes
- }
-
- override def deserialize(msg: Array[Byte]): Any = {
- input.setBuffer(msg)
- val sourceTaskId: JInteger = input.readInt
- val sourceStreamId: String = input.readString
- val listDelegate = kryo.readObject[ListDelegate](input, classOf[ListDelegate])
- new GearpumpTuple(listDelegate.getDelegate, sourceTaskId, sourceStreamId, null)
- }
-}
[14/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/main/scala/org/apache/gearpump/services/MasterService.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/main/scala/org/apache/gearpump/services/MasterService.scala b/services/jvm/src/main/scala/org/apache/gearpump/services/MasterService.scala
new file mode 100644
index 0000000..32c9f08
--- /dev/null
+++ b/services/jvm/src/main/scala/org/apache/gearpump/services/MasterService.scala
@@ -0,0 +1,350 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.services
+
+import java.io.{File, IOException}
+import java.nio.charset.StandardCharsets.UTF_8
+import java.nio.file.Files
+import java.nio.file.StandardOpenOption.{APPEND, WRITE}
+import scala.collection.JavaConverters._
+import scala.concurrent.Future
+import scala.util.{Failure, Success}
+
+import akka.actor.{ActorRef, ActorSystem}
+import akka.http.scaladsl.server.Directives._
+import akka.http.scaladsl.server.directives.ParameterDirectives.ParamMagnet
+import akka.http.scaladsl.unmarshalling.Unmarshaller._
+import akka.stream.Materializer
+import com.typesafe.config.Config
+
+import org.apache.gearpump.cluster.AppMasterToMaster.{GetAllWorkers, GetMasterData, GetWorkerData, MasterData, WorkerData}
+import org.apache.gearpump.cluster.ClientToMaster.{QueryHistoryMetrics, QueryMasterConfig, ReadOption}
+import org.apache.gearpump.cluster.MasterToAppMaster.{AppMastersData, AppMastersDataRequest, WorkerList}
+import org.apache.gearpump.cluster.MasterToClient.{HistoryMetrics, MasterConfig, SubmitApplicationResultValue}
+import org.apache.gearpump.cluster.client.ClientContext
+import org.apache.gearpump.cluster.worker.WorkerSummary
+import org.apache.gearpump.cluster.{ClusterConfig, UserConfig}
+import org.apache.gearpump.jarstore.JarStoreService
+import org.apache.gearpump.partitioner.{PartitionerByClassName, PartitionerDescription}
+import org.apache.gearpump.services.MasterService.{BuiltinPartitioners, SubmitApplicationRequest}
+// NOTE: This cannot be removed!!!
+import org.apache.gearpump.services.util.UpickleUtil._
+import org.apache.gearpump.streaming.{ProcessorDescription, ProcessorId, StreamApplication}
+import org.apache.gearpump.util.ActorUtil._
+import org.apache.gearpump.util.FileDirective._
+import org.apache.gearpump.util.{Constants, Graph, Util}
+
+/** Manages service for master node */
+class MasterService(val master: ActorRef,
+ val jarStore: JarStoreService, override val system: ActorSystem)
+ extends BasicService {
+
+ import upickle.default.{read, write}
+
+ private val systemConfig = system.settings.config
+ private val concise = systemConfig.getBoolean(Constants.GEARPUMP_SERVICE_RENDER_CONFIG_CONCISE)
+
+ protected override def doRoute(implicit mat: Materializer) = pathPrefix("master") {
+ pathEnd {
+ get {
+ onComplete(askActor[MasterData](master, GetMasterData)) {
+ case Success(value: MasterData) => complete(write(value))
+ case Failure(ex) => failWith(ex)
+ }
+ }
+ } ~
+ path("applist") {
+ onComplete(askActor[AppMastersData](master, AppMastersDataRequest)) {
+ case Success(value: AppMastersData) =>
+ complete(write(value))
+ case Failure(ex) => failWith(ex)
+ }
+ } ~
+ path("workerlist") {
+ def future: Future[List[WorkerSummary]] = askActor[WorkerList](master, GetAllWorkers)
+ .flatMap { workerList =>
+ val workers = workerList.workers
+ val workerDataList = List.empty[WorkerSummary]
+
+ Future.fold(workers.map { workerId =>
+ askWorker[WorkerData](master, workerId, GetWorkerData(workerId))
+ })(workerDataList) { (workerDataList, workerData) =>
+ workerDataList :+ workerData.workerDescription
+ }
+ }
+ onComplete(future) {
+ case Success(result: List[WorkerSummary]) => complete(write(result))
+ case Failure(ex) => failWith(ex)
+ }
+ } ~
+ path("config") {
+ onComplete(askActor[MasterConfig](master, QueryMasterConfig)) {
+ case Success(value: MasterConfig) =>
+ val config = Option(value.config).map(ClusterConfig.render(_, concise)).getOrElse("{}")
+ complete(config)
+ case Failure(ex) =>
+ failWith(ex)
+ }
+ } ~
+ path("metrics" / RestPath) { path =>
+ parameters(ParamMagnet(ReadOption.Key ? ReadOption.ReadLatest)) { readOption: String =>
+ val query = QueryHistoryMetrics(path.head.toString, readOption)
+ onComplete(askActor[HistoryMetrics](master, query)) {
+ case Success(value) =>
+ complete(write(value))
+ case Failure(ex) =>
+ failWith(ex)
+ }
+ }
+ } ~
+ path("submitapp") {
+ post {
+ uploadFile { form =>
+ val jar = form.getFile("jar").map(_.file)
+ val configFile = form.getFile("configfile").map(_.file)
+ val configString = form.getValue("configstring").getOrElse("")
+ val executorCount = form.getValue("executorcount").getOrElse("1").toInt
+ val args = form.getValue("args").getOrElse("")
+
+ val mergedConfigFile = mergeConfig(configFile, configString)
+
+ onComplete(Future(
+ MasterService.submitGearApp(jar, executorCount, args, systemConfig, mergedConfigFile)
+ )) {
+ case Success(success) =>
+ val response = MasterService.AppSubmissionResult(success)
+ complete(write(response))
+ case Failure(ex) =>
+ failWith(ex)
+ }
+ }
+ }
+ } ~
+ path("submitstormapp") {
+ post {
+ uploadFile { form =>
+ val jar = form.getFile("jar").map(_.file)
+ val configFile = form.getFile("configfile").map(_.file)
+ val args = form.getValue("args").getOrElse("")
+ onComplete(Future(
+ MasterService.submitStormApp(jar, configFile, args, systemConfig)
+ )) {
+ case Success(success) =>
+ val response = MasterService.AppSubmissionResult(success)
+ complete(write(response))
+ case Failure(ex) =>
+ failWith(ex)
+ }
+ }
+ }
+ } ~
+ path("submitdag") {
+ post {
+ entity(as[String]) { request =>
+ val msg = java.net.URLDecoder.decode(request, "UTF-8")
+ val submitApplicationRequest = read[SubmitApplicationRequest](msg)
+ import submitApplicationRequest.{appName, dag, processors, userconfig}
+ val context = ClientContext(system.settings.config, system, master)
+
+ val graph = dag.mapVertex { processorId =>
+ processors(processorId)
+ }.mapEdge { (node1, edge, node2) =>
+ PartitionerDescription(new PartitionerByClassName(edge))
+ }
+
+ val effectiveConfig = if (userconfig == null) UserConfig.empty else userconfig
+ val appId = context.submit(new StreamApplication(appName, effectiveConfig, graph))
+
+ import upickle.default.write
+ val submitApplicationResultValue = SubmitApplicationResultValue(appId)
+ val jsonData = write(submitApplicationResultValue)
+ complete(jsonData)
+ }
+ }
+ } ~
+ path("uploadjar") {
+ uploadFile { form =>
+ val jar = form.getFile("jar").map(_.file)
+ if (jar.isEmpty) {
+ complete(write(
+ MasterService.Status(success = false, reason = "Jar file not found")))
+ } else {
+ val jarFile = Util.uploadJar(jar.get, jarStore)
+ complete(write(jarFile))
+ }
+ }
+ } ~
+ path("partitioners") {
+ get {
+ complete(write(BuiltinPartitioners(Constants.BUILTIN_PARTITIONERS.map(_.getName))))
+ }
+ }
+ }
+
+ private def mergeConfig(configFile: Option[File], configString: String): Option[File] = {
+ if (configString == null || configString.isEmpty) {
+ configFile
+ } else {
+ configFile match {
+ case Some(file) =>
+ Files.write(file.toPath, ("\n" + configString).getBytes(UTF_8), APPEND)
+ Some(file)
+ case None =>
+ val file = File.createTempFile("\"userfile_configstring_", ".conf")
+ Files.write(file.toPath, configString.getBytes(UTF_8), WRITE)
+ Some(file)
+ }
+ }
+ }
+}
+
+object MasterService {
+
+ case class BuiltinPartitioners(partitioners: Array[String])
+
+ case class AppSubmissionResult(success: Boolean)
+
+ case class Status(success: Boolean, reason: String = null)
+
+ /**
+ * Submits Native Application.
+ */
+ def submitGearApp(
+ jar: Option[File], executorNum: Int, args: String,
+ systemConfig: Config, userConfigFile: Option[File]): Boolean = {
+ submitAndDeleteTempFiles(
+ "org.apache.gearpump.cluster.main.AppSubmitter",
+ argsArray = Array("-executors", executorNum.toString) ++ spaceSeparatedArgumentsToArray(args),
+ fileMap = Map("jar" -> jar).filter(_._2.isDefined).mapValues(_.get),
+ classPath = getUserApplicationClassPath,
+ systemConfig,
+ userConfigFile
+ )
+ }
+
+ /**
+ * Submits Storm application.
+ */
+ def submitStormApp(
+ jar: Option[File], stormConf: Option[File], args: String, systemConfig: Config): Boolean = {
+ submitAndDeleteTempFiles(
+ "org.apache.gearpump.experiments.storm.main.GearpumpStormClient",
+ argsArray = spaceSeparatedArgumentsToArray(args),
+ fileMap = Map("jar" -> jar, "config" -> stormConf).filter(_._2.isDefined).mapValues(_.get),
+ classPath = getStormApplicationClassPath,
+ systemConfig,
+ userConfigFile = None
+ )
+ }
+
+ private def submitAndDeleteTempFiles(
+ mainClass: String, argsArray: Array[String], fileMap: Map[String, File],
+ classPath: Array[String], systemConfig: Config,
+ userConfigFile: Option[File] = None): Boolean = {
+ try {
+ val jar = fileMap.get("jar")
+ if (jar.isEmpty) {
+ throw new IOException("JAR file not supplied")
+ }
+
+ val process = Util.startProcess(
+ clusterOptions(systemConfig, userConfigFile),
+ classPath,
+ mainClass,
+ arguments = createFilePathArgArray(fileMap) ++ argsArray
+ )
+
+ val retval = process.exitValue()
+ if (retval != 0) {
+ throw new IOException(s"Process exit abnormally with exit code $retval.\n" +
+ s"Error message: ${process.logger.error}")
+ }
+ true
+ } finally {
+ fileMap.values.foreach(_.delete)
+ if (userConfigFile.isDefined) {
+ userConfigFile.get.delete()
+ }
+ }
+ }
+
+ /**
+ * Returns Java options for gearpump cluster
+ */
+ private def clusterOptions(systemConfig: Config, userConfigFile: Option[File]): Array[String] = {
+ var options = Array(
+ s"-D${Constants.GEARPUMP_HOME}=${systemConfig.getString(Constants.GEARPUMP_HOME)}",
+ s"-D${Constants.GEARPUMP_HOSTNAME}=${systemConfig.getString(Constants.GEARPUMP_HOSTNAME)}",
+ s"-D${Constants.PREFER_IPV4}=true"
+ )
+
+ val masters = systemConfig.getStringList(Constants.GEARPUMP_CLUSTER_MASTERS).asScala
+ .toList.flatMap(Util.parseHostList)
+ options ++= masters.zipWithIndex.map { case (master, index) =>
+ s"-D${Constants.GEARPUMP_CLUSTER_MASTERS}.$index=${master.host}:${master.port}"
+ }.toArray[String]
+
+ if (userConfigFile.isDefined) {
+ options :+= s"-D${Constants.GEARPUMP_CUSTOM_CONFIG_FILE}=${userConfigFile.get.getPath}"
+ }
+ options
+ }
+
+ /**
+ * Filter all defined file paths and store their config key and path into an array.
+ */
+ private def createFilePathArgArray(fileMap: Map[String, File]): Array[String] = {
+ var args = Array.empty[String]
+ fileMap.foreach({ case (key, path) =>
+ args ++= Array(s"-$key", path.getPath)
+ })
+ args
+ }
+
+ /**
+ * Returns a space separated arguments as an array.
+ */
+ private def spaceSeparatedArgumentsToArray(str: String): Array[String] = {
+ str.split(" +").filter(_.nonEmpty)
+ }
+
+ private val homeDir = System.getProperty(Constants.GEARPUMP_HOME) + "/"
+ private val libHomeDir = homeDir + "lib/"
+
+ private def getUserApplicationClassPath: Array[String] = {
+ Array(
+ homeDir + "conf",
+ libHomeDir + "daemon/*",
+ libHomeDir + "yarn/*",
+ libHomeDir + "*"
+ )
+ }
+
+ private def getStormApplicationClassPath: Array[String] = {
+ getUserApplicationClassPath ++ Array(
+ libHomeDir + "storm/*"
+ )
+ }
+
+ case class SubmitApplicationRequest(
+ appName: String,
+ processors: Map[ProcessorId, ProcessorDescription],
+ dag: Graph[Int, String],
+ userconfig: UserConfig)
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/main/scala/org/apache/gearpump/services/RestServices.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/main/scala/org/apache/gearpump/services/RestServices.scala b/services/jvm/src/main/scala/org/apache/gearpump/services/RestServices.scala
new file mode 100644
index 0000000..87f9e34
--- /dev/null
+++ b/services/jvm/src/main/scala/org/apache/gearpump/services/RestServices.scala
@@ -0,0 +1,105 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.services
+
+import scala.concurrent.Await
+import scala.concurrent.duration._
+
+import akka.actor.{ActorRef, ActorSystem}
+import akka.http.scaladsl.model.StatusCodes._
+import akka.http.scaladsl.server.Directives._
+import akka.http.scaladsl.server.{Route, _}
+import akka.stream.ActorMaterializer
+import akka.util.Timeout
+import org.apache.commons.lang.exception.ExceptionUtils
+
+import org.apache.gearpump.jarstore.JarStoreService
+import org.apache.gearpump.util.{Constants, LogUtil}
+// NOTE: This cannot be removed!!!
+import org.apache.gearpump.services.util.UpickleUtil._
+
+/** Contains all REST API service endpoints */
+class RestServices(master: ActorRef, mat: ActorMaterializer, system: ActorSystem)
+ extends RouteService {
+
+ implicit val timeout = Constants.FUTURE_TIMEOUT
+
+ private val config = system.settings.config
+
+ private val jarStoreService = JarStoreService.get(config)
+ jarStoreService.init(config, system)
+
+ private val LOG = LogUtil.getLogger(getClass)
+
+ private val securityEnabled = config.getBoolean(
+ Constants.GEARPUMP_UI_SECURITY_AUTHENTICATION_ENABLED)
+
+ private val supervisorPath = system.settings.config.getString(
+ Constants.GEARPUMP_SERVICE_SUPERVISOR_PATH)
+
+ private val myExceptionHandler: ExceptionHandler = ExceptionHandler {
+ case ex: Throwable => {
+ extractUri { uri =>
+ LOG.error(s"Request to $uri could not be handled normally", ex)
+ complete(InternalServerError, ExceptionUtils.getStackTrace(ex))
+ }
+ }
+ }
+
+ // Makes sure staticRoute is the final one, as it will try to lookup resource in local path
+ // if there is no match in previous routes
+ private val static = new StaticService(system, supervisorPath).route
+
+ def supervisor: ActorRef = {
+ if (supervisorPath == null || supervisorPath.isEmpty()) {
+ null
+ } else {
+ val actorRef = system.actorSelection(supervisorPath).resolveOne()
+ Await.result(actorRef, new Timeout(Duration.create(5, "seconds")).duration)
+ }
+ }
+
+ override def route: Route = {
+ if (securityEnabled) {
+ val security = new SecurityService(services, system)
+ handleExceptions(myExceptionHandler) {
+ security.route ~ static
+ }
+ } else {
+ handleExceptions(myExceptionHandler) {
+ services.route ~ static
+ }
+ }
+ }
+
+ private def services: RouteService = {
+
+ val admin = new AdminService(system)
+ val masterService = new MasterService(master, jarStoreService, system)
+ val worker = new WorkerService(master, system)
+ val app = new AppMasterService(master, jarStoreService, system)
+ val sup = new SupervisorService(master, supervisor, system)
+
+ new RouteService {
+ override def route: Route = {
+ admin.route ~ sup.route ~ masterService.route ~ worker.route ~ app.route
+ }
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/main/scala/org/apache/gearpump/services/SecurityService.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/main/scala/org/apache/gearpump/services/SecurityService.scala b/services/jvm/src/main/scala/org/apache/gearpump/services/SecurityService.scala
new file mode 100644
index 0000000..804b34f
--- /dev/null
+++ b/services/jvm/src/main/scala/org/apache/gearpump/services/SecurityService.scala
@@ -0,0 +1,290 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.services
+
+import scala.concurrent.{ExecutionContext, Future}
+import scala.util.{Failure, Success, Try}
+
+import akka.actor.ActorSystem
+import akka.http.scaladsl.model.headers.{HttpChallenge, HttpCookie, HttpCookiePair}
+import akka.http.scaladsl.model.{RemoteAddress, StatusCodes, Uri}
+import akka.http.scaladsl.server.AuthenticationFailedRejection.{CredentialsMissing, CredentialsRejected}
+import akka.http.scaladsl.server.Directives._
+import akka.http.scaladsl.server._
+import akka.http.scaladsl.server.directives.FormFieldDirectives.FieldMagnet
+import akka.stream.Materializer
+import com.typesafe.config.Config
+import com.softwaremill.session.SessionDirectives._
+import com.softwaremill.session.SessionOptions._
+import com.softwaremill.session.{MultiValueSessionSerializer, SessionConfig, SessionManager}
+import upickle.default.write
+
+import org.apache.gearpump.security.{Authenticator => BaseAuthenticator}
+import org.apache.gearpump.services.SecurityService.{User, UserSession}
+import org.apache.gearpump.services.security.oauth2.OAuth2Authenticator
+import org.apache.gearpump.util.{Constants, LogUtil}
+// NOTE: This cannot be removed!!!
+import org.apache.gearpump.services.util.UpickleUtil._
+
+/**
+ * Security authentication endpoint.
+ *
+ * - When user cannot be authenticated, will reject with 401 AuthenticationFailedRejection
+ * - When user can be authenticated, but are not authorized to access certail resource, will
+ * return a 405 AuthorizationFailedRejection.
+ * - When web UI frontend receive 401, it should redirect the UI to login page.
+ * - When web UI receive 405,it should display errors like
+ * "current user is not authorized to access this resource."
+ *
+ * The Authenticator used is pluggable, the current Authenticator is resolved by looking up
+ * config path [[org.apache.gearpump.util.Constants.GEARPUMP_UI_AUTHENTICATOR_CLASS]].
+ *
+ * See [[org.apache.gearpump.security.Authenticator]] to find more info on custom Authenticator.
+ */
+class SecurityService(inner: RouteService, implicit val system: ActorSystem) extends RouteService {
+
+ // Use scheme "GearpumpBasic" to avoid popping up web browser native authentication box.
+ private val challenge = HttpChallenge(scheme = "GearpumpBasic", realm = "gearpump",
+ params = Map.empty)
+
+ val LOG = LogUtil.getLogger(getClass, "AUDIT")
+
+ private val config = system.settings.config
+ private val sessionConfig = SessionConfig.fromConfig(config)
+ private implicit val sessionManager: SessionManager[UserSession] =
+ new SessionManager[UserSession](sessionConfig)
+
+ private val authenticator = {
+ val clazz = Class.forName(config.getString(Constants.GEARPUMP_UI_AUTHENTICATOR_CLASS))
+ val constructor = clazz.getConstructor(classOf[Config])
+ val authenticator = constructor.newInstance(config).asInstanceOf[BaseAuthenticator]
+ authenticator
+ }
+
+ private def configToMap(config: Config, path: String) = {
+ import scala.collection.JavaConverters._
+ config.getConfig(path).root.unwrapped.asScala.toMap map { case (k, v) => k -> v.toString }
+ }
+
+ private val oauth2Providers: Map[String, String] = {
+ if (config.getBoolean(Constants.GEARPUMP_UI_OAUTH2_AUTHENTICATOR_ENABLED)) {
+ val map = configToMap(config, Constants.GEARPUMP_UI_OAUTH2_AUTHENTICATORS)
+ map.keys.toList.map { key =>
+ val iconPath = config.getString(s"${Constants.GEARPUMP_UI_OAUTH2_AUTHENTICATORS}.$key.icon")
+ (key, iconPath)
+ }.toMap
+ } else {
+ Map.empty[String, String]
+ }
+ }
+
+ private def authenticate(user: String, pass: String)(implicit ec: ExecutionContext)
+ : Future[Option[UserSession]] = {
+ authenticator.authenticate(user, pass, ec).map { result =>
+ if (result.authenticated) {
+ Some(UserSession(user, result.permissionLevel))
+ } else {
+ None
+ }
+ }
+ }
+
+ private def rejectMissingCredentials: Route = {
+ reject(AuthenticationFailedRejection(CredentialsMissing, challenge))
+ }
+
+ private def rejectWrongCredentials: Route = {
+ reject(AuthenticationFailedRejection(CredentialsRejected, challenge))
+ }
+
+ private def requireAuthentication(inner: UserSession => Route): Route = {
+ optionalSession(oneOff, usingCookiesOrHeaders) { sessionOption =>
+ sessionOption match {
+ case Some(session) => {
+ inner(session)
+ }
+ case None =>
+ rejectMissingCredentials
+ }
+ }
+ }
+
+ private def login(session: UserSession, ip: String, redirectToRoot: Boolean = false): Route = {
+ setSession(oneOff, usingCookies, session) {
+ val user = session.user
+ // Default: 1 day
+ val maxAgeMs = 1000 * sessionConfig.sessionMaxAgeSeconds.getOrElse(24 * 3600L)
+ setCookie(HttpCookie.fromPair(HttpCookiePair("username", user), path = Some("/"),
+ maxAge = Some(maxAgeMs))) {
+ LOG.info(s"user $user login from $ip")
+ if (redirectToRoot) {
+ redirect(Uri("/"), StatusCodes.TemporaryRedirect)
+ } else {
+ complete(write(new User(user)))
+ }
+ }
+ }
+ }
+
+ private def logout(user: UserSession, ip: String): Route = {
+ invalidateSession(oneOff, usingCookies) { ctx =>
+ LOG.info(s"user ${user.user} logout from $ip")
+ ctx.complete(write(new User(user.user)))
+ }
+ }
+
+ // Only admin are able to access operation like post/delete/put
+ private def requireAuthorization(user: UserSession, route: => Route): Route = {
+ // Valid user
+ if (user.permissionLevel >= BaseAuthenticator.User.permissionLevel) {
+ route
+ } else {
+ // Possibly a guest or not authenticated.
+ (put | delete | post) {
+ // Reject with 405 authorization error
+ reject(AuthorizationFailedRejection)
+ } ~
+ get {
+ route
+ }
+ }
+ }
+
+ private val unknownIp: Directive1[RemoteAddress] = {
+ Directive[Tuple1[RemoteAddress]]{ inner =>
+ inner(new Tuple1(RemoteAddress.Unknown))
+ }
+ }
+
+ override val route: Route = {
+
+ extractExecutionContext{implicit ec: ExecutionContext =>
+ extractMaterializer{implicit mat: Materializer =>
+ (extractClientIP | unknownIp) { ip =>
+ pathPrefix("login") {
+ pathEndOrSingleSlash {
+ get {
+ getFromResource("login/login.html")
+ } ~
+ post {
+ // Guest account don't have permission to submit new application in UI
+ formField(FieldMagnet('username.as[String])) {user: String =>
+ formFields(FieldMagnet('password.as[String])) {pass: String =>
+ val result = authenticate(user, pass)
+ onSuccess(result) {
+ case Some(session) =>
+ login(session, ip.toString)
+ case None =>
+ rejectWrongCredentials
+ }
+ }
+ }
+ }
+ } ~
+ path ("oauth2" / "providers") {
+ // Responds with a list of OAuth2 providers.
+ complete(write(oauth2Providers))
+ } ~
+ // Support OAUTH Authentication
+ pathPrefix ("oauth2"/ Segment) {providerName =>
+ // Resolve OAUTH Authentication Provider
+ val oauthService = OAuth2Authenticator.get(config, providerName, ec)
+
+ if (oauthService == null) {
+ // OAuth2 is disabled.
+ complete(StatusCodes.NotFound)
+ } else {
+
+ def loginWithOAuth2Parameters(parameters: Map[String, String]): Route = {
+ val result = oauthService.authenticate(parameters)
+ onComplete(result) {
+ case Success(session) =>
+ login(session, ip.toString, redirectToRoot = true)
+ case Failure(ex) => {
+ LOG.info(s"Failed to login user from ${ip.toString}", ex)
+ rejectWrongCredentials
+ }
+ }
+ }
+
+ path ("authorize") {
+ // Redirects to OAuth2 service provider for authorization.
+ redirect(Uri(oauthService.getAuthorizationUrl), StatusCodes.TemporaryRedirect)
+ } ~
+ path ("accesstoken") {
+ post {
+ // Guest account don't have permission to submit new application in UI
+ formField(FieldMagnet('accesstoken.as[String])) {accesstoken: String =>
+ loginWithOAuth2Parameters(Map("accesstoken" -> accesstoken))
+ }
+ }
+ } ~
+ path("callback") {
+ // Login with authorization code or access token.
+ parameterMap {parameters =>
+ loginWithOAuth2Parameters(parameters)
+ }
+ }
+ }
+ }
+ } ~
+ path("logout") {
+ post {
+ requireAuthentication {session =>
+ logout(session, ip.toString())
+ }
+ }
+ } ~
+ requireAuthentication {user =>
+ requireAuthorization(user, inner.route)
+ }
+ }}}
+
+ }
+}
+
+object SecurityService {
+
+ val SESSION_MANAGER_KEY = "akka.http.session.server-secret"
+
+ case class UserSession(user: String, permissionLevel: Int)
+
+ object UserSession {
+
+ private val User = "user"
+ private val PermissionLevel = "permissionLevel"
+
+ implicit def serializer: MultiValueSessionSerializer[UserSession] = {
+ new MultiValueSessionSerializer[UserSession](
+ toMap = {t: UserSession =>
+ Map(User -> t.user, PermissionLevel -> t.permissionLevel.toString)
+ },
+ fromMap = {m: Map[String, String] =>
+ if (m.contains(User)) {
+ Try(UserSession(m(User), m(PermissionLevel).toInt))
+ } else {
+ Failure[UserSession](new Exception("Fail to parse session "))
+ }
+ }
+ )
+ }
+ }
+
+ case class User(user: String)
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/main/scala/org/apache/gearpump/services/StaticService.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/main/scala/org/apache/gearpump/services/StaticService.scala b/services/jvm/src/main/scala/org/apache/gearpump/services/StaticService.scala
new file mode 100644
index 0000000..284d3f2
--- /dev/null
+++ b/services/jvm/src/main/scala/org/apache/gearpump/services/StaticService.scala
@@ -0,0 +1,70 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.services
+
+import akka.actor.ActorSystem
+import akka.http.scaladsl.model._
+import akka.http.scaladsl.server.Directives._
+import akka.stream.Materializer
+
+import org.apache.gearpump.util.Util
+// NOTE: This cannot be removed!!!
+import org.apache.gearpump.services.util.UpickleUtil._
+
+/**
+ * static resource files.
+ */
+class StaticService(override val system: ActorSystem, supervisorPath: String)
+ extends BasicService {
+
+ private val version = Util.version
+
+ protected override def prefix = Neutral
+
+ override def cache: Boolean = true
+
+ protected override def doRoute(implicit mat: Materializer) = {
+ path("version") {
+ get { ctx =>
+ ctx.complete(version)
+ }
+ } ~
+ // For YARN usage, we need to make sure supervisor-path
+ // can be accessed without authentication.
+ path("supervisor-actor-path") {
+ get {
+ complete(supervisorPath)
+ }
+ } ~
+ pathEndOrSingleSlash {
+ getFromResource("index.html")
+ } ~
+ path("favicon.ico") {
+ complete(StatusCodes.NotFound)
+ } ~
+ pathPrefix("webjars") {
+ get {
+ getFromResourceDirectory("META-INF/resources/webjars")
+ }
+ } ~
+ path(Rest) { path =>
+ getFromResource("%s" format path)
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/main/scala/org/apache/gearpump/services/SupervisorService.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/main/scala/org/apache/gearpump/services/SupervisorService.scala b/services/jvm/src/main/scala/org/apache/gearpump/services/SupervisorService.scala
new file mode 100644
index 0000000..fecf5ad
--- /dev/null
+++ b/services/jvm/src/main/scala/org/apache/gearpump/services/SupervisorService.scala
@@ -0,0 +1,116 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.services
+
+import scala.concurrent.Future
+import scala.util.{Failure, Success}
+
+import akka.actor.{ActorRef, ActorSystem}
+import akka.http.scaladsl.server.Directives._
+import akka.http.scaladsl.server.Route
+import akka.stream.Materializer
+
+import org.apache.gearpump.cluster.AppMasterToMaster.{GetWorkerData, WorkerData}
+import org.apache.gearpump.cluster.ClientToMaster._
+import org.apache.gearpump.cluster.worker.WorkerId
+import org.apache.gearpump.services.SupervisorService.{Path, Status}
+import org.apache.gearpump.util.ActorUtil._
+// NOTE: This cannot be removed!!!
+import org.apache.gearpump.services.util.UpickleUtil._
+
+/** Responsible for adding/removing machines. Typically it delegates to YARN. */
+class SupervisorService(
+ val master: ActorRef, val supervisor: ActorRef, override val system: ActorSystem)
+ extends BasicService {
+
+ import upickle.default.write
+
+ /**
+ * TODO: Add additional check to ensure the user have enough authorization to
+ * add/remove a worker machine
+ */
+ private def authorize(internal: Route): Route = {
+ if (supervisor == null) {
+ failWith(new Exception("API not enabled, cannot find a valid supervisor! " +
+ "Please make sure Gearpump is running on top of YARN or other resource managers"))
+ } else {
+ internal
+ }
+ }
+
+ protected override def doRoute(implicit mat: Materializer) = pathPrefix("supervisor") {
+ pathEnd {
+ get {
+ val path = if (supervisor == null) {
+ null
+ } else {
+ supervisor.path.toString
+ }
+ complete(write(Path(path)))
+ }
+ } ~
+ path("status") {
+ post {
+ if (supervisor == null) {
+ complete(write(Status(enabled = false)))
+ } else {
+ complete(write(Status(enabled = true)))
+ }
+ }
+ } ~
+ path("addworker" / IntNumber) { workerCount =>
+ post {
+ authorize {
+ onComplete(askActor[CommandResult](supervisor, AddWorker(workerCount))) {
+ case Success(value) =>
+ complete(write(value))
+ case Failure(ex) =>
+ failWith(ex)
+ }
+ }
+ }
+ } ~
+ path("removeworker" / Segment) { workerIdString =>
+ post {
+ authorize {
+ val workerId = WorkerId.parse(workerIdString)
+ def future(): Future[CommandResult] = {
+ askWorker[WorkerData](master, workerId, GetWorkerData(workerId)).flatMap{workerData =>
+ val containerId = workerData.workerDescription.resourceManagerContainerId
+ askActor[CommandResult](supervisor, RemoveWorker(containerId))
+ }
+ }
+
+ onComplete[CommandResult](future()) {
+ case Success(value) =>
+ complete(write(value))
+ case Failure(ex) =>
+ failWith(ex)
+ }
+ }
+ }
+ }
+ }
+}
+
+object SupervisorService {
+ case class Status(enabled: Boolean)
+
+ case class Path(path: String)
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/main/scala/org/apache/gearpump/services/WorkerService.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/main/scala/org/apache/gearpump/services/WorkerService.scala b/services/jvm/src/main/scala/org/apache/gearpump/services/WorkerService.scala
new file mode 100644
index 0000000..8268d61
--- /dev/null
+++ b/services/jvm/src/main/scala/org/apache/gearpump/services/WorkerService.scala
@@ -0,0 +1,79 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.services
+
+import scala.util.{Failure, Success}
+
+import akka.actor.{ActorRef, ActorSystem}
+import akka.http.scaladsl.server.Directives._
+import akka.stream.Materializer
+
+import org.apache.gearpump.cluster.AppMasterToMaster.{GetWorkerData, WorkerData}
+import org.apache.gearpump.cluster.ClientToMaster.{QueryHistoryMetrics, QueryWorkerConfig, ReadOption}
+import org.apache.gearpump.cluster.ClusterConfig
+import org.apache.gearpump.cluster.MasterToClient.{HistoryMetrics, WorkerConfig}
+import org.apache.gearpump.cluster.worker.WorkerId
+import org.apache.gearpump.util.ActorUtil._
+import org.apache.gearpump.util.Constants
+// NOTE: This cannot be removed!!!
+import org.apache.gearpump.services.util.UpickleUtil._
+
+/** Service to handle worker related queries */
+class WorkerService(val master: ActorRef, override val system: ActorSystem)
+ extends BasicService {
+
+ import upickle.default.write
+ private val systemConfig = system.settings.config
+ private val concise = systemConfig.getBoolean(Constants.GEARPUMP_SERVICE_RENDER_CONFIG_CONCISE)
+
+ protected override def doRoute(implicit mat: Materializer) = pathPrefix("worker" / Segment) {
+ workerIdString => {
+ pathEnd {
+ val workerId = WorkerId.parse(workerIdString)
+ onComplete(askWorker[WorkerData](master, workerId, GetWorkerData(workerId))) {
+ case Success(value: WorkerData) =>
+ complete(write(value.workerDescription))
+ case Failure(ex) => failWith(ex)
+ }
+ }
+ }~
+ path("config") {
+ val workerId = WorkerId.parse(workerIdString)
+ onComplete(askWorker[WorkerConfig](master, workerId, QueryWorkerConfig(workerId))) {
+ case Success(value: WorkerConfig) =>
+ val config = Option(value.config).map(ClusterConfig.render(_, concise)).getOrElse("{}")
+ complete(config)
+ case Failure(ex) =>
+ failWith(ex)
+ }
+ } ~
+ path("metrics" / RestPath ) { path =>
+ val workerId = WorkerId.parse(workerIdString)
+ parameter(ReadOption.Key ? ReadOption.ReadLatest) { readOption =>
+ val query = QueryHistoryMetrics(path.head.toString, readOption)
+ onComplete(askWorker[HistoryMetrics](master, workerId, query)) {
+ case Success(value) =>
+ complete(write(value))
+ case Failure(ex) =>
+ failWith(ex)
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/main/scala/org/apache/gearpump/services/main/Services.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/main/scala/org/apache/gearpump/services/main/Services.scala b/services/jvm/src/main/scala/org/apache/gearpump/services/main/Services.scala
new file mode 100644
index 0000000..23c95c4
--- /dev/null
+++ b/services/jvm/src/main/scala/org/apache/gearpump/services/main/Services.scala
@@ -0,0 +1,148 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.services.main
+
+import java.util.Random
+import scala.collection.JavaConverters._
+import scala.concurrent.Await
+
+import akka.actor.ActorSystem
+import akka.http.scaladsl.Http
+import akka.http.scaladsl.server.Route
+import akka.stream.ActorMaterializer
+import com.typesafe.config.ConfigValueFactory
+import org.slf4j.Logger
+import sun.misc.BASE64Encoder
+
+import org.apache.gearpump.cluster.ClusterConfig
+import org.apache.gearpump.cluster.main.{ArgumentsParser, CLIOption, Gear}
+import org.apache.gearpump.cluster.master.MasterProxy
+import org.apache.gearpump.services.{RestServices, SecurityService}
+import org.apache.gearpump.util.LogUtil.ProcessType
+import org.apache.gearpump.util.{AkkaApp, Constants, LogUtil, Util}
+
+/** Command line to start UI server */
+object Services extends AkkaApp with ArgumentsParser {
+
+ private val LOG = LogUtil.getLogger(getClass)
+
+ override val options: Array[(String, CLIOption[Any])] = Array(
+ "master" -> CLIOption("<host:port>", required = false),
+ Gear.OPTION_CONFIG -> CLIOption("<provide a custom configuration file>", required = false),
+ "supervisor" -> CLIOption("<Supervisor Actor Path>", required = false, Some("")))
+
+ override val description = "UI Server"
+
+ override def akkaConfig: Config = {
+ ClusterConfig.ui()
+ }
+
+ override def help(): Unit = {
+ // scalastyle:off println
+ Console.println("UI Server")
+ // scalastyle:on println
+ }
+
+ private var killFunction: Option[() => Unit] = None
+
+ override def main(inputAkkaConf: Config, args: Array[String]): Unit = {
+
+ val argConfig = parse(args)
+ var akkaConf =
+ if (argConfig.exists(Gear.OPTION_CONFIG)) {
+ ClusterConfig.ui(argConfig.getString(Gear.OPTION_CONFIG))
+ } else {
+ inputAkkaConf
+ }
+
+ val LOG: Logger = {
+ LogUtil.loadConfiguration(akkaConf, ProcessType.UI)
+ LogUtil.getLogger(getClass)
+ }
+
+ if (argConfig.exists("master")) {
+ val master = argConfig.getString("master")
+ akkaConf = akkaConf.withValue(Constants.GEARPUMP_CLUSTER_MASTERS,
+ ConfigValueFactory.fromIterable(List(master).asJava))
+ }
+
+ akkaConf = akkaConf.withValue(Constants.GEARPUMP_SERVICE_SUPERVISOR_PATH,
+ ConfigValueFactory.fromAnyRef(argConfig.getString("supervisor")))
+ // Creates a random unique secret key for session manager.
+ // All previous stored session token cookies will be invalidated when UI
+ // server is restarted.
+ .withValue(SecurityService.SESSION_MANAGER_KEY,
+ ConfigValueFactory.fromAnyRef(randomSeverSecret()))
+
+ val masterCluster = akkaConf.getStringList(Constants.GEARPUMP_CLUSTER_MASTERS).asScala
+ .flatMap(Util.parseHostList)
+
+ implicit val system = ActorSystem("services", akkaConf)
+ implicit val executionContext = system.dispatcher
+
+ import scala.concurrent.duration._
+ val master = system.actorOf(MasterProxy.props(masterCluster, 1.day),
+ s"masterproxy${system.name}")
+ val (host, port) = parseHostPort(system.settings.config)
+
+ implicit val mat = ActorMaterializer()
+ val services = new RestServices(master, mat, system)
+
+ val bindFuture = Http().bindAndHandle(Route.handlerFlow(services.route), host, port)
+ Await.result(bindFuture, 15.seconds)
+
+ val displayHost = if (host == "0.0.0.0") "127.0.0.1" else host
+ LOG.info(s"Please browse to http://$displayHost:$port to see the web UI")
+
+ // scalastyle:off println
+ println(s"Please browse to http://$displayHost:$port to see the web UI")
+ // scalastyle:on println
+
+ killFunction = Some { () =>
+ LOG.info("Shutting down UI Server")
+ system.terminate()
+ }
+
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+
+ private def randomSeverSecret(): String = {
+ val random = new Random()
+ val length = 64 // Required
+ val bytes = new Array[Byte](length)
+ random.nextBytes(bytes)
+ val endecoder = new BASE64Encoder()
+ endecoder.encode(bytes)
+ }
+
+ private def parseHostPort(config: Config): (String, Int) = {
+ val port = config.getInt(Constants.GEARPUMP_SERVICE_HTTP)
+ val host = config.getString(Constants.GEARPUMP_SERVICE_HOST)
+ (host, port)
+ }
+
+ // TODO: fix this
+ // Hacks around for YARN module, so that we can kill the UI server
+ // when application is shutting down.
+ def kill(): Unit = {
+ if (killFunction.isDefined) {
+ killFunction.get.apply()
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/main/scala/org/apache/gearpump/services/package.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/main/scala/org/apache/gearpump/services/package.scala b/services/jvm/src/main/scala/org/apache/gearpump/services/package.scala
new file mode 100644
index 0000000..12dec1d
--- /dev/null
+++ b/services/jvm/src/main/scala/org/apache/gearpump/services/package.scala
@@ -0,0 +1,22 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump
+
+package object services {
+ final val REST_VERSION = "v1.0"
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/main/scala/org/apache/gearpump/services/security/oauth2/OAuth2Authenticator.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/main/scala/org/apache/gearpump/services/security/oauth2/OAuth2Authenticator.scala b/services/jvm/src/main/scala/org/apache/gearpump/services/security/oauth2/OAuth2Authenticator.scala
new file mode 100644
index 0000000..e9008aa
--- /dev/null
+++ b/services/jvm/src/main/scala/org/apache/gearpump/services/security/oauth2/OAuth2Authenticator.scala
@@ -0,0 +1,152 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.services.security.oauth2
+
+import scala.concurrent.{ExecutionContext, Future}
+
+import com.typesafe.config.Config
+
+import org.apache.gearpump.services.SecurityService.UserSession
+import org.apache.gearpump.util.Constants
+import org.apache.gearpump.util.Constants._
+
+/**
+ *
+ * Uses OAuth2 social-login as the mechanism for authentication.
+ * @see [[https://tools.ietf.org/html/rfc6749]] to find what is OAuth2, and how it works.
+ *
+ * Basically flow for OAuth2 Authentication:
+ * 1. User accesses Gearpump UI website, and choose to login with OAuth2 server.
+ * 2. Gearpump UI website redirects user to OAuth2 server domain authorization endpoint.
+ * 3. End user complete the authorization in the domain of OAuth2 server.
+ * 4. OAuth2 server redirects user back to Gearpump UI server.
+ * 5. Gearpump UI server verify the tokens and extract credentials from query
+ * parameters and form fields.
+ *
+ * NOTE: '''Thread-safety''' is a MUST requirement. Developer need to ensure the sub-class is
+ * thread-safe. Sub-class should have a parameterless constructor.
+ *
+ * NOTE: OAuth2 Authenticator requires access of Internet. Please make sure HTTP proxy are
+ * set properly if applied.
+ *
+ * Example: Config proxy when UI server is started on Windows:
+ * {{{
+ * > set JAVA_OPTS=-Dhttp.proxyHost=xx.com -Dhttp.proxyPort=8088 -Dhttps.proxyHost=xx.com
+ * -Dhttps.proxyPort=8088
+ * > bin\services
+ * }}}
+ *
+ * Example: Config proxy when UI server is started on Linux:
+ * {{{
+ * $ export JAVA_OPTS="-Dhttp.proxyHost=xx.com -Dhttp.proxyPort=8088 -Dhttps.proxyHost=xx.com
+ * -Dhttps.proxyPort=8088"
+ * $ bin/services
+ * }}}
+ */
+trait OAuth2Authenticator {
+
+ /**
+ * Inits authenticator with config which contains client ID, client secret, and etc..
+ *
+ * Typically, the client key and client secret is provided by OAuth2 Authorization server
+ * when user register an application there.
+ * See [[https://tools.ietf.org/html/rfc6749]] for definition of client, client Id,
+ * and client secret.
+ *
+ * See [[https://developer.github.com/v3/oauth/]] for an actual example of how Github
+ * use client key, and client secret.
+ *
+ * NOTE: '''Thread-Safety''': Framework ensures this call is synchronized.
+ *
+ * @param config Client Id, client secret, callback URL and etc..
+ * @param executionContext ExecutionContext from hosting environment.
+ */
+ def init(config: Config, executionContext: ExecutionContext): Unit
+
+ /**
+ * Returns the OAuth Authorization URL so for redirection to that address to do OAuth2
+ * authorization.
+ *
+ * NOTE: '''Thread-Safety''': This can be called in a multi-thread environment. Developer
+ * need to ensure thread safety.
+ */
+ def getAuthorizationUrl: String
+
+ /**
+ * After authorization, OAuth2 server redirects user back with tokens. This verify the
+ * tokens, retrieve the profiles, and return [[UserSession]] information.
+ *
+ * NOTE: This is an Async call.
+ *
+ * NOTE: This call requires external internet access.
+ *
+ * NOTE: '''Thread-Safety''': This can be called in a multi-thread environment. Developer
+ * need to ensure thread safety.
+ *
+ * @param parameters HTTP Query and Post parameters, which typically contains Authorization code.
+ * @return UserSession if authentication pass.
+ */
+ def authenticate(parameters: Map[String, String]): Future[UserSession]
+
+ /**
+ * Clean up resource
+ */
+ def close(): Unit
+}
+
+object OAuth2Authenticator {
+
+ // Serves as a quick immutable lookup cache
+ private var providers = Map.empty[String, OAuth2Authenticator]
+
+ /**
+ * Load Authenticator from [[Constants.GEARPUMP_UI_OAUTH2_AUTHENTICATORS]]
+ *
+ * @param provider, Name for the OAuth2 Authentication Service.
+ * @return Returns null if the OAuth2 Authentication is disabled.
+ */
+ def get(config: Config, provider: String, executionContext: ExecutionContext)
+ : OAuth2Authenticator = {
+
+ if (providers.contains(provider)) {
+ providers(provider)
+ } else {
+ val path = s"${Constants.GEARPUMP_UI_OAUTH2_AUTHENTICATORS}.$provider"
+ val enabled = config.getBoolean(Constants.GEARPUMP_UI_OAUTH2_AUTHENTICATOR_ENABLED)
+ if (enabled && config.hasPath(path)) {
+ this.synchronized {
+ if (providers.contains(provider)) {
+ providers(provider)
+ } else {
+ val authenticatorConfig = config.getConfig(path)
+ val authenticatorClass = authenticatorConfig.getString(
+ GEARPUMP_UI_OAUTH2_AUTHENTICATOR_CLASS)
+ val clazz = Thread.currentThread().getContextClassLoader.loadClass(authenticatorClass)
+ val authenticator = clazz.newInstance().asInstanceOf[OAuth2Authenticator]
+ authenticator.init(authenticatorConfig, executionContext)
+ providers += provider -> authenticator
+ authenticator
+ }
+ }
+ } else {
+ null
+ }
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/main/scala/org/apache/gearpump/services/security/oauth2/impl/BaseOAuth2Authenticator.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/main/scala/org/apache/gearpump/services/security/oauth2/impl/BaseOAuth2Authenticator.scala b/services/jvm/src/main/scala/org/apache/gearpump/services/security/oauth2/impl/BaseOAuth2Authenticator.scala
new file mode 100644
index 0000000..603fb1d
--- /dev/null
+++ b/services/jvm/src/main/scala/org/apache/gearpump/services/security/oauth2/impl/BaseOAuth2Authenticator.scala
@@ -0,0 +1,232 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.services.security.oauth2.impl
+
+import java.util.concurrent.atomic.AtomicBoolean
+import scala.collection.mutable.StringBuilder
+import scala.concurrent.{ExecutionContext, Future, Promise}
+import scala.util.{Failure, Success}
+
+import com.typesafe.config.Config
+import com.github.scribejava.core.builder.ServiceBuilderAsync
+import com.github.scribejava.core.builder.api.DefaultApi20
+import com.github.scribejava.core.model._
+import com.github.scribejava.core.oauth.OAuth20Service
+import com.github.scribejava.core.utils.OAuthEncoder
+import com.ning.http.client.AsyncHttpClientConfig
+
+import org.apache.gearpump.security.Authenticator
+import org.apache.gearpump.services.SecurityService.UserSession
+import org.apache.gearpump.services.security.oauth2.OAuth2Authenticator
+import org.apache.gearpump.services.security.oauth2.impl.BaseOAuth2Authenticator.BaseApi20
+import org.apache.gearpump.util.Constants._
+import org.apache.gearpump.util.Util
+
+/**
+ * Uses Ning AsyncClient to connect to OAuth2 service.
+ *
+ * See [[org.apache.gearpump.services.security.oauth2.OAuth2Authenticator]]
+ * for more API information.
+ */
+abstract class BaseOAuth2Authenticator extends OAuth2Authenticator {
+
+ // Authorize Url for end user to authorize
+ protected def authorizeUrl: String
+
+ // Used to fetch the Access Token.
+ protected def accessTokenEndpoint: String
+
+ // Protected resource Url to get the user profile
+ protected def protectedResourceUrl: String
+
+ // Extracts the username information from response of protectedResourceUrl
+ protected def extractUserName(body: String): String
+
+ // Scope required to access protectedResourceUrl
+ protected def scope: String
+
+ // OAuth2 endpoint definition for ScribeJava.
+ protected def oauth2Api(): DefaultApi20 = {
+ new BaseApi20(authorizeUrl, accessTokenEndpoint)
+ }
+
+ protected var oauthService: OAuth20Service = null
+
+ protected var executionContext: ExecutionContext = null
+
+ private var defaultPermissionLevel = Authenticator.Guest.permissionLevel
+
+ // Synchronization ensured by the caller
+ override def init(config: Config, executionContext: ExecutionContext): Unit = {
+ if (this.oauthService == null) {
+ val callback = config.getString(GEARPUMP_UI_OAUTH2_AUTHENTICATOR_CALLBACK)
+ val clientId = config.getString(GEARPUMP_UI_OAUTH2_AUTHENTICATOR_CLIENT_ID)
+ val clientSecret = config.getString(GEARPUMP_UI_OAUTH2_AUTHENTICATOR_CLIENT_SECRET)
+ defaultPermissionLevel = {
+ val role = config.getString(GEARPUMP_UI_OAUTH2_AUTHENTICATOR_DEFAULT_USER_ROLE)
+ role match {
+ case "guest" => Authenticator.Guest.permissionLevel
+ case "user" => Authenticator.User.permissionLevel
+ case "admin" => Authenticator.Admin.permissionLevel
+ case _ => Authenticator.UnAuthenticated.permissionLevel
+ }
+ }
+ this.oauthService = buildOAuth2Service(clientId, clientSecret, callback)
+ this.executionContext = executionContext
+ }
+ }
+
+ private val isClosed: AtomicBoolean = new AtomicBoolean(false)
+
+ override def close(): Unit = {
+ if (isClosed.compareAndSet(false, true)) {
+ if (null != oauthService && null != oauthService.getAsyncHttpClient()) {
+ oauthService.getAsyncHttpClient().close()
+ }
+ }
+ }
+
+ override def getAuthorizationUrl(): String = {
+ oauthService.getAuthorizationUrl()
+ }
+
+ protected def authenticateWithAccessToken(accessToken: OAuth2AccessToken): Future[UserSession] = {
+ val promise = Promise[UserSession]()
+ val request = new OAuthRequestAsync(Verb.GET, protectedResourceUrl, oauthService)
+ oauthService.signRequest(accessToken, request)
+ request.sendAsync {
+ new OAuthAsyncRequestCallback[Response] {
+ override def onCompleted(response: Response): Unit = {
+ try {
+ val user = extractUserName(response.getBody)
+ promise.success(new UserSession(user, defaultPermissionLevel))
+ } catch {
+ case ex: Throwable =>
+ promise.failure(ex)
+ }
+ }
+
+ override def onThrowable(throwable: Throwable): Unit = {
+ promise.failure(throwable)
+ }
+ }
+ }
+ promise.future
+ }
+
+ protected def authenticateWithAuthorizationCode(code: String): Future[UserSession] = {
+
+ implicit val ec: ExecutionContext = executionContext
+
+ val promise = Promise[UserSession]()
+ oauthService.getAccessTokenAsync(code,
+
+ new OAuthAsyncRequestCallback[OAuth2AccessToken] {
+ override def onCompleted(accessToken: OAuth2AccessToken): Unit = {
+ authenticateWithAccessToken(accessToken).onComplete {
+ case Success(user) => promise.success(user)
+ case Failure(ex) => promise.failure(ex)
+ }
+ }
+
+ override def onThrowable(throwable: Throwable): Unit = {
+ promise.failure(throwable)
+ }
+ })
+ promise.future
+ }
+
+ override def authenticate(parameters: Map[String, String]): Future[UserSession] = {
+
+ val code = parameters.get(GEARPUMP_UI_OAUTH2_AUTHENTICATOR_AUTHORIZATION_CODE)
+ val accessToken = parameters.get(GEARPUMP_UI_OAUTH2_AUTHENTICATOR_ACCESS_TOKEN)
+
+ if (accessToken.isDefined) {
+ authenticateWithAccessToken(new OAuth2AccessToken(accessToken.get))
+ } else if (code.isDefined) {
+ authenticateWithAuthorizationCode(code.get)
+ } else {
+ // Fails authentication if code not exist
+ Future.failed(new Exception("Fail to authenticate user as there is no code parameter in URL"))
+ }
+ }
+
+ private def buildOAuth2Service(clientId: String, clientSecret: String, callback: String)
+ : OAuth20Service = {
+ val state: String = "state" + Util.randInt()
+ ScribeJavaConfig.setForceTypeOfHttpRequests(
+ ForceTypeOfHttpRequest.FORCE_ASYNC_ONLY_HTTP_REQUESTS)
+ val clientConfig: AsyncHttpClientConfig = new AsyncHttpClientConfig.Builder()
+ .setMaxConnections(5)
+ .setUseProxyProperties(true)
+ .setRequestTimeout(60000)
+ .setAllowPoolingConnections(false)
+ .setPooledConnectionIdleTimeout(60000)
+ .setReadTimeout(60000).build
+
+ val service: OAuth20Service = new ServiceBuilderAsync()
+ .apiKey(clientId)
+ .apiSecret(clientSecret)
+ .scope(scope)
+ .state(state)
+ .callback(callback)
+ .asyncHttpClientConfig(clientConfig)
+ .build(oauth2Api())
+
+ service
+ }
+}
+
+object BaseOAuth2Authenticator {
+
+ class BaseApi20(authorizeUrl: String, accessTokenEndpoint: String) extends DefaultApi20 {
+ def getAccessTokenEndpoint: String = {
+ accessTokenEndpoint
+ }
+
+ def getAuthorizationUrl(config: OAuthConfig): String = {
+ val sb: StringBuilder = new StringBuilder(String.format(authorizeUrl,
+ config.getResponseType, config.getApiKey, OAuthEncoder.encode(config.getCallback),
+ OAuthEncoder.encode(config.getScope)))
+ val state: String = config.getState
+ if (state != null) {
+ sb.append('&').append(OAuthConstants.STATE).append('=').append(OAuthEncoder.encode(state))
+ }
+ sb.toString
+ }
+
+ override def createService(config: OAuthConfig): OAuth20Service = {
+ new OAuth20Service(this, config) {
+
+ protected override def createAccessTokenRequest[T <: AbstractRequest](
+ code: String, request: T): T = {
+ super.createAccessTokenRequest(code, request)
+
+ if (!getConfig.hasGrantType) {
+ request.addParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.AUTHORIZATION_CODE)
+ }
+
+ // Work-around for issue https://github.com/scribejava/scribejava/issues/641
+ request.addHeader("Content-Type", "application/x-www-form-urlencoded")
+ request
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/main/scala/org/apache/gearpump/services/security/oauth2/impl/CloudFoundryUAAOAuth2Authenticator.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/main/scala/org/apache/gearpump/services/security/oauth2/impl/CloudFoundryUAAOAuth2Authenticator.scala b/services/jvm/src/main/scala/org/apache/gearpump/services/security/oauth2/impl/CloudFoundryUAAOAuth2Authenticator.scala
new file mode 100644
index 0000000..ded50a7
--- /dev/null
+++ b/services/jvm/src/main/scala/org/apache/gearpump/services/security/oauth2/impl/CloudFoundryUAAOAuth2Authenticator.scala
@@ -0,0 +1,244 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.services.security.oauth2.impl
+
+import scala.concurrent.{ExecutionContext, Future, Promise}
+
+import com.typesafe.config.Config
+import com.github.scribejava.core.builder.api.DefaultApi20
+import com.github.scribejava.core.model._
+import com.github.scribejava.core.oauth.OAuth20Service
+import com.ning.http.client
+import com.ning.http.client.{AsyncCompletionHandler, AsyncHttpClient}
+import spray.json.{JsString, _}
+import sun.misc.BASE64Encoder
+
+import org.apache.gearpump.services.SecurityService.UserSession
+import org.apache.gearpump.services.security.oauth2.impl.BaseOAuth2Authenticator.BaseApi20
+import org.apache.gearpump.util.Constants._
+
+/**
+ *
+ * Does authentication with CloudFoundry UAA service. Currently it only
+ * extract the email address of end user.
+ *
+ * For what is UAA,
+ * See [[https://github.com/cloudfoundry/uaa for information about CloudFoundry UAA]]
+ * (User Account and Authentication Service)
+ *
+ * Pre-requisite steps to use this Authenticator:
+ *
+ * Step1: Register your website to UAA with tool uaac.
+ * 1) Check tutorial on uaac at
+ * [[https://docs.cloudfoundry.org/adminguide/uaa-user-management.html]]
+ *
+ * 2) Open a bash shell, set the UAA server by command `uaac target`
+ * {{{
+ * uaac target [your uaa server url]
+ * }}}
+ *
+ * NOTE: [your uaa server url] should match the uaahost settings in gear.conf
+ *
+ * 3) Login in as user admin by
+ * {{{
+ * uaac token client get admin -s MyAdminPassword
+ * }}}
+ *
+ * 4) Create a new Application (Client) in UAA,
+ * {{{
+ * uaac client add [your_client_id]
+ * --scope "openid cloud_controller.read"
+ * --authorized_grant_types "authorization_code client_credentials refresh_token"
+ * --authorities "openid cloud_controller.read"
+ * --redirect_uri [your_redirect_url]
+ * --autoapprove true
+ * --secret [your_client_secret]
+ * }}}
+ *
+ * Step2: Configure the OAuth2 information in gear.conf
+ *
+ * 1) Enable OAuth2 authentication by setting "gearpump.ui-security.oauth2-authenticator-enabled"
+ * as true.
+ *
+ * 2) Navigate to section "gearpump.ui-security.oauth2-authenticators.cloudfoundryuaa"
+ *
+ * 3) Config gear.conf "gearpump.ui-security.oauth2-authenticators.cloudfoundryuaa" section.
+ * Please make sure class name, client ID, client Secret, and callback URL are set properly.
+ *
+ * NOTE: The callback URL here should match what you set on CloudFoundry UAA in step1.
+ *
+ * Step3: Restart the UI service and try the "social login" button for UAA.
+ *
+ * NOTE: OAuth requires Internet access, @see
+ * [[org.apache.gearpump.services.security.oauth2.OAuth2Authenticator]] to find tutorials to
+ * configure Internet proxy.
+ *
+ * See [[org.apache.gearpump.services.security.oauth2.OAuth2Authenticator]] for more background
+ * information of OAuth2.
+ */
+class CloudFoundryUAAOAuth2Authenticator extends BaseOAuth2Authenticator {
+
+ import org.apache.gearpump.services.security.oauth2.impl.CloudFoundryUAAOAuth2Authenticator._
+
+ private var host: String = null
+
+ protected override def authorizeUrl: String =
+ s"$host/oauth/authorize?response_type=%s&client_id=%s&redirect_uri=%s&scope=%s"
+
+ protected override def accessTokenEndpoint: String = s"$host/oauth/token"
+
+ protected override def protectedResourceUrl: String = s"$host/userinfo"
+
+ protected override def scope: String = "openid,cloud_controller.read"
+
+ private var additionalAuthenticator: Option[AdditionalAuthenticator] = None
+
+ override def init(config: Config, executionContext: ExecutionContext): Unit = {
+ host = config.getString("uaahost")
+ super.init(config, executionContext)
+
+ if (config.getBoolean(ADDITIONAL_AUTHENTICATOR_ENABLED)) {
+ val additionalAuthenticatorConfig = config.getConfig(ADDITIONAL_AUTHENTICATOR)
+ val authenticatorClass = additionalAuthenticatorConfig
+ .getString(GEARPUMP_UI_OAUTH2_AUTHENTICATOR_CLASS)
+ val clazz = Thread.currentThread().getContextClassLoader.loadClass(authenticatorClass)
+ val authenticator = clazz.newInstance().asInstanceOf[AdditionalAuthenticator]
+ authenticator.init(additionalAuthenticatorConfig, executionContext)
+ additionalAuthenticator = Option(authenticator)
+ }
+ }
+
+ protected override def extractUserName(body: String): String = {
+ val email = body.parseJson.asJsObject.fields("email").asInstanceOf[JsString]
+ email.value
+ }
+
+ protected override def oauth2Api(): DefaultApi20 = {
+ new CloudFoundryUAAService(authorizeUrl, accessTokenEndpoint)
+ }
+
+ protected override def authenticateWithAccessToken(accessToken: OAuth2AccessToken)
+ : Future[UserSession] = {
+
+ implicit val ec: ExecutionContext = executionContext
+
+ if (additionalAuthenticator.isDefined) {
+ super.authenticateWithAccessToken(accessToken).flatMap { user =>
+ additionalAuthenticator.get.authenticate(oauthService.getAsyncHttpClient, accessToken, user)
+ }
+ } else {
+ super.authenticateWithAccessToken(accessToken)
+ }
+ }
+}
+
+object CloudFoundryUAAOAuth2Authenticator {
+ private val RESPONSE_TYPE = "response_type"
+
+ val ADDITIONAL_AUTHENTICATOR_ENABLED = "additional-authenticator-enabled"
+ val ADDITIONAL_AUTHENTICATOR = "additional-authenticator"
+
+ private class CloudFoundryUAAService(authorizeUrl: String, accessTokenEndpoint: String)
+ extends BaseApi20(authorizeUrl, accessTokenEndpoint) {
+
+ private def base64(in: String): String = {
+ val encoder = new BASE64Encoder()
+ val utf8 = "UTF-8"
+ encoder.encode(in.getBytes(utf8))
+ }
+
+ override def createService(config: OAuthConfig): OAuth20Service = {
+ new OAuth20Service(this, config) {
+
+ protected override def createAccessTokenRequest[T <: AbstractRequest](
+ code: String, request: T): T = {
+ val config: OAuthConfig = getConfig()
+
+ request.addParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.AUTHORIZATION_CODE)
+ request.addParameter(OAuthConstants.CODE, code)
+ request.addParameter(RESPONSE_TYPE, "token")
+ request.addParameter(OAuthConstants.REDIRECT_URI, config.getCallback)
+
+ // Work around issue https://github.com/scribejava/scribejava/issues/641
+ request.addHeader("Content-Type", "application/x-www-form-urlencoded")
+
+ // CloudFoundry requires a Authorization header encoded with client Id and secret.
+ val authorizationHeader = "Basic " + base64(config.getApiKey + ":" + config.getApiSecret)
+ request.addHeader("Authorization", authorizationHeader)
+ request
+ }
+ }
+ }
+ }
+
+ /**
+ * Additional authenticator to check more credential attributes of user before logging in.
+ * This authenticator is applied AFTER user pass the initial (default) authenticator.
+ */
+ trait AdditionalAuthenticator {
+
+ /**
+ * Initialization
+ *
+ * @param config Configurations specifically used for this authenticator.
+ * @param executionContext Execution Context to use to run futures.
+ */
+ def init(config: Config, executionContext: ExecutionContext): Unit
+
+ /**
+ *
+ * @param accessToken, the accessToken for the UAA
+ * @param user user session returned by previous authenticator
+ * @return an updated UserSession
+ */
+ def authenticate(
+ asyncClient: AsyncHttpClient, accessToken: OAuth2AccessToken, user: UserSession)
+ : Future[UserSession]
+ }
+
+ val ORGANIZATION_URL = "organization-url"
+
+ class OrganizationAccessChecker extends AdditionalAuthenticator {
+ private var organizationUrl: String = null
+ private implicit var executionContext: ExecutionContext = null
+
+ override def init(config: Config, executionContext: ExecutionContext): Unit = {
+ this.organizationUrl = config.getString(ORGANIZATION_URL)
+ this.executionContext = executionContext
+ }
+
+ override def authenticate(asyncClient: AsyncHttpClient, accessToken: OAuth2AccessToken,
+ user: UserSession): Future[UserSession] = {
+
+ val promise = Promise[UserSession]()
+ val builder = asyncClient.prepareGet(organizationUrl)
+ builder.addHeader("Authorization", s"bearer ${accessToken.getAccessToken}")
+ builder.execute(new AsyncCompletionHandler[Unit] {
+ override def onCompleted(response: client.Response): Unit = {
+ if (response.getStatusCode == 200) {
+ promise.success(user)
+ } else {
+ promise.failure(new Exception(response.getResponseBody))
+ }
+ }
+ })
+ promise.future
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/main/scala/org/apache/gearpump/services/security/oauth2/impl/GoogleOAuth2Authenticator.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/main/scala/org/apache/gearpump/services/security/oauth2/impl/GoogleOAuth2Authenticator.scala b/services/jvm/src/main/scala/org/apache/gearpump/services/security/oauth2/impl/GoogleOAuth2Authenticator.scala
new file mode 100644
index 0000000..c62071c
--- /dev/null
+++ b/services/jvm/src/main/scala/org/apache/gearpump/services/security/oauth2/impl/GoogleOAuth2Authenticator.scala
@@ -0,0 +1,108 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.services.security.oauth2.impl
+
+import com.github.scribejava.apis.google.GoogleJsonTokenExtractor
+import com.github.scribejava.core.builder.api.DefaultApi20
+import com.github.scribejava.core.extractors.TokenExtractor
+import com.github.scribejava.core.model._
+import spray.json._
+
+/**
+ *
+ * Does authentication with Google OAuth2 service. It only extract the email address
+ * from user profile of Google.
+ *
+ * Pre-requisite steps to use this Authenticator:
+ *
+ * Step1: Register your website as an OAuth2 Application on Google
+ * 1) Create an application representing your website at [[https://console.developers.google.com]]
+ *
+ * 2) In "API Manager" of your created application, enable API "Google+ API"
+ *
+ * 3) Create OAuth client ID for this application. In "Credentials" tab of "API Manager",
+ * choose "Create credentials", and then select OAuth client ID. Follow the wizard
+ * to set callback URL, and generate client ID, and client Secret. Callback URL is NOT optional.
+ *
+ * Step2: Configure the OAuth2 information in gear.conf
+ *
+ * 1) Enable OAuth2 authentication by setting "gearpump.ui-security.oauth2-authenticator-enabled"
+ * as true.
+ *
+ * 2) Configure section "gearpump.ui-security.oauth2-authenticators.google". Please make sure
+ * class name, client ID, client Secret, and callback URL are set properly.
+ *
+ * NOTE: callback URL set here should match what is configured on Google in step1.
+ *
+ * Step3: Restart the UI service and try out the Google social login button in UI.
+ *
+ * NOTE: OAuth requires Internet access, @see
+ * [[org.apache.gearpump.services.security.oauth2.OAuth2Authenticator]] to find
+ * some helpful tutorials
+ *
+ * NOTE: Google use scope to define what data can be fetched by OAuth2. Currently we use profile
+ * [[https://www.googleapis.com/auth/userinfo.email]]. However, Google may change the profile
+ * in future.
+ *
+ * TODO Currently, this doesn't verify the state from Google OAuth2 response.
+ *
+ * See [[org.apache.gearpump.services.security.oauth2.OAuth2Authenticator]] for more
+ * API information.
+ */
+class GoogleOAuth2Authenticator extends BaseOAuth2Authenticator {
+
+ import org.apache.gearpump.services.security.oauth2.impl.GoogleOAuth2Authenticator._
+
+ protected override def authorizeUrl: String = AuthorizeUrl
+
+ protected override def accessTokenEndpoint: String = AccessEndpoint
+
+ protected override def protectedResourceUrl: String = ResourceUrl
+
+ protected override def scope: String = GoogleOAuth2Authenticator.Scope
+
+ protected override def extractUserName(body: String): String = {
+ val emails = body.parseJson.asJsObject.fields("emails").asInstanceOf[JsArray]
+ val email = emails.elements(0).asJsObject("Cannot find email account")
+ .fields("value").asInstanceOf[JsString].value
+ email
+ }
+
+ override def oauth2Api(): DefaultApi20 = new AsyncGoogleApi20(authorizeUrl, accessTokenEndpoint)
+}
+
+object GoogleOAuth2Authenticator {
+
+ import org.apache.gearpump.services.security.oauth2.impl.BaseOAuth2Authenticator._
+
+ // scalastyle:off line.size.limit
+ val AuthorizeUrl = "https://accounts.google.com/o/oauth2/auth?response_type=%s&client_id=%s&redirect_uri=%s&scope=%s"
+ // scalastyle:on line.size.limit
+ val AccessEndpoint = "https://www.googleapis.com/oauth2/v4/token"
+ val ResourceUrl = "https://www.googleapis.com/plus/v1/people/me"
+ val Scope = "https://www.googleapis.com/auth/userinfo.email"
+
+ private class AsyncGoogleApi20(authorizeUrl: String, accessEndpoint: String)
+ extends BaseApi20(authorizeUrl, accessEndpoint) {
+
+ override def getAccessTokenExtractor: TokenExtractor[OAuth2AccessToken] = {
+ GoogleJsonTokenExtractor.instance
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/main/scala/org/apache/gearpump/services/util/UpickleUtil.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/main/scala/org/apache/gearpump/services/util/UpickleUtil.scala b/services/jvm/src/main/scala/org/apache/gearpump/services/util/UpickleUtil.scala
new file mode 100644
index 0000000..caa3a33
--- /dev/null
+++ b/services/jvm/src/main/scala/org/apache/gearpump/services/util/UpickleUtil.scala
@@ -0,0 +1,49 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.services.util
+
+import upickle.Js
+
+import org.apache.gearpump.cluster.worker.WorkerId
+import org.apache.gearpump.util.Graph
+
+object UpickleUtil {
+
+ // For implicit type, we need to add EXPLICIT return type, otherwise, upickle may NOT infer the
+ // reader type automatically.
+ // See issue https://github.com/lihaoyi/upickle-pprint/issues/102
+ implicit val graphReader: upickle.default.Reader[Graph[Int, String]] = {
+ upickle.default.Reader[Graph[Int, String]] {
+ case Js.Obj(verties, edges) =>
+ val vertexList = upickle.default.readJs[List[Int]](verties._2)
+ val edgeList = upickle.default.readJs[List[(Int, String, Int)]](edges._2)
+ Graph(vertexList, edgeList)
+ }
+ }
+
+ implicit val workerIdReader: upickle.default.Reader[WorkerId] = upickle.default.Reader[WorkerId] {
+ case Js.Str(str) =>
+ WorkerId.parse(str)
+ }
+
+ implicit val workerIdWriter: upickle.default.Writer[WorkerId] = upickle.default.Writer[WorkerId] {
+ case workerId: WorkerId =>
+ Js.Str(WorkerId.render(workerId))
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/test/scala/io/gearpump/services/AdminServiceSpec.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/test/scala/io/gearpump/services/AdminServiceSpec.scala b/services/jvm/src/test/scala/io/gearpump/services/AdminServiceSpec.scala
deleted file mode 100644
index e67731e..0000000
--- a/services/jvm/src/test/scala/io/gearpump/services/AdminServiceSpec.scala
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.services
-
-import scala.concurrent.Await
-import scala.concurrent.duration._
-
-import akka.actor.ActorSystem
-import akka.http.scaladsl.testkit.{RouteTestTimeout, ScalatestRouteTest}
-import com.typesafe.config.Config
-import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
-
-import io.gearpump.cluster.TestUtil
-
-// NOTE: This cannot be removed!!!
-import io.gearpump.services.util.UpickleUtil._
-
-class AdminServiceSpec
- extends FlatSpec with ScalatestRouteTest with Matchers with BeforeAndAfterAll {
-
- override def testConfig: Config = TestUtil.DEFAULT_CONFIG
-
- implicit def actorSystem: ActorSystem = system
-
- it should "shutdown the ActorSystem when receiving terminate" in {
- val route = new AdminService(actorSystem).route
- implicit val customTimeout = RouteTestTimeout(15.seconds)
- (Post(s"/terminate") ~> route) ~> check {
- assert(status.intValue() == 404)
- }
-
- Await.result(actorSystem.whenTerminated, 20.seconds)
-
- // terminate should terminate current actor system
- assert(actorSystem.whenTerminated.isCompleted)
- }
-}
[16/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/integrationtest/core/src/it/scala/io/gearpump/integrationtest/MiniClusterProvider.scala
----------------------------------------------------------------------
diff --git a/integrationtest/core/src/it/scala/io/gearpump/integrationtest/MiniClusterProvider.scala b/integrationtest/core/src/it/scala/io/gearpump/integrationtest/MiniClusterProvider.scala
index 32d8bb7..4a161c7 100644
--- a/integrationtest/core/src/it/scala/io/gearpump/integrationtest/MiniClusterProvider.scala
+++ b/integrationtest/core/src/it/scala/io/gearpump/integrationtest/MiniClusterProvider.scala
@@ -15,9 +15,9 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package io.gearpump.integrationtest
+package org.apache.gearpump.integrationtest
-import io.gearpump.integrationtest.minicluster.MiniCluster
+import org.apache.gearpump.integrationtest.minicluster.MiniCluster
/**
* Provides a min cluster of Gearpump, which contains one or more masters, and workers.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/integrationtest/core/src/it/scala/io/gearpump/integrationtest/TestSpecBase.scala
----------------------------------------------------------------------
diff --git a/integrationtest/core/src/it/scala/io/gearpump/integrationtest/TestSpecBase.scala b/integrationtest/core/src/it/scala/io/gearpump/integrationtest/TestSpecBase.scala
index 6e4a471..dabcc71 100644
--- a/integrationtest/core/src/it/scala/io/gearpump/integrationtest/TestSpecBase.scala
+++ b/integrationtest/core/src/it/scala/io/gearpump/integrationtest/TestSpecBase.scala
@@ -15,13 +15,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package io.gearpump.integrationtest
+package org.apache.gearpump.integrationtest
import org.scalatest._
-import io.gearpump.cluster.MasterToAppMaster
-import io.gearpump.cluster.MasterToAppMaster.AppMasterData
-import io.gearpump.util.LogUtil
+import org.apache.gearpump.cluster.MasterToAppMaster
+import org.apache.gearpump.cluster.MasterToAppMaster.AppMasterData
+import org.apache.gearpump.util.LogUtil
/**
* The abstract test spec
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/CommandLineSpec.scala
----------------------------------------------------------------------
diff --git a/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/CommandLineSpec.scala b/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/CommandLineSpec.scala
index 9c0c779..eabc684 100644
--- a/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/CommandLineSpec.scala
+++ b/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/CommandLineSpec.scala
@@ -15,10 +15,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package io.gearpump.integrationtest.checklist
+package org.apache.gearpump.integrationtest.checklist
-import io.gearpump.cluster.MasterToAppMaster
-import io.gearpump.integrationtest.TestSpecBase
+import org.apache.gearpump.cluster.MasterToAppMaster
+import org.apache.gearpump.integrationtest.TestSpecBase
/**
* The test spec checks the command-line usage
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/ConnectorKafkaSpec.scala
----------------------------------------------------------------------
diff --git a/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/ConnectorKafkaSpec.scala b/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/ConnectorKafkaSpec.scala
index 321b395..d8bdc1e 100644
--- a/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/ConnectorKafkaSpec.scala
+++ b/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/ConnectorKafkaSpec.scala
@@ -15,12 +15,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package io.gearpump.integrationtest.checklist
+package org.apache.gearpump.integrationtest.checklist
import org.scalatest.TestData
-import io.gearpump.integrationtest.kafka._
-import io.gearpump.integrationtest.{TestSpecBase, Util}
+import org.apache.gearpump.integrationtest.kafka._
+import org.apache.gearpump.integrationtest.{TestSpecBase, Util}
/**
* The test spec checks the Kafka datasource connector
@@ -58,7 +58,7 @@ class ConnectorKafkaSpec extends TestSpecBase {
kafkaCluster.produceDataToKafka(sourceTopic, messageNum)
// exercise
- val args = Array("io.gearpump.streaming.examples.kafka.KafkaReadWrite",
+ val args = Array("org.apache.gearpump.streaming.examples.kafka.KafkaReadWrite",
"-zookeeperConnect", kafkaCluster.getZookeeperConnectString,
"-brokerList", kafkaCluster.getBrokerListConnectString,
"-sourceTopic", sourceTopic,
@@ -86,7 +86,7 @@ class ConnectorKafkaSpec extends TestSpecBase {
producer.start()
// exercise
- val args = Array("io.gearpump.streaming.examples.kafka.KafkaReadWrite",
+ val args = Array("org.apache.gearpump.streaming.examples.kafka.KafkaReadWrite",
"-zookeeperConnect", kafkaCluster.getZookeeperConnectString,
"-brokerList", kafkaCluster.getBrokerListConnectString,
"-sourceTopic", sourceTopic,
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/DynamicDagSpec.scala
----------------------------------------------------------------------
diff --git a/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/DynamicDagSpec.scala b/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/DynamicDagSpec.scala
index 588e7c7..56b33c1 100644
--- a/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/DynamicDagSpec.scala
+++ b/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/DynamicDagSpec.scala
@@ -15,18 +15,18 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package io.gearpump.integrationtest.checklist
+package org.apache.gearpump.integrationtest.checklist
-import io.gearpump.integrationtest.{TestSpecBase, Util}
-import io.gearpump.metrics.Metrics.Meter
-import io.gearpump.streaming._
-import io.gearpump.streaming.appmaster.ProcessorSummary
+import org.apache.gearpump.integrationtest.{TestSpecBase, Util}
+import org.apache.gearpump.metrics.Metrics.Meter
+import org.apache.gearpump.streaming._
+import org.apache.gearpump.streaming.appmaster.ProcessorSummary
class DynamicDagSpec extends TestSpecBase {
lazy val solJar = cluster.queryBuiltInExampleJars("sol-").head
- val splitTaskClass = "io.gearpump.streaming.examples.wordcount.Split"
- val sumTaskClass = "io.gearpump.streaming.examples.wordcount.Sum"
+ val splitTaskClass = "org.apache.gearpump.streaming.examples.wordcount.Split"
+ val sumTaskClass = "org.apache.gearpump.streaming.examples.wordcount.Sum"
val solName = "sol"
"dynamic dag" should {
@@ -34,7 +34,7 @@ class DynamicDagSpec extends TestSpecBase {
val partitioners = restClient.queryBuiltInPartitioners()
partitioners.length should be > 0
partitioners.foreach(clazz =>
- clazz should startWith("io.gearpump.partitioner.")
+ clazz should startWith("org.apache.gearpump.partitioner.")
)
}
@@ -86,7 +86,7 @@ class DynamicDagSpec extends TestSpecBase {
}, "new processor added")
processorHasThroughput(appId, laterProcessors.keySet.max, "receiveThroughput")
- val fakeTaskClass = "io.gearpump.streaming.examples.wordcount.Fake"
+ val fakeTaskClass = "org.apache.gearpump.streaming.examples.wordcount.Fake"
replaceProcessor(appId, laterProcessors.keySet.max, fakeTaskClass)
Util.retryUntil(() => {
val processorsAfterFailure = restClient.queryStreamingAppDetail(appId).processors
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/ExampleSpec.scala
----------------------------------------------------------------------
diff --git a/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/ExampleSpec.scala b/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/ExampleSpec.scala
index 20d1b12..27e4665 100644
--- a/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/ExampleSpec.scala
+++ b/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/ExampleSpec.scala
@@ -15,13 +15,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package io.gearpump.integrationtest.checklist
+package org.apache.gearpump.integrationtest.checklist
import org.apache.log4j.Logger
-import io.gearpump.integrationtest.{Docker, TestSpecBase, Util}
-import io.gearpump.streaming._
-import io.gearpump.streaming.appmaster.ProcessorSummary
+import org.apache.gearpump.integrationtest.{Docker, TestSpecBase, Util}
+import org.apache.gearpump.streaming._
+import org.apache.gearpump.streaming.appmaster.ProcessorSummary
/**
* The test spec will perform destructive operations to check the stability
@@ -33,8 +33,8 @@ class ExampleSpec extends TestSpecBase {
"distributed shell" should {
"execute commands on machines where its executors are running" in {
val distShellJar = cluster.queryBuiltInExampleJars("distributedshell-").head
- val mainClass = "io.gearpump.examples.distributedshell.DistributedShell"
- val clientClass = "io.gearpump.examples.distributedshell.DistributedShellClient"
+ val mainClass = "org.apache.gearpump.examples.distributedshell.DistributedShell"
+ val clientClass = "org.apache.gearpump.examples.distributedshell.DistributedShellClient"
val appId = restClient.getNextAvailableAppId()
val success = restClient.submitApp(distShellJar, cluster.getWorkerHosts.length, mainClass)
success shouldBe true
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/MessageDeliverySpec.scala
----------------------------------------------------------------------
diff --git a/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/MessageDeliverySpec.scala b/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/MessageDeliverySpec.scala
index 3f70339..bb9982a 100644
--- a/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/MessageDeliverySpec.scala
+++ b/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/MessageDeliverySpec.scala
@@ -16,14 +16,14 @@
* limitations under the License.
*/
-package io.gearpump.integrationtest.checklist
+package org.apache.gearpump.integrationtest.checklist
import org.apache.log4j.Logger
-import io.gearpump.integrationtest.hadoop.HadoopCluster._
-import io.gearpump.integrationtest.kafka.KafkaCluster._
-import io.gearpump.integrationtest.kafka.{ResultVerifier, SimpleKafkaReader}
-import io.gearpump.integrationtest.{TestSpecBase, Util}
+import org.apache.gearpump.integrationtest.hadoop.HadoopCluster._
+import org.apache.gearpump.integrationtest.kafka.KafkaCluster._
+import org.apache.gearpump.integrationtest.kafka.{ResultVerifier, SimpleKafkaReader}
+import org.apache.gearpump.integrationtest.{TestSpecBase, Util}
/**
* Checks message delivery consistency, like at-least-once, and exactly-once.
@@ -55,7 +55,7 @@ class MessageDeliverySpec extends TestSpecBase {
withHadoopCluster { hadoopCluster =>
// exercise
- val args = Array("io.gearpump.streaming.examples.state.MessageCountApp",
+ val args = Array("org.apache.gearpump.streaming.examples.state.MessageCountApp",
"-defaultFS", hadoopCluster.getDefaultFS,
"-zookeeperConnect", kafkaCluster.getZookeeperConnectString,
"-brokerList", kafkaCluster.getBrokerListConnectString,
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/RestServiceSpec.scala
----------------------------------------------------------------------
diff --git a/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/RestServiceSpec.scala b/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/RestServiceSpec.scala
index 3ce8a5d..2f5bb64 100644
--- a/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/RestServiceSpec.scala
+++ b/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/RestServiceSpec.scala
@@ -15,14 +15,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package io.gearpump.integrationtest.checklist
+package org.apache.gearpump.integrationtest.checklist
import scala.concurrent.duration._
-import io.gearpump.cluster.MasterToAppMaster
-import io.gearpump.cluster.master.MasterStatus
-import io.gearpump.cluster.worker.{WorkerId, WorkerSummary}
-import io.gearpump.integrationtest.{TestSpecBase, Util}
+import org.apache.gearpump.cluster.MasterToAppMaster
+import org.apache.gearpump.cluster.master.MasterStatus
+import org.apache.gearpump.cluster.worker.{WorkerId, WorkerSummary}
+import org.apache.gearpump.integrationtest.{TestSpecBase, Util}
/**
* The test spec checks REST service usage
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/StabilitySpec.scala
----------------------------------------------------------------------
diff --git a/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/StabilitySpec.scala b/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/StabilitySpec.scala
index b002f70..4b15055 100644
--- a/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/StabilitySpec.scala
+++ b/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/StabilitySpec.scala
@@ -15,14 +15,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package io.gearpump.integrationtest.checklist
+package org.apache.gearpump.integrationtest.checklist
import scala.concurrent.duration.Duration
-import io.gearpump.cluster.MasterToAppMaster
-import io.gearpump.cluster.worker.WorkerId
-import io.gearpump.integrationtest.{TestSpecBase, Util}
-import io.gearpump.util.{Constants, LogUtil}
+import org.apache.gearpump.cluster.MasterToAppMaster
+import org.apache.gearpump.cluster.worker.WorkerId
+import org.apache.gearpump.integrationtest.{TestSpecBase, Util}
+import org.apache.gearpump.util.{Constants, LogUtil}
/**
* The test spec will perform destructive operations to check the stability. Operations
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/StormCompatibilitySpec.scala
----------------------------------------------------------------------
diff --git a/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/StormCompatibilitySpec.scala b/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/StormCompatibilitySpec.scala
index 7d0a672..b327bf4 100644
--- a/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/StormCompatibilitySpec.scala
+++ b/integrationtest/core/src/it/scala/io/gearpump/integrationtest/checklist/StormCompatibilitySpec.scala
@@ -15,11 +15,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package io.gearpump.integrationtest.checklist
+package org.apache.gearpump.integrationtest.checklist
-import io.gearpump.integrationtest.kafka.{KafkaCluster, MessageLossDetector, SimpleKafkaReader}
-import io.gearpump.integrationtest.storm.StormClient
-import io.gearpump.integrationtest.{TestSpecBase, Util}
+import org.apache.gearpump.integrationtest.kafka.{KafkaCluster, MessageLossDetector, SimpleKafkaReader}
+import org.apache.gearpump.integrationtest.storm.StormClient
+import org.apache.gearpump.integrationtest.{TestSpecBase, Util}
/**
* The test spec checks the compatibility of running Storm applications
@@ -129,9 +129,9 @@ class StormCompatibilitySpec extends TestSpecBase {
val stormJar = getStormJar(stormVersion)
val topologyName = getTopologyName("storm_kafka", stormVersion)
val stormKafkaTopology =
- s"io.gearpump.integrationtest.storm.Storm${stormVersion}KafkaTopology"
+ s"org.apache.gearpump.integrationtest.storm.Storm${stormVersion}KafkaTopology"
- import io.gearpump.integrationtest.kafka.KafkaCluster._
+ import org.apache.gearpump.integrationtest.kafka.KafkaCluster._
withKafkaCluster(cluster) {
kafkaCluster =>
val sourcePartitionNum = 2
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/integrationtest/core/src/it/scala/io/gearpump/integrationtest/suites/StandaloneModeSuite.scala
----------------------------------------------------------------------
diff --git a/integrationtest/core/src/it/scala/io/gearpump/integrationtest/suites/StandaloneModeSuite.scala b/integrationtest/core/src/it/scala/io/gearpump/integrationtest/suites/StandaloneModeSuite.scala
index 4178e66..7942308 100644
--- a/integrationtest/core/src/it/scala/io/gearpump/integrationtest/suites/StandaloneModeSuite.scala
+++ b/integrationtest/core/src/it/scala/io/gearpump/integrationtest/suites/StandaloneModeSuite.scala
@@ -15,13 +15,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package io.gearpump.integrationtest.suites
+package org.apache.gearpump.integrationtest.suites
import org.scalatest._
-import io.gearpump.integrationtest.MiniClusterProvider
-import io.gearpump.integrationtest.checklist._
-import io.gearpump.integrationtest.minicluster.MiniCluster
+import org.apache.gearpump.integrationtest.MiniClusterProvider
+import org.apache.gearpump.integrationtest.checklist._
+import org.apache.gearpump.integrationtest.minicluster.MiniCluster
/**
* Launch a Gearpump cluster in standalone mode and run all test specs. To test a specific
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/integrationtest/core/src/main/scala/io/gearpump/integrationtest/Docker.scala
----------------------------------------------------------------------
diff --git a/integrationtest/core/src/main/scala/io/gearpump/integrationtest/Docker.scala b/integrationtest/core/src/main/scala/io/gearpump/integrationtest/Docker.scala
index aee2681..f315ad3 100644
--- a/integrationtest/core/src/main/scala/io/gearpump/integrationtest/Docker.scala
+++ b/integrationtest/core/src/main/scala/io/gearpump/integrationtest/Docker.scala
@@ -15,7 +15,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package io.gearpump.integrationtest
+package org.apache.gearpump.integrationtest
import org.apache.log4j.Logger
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/integrationtest/core/src/main/scala/io/gearpump/integrationtest/ShellExec.scala
----------------------------------------------------------------------
diff --git a/integrationtest/core/src/main/scala/io/gearpump/integrationtest/ShellExec.scala b/integrationtest/core/src/main/scala/io/gearpump/integrationtest/ShellExec.scala
index 9045efe..25d7ee3 100644
--- a/integrationtest/core/src/main/scala/io/gearpump/integrationtest/ShellExec.scala
+++ b/integrationtest/core/src/main/scala/io/gearpump/integrationtest/ShellExec.scala
@@ -15,7 +15,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package io.gearpump.integrationtest
+package org.apache.gearpump.integrationtest
import scala.collection.JavaConverters._
import scala.concurrent.ExecutionContext.Implicits.global
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/integrationtest/core/src/main/scala/io/gearpump/integrationtest/Util.scala
----------------------------------------------------------------------
diff --git a/integrationtest/core/src/main/scala/io/gearpump/integrationtest/Util.scala b/integrationtest/core/src/main/scala/io/gearpump/integrationtest/Util.scala
index 71429b2..7e7085d 100644
--- a/integrationtest/core/src/main/scala/io/gearpump/integrationtest/Util.scala
+++ b/integrationtest/core/src/main/scala/io/gearpump/integrationtest/Util.scala
@@ -15,7 +15,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package io.gearpump.integrationtest
+package org.apache.gearpump.integrationtest
import scala.concurrent.duration._
import scala.util.{Failure, Success, Try}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/integrationtest/core/src/main/scala/io/gearpump/integrationtest/hadoop/HadoopCluster.scala
----------------------------------------------------------------------
diff --git a/integrationtest/core/src/main/scala/io/gearpump/integrationtest/hadoop/HadoopCluster.scala b/integrationtest/core/src/main/scala/io/gearpump/integrationtest/hadoop/HadoopCluster.scala
index 6d277f0..f836abd 100644
--- a/integrationtest/core/src/main/scala/io/gearpump/integrationtest/hadoop/HadoopCluster.scala
+++ b/integrationtest/core/src/main/scala/io/gearpump/integrationtest/hadoop/HadoopCluster.scala
@@ -16,11 +16,11 @@
* limitations under the License.
*/
-package io.gearpump.integrationtest.hadoop
+package org.apache.gearpump.integrationtest.hadoop
import org.apache.log4j.Logger
-import io.gearpump.integrationtest.{Docker, Util}
+import org.apache.gearpump.integrationtest.{Docker, Util}
object HadoopCluster {
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/integrationtest/core/src/main/scala/io/gearpump/integrationtest/kafka/KafkaCluster.scala
----------------------------------------------------------------------
diff --git a/integrationtest/core/src/main/scala/io/gearpump/integrationtest/kafka/KafkaCluster.scala b/integrationtest/core/src/main/scala/io/gearpump/integrationtest/kafka/KafkaCluster.scala
index 862fc58..15ba084 100644
--- a/integrationtest/core/src/main/scala/io/gearpump/integrationtest/kafka/KafkaCluster.scala
+++ b/integrationtest/core/src/main/scala/io/gearpump/integrationtest/kafka/KafkaCluster.scala
@@ -15,12 +15,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package io.gearpump.integrationtest.kafka
+package org.apache.gearpump.integrationtest.kafka
import org.apache.log4j.Logger
-import io.gearpump.integrationtest.minicluster.MiniCluster
-import io.gearpump.integrationtest.{Docker, Util}
+import org.apache.gearpump.integrationtest.minicluster.MiniCluster
+import org.apache.gearpump.integrationtest.{Docker, Util}
object KafkaCluster {
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/integrationtest/core/src/main/scala/io/gearpump/integrationtest/kafka/NumericalDataProducer.scala
----------------------------------------------------------------------
diff --git a/integrationtest/core/src/main/scala/io/gearpump/integrationtest/kafka/NumericalDataProducer.scala b/integrationtest/core/src/main/scala/io/gearpump/integrationtest/kafka/NumericalDataProducer.scala
index 03bb9fb..1cf3125 100644
--- a/integrationtest/core/src/main/scala/io/gearpump/integrationtest/kafka/NumericalDataProducer.scala
+++ b/integrationtest/core/src/main/scala/io/gearpump/integrationtest/kafka/NumericalDataProducer.scala
@@ -15,7 +15,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package io.gearpump.integrationtest.kafka
+package org.apache.gearpump.integrationtest.kafka
import java.util.Properties
@@ -23,7 +23,7 @@ import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord}
import org.apache.kafka.common.serialization.ByteArraySerializer
import org.apache.log4j.Logger
-import io.gearpump.streaming.serializer.ChillSerializer
+import org.apache.gearpump.streaming.serializer.ChillSerializer
class NumericalDataProducer(topic: String, bootstrapServers: String) {
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/integrationtest/core/src/main/scala/io/gearpump/integrationtest/kafka/ResultVerifier.scala
----------------------------------------------------------------------
diff --git a/integrationtest/core/src/main/scala/io/gearpump/integrationtest/kafka/ResultVerifier.scala b/integrationtest/core/src/main/scala/io/gearpump/integrationtest/kafka/ResultVerifier.scala
index 98aceba..1f773d3 100644
--- a/integrationtest/core/src/main/scala/io/gearpump/integrationtest/kafka/ResultVerifier.scala
+++ b/integrationtest/core/src/main/scala/io/gearpump/integrationtest/kafka/ResultVerifier.scala
@@ -15,7 +15,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package io.gearpump.integrationtest.kafka
+package org.apache.gearpump.integrationtest.kafka
import scala.collection.mutable
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/integrationtest/core/src/main/scala/io/gearpump/integrationtest/kafka/SimpleKafkaReader.scala
----------------------------------------------------------------------
diff --git a/integrationtest/core/src/main/scala/io/gearpump/integrationtest/kafka/SimpleKafkaReader.scala b/integrationtest/core/src/main/scala/io/gearpump/integrationtest/kafka/SimpleKafkaReader.scala
index 29289d9..392ca86 100644
--- a/integrationtest/core/src/main/scala/io/gearpump/integrationtest/kafka/SimpleKafkaReader.scala
+++ b/integrationtest/core/src/main/scala/io/gearpump/integrationtest/kafka/SimpleKafkaReader.scala
@@ -15,7 +15,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package io.gearpump.integrationtest.kafka
+package org.apache.gearpump.integrationtest.kafka
import scala.util.{Failure, Success}
@@ -23,7 +23,7 @@ import kafka.api.FetchRequestBuilder
import kafka.consumer.SimpleConsumer
import kafka.utils.Utils
-import io.gearpump.streaming.serializer.ChillSerializer
+import org.apache.gearpump.streaming.serializer.ChillSerializer
class SimpleKafkaReader(verifier: ResultVerifier, topic: String, partition: Int = 0,
host: String, port: Int) {
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/integrationtest/core/src/main/scala/io/gearpump/integrationtest/minicluster/BaseContainer.scala
----------------------------------------------------------------------
diff --git a/integrationtest/core/src/main/scala/io/gearpump/integrationtest/minicluster/BaseContainer.scala b/integrationtest/core/src/main/scala/io/gearpump/integrationtest/minicluster/BaseContainer.scala
index e5c7cb7..73413da 100644
--- a/integrationtest/core/src/main/scala/io/gearpump/integrationtest/minicluster/BaseContainer.scala
+++ b/integrationtest/core/src/main/scala/io/gearpump/integrationtest/minicluster/BaseContainer.scala
@@ -15,11 +15,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package io.gearpump.integrationtest.minicluster
+package org.apache.gearpump.integrationtest.minicluster
import scala.sys.process._
-import io.gearpump.integrationtest.Docker
+import org.apache.gearpump.integrationtest.Docker
/**
* A helper to instantiate the base image for different usage.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/integrationtest/core/src/main/scala/io/gearpump/integrationtest/minicluster/CommandLineClient.scala
----------------------------------------------------------------------
diff --git a/integrationtest/core/src/main/scala/io/gearpump/integrationtest/minicluster/CommandLineClient.scala b/integrationtest/core/src/main/scala/io/gearpump/integrationtest/minicluster/CommandLineClient.scala
index 5eebd30..884a8d1 100644
--- a/integrationtest/core/src/main/scala/io/gearpump/integrationtest/minicluster/CommandLineClient.scala
+++ b/integrationtest/core/src/main/scala/io/gearpump/integrationtest/minicluster/CommandLineClient.scala
@@ -15,12 +15,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package io.gearpump.integrationtest.minicluster
+package org.apache.gearpump.integrationtest.minicluster
import org.apache.log4j.Logger
-import io.gearpump.cluster.MasterToAppMaster
-import io.gearpump.integrationtest.Docker
+import org.apache.gearpump.cluster.MasterToAppMaster
+import org.apache.gearpump.integrationtest.Docker
/**
* A command-line client to operate a Gearpump cluster
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/integrationtest/core/src/main/scala/io/gearpump/integrationtest/minicluster/MiniCluster.scala
----------------------------------------------------------------------
diff --git a/integrationtest/core/src/main/scala/io/gearpump/integrationtest/minicluster/MiniCluster.scala b/integrationtest/core/src/main/scala/io/gearpump/integrationtest/minicluster/MiniCluster.scala
index bfdecee..4d439e8 100644
--- a/integrationtest/core/src/main/scala/io/gearpump/integrationtest/minicluster/MiniCluster.scala
+++ b/integrationtest/core/src/main/scala/io/gearpump/integrationtest/minicluster/MiniCluster.scala
@@ -15,14 +15,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package io.gearpump.integrationtest.minicluster
+package org.apache.gearpump.integrationtest.minicluster
import java.io.IOException
import scala.collection.mutable.ListBuffer
import org.apache.log4j.Logger
-import io.gearpump.integrationtest.{Docker, Util}
+import org.apache.gearpump.integrationtest.{Docker, Util}
/**
* This class is a test driver for end-to-end integration test.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/integrationtest/core/src/main/scala/io/gearpump/integrationtest/minicluster/RestClient.scala
----------------------------------------------------------------------
diff --git a/integrationtest/core/src/main/scala/io/gearpump/integrationtest/minicluster/RestClient.scala b/integrationtest/core/src/main/scala/io/gearpump/integrationtest/minicluster/RestClient.scala
index 72b0f84..a2d8f99 100644
--- a/integrationtest/core/src/main/scala/io/gearpump/integrationtest/minicluster/RestClient.scala
+++ b/integrationtest/core/src/main/scala/io/gearpump/integrationtest/minicluster/RestClient.scala
@@ -15,7 +15,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package io.gearpump.integrationtest.minicluster
+package org.apache.gearpump.integrationtest.minicluster
import scala.reflect.ClassTag
@@ -24,23 +24,23 @@ import org.apache.log4j.Logger
import upickle.Js
import upickle.default._
-import io.gearpump.cluster.AppMasterToMaster.MasterData
-import io.gearpump.cluster.MasterToAppMaster.{AppMasterData, AppMastersData}
-import io.gearpump.cluster.MasterToClient.HistoryMetrics
-import io.gearpump.cluster.master.MasterSummary
-import io.gearpump.cluster.worker.{WorkerId, WorkerSummary}
-import io.gearpump.cluster.{AppJar, MasterToAppMaster}
-import io.gearpump.integrationtest.{Docker, Util}
-import io.gearpump.services.AppMasterService.Status
-import io.gearpump.services.MasterService.{AppSubmissionResult, BuiltinPartitioners}
+import org.apache.gearpump.cluster.AppMasterToMaster.MasterData
+import org.apache.gearpump.cluster.MasterToAppMaster.{AppMasterData, AppMastersData}
+import org.apache.gearpump.cluster.MasterToClient.HistoryMetrics
+import org.apache.gearpump.cluster.master.MasterSummary
+import org.apache.gearpump.cluster.worker.{WorkerId, WorkerSummary}
+import org.apache.gearpump.cluster.{AppJar, MasterToAppMaster}
+import org.apache.gearpump.integrationtest.{Docker, Util}
+import org.apache.gearpump.services.AppMasterService.Status
+import org.apache.gearpump.services.MasterService.{AppSubmissionResult, BuiltinPartitioners}
// NOTE: This cannot be removed!!!
-import io.gearpump.services.util.UpickleUtil._
-import io.gearpump.streaming.ProcessorDescription
-import io.gearpump.streaming.appmaster.AppMaster.ExecutorBrief
-import io.gearpump.streaming.appmaster.DagManager.{DAGOperationResult, ReplaceProcessor}
-import io.gearpump.streaming.appmaster.StreamAppMasterSummary
-import io.gearpump.streaming.executor.Executor.ExecutorSummary
-import io.gearpump.util.{Constants, Graph}
+import org.apache.gearpump.services.util.UpickleUtil._
+import org.apache.gearpump.streaming.ProcessorDescription
+import org.apache.gearpump.streaming.appmaster.AppMaster.ExecutorBrief
+import org.apache.gearpump.streaming.appmaster.DagManager.{DAGOperationResult, ReplaceProcessor}
+import org.apache.gearpump.streaming.appmaster.StreamAppMasterSummary
+import org.apache.gearpump.streaming.executor.Executor.ExecutorSummary
+import org.apache.gearpump.util.{Constants, Graph}
/**
* A REST client to operate a Gearpump cluster
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/integrationtest/core/src/main/scala/io/gearpump/integrationtest/storm/StormClient.scala
----------------------------------------------------------------------
diff --git a/integrationtest/core/src/main/scala/io/gearpump/integrationtest/storm/StormClient.scala b/integrationtest/core/src/main/scala/io/gearpump/integrationtest/storm/StormClient.scala
index ea9ca65..79adfc4 100644
--- a/integrationtest/core/src/main/scala/io/gearpump/integrationtest/storm/StormClient.scala
+++ b/integrationtest/core/src/main/scala/io/gearpump/integrationtest/storm/StormClient.scala
@@ -16,14 +16,14 @@
* limitations under the License.
*/
-package io.gearpump.integrationtest.storm
+package org.apache.gearpump.integrationtest.storm
import scala.util.Random
import backtype.storm.utils.{DRPCClient, Utils}
-import io.gearpump.integrationtest.minicluster.{BaseContainer, MiniCluster, RestClient}
-import io.gearpump.integrationtest.{Docker, Util}
+import org.apache.gearpump.integrationtest.minicluster.{BaseContainer, MiniCluster, RestClient}
+import org.apache.gearpump.integrationtest.{Docker, Util}
class StormClient(cluster: MiniCluster, restClient: RestClient) {
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/integrationtest/storm010/src/main/scala/io/gearpump/integrationtest/storm/Adaptor.scala
----------------------------------------------------------------------
diff --git a/integrationtest/storm010/src/main/scala/io/gearpump/integrationtest/storm/Adaptor.scala b/integrationtest/storm010/src/main/scala/io/gearpump/integrationtest/storm/Adaptor.scala
index 6e4f257..67a2491 100644
--- a/integrationtest/storm010/src/main/scala/io/gearpump/integrationtest/storm/Adaptor.scala
+++ b/integrationtest/storm010/src/main/scala/io/gearpump/integrationtest/storm/Adaptor.scala
@@ -15,7 +15,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package io.gearpump.integrationtest.storm
+package org.apache.gearpump.integrationtest.storm
import backtype.storm.topology.base.BaseBasicBolt
import backtype.storm.topology.{BasicOutputCollector, OutputFieldsDeclarer}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/integrationtest/storm010/src/main/scala/io/gearpump/integrationtest/storm/Storm010KafkaTopology.scala
----------------------------------------------------------------------
diff --git a/integrationtest/storm010/src/main/scala/io/gearpump/integrationtest/storm/Storm010KafkaTopology.scala b/integrationtest/storm010/src/main/scala/io/gearpump/integrationtest/storm/Storm010KafkaTopology.scala
index fa48112..a0d9a42 100644
--- a/integrationtest/storm010/src/main/scala/io/gearpump/integrationtest/storm/Storm010KafkaTopology.scala
+++ b/integrationtest/storm010/src/main/scala/io/gearpump/integrationtest/storm/Storm010KafkaTopology.scala
@@ -16,7 +16,7 @@
* limitations under the License.
*/
-package io.gearpump.integrationtest.storm
+package org.apache.gearpump.integrationtest.storm
import java.util.{ArrayList => JArrayList, HashMap => JHashMap, Map => JMap}
@@ -25,7 +25,7 @@ import backtype.storm.{Config, StormSubmitter}
import storm.kafka.bolt.KafkaBolt
import storm.kafka.{KafkaSpout, SpoutConfig, ZkHosts}
-import io.gearpump.cluster.main.{ArgumentsParser, CLIOption}
+import org.apache.gearpump.cluster.main.{ArgumentsParser, CLIOption}
/**
* Tests Storm 0.10.x compatibility over Gearpump
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/integrationtest/storm09/src/main/scala/io/gearpump/integrationtest/storm/Adaptor.scala
----------------------------------------------------------------------
diff --git a/integrationtest/storm09/src/main/scala/io/gearpump/integrationtest/storm/Adaptor.scala b/integrationtest/storm09/src/main/scala/io/gearpump/integrationtest/storm/Adaptor.scala
index 6e4f257..67a2491 100644
--- a/integrationtest/storm09/src/main/scala/io/gearpump/integrationtest/storm/Adaptor.scala
+++ b/integrationtest/storm09/src/main/scala/io/gearpump/integrationtest/storm/Adaptor.scala
@@ -15,7 +15,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package io.gearpump.integrationtest.storm
+package org.apache.gearpump.integrationtest.storm
import backtype.storm.topology.base.BaseBasicBolt
import backtype.storm.topology.{BasicOutputCollector, OutputFieldsDeclarer}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/integrationtest/storm09/src/main/scala/io/gearpump/integrationtest/storm/Storm09KafkaTopology.scala
----------------------------------------------------------------------
diff --git a/integrationtest/storm09/src/main/scala/io/gearpump/integrationtest/storm/Storm09KafkaTopology.scala b/integrationtest/storm09/src/main/scala/io/gearpump/integrationtest/storm/Storm09KafkaTopology.scala
index 918dc56..5b74d60 100644
--- a/integrationtest/storm09/src/main/scala/io/gearpump/integrationtest/storm/Storm09KafkaTopology.scala
+++ b/integrationtest/storm09/src/main/scala/io/gearpump/integrationtest/storm/Storm09KafkaTopology.scala
@@ -15,7 +15,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package io.gearpump.integrationtest.storm
+package org.apache.gearpump.integrationtest.storm
import java.util.{ArrayList => JArrayList, HashMap => JHashMap, Map => JMap}
@@ -24,7 +24,7 @@ import backtype.storm.{Config, StormSubmitter}
import storm.kafka.bolt.KafkaBolt
import storm.kafka.{KafkaSpout, SpoutConfig, ZkHosts}
-import io.gearpump.cluster.main.{ArgumentsParser, CLIOption}
+import org.apache.gearpump.cluster.main.{ArgumentsParser, CLIOption}
/**
* Tests Storm 0.9.x compatibility over Gearpump
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/project/Build.scala
----------------------------------------------------------------------
diff --git a/project/Build.scala b/project/Build.scala
index b9e6f94..9a3e980 100644
--- a/project/Build.scala
+++ b/project/Build.scala
@@ -226,8 +226,7 @@ object Build extends sbt.Build {
external_monoid,
external_serializer,
external_hbase,
- external_hadoopfs,
- streaming)
+ external_hadoopfs)
lazy val gearpumpUnidocSetting = scalaJavaUnidocSettings ++ Seq(
unidocProjectFilter in(ScalaUnidoc, unidoc) := projectsWithDoc,
@@ -244,7 +243,9 @@ object Build extends sbt.Build {
)
private def ignoreUndocumentedPackages(packages: Seq[Seq[File]]): Seq[Seq[File]] = {
- packages.map(_.filterNot(_.getCanonicalPath.contains("akka")))
+ packages
+ .map(_.filterNot(_.getName.contains("$")))
+ .map(_.filterNot(_.getCanonicalPath.contains("akka")))
}
lazy val root = Project(
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/project/BuildExample.scala
----------------------------------------------------------------------
diff --git a/project/BuildExample.scala b/project/BuildExample.scala
index 3bd93c3..a4ae87b 100644
--- a/project/BuildExample.scala
+++ b/project/BuildExample.scala
@@ -36,7 +36,7 @@ object BuildExample extends sbt.Build {
settings = commonSettings ++ noPublish ++ myAssemblySettings ++
Seq(
mainClass in(Compile, packageBin) :=
- Some("io.gearpump.streaming.examples.wordcountjava.WordCount"),
+ Some("org.apache.gearpump.streaming.examples.wordcountjava.WordCount"),
target in assembly := baseDirectory.value.getParentFile.getParentFile / "target" /
CrossVersion.binaryScalaVersion(scalaVersion.value)
@@ -49,7 +49,7 @@ object BuildExample extends sbt.Build {
settings = commonSettings ++ noPublish ++ myAssemblySettings ++
Seq(
mainClass in(Compile, packageBin) :=
- Some("io.gearpump.streaming.examples.wordcount.WordCount"),
+ Some("org.apache.gearpump.streaming.examples.wordcount.WordCount"),
target in assembly := baseDirectory.value.getParentFile.getParentFile / "target" /
CrossVersion.binaryScalaVersion(scalaVersion.value)
@@ -61,7 +61,7 @@ object BuildExample extends sbt.Build {
base = file("examples/streaming/sol"),
settings = commonSettings ++ noPublish ++ myAssemblySettings ++
Seq(
- mainClass in(Compile, packageBin) := Some("io.gearpump.streaming.examples.sol.SOL"),
+ mainClass in(Compile, packageBin) := Some("org.apache.gearpump.streaming.examples.sol.SOL"),
target in assembly := baseDirectory.value.getParentFile.getParentFile / "target" /
CrossVersion.binaryScalaVersion(scalaVersion.value)
@@ -74,7 +74,7 @@ object BuildExample extends sbt.Build {
settings = commonSettings ++ noPublish ++ myAssemblySettings ++
Seq(
mainClass in(Compile, packageBin) :=
- Some("io.gearpump.streaming.examples.complexdag.Dag"),
+ Some("org.apache.gearpump.streaming.examples.complexdag.Dag"),
target in assembly := baseDirectory.value.getParentFile.getParentFile / "target" /
CrossVersion.binaryScalaVersion(scalaVersion.value)
@@ -93,7 +93,7 @@ object BuildExample extends sbt.Build {
"com.lihaoyi" %% "upickle" % upickleVersion
),
mainClass in(Compile, packageBin) :=
- Some("io.gearpump.streaming.examples.transport.Transport"),
+ Some("org.apache.gearpump.streaming.examples.transport.Transport"),
target in assembly := baseDirectory.value.getParentFile.getParentFile / "target" /
CrossVersion.binaryScalaVersion(scalaVersion.value)
@@ -106,7 +106,7 @@ object BuildExample extends sbt.Build {
settings = commonSettings ++ noPublish ++ myAssemblySettings ++
Seq(
mainClass in(Compile, packageBin) :=
- Some("io.gearpump.examples.distributedshell.DistributedShell"),
+ Some("org.apache.gearpump.examples.distributedshell.DistributedShell"),
target in assembly := baseDirectory.value.getParentFile / "target" /
CrossVersion.binaryScalaVersion(scalaVersion.value)
@@ -126,7 +126,7 @@ object BuildExample extends sbt.Build {
"io.spray" %% "spray-routing-shapeless2" % sprayVersion
),
mainClass in(Compile, packageBin) :=
- Some("io.gearpump.experiments.distributeservice.DistributeService"),
+ Some("org.apache.gearpump.experiments.distributeservice.DistributeService"),
target in assembly := baseDirectory.value.getParentFile / "target" /
CrossVersion.binaryScalaVersion(scalaVersion.value)
@@ -150,7 +150,7 @@ object BuildExample extends sbt.Build {
exclude("org.ow2.asm", "asm")
),
mainClass in(Compile, packageBin) :=
- Some("io.gearpump.streaming.examples.fsio.SequenceFileIO"),
+ Some("org.apache.gearpump.streaming.examples.fsio.SequenceFileIO"),
target in assembly := baseDirectory.value.getParentFile.getParentFile / "target" /
CrossVersion.binaryScalaVersion(scalaVersion.value)
@@ -163,7 +163,7 @@ object BuildExample extends sbt.Build {
settings = commonSettings ++ noPublish ++ myAssemblySettings ++
Seq(
mainClass in(Compile, packageBin) :=
- Some("io.gearpump.streaming.examples.kafka.wordcount.KafkaWordCount"),
+ Some("org.apache.gearpump.streaming.examples.kafka.wordcount.KafkaWordCount"),
target in assembly := baseDirectory.value.getParentFile.getParentFile / "target" /
CrossVersion.binaryScalaVersion(scalaVersion.value)
@@ -186,7 +186,7 @@ object BuildExample extends sbt.Build {
"io.spray" %% "spray-json" % sprayJsonVersion
),
mainClass in(Compile, packageBin) :=
- Some("io.gearpump.streaming.examples.stock.main.Stock"),
+ Some("org.apache.gearpump.streaming.examples.stock.main.Stock"),
target in assembly := baseDirectory.value.getParentFile.getParentFile / "target" /
CrossVersion.binaryScalaVersion(scalaVersion.value)
@@ -210,7 +210,7 @@ object BuildExample extends sbt.Build {
"org.apache.hadoop" % "hadoop-hdfs" % clouderaVersion
),
mainClass in(Compile, packageBin) :=
- Some("io.gearpump.streaming.examples.state.MessageCountApp"),
+ Some("org.apache.gearpump.streaming.examples.state.MessageCountApp"),
target in assembly := baseDirectory.value.getParentFile.getParentFile / "target" /
CrossVersion.binaryScalaVersion(scalaVersion.value)
@@ -223,7 +223,7 @@ object BuildExample extends sbt.Build {
base = file("examples/pagerank"),
settings = commonSettings ++ noPublish ++ myAssemblySettings ++ Seq(
mainClass in(Compile, packageBin) :=
- Some("io.gearpump.experiments.pagerank.example.PageRankExample"),
+ Some("org.apache.gearpump.experiments.pagerank.example.PageRankExample"),
target in assembly := baseDirectory.value.getParentFile.getParentFile / "target" /
CrossVersion.binaryScalaVersion(scalaVersion.value)
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/project/Pack.scala
----------------------------------------------------------------------
diff --git a/project/Pack.scala b/project/Pack.scala
index 7339d1d..a675bdf 100644
--- a/project/Pack.scala
+++ b/project/Pack.scala
@@ -62,13 +62,13 @@ object Pack extends sbt.Build {
packSettings ++
Seq(
packMain := Map(
- "gear" -> "io.gearpump.cluster.main.Gear",
- "local" -> "io.gearpump.cluster.main.Local",
- "master" -> "io.gearpump.cluster.main.Master",
- "worker" -> "io.gearpump.cluster.main.Worker",
- "services" -> "io.gearpump.services.main.Services",
- "yarnclient" -> "io.gearpump.experiments.yarn.client.Client",
- "storm" -> "io.gearpump.experiments.storm.StormRunner"
+ "gear" -> "org.apache.gearpump.cluster.main.Gear",
+ "local" -> "org.apache.gearpump.cluster.main.Local",
+ "master" -> "org.apache.gearpump.cluster.main.Master",
+ "worker" -> "org.apache.gearpump.cluster.main.Worker",
+ "services" -> "org.apache.gearpump.services.main.Services",
+ "yarnclient" -> "org.apache.gearpump.experiments.yarn.client.Client",
+ "storm" -> "org.apache.gearpump.experiments.storm.StormRunner"
),
packJvmOpts := Map(
"gear" -> Seq("-Djava.net.preferIPv4Stack=true", "-Dgearpump.home=${PROG_HOME}"),
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/README.md
----------------------------------------------------------------------
diff --git a/services/README.md b/services/README.md
index 478fa27..ca35301 100644
--- a/services/README.md
+++ b/services/README.md
@@ -11,7 +11,7 @@ cd ~/gearpump
sbt clean publishLocal assembly pack
target/pack/bin/local
target/pack/bin/services
-target/pack/bin/gear app -jar ./examples/complexdag/target/scala-2.11/gepump-examples-complexdag_2.11-0.2.4-SNAPSHOT.jar io.gearpump.streaming.examples.complexdag.Dag
+target/pack/bin/gear app -jar ./examples/complexdag/target/scala-2.11/gepump-examples-complexdag_2.11-0.2.4-SNAPSHOT.jar org.apache.gearpump.streaming.examples.complexdag.Dag
```
Launch your browser at http://localhost:8090
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/dashboard/dashboard.js
----------------------------------------------------------------------
diff --git a/services/dashboard/dashboard.js b/services/dashboard/dashboard.js
index 37af2bf..87ac50f 100644
--- a/services/dashboard/dashboard.js
+++ b/services/dashboard/dashboard.js
@@ -22,7 +22,7 @@
'cfp.loadingBarInterceptor',
'ngFileUpload',
'dashing',
- 'io.gearpump.models'
+ 'org.apache.gearpump.models'
])
// configure routes
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/dashboard/services/models/dag.js
----------------------------------------------------------------------
diff --git a/services/dashboard/services/models/dag.js b/services/dashboard/services/models/dag.js
index bff12db..84d2492 100644
--- a/services/dashboard/services/models/dag.js
+++ b/services/dashboard/services/models/dag.js
@@ -3,7 +3,7 @@
* See accompanying LICENSE file.
*/
-angular.module('io.gearpump.models')
+angular.module('org.apache.gearpump.models')
.service('Dag', function () {
'use strict';
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/dashboard/services/models/metrics.js
----------------------------------------------------------------------
diff --git a/services/dashboard/services/models/metrics.js b/services/dashboard/services/models/metrics.js
index 00b2305..3a48f1f 100644
--- a/services/dashboard/services/models/metrics.js
+++ b/services/dashboard/services/models/metrics.js
@@ -3,7 +3,7 @@
* See accompanying LICENSE file.
*/
-angular.module('io.gearpump.models')
+angular.module('org.apache.gearpump.models')
/** TODO: to be absorbed as scalajs (#458) */
.factory('Metrics', [function () {
@@ -54,11 +54,11 @@ angular.module('io.gearpump.models')
/** automatically guess metric type and decode or return null */
$auto: function (data) {
switch (data.value.$type) {
- case 'io.gearpump.metrics.Metrics.Meter':
+ case 'org.apache.gearpump.metrics.Metrics.Meter':
return decoder.meter(data);
- case 'io.gearpump.metrics.Metrics.Histogram':
+ case 'org.apache.gearpump.metrics.Metrics.Histogram':
return decoder.histogram(data);
- case 'io.gearpump.metrics.Metrics.Gauge':
+ case 'org.apache.gearpump.metrics.Metrics.Gauge':
return decoder.gauge(data);
default:
console.warn({message: 'Unknown metric type', type: data.value.$type});
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/dashboard/services/models/metrics_provider.js
----------------------------------------------------------------------
diff --git a/services/dashboard/services/models/metrics_provider.js b/services/dashboard/services/models/metrics_provider.js
index cddd1f1..57c6f7c 100644
--- a/services/dashboard/services/models/metrics_provider.js
+++ b/services/dashboard/services/models/metrics_provider.js
@@ -3,7 +3,7 @@
* See accompanying LICENSE file.
*/
-angular.module('io.gearpump.models')
+angular.module('org.apache.gearpump.models')
.service('MetricsProvider', function () {
'use strict';
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/dashboard/services/models/models.js
----------------------------------------------------------------------
diff --git a/services/dashboard/services/models/models.js b/services/dashboard/services/models/models.js
index 15755bc..8265bac 100644
--- a/services/dashboard/services/models/models.js
+++ b/services/dashboard/services/models/models.js
@@ -3,7 +3,7 @@
* See accompanying LICENSE file.
*/
-angular.module('io.gearpump.models', [])
+angular.module('org.apache.gearpump.models', [])
/** TODO: to be absorbed as scalajs */
.factory('models', ['$timeout', 'conf', 'restapi', 'locator', 'StreamingAppDag', 'Metrics',
@@ -388,7 +388,7 @@ angular.module('io.gearpump.models', [])
return getter._appMetrics(appId, {all: 'latest'});
},
_appMetrics: function (appId, args) {
- args.aggregator = 'io.gearpump.streaming.metrics.ProcessorAggregator';
+ args.aggregator = 'org.apache.gearpump.streaming.metrics.ProcessorAggregator';
args.decoder = decoder.appMetrics;
return getter._metrics('appmaster/' + appId + '/metrics/app' + appId, '', args);
},
@@ -397,7 +397,7 @@ angular.module('io.gearpump.models', [])
'&startTask=' + range.start + '&endTask=' + (range.stop + 1) : '';
var args = {
all: 'latest',
- aggregator: 'io.gearpump.streaming.metrics.TaskFilterAggregator' +
+ aggregator: 'org.apache.gearpump.streaming.metrics.TaskFilterAggregator' +
'&startProcessor=' + processorId + '&endProcessor=' + (processorId + 1) + taskRangeArgs,
decoder: decoder.appTaskLatestMetricValues
};
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/dashboard/services/models/streamingapp_dag.js
----------------------------------------------------------------------
diff --git a/services/dashboard/services/models/streamingapp_dag.js b/services/dashboard/services/models/streamingapp_dag.js
index 7fd5800..c882b89 100644
--- a/services/dashboard/services/models/streamingapp_dag.js
+++ b/services/dashboard/services/models/streamingapp_dag.js
@@ -3,7 +3,7 @@
* See accompanying LICENSE file.
*/
-angular.module('io.gearpump.models')
+angular.module('org.apache.gearpump.models')
.service('StreamingAppDag', ['Dag', 'StreamingAppMetricsProvider', function (Dag, StreamingAppMetricsProvider) {
'use strict';
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/dashboard/services/models/streamingapp_metrics_provider.js
----------------------------------------------------------------------
diff --git a/services/dashboard/services/models/streamingapp_metrics_provider.js b/services/dashboard/services/models/streamingapp_metrics_provider.js
index 2a9f655..3a2d37b 100644
--- a/services/dashboard/services/models/streamingapp_metrics_provider.js
+++ b/services/dashboard/services/models/streamingapp_metrics_provider.js
@@ -3,7 +3,7 @@
* See accompanying LICENSE file.
*/
-angular.module('io.gearpump.models')
+angular.module('org.apache.gearpump.models')
.service('StreamingAppMetricsProvider', ['MetricsProvider', function (MetricsProvider) {
'use strict';
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/dashboard/services/restapi.js
----------------------------------------------------------------------
diff --git a/services/dashboard/services/restapi.js b/services/dashboard/services/restapi.js
index 29a1683..3bad10c 100644
--- a/services/dashboard/services/restapi.js
+++ b/services/dashboard/services/restapi.js
@@ -220,7 +220,7 @@ angular.module('dashboard')
replaceDagProcessor: function (files, formFormNames, appId, oldProcessorId, newProcessorDescription, onComplete) {
var url = restapiV1Root + 'appmaster/' + appId + '/dynamicdag';
var args = {
- "$type": 'io.gearpump.streaming.appmaster.DagManager.ReplaceProcessor',
+ "$type": 'org.apache.gearpump.streaming.appmaster.DagManager.ReplaceProcessor',
oldProcessorId: oldProcessorId,
newProcessorDescription: angular.merge({
id: oldProcessorId
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/js/src/main/scala/io/gearpump/dashboard/DashboardApp.scala
----------------------------------------------------------------------
diff --git a/services/js/src/main/scala/io/gearpump/dashboard/DashboardApp.scala b/services/js/src/main/scala/io/gearpump/dashboard/DashboardApp.scala
deleted file mode 100644
index 3d80c4e..0000000
--- a/services/js/src/main/scala/io/gearpump/dashboard/DashboardApp.scala
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.dashboard
-
-import scala.scalajs.js.JSApp
-import scala.scalajs.js.annotation.JSExport
-
-@JSExport
-object DashboardApp extends JSApp {
- override def main(): Unit = {
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/js/src/main/scala/org/apache/gearpump/dashboard/DashboardApp.scala
----------------------------------------------------------------------
diff --git a/services/js/src/main/scala/org/apache/gearpump/dashboard/DashboardApp.scala b/services/js/src/main/scala/org/apache/gearpump/dashboard/DashboardApp.scala
new file mode 100644
index 0000000..f4e64f2
--- /dev/null
+++ b/services/js/src/main/scala/org/apache/gearpump/dashboard/DashboardApp.scala
@@ -0,0 +1,28 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.dashboard
+
+import scala.scalajs.js.JSApp
+import scala.scalajs.js.annotation.JSExport
+
+@JSExport
+object DashboardApp extends JSApp {
+ override def main(): Unit = {
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/main/scala/io/gearpump/services/AdminService.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/main/scala/io/gearpump/services/AdminService.scala b/services/jvm/src/main/scala/io/gearpump/services/AdminService.scala
deleted file mode 100644
index eb6531f..0000000
--- a/services/jvm/src/main/scala/io/gearpump/services/AdminService.scala
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.services
-
-import akka.actor.ActorSystem
-import akka.http.scaladsl.model._
-import akka.http.scaladsl.server.Directives._
-import akka.stream.Materializer
-
-// NOTE: This cannot be removed!!!
-import io.gearpump.services.util.UpickleUtil._
-
-/**
- * AdminService is for cluster-wide managements. it is not related with
- * specific application.
- *
- * For example:
- * - Security management: Add user, remove user.
- * - Configuration management: Change configurations.
- * - Machine management: Add worker machines, remove worker machines, and add masters.
- */
-
-// TODO: Add YARN resource manager capacities to add/remove machines.
-class AdminService(override val system: ActorSystem)
- extends BasicService {
-
- protected override def prefix = Neutral
-
- protected override def doRoute(implicit mat: Materializer) = {
- path("terminate") {
- post {
- system.terminate()
- complete(StatusCodes.NotFound)
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/main/scala/io/gearpump/services/AppMasterService.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/main/scala/io/gearpump/services/AppMasterService.scala b/services/jvm/src/main/scala/io/gearpump/services/AppMasterService.scala
deleted file mode 100644
index 060e780..0000000
--- a/services/jvm/src/main/scala/io/gearpump/services/AppMasterService.scala
+++ /dev/null
@@ -1,226 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.services
-
-import scala.util.{Failure, Success, Try}
-
-import akka.actor.{ActorRef, ActorSystem}
-import akka.http.scaladsl.model.{FormData, Multipart}
-import akka.http.scaladsl.server.Directives._
-import akka.http.scaladsl.server.Route
-import akka.http.scaladsl.server.directives.ParameterDirectives.ParamMagnet
-import akka.stream.Materializer
-import upickle.default.{read, write}
-
-import io.gearpump.cluster.AppMasterToMaster.{AppMasterSummary, GeneralAppMasterSummary}
-import io.gearpump.cluster.ClientToMaster._
-import io.gearpump.cluster.ClusterConfig
-import io.gearpump.cluster.MasterToAppMaster.{AppMasterData, AppMasterDataDetailRequest, AppMasterDataRequest}
-import io.gearpump.cluster.MasterToClient._
-import io.gearpump.jarstore.JarStoreService
-import io.gearpump.services.AppMasterService.Status
-// NOTE: This cannot be removed!!!
-import io.gearpump.services.util.UpickleUtil._
-import io.gearpump.streaming.AppMasterToMaster.StallingTasks
-import io.gearpump.streaming.appmaster.DagManager._
-import io.gearpump.streaming.appmaster.StreamAppMasterSummary
-import io.gearpump.streaming.executor.Executor.{ExecutorConfig, ExecutorSummary, GetExecutorSummary, QueryExecutorConfig}
-import io.gearpump.util.ActorUtil.{askActor, askAppMaster}
-import io.gearpump.util.FileDirective._
-import io.gearpump.util.{Constants, Util}
-
-/**
- * Management service for AppMaster
- */
-class AppMasterService(val master: ActorRef,
- val jarStore: JarStoreService, override val system: ActorSystem)
- extends BasicService {
-
- private val systemConfig = system.settings.config
- private val concise = systemConfig.getBoolean(Constants.GEARPUMP_SERVICE_RENDER_CONFIG_CONCISE)
-
- protected override def doRoute(implicit mat: Materializer) = pathPrefix("appmaster" / IntNumber) {
- appId => {
- path("dynamicdag") {
- parameters(ParamMagnet("args")) { args: String =>
- def replaceProcessor(dagOperation: DAGOperation): Route = {
- onComplete(askAppMaster[DAGOperationResult](master, appId, dagOperation)) {
- case Success(value) =>
- complete(write(value))
- case Failure(ex) =>
- failWith(ex)
- }
- }
-
- val msg = java.net.URLDecoder.decode(args, "UTF-8")
- val dagOperation = read[DAGOperation](msg)
- (post & entity(as[Multipart.FormData])) { _ =>
- uploadFile { form =>
- val jar = form.getFile("jar").map(_.file)
-
- if (jar.nonEmpty) {
- dagOperation match {
- case replace: ReplaceProcessor =>
- val description = replace.newProcessorDescription.copy(jar =
- Util.uploadJar(jar.get, jarStore))
- val dagOperationWithJar = replace.copy(newProcessorDescription = description)
- replaceProcessor(dagOperationWithJar)
- }
- } else {
- replaceProcessor(dagOperation)
- }
- }
- } ~ (post & entity(as[FormData])) { _ =>
- replaceProcessor(dagOperation)
- }
- }
- } ~
- path("stallingtasks") {
- onComplete(askAppMaster[StallingTasks](master, appId, GetStallingTasks(appId))) {
- case Success(value) =>
- complete(write(value))
- case Failure(ex) => failWith(ex)
- }
- } ~
- path("errors") {
- onComplete(askAppMaster[LastFailure](master, appId, GetLastFailure(appId))) {
- case Success(value) =>
- complete(write(value))
- case Failure(ex) => failWith(ex)
- }
- } ~
- path("restart") {
- post {
- onComplete(askActor[SubmitApplicationResult](master, RestartApplication(appId))) {
- case Success(_) =>
- complete(write(Status(true)))
- case Failure(ex) =>
- complete(write(Status(false, ex.getMessage)))
- }
- }
- } ~
- path("config") {
- onComplete(askActor[AppMasterConfig](master, QueryAppMasterConfig(appId))) {
- case Success(value: AppMasterConfig) =>
- val config = Option(value.config).map(ClusterConfig.render(_, concise)).getOrElse("{}")
- complete(config)
- case Failure(ex) =>
- failWith(ex)
- }
- } ~
- pathPrefix("executor" / Segment) { executorIdString =>
- path("config") {
- val executorId = Integer.parseInt(executorIdString)
- onComplete(askAppMaster[ExecutorConfig](master, appId, QueryExecutorConfig(executorId))) {
- case Success(value) =>
- val config = Option(value.config).map(ClusterConfig.render(_, concise))
- .getOrElse("{}")
- complete(config)
- case Failure(ex) =>
- failWith(ex)
- }
- } ~
- pathEnd {
- get {
- val executorId = Integer.parseInt(executorIdString)
- onComplete(askAppMaster[ExecutorSummary](master, appId,
- GetExecutorSummary(executorId))) {
- case Success(value) =>
- complete(write(value))
- case Failure(ex) =>
- failWith(ex)
- }
- }
- }
- } ~
- path("metrics" / RestPath) { path =>
- parameterMap { optionMap =>
- parameter("aggregator" ? "") { aggregator =>
- parameter(ReadOption.Key ? ReadOption.ReadLatest) { readOption =>
- val query = QueryHistoryMetrics(path.head.toString, readOption, aggregator, optionMap)
- onComplete(askAppMaster[HistoryMetrics](master, appId, query)) {
- case Success(value) =>
- complete(write(value))
- case Failure(ex) =>
- failWith(ex)
- }
- }
- }
- }
- } ~
- pathEnd {
- get {
- parameter("detail" ? "false") { detail =>
- val queryDetails = Try(detail.toBoolean).getOrElse(false)
- val request = AppMasterDataDetailRequest(appId)
- queryDetails match {
- case true =>
- onComplete(askAppMaster[AppMasterSummary](master, appId, request)) {
- case Success(value) =>
- value match {
- case data: GeneralAppMasterSummary =>
- complete(write(data))
- case data: StreamAppMasterSummary =>
- complete(write(data))
- }
- case Failure(ex) =>
- failWith(ex)
- }
-
- case false =>
- onComplete(askActor[AppMasterData](master, AppMasterDataRequest(appId))) {
- case Success(value) =>
- complete(write(value))
- case Failure(ex) =>
- failWith(ex)
- }
- }
- }
- }
- } ~
- pathEnd {
- delete {
- val writer = (result: ShutdownApplicationResult) => {
- val output = if (result.appId.isSuccess) {
- Map("status" -> "success", "info" -> null)
- } else {
- Map("status" -> "fail", "info" -> result.appId.failed.get.toString)
- }
- write(output)
- }
- onComplete(askActor[ShutdownApplicationResult](master, ShutdownApplication(appId))) {
- case Success(result) =>
- val output = if (result.appId.isSuccess) {
- Map("status" -> "success", "info" -> null)
- } else {
- Map("status" -> "fail", "info" -> result.appId.failed.get.toString)
- }
- complete(write(output))
- case Failure(ex) =>
- failWith(ex)
- }
- }
- }
- }
- }
-}
-
-object AppMasterService {
- case class Status(success: Boolean, reason: String = null)
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/main/scala/io/gearpump/services/BasicService.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/main/scala/io/gearpump/services/BasicService.scala b/services/jvm/src/main/scala/io/gearpump/services/BasicService.scala
deleted file mode 100644
index 75f033b..0000000
--- a/services/jvm/src/main/scala/io/gearpump/services/BasicService.scala
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.services
-
-import scala.concurrent.ExecutionContext
-
-import akka.actor.ActorSystem
-import akka.http.scaladsl.model.headers.CacheDirectives.{`max-age`, `no-cache`}
-import akka.http.scaladsl.model.headers.`Cache-Control`
-import akka.http.scaladsl.server.Directives._
-import akka.http.scaladsl.server.Route
-import akka.stream.Materializer
-
-import io.gearpump.util.{Constants, LogUtil}
-// NOTE: This cannot be removed!!!
-import io.gearpump.services.util.UpickleUtil._
-
-trait RouteService {
- def route: Route
-}
-
-/**
- * Wraps the cache behavior, and some common utils.
- */
-trait BasicService extends RouteService {
-
- implicit def system: ActorSystem
-
- implicit def timeout: akka.util.Timeout = Constants.FUTURE_TIMEOUT
-
- implicit def ec: ExecutionContext = system.dispatcher
-
- protected def doRoute(implicit mat: Materializer): Route
-
- protected def prefix = Slash ~ "api" / s"$REST_VERSION"
-
- protected val LOG = LogUtil.getLogger(getClass)
-
- protected def cache = false
- private val noCacheHeader = `Cache-Control`(`no-cache`, `max-age`(0L))
-
- def route: Route = encodeResponse {
- extractMaterializer { implicit mat =>
- rawPathPrefix(prefix) {
- if (cache) {
- doRoute(mat)
- } else {
- respondWithHeader(noCacheHeader) {
- doRoute(mat)
- }
- }
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/main/scala/io/gearpump/services/MasterService.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/main/scala/io/gearpump/services/MasterService.scala b/services/jvm/src/main/scala/io/gearpump/services/MasterService.scala
deleted file mode 100644
index 6ca0f98..0000000
--- a/services/jvm/src/main/scala/io/gearpump/services/MasterService.scala
+++ /dev/null
@@ -1,350 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.services
-
-import java.io.{File, IOException}
-import java.nio.charset.StandardCharsets.UTF_8
-import java.nio.file.Files
-import java.nio.file.StandardOpenOption.{APPEND, WRITE}
-import scala.collection.JavaConverters._
-import scala.concurrent.Future
-import scala.util.{Failure, Success}
-
-import akka.actor.{ActorRef, ActorSystem}
-import akka.http.scaladsl.server.Directives._
-import akka.http.scaladsl.server.directives.ParameterDirectives.ParamMagnet
-import akka.http.scaladsl.unmarshalling.Unmarshaller._
-import akka.stream.Materializer
-import com.typesafe.config.Config
-
-import io.gearpump.cluster.AppMasterToMaster.{GetAllWorkers, GetMasterData, GetWorkerData, MasterData, WorkerData}
-import io.gearpump.cluster.ClientToMaster.{QueryHistoryMetrics, QueryMasterConfig, ReadOption}
-import io.gearpump.cluster.MasterToAppMaster.{AppMastersData, AppMastersDataRequest, WorkerList}
-import io.gearpump.cluster.MasterToClient.{HistoryMetrics, MasterConfig, SubmitApplicationResultValue}
-import io.gearpump.cluster.client.ClientContext
-import io.gearpump.cluster.worker.WorkerSummary
-import io.gearpump.cluster.{ClusterConfig, UserConfig}
-import io.gearpump.jarstore.JarStoreService
-import io.gearpump.partitioner.{PartitionerByClassName, PartitionerDescription}
-import io.gearpump.services.MasterService.{BuiltinPartitioners, SubmitApplicationRequest}
-// NOTE: This cannot be removed!!!
-import io.gearpump.services.util.UpickleUtil._
-import io.gearpump.streaming.{ProcessorDescription, ProcessorId, StreamApplication}
-import io.gearpump.util.ActorUtil._
-import io.gearpump.util.FileDirective._
-import io.gearpump.util.{Constants, Graph, Util}
-
-/** Manages service for master node */
-class MasterService(val master: ActorRef,
- val jarStore: JarStoreService, override val system: ActorSystem)
- extends BasicService {
-
- import upickle.default.{read, write}
-
- private val systemConfig = system.settings.config
- private val concise = systemConfig.getBoolean(Constants.GEARPUMP_SERVICE_RENDER_CONFIG_CONCISE)
-
- protected override def doRoute(implicit mat: Materializer) = pathPrefix("master") {
- pathEnd {
- get {
- onComplete(askActor[MasterData](master, GetMasterData)) {
- case Success(value: MasterData) => complete(write(value))
- case Failure(ex) => failWith(ex)
- }
- }
- } ~
- path("applist") {
- onComplete(askActor[AppMastersData](master, AppMastersDataRequest)) {
- case Success(value: AppMastersData) =>
- complete(write(value))
- case Failure(ex) => failWith(ex)
- }
- } ~
- path("workerlist") {
- def future: Future[List[WorkerSummary]] = askActor[WorkerList](master, GetAllWorkers)
- .flatMap { workerList =>
- val workers = workerList.workers
- val workerDataList = List.empty[WorkerSummary]
-
- Future.fold(workers.map { workerId =>
- askWorker[WorkerData](master, workerId, GetWorkerData(workerId))
- })(workerDataList) { (workerDataList, workerData) =>
- workerDataList :+ workerData.workerDescription
- }
- }
- onComplete(future) {
- case Success(result: List[WorkerSummary]) => complete(write(result))
- case Failure(ex) => failWith(ex)
- }
- } ~
- path("config") {
- onComplete(askActor[MasterConfig](master, QueryMasterConfig)) {
- case Success(value: MasterConfig) =>
- val config = Option(value.config).map(ClusterConfig.render(_, concise)).getOrElse("{}")
- complete(config)
- case Failure(ex) =>
- failWith(ex)
- }
- } ~
- path("metrics" / RestPath) { path =>
- parameters(ParamMagnet(ReadOption.Key ? ReadOption.ReadLatest)) { readOption: String =>
- val query = QueryHistoryMetrics(path.head.toString, readOption)
- onComplete(askActor[HistoryMetrics](master, query)) {
- case Success(value) =>
- complete(write(value))
- case Failure(ex) =>
- failWith(ex)
- }
- }
- } ~
- path("submitapp") {
- post {
- uploadFile { form =>
- val jar = form.getFile("jar").map(_.file)
- val configFile = form.getFile("configfile").map(_.file)
- val configString = form.getValue("configstring").getOrElse("")
- val executorCount = form.getValue("executorcount").getOrElse("1").toInt
- val args = form.getValue("args").getOrElse("")
-
- val mergedConfigFile = mergeConfig(configFile, configString)
-
- onComplete(Future(
- MasterService.submitGearApp(jar, executorCount, args, systemConfig, mergedConfigFile)
- )) {
- case Success(success) =>
- val response = MasterService.AppSubmissionResult(success)
- complete(write(response))
- case Failure(ex) =>
- failWith(ex)
- }
- }
- }
- } ~
- path("submitstormapp") {
- post {
- uploadFile { form =>
- val jar = form.getFile("jar").map(_.file)
- val configFile = form.getFile("configfile").map(_.file)
- val args = form.getValue("args").getOrElse("")
- onComplete(Future(
- MasterService.submitStormApp(jar, configFile, args, systemConfig)
- )) {
- case Success(success) =>
- val response = MasterService.AppSubmissionResult(success)
- complete(write(response))
- case Failure(ex) =>
- failWith(ex)
- }
- }
- }
- } ~
- path("submitdag") {
- post {
- entity(as[String]) { request =>
- val msg = java.net.URLDecoder.decode(request, "UTF-8")
- val submitApplicationRequest = read[SubmitApplicationRequest](msg)
- import submitApplicationRequest.{appName, dag, processors, userconfig}
- val context = ClientContext(system.settings.config, system, master)
-
- val graph = dag.mapVertex { processorId =>
- processors(processorId)
- }.mapEdge { (node1, edge, node2) =>
- PartitionerDescription(new PartitionerByClassName(edge))
- }
-
- val effectiveConfig = if (userconfig == null) UserConfig.empty else userconfig
- val appId = context.submit(new StreamApplication(appName, effectiveConfig, graph))
-
- import upickle.default.write
- val submitApplicationResultValue = SubmitApplicationResultValue(appId)
- val jsonData = write(submitApplicationResultValue)
- complete(jsonData)
- }
- }
- } ~
- path("uploadjar") {
- uploadFile { form =>
- val jar = form.getFile("jar").map(_.file)
- if (jar.isEmpty) {
- complete(write(
- MasterService.Status(success = false, reason = "Jar file not found")))
- } else {
- val jarFile = Util.uploadJar(jar.get, jarStore)
- complete(write(jarFile))
- }
- }
- } ~
- path("partitioners") {
- get {
- complete(write(BuiltinPartitioners(Constants.BUILTIN_PARTITIONERS.map(_.getName))))
- }
- }
- }
-
- private def mergeConfig(configFile: Option[File], configString: String): Option[File] = {
- if (configString == null || configString.isEmpty) {
- configFile
- } else {
- configFile match {
- case Some(file) =>
- Files.write(file.toPath, ("\n" + configString).getBytes(UTF_8), APPEND)
- Some(file)
- case None =>
- val file = File.createTempFile("\"userfile_configstring_", ".conf")
- Files.write(file.toPath, configString.getBytes(UTF_8), WRITE)
- Some(file)
- }
- }
- }
-}
-
-object MasterService {
-
- case class BuiltinPartitioners(partitioners: Array[String])
-
- case class AppSubmissionResult(success: Boolean)
-
- case class Status(success: Boolean, reason: String = null)
-
- /**
- * Submits Native Application.
- */
- def submitGearApp(
- jar: Option[File], executorNum: Int, args: String,
- systemConfig: Config, userConfigFile: Option[File]): Boolean = {
- submitAndDeleteTempFiles(
- "io.gearpump.cluster.main.AppSubmitter",
- argsArray = Array("-executors", executorNum.toString) ++ spaceSeparatedArgumentsToArray(args),
- fileMap = Map("jar" -> jar).filter(_._2.isDefined).mapValues(_.get),
- classPath = getUserApplicationClassPath,
- systemConfig,
- userConfigFile
- )
- }
-
- /**
- * Submits Storm application.
- */
- def submitStormApp(
- jar: Option[File], stormConf: Option[File], args: String, systemConfig: Config): Boolean = {
- submitAndDeleteTempFiles(
- "io.gearpump.experiments.storm.main.GearpumpStormClient",
- argsArray = spaceSeparatedArgumentsToArray(args),
- fileMap = Map("jar" -> jar, "config" -> stormConf).filter(_._2.isDefined).mapValues(_.get),
- classPath = getStormApplicationClassPath,
- systemConfig,
- userConfigFile = None
- )
- }
-
- private def submitAndDeleteTempFiles(
- mainClass: String, argsArray: Array[String], fileMap: Map[String, File],
- classPath: Array[String], systemConfig: Config,
- userConfigFile: Option[File] = None): Boolean = {
- try {
- val jar = fileMap.get("jar")
- if (jar.isEmpty) {
- throw new IOException("JAR file not supplied")
- }
-
- val process = Util.startProcess(
- clusterOptions(systemConfig, userConfigFile),
- classPath,
- mainClass,
- arguments = createFilePathArgArray(fileMap) ++ argsArray
- )
-
- val retval = process.exitValue()
- if (retval != 0) {
- throw new IOException(s"Process exit abnormally with exit code $retval.\n" +
- s"Error message: ${process.logger.error}")
- }
- true
- } finally {
- fileMap.values.foreach(_.delete)
- if (userConfigFile.isDefined) {
- userConfigFile.get.delete()
- }
- }
- }
-
- /**
- * Returns Java options for gearpump cluster
- */
- private def clusterOptions(systemConfig: Config, userConfigFile: Option[File]): Array[String] = {
- var options = Array(
- s"-D${Constants.GEARPUMP_HOME}=${systemConfig.getString(Constants.GEARPUMP_HOME)}",
- s"-D${Constants.GEARPUMP_HOSTNAME}=${systemConfig.getString(Constants.GEARPUMP_HOSTNAME)}",
- s"-D${Constants.PREFER_IPV4}=true"
- )
-
- val masters = systemConfig.getStringList(Constants.GEARPUMP_CLUSTER_MASTERS).asScala
- .toList.flatMap(Util.parseHostList)
- options ++= masters.zipWithIndex.map { case (master, index) =>
- s"-D${Constants.GEARPUMP_CLUSTER_MASTERS}.$index=${master.host}:${master.port}"
- }.toArray[String]
-
- if (userConfigFile.isDefined) {
- options :+= s"-D${Constants.GEARPUMP_CUSTOM_CONFIG_FILE}=${userConfigFile.get.getPath}"
- }
- options
- }
-
- /**
- * Filter all defined file paths and store their config key and path into an array.
- */
- private def createFilePathArgArray(fileMap: Map[String, File]): Array[String] = {
- var args = Array.empty[String]
- fileMap.foreach({ case (key, path) =>
- args ++= Array(s"-$key", path.getPath)
- })
- args
- }
-
- /**
- * Returns a space separated arguments as an array.
- */
- private def spaceSeparatedArgumentsToArray(str: String): Array[String] = {
- str.split(" +").filter(_.nonEmpty)
- }
-
- private val homeDir = System.getProperty(Constants.GEARPUMP_HOME) + "/"
- private val libHomeDir = homeDir + "lib/"
-
- private def getUserApplicationClassPath: Array[String] = {
- Array(
- homeDir + "conf",
- libHomeDir + "daemon/*",
- libHomeDir + "yarn/*",
- libHomeDir + "*"
- )
- }
-
- private def getStormApplicationClassPath: Array[String] = {
- getUserApplicationClassPath ++ Array(
- libHomeDir + "storm/*"
- )
- }
-
- case class SubmitApplicationRequest(
- appName: String,
- processors: Map[ProcessorId, ProcessorDescription],
- dag: Graph[Int, String],
- userconfig: UserConfig)
-}
[41/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/io/gearpump/cluster/appmaster/AppMasterRuntimeEnvironmentSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/io/gearpump/cluster/appmaster/AppMasterRuntimeEnvironmentSpec.scala b/core/src/test/scala/io/gearpump/cluster/appmaster/AppMasterRuntimeEnvironmentSpec.scala
deleted file mode 100644
index 00bd408..0000000
--- a/core/src/test/scala/io/gearpump/cluster/appmaster/AppMasterRuntimeEnvironmentSpec.scala
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.appmaster
-
-import scala.concurrent.Await
-import scala.concurrent.duration.Duration
-
-import akka.actor._
-import akka.testkit.TestProbe
-import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
-
-import io.gearpump.TestProbeUtil._
-import io.gearpump.cluster.AppMasterToMaster.RegisterAppMaster
-import io.gearpump.cluster._
-import io.gearpump.cluster.appmaster.AppMasterRuntimeEnvironment._
-import io.gearpump.cluster.appmaster.AppMasterRuntimeEnvironmentSpec.TestAppMasterEnv
-import io.gearpump.cluster.appmaster.ExecutorSystemScheduler.StartExecutorSystems
-import io.gearpump.cluster.appmaster.MasterConnectionKeeper.MasterConnectionStatus.{MasterConnected, MasterStopped}
-
-class AppMasterRuntimeEnvironmentSpec extends FlatSpec with Matchers with BeforeAndAfterAll {
- implicit var system: ActorSystem = null
-
- override def beforeAll(): Unit = {
- system = ActorSystem("test", TestUtil.DEFAULT_CONFIG)
- }
-
- override def afterAll(): Unit = {
- system.terminate()
- Await.result(system.whenTerminated, Duration.Inf)
- }
-
- "MasterWithExecutorSystemProvider" should
- "forward request StartExecutorSystem to ExecutorSystemProvider" in {
-
- val client = TestProbe()
- val master = TestProbe()
- val provider = TestProbe()
- val providerProps: Props = provider
- val masterEnhanced = system.actorOf(Props(
- new MasterWithExecutorSystemProvider(master.ref, providerProps)))
-
- val start = StartExecutorSystems(null, null)
- client.send(masterEnhanced, start)
- provider.expectMsg(start)
-
- val anyOtherMessage = "any other message"
- client.send(masterEnhanced, anyOtherMessage)
- master.expectMsg(anyOtherMessage)
- system.stop(masterEnhanced)
- }
-
- "LazyStartAppMaster" should "forward command to appmaster when app master started" in {
-
- val appMaster = TestProbe()
- val appMasterProps: Props = appMaster
- val lazyAppMaster = system.actorOf(Props(new LazyStartAppMaster(appId = 0, appMasterProps)))
- val msg = "Some"
- lazyAppMaster ! msg
- lazyAppMaster ! StartAppMaster
- appMaster.expectMsg(msg)
-
- system.stop(appMaster.ref)
- val client = TestProbe()
- client.watch(lazyAppMaster)
- client.expectTerminated(lazyAppMaster)
- }
-
- "AppMasterRuntimeEnvironment" should "start appMaster when master is connected" in {
- val TestAppMasterEnv(master, appMaster, masterConnectionKeeper, runtimeEnv) =
- setupAppMasterRuntimeEnv()
-
- masterConnectionKeeper.send(runtimeEnv, MasterConnected)
- appMaster.expectMsg(StartAppMaster)
- }
-
- "AppMasterRuntimeEnvironment" should "shutdown itself when master is stopped" in {
-
- val TestAppMasterEnv(master, appMaster, masterConnectionKeeper, runtimeEnv) =
- setupAppMasterRuntimeEnv()
-
- masterConnectionKeeper.send(runtimeEnv, MasterStopped)
- val client = TestProbe()
- client.watch(runtimeEnv)
- client.expectTerminated(runtimeEnv)
- }
-
- "AppMasterRuntimeEnvironment" should "shutdown itself when appMaster is stopped" in {
-
- val TestAppMasterEnv(master, appMaster, masterConnectionKeeper, runtimeEnv) =
- setupAppMasterRuntimeEnv()
-
- val client = TestProbe()
- client.watch(runtimeEnv)
- system.stop(appMaster.ref)
- client.expectTerminated(runtimeEnv)
- }
-
- private def setupAppMasterRuntimeEnv(): TestAppMasterEnv = {
- val appContext = AppMasterContext(0, null, null, null, null, null, null)
- val app = AppDescription("app", "AppMasterClass", null, null)
- val master = TestProbe()
- val masterFactory = (_: AppId, _: MasterActorRef) => toProps(master)
- val appMaster = TestProbe()
- val appMasterFactory = (_: AppMasterContext, _: AppDescription) => toProps(appMaster)
- val masterConnectionKeeper = TestProbe()
- val masterConnectionKeeperFactory =
- (_: MasterActorRef, _: RegisterAppMaster, _: ListenerActorRef) =>
- toProps(masterConnectionKeeper)
-
- val runtimeEnv = system.actorOf(
- Props(new AppMasterRuntimeEnvironment(
- appContext, app, List(master.ref.path), masterFactory,
- appMasterFactory, masterConnectionKeeperFactory)))
-
- TestAppMasterEnv(master, appMaster, masterConnectionKeeper, runtimeEnv)
- }
-}
-
-object AppMasterRuntimeEnvironmentSpec {
-
- case class TestAppMasterEnv(
- master: TestProbe, appMaster: TestProbe, connectionkeeper: TestProbe,
- appMasterRuntimeEnv: ActorRef)
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/io/gearpump/cluster/appmaster/ExecutorSystemLauncherSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/io/gearpump/cluster/appmaster/ExecutorSystemLauncherSpec.scala b/core/src/test/scala/io/gearpump/cluster/appmaster/ExecutorSystemLauncherSpec.scala
deleted file mode 100644
index 3595960..0000000
--- a/core/src/test/scala/io/gearpump/cluster/appmaster/ExecutorSystemLauncherSpec.scala
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.appmaster
-
-import scala.concurrent.Await
-import scala.concurrent.duration._
-
-import akka.actor.{ActorSystem, Props}
-import akka.testkit.TestProbe
-import com.typesafe.config.ConfigValueFactory
-import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
-
-import io.gearpump.cluster.AppMasterToWorker.LaunchExecutor
-import io.gearpump.cluster.TestUtil
-import io.gearpump.cluster.WorkerToAppMaster.ExecutorLaunchRejected
-import io.gearpump.cluster.appmaster.ExecutorSystemLauncher._
-import io.gearpump.cluster.appmaster.ExecutorSystemScheduler.Session
-import io.gearpump.cluster.scheduler.Resource
-import io.gearpump.cluster.worker.WorkerId
-import io.gearpump.util.ActorSystemBooter.{ActorSystemRegistered, RegisterActorSystem}
-import io.gearpump.util.Constants
-
-class ExecutorSystemLauncherSpec extends FlatSpec with Matchers with BeforeAndAfterAll {
- implicit var system: ActorSystem = null
- val workerId: WorkerId = WorkerId(0, 0L)
- val appId = 0
- val executorId = 0
- val url = "akka.tcp://worker@127.0.0.1:3000"
- val session = Session(null, null)
- val launchExecutorSystemTimeout = 3000
- val activeConfig = TestUtil.DEFAULT_CONFIG.
- withValue(Constants.GEARPUMP_START_EXECUTOR_SYSTEM_TIMEOUT_MS,
- ConfigValueFactory.fromAnyRef(launchExecutorSystemTimeout))
-
- override def beforeAll(): Unit = {
- system = ActorSystem("test", activeConfig)
- }
-
- override def afterAll(): Unit = {
- system.terminate()
- Await.result(system.whenTerminated, Duration.Inf)
- }
-
- it should "report success when worker launch the system successfully" in {
- val worker = TestProbe()
- val client = TestProbe()
-
- val launcher = system.actorOf(Props(new ExecutorSystemLauncher(appId, session)))
- client.watch(launcher)
- client.send(launcher, LaunchExecutorSystem(WorkerInfo(workerId, worker.ref), 0, Resource(1)))
-
- worker.expectMsgType[LaunchExecutor]
- worker.reply(RegisterActorSystem(url))
-
- worker.expectMsgType[ActorSystemRegistered]
-
- client.expectMsgType[LaunchExecutorSystemSuccess]
- client.expectTerminated(launcher)
- }
-
- it should "report failure when worker refuse to launch the system explicitly" in {
- val worker = TestProbe()
- val client = TestProbe()
-
- val resource = Resource(4)
-
- val launcher = system.actorOf(Props(new ExecutorSystemLauncher(appId, session)))
- client.watch(launcher)
- client.send(launcher, LaunchExecutorSystem(WorkerInfo(workerId, worker.ref), 0, resource))
-
- worker.expectMsgType[LaunchExecutor]
- worker.reply(ExecutorLaunchRejected())
-
- client.expectMsg(LaunchExecutorSystemRejected(resource, null, session))
- client.expectTerminated(launcher)
- }
-
- it should "report timeout when trying to start a executor system on worker, " +
- "and worker doesn't response" in {
- val client = TestProbe()
- val worker = TestProbe()
- val launcher = system.actorOf(Props(new ExecutorSystemLauncher(appId, session)))
- client.send(launcher, LaunchExecutorSystem(WorkerInfo(workerId, worker.ref), 0, Resource(1)))
- client.watch(launcher)
- val waitFor = launchExecutorSystemTimeout + 10000
- client.expectMsgType[LaunchExecutorSystemTimeout](waitFor.milliseconds)
- client.expectTerminated(launcher, waitFor.milliseconds)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/io/gearpump/cluster/appmaster/ExecutorSystemSchedulerSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/io/gearpump/cluster/appmaster/ExecutorSystemSchedulerSpec.scala b/core/src/test/scala/io/gearpump/cluster/appmaster/ExecutorSystemSchedulerSpec.scala
deleted file mode 100644
index c2f6ee8..0000000
--- a/core/src/test/scala/io/gearpump/cluster/appmaster/ExecutorSystemSchedulerSpec.scala
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.appmaster
-
-import scala.concurrent.Await
-import scala.concurrent.duration._
-
-import akka.actor.{Actor, ActorSystem, Props}
-import akka.testkit.TestProbe
-import org.scalatest.{BeforeAndAfterEach, FlatSpec, Matchers}
-
-import io.gearpump.cluster.AppMasterToMaster.RequestResource
-import io.gearpump.cluster.MasterToAppMaster.ResourceAllocated
-import io.gearpump.cluster.appmaster.ExecutorSystemLauncher._
-import io.gearpump.cluster.appmaster.ExecutorSystemScheduler._
-import io.gearpump.cluster.appmaster.ExecutorSystemSchedulerSpec.{ExecutorSystemLauncherStarted, MockExecutorSystemLauncher}
-import io.gearpump.cluster.scheduler.{Resource, ResourceAllocation, ResourceRequest}
-import io.gearpump.cluster.worker.WorkerId
-import io.gearpump.cluster.{AppJar, TestUtil}
-import io.gearpump.jarstore.FilePath
-
-class ExecutorSystemSchedulerSpec extends FlatSpec with Matchers with BeforeAndAfterEach {
- val appId = 0
- val workerId = WorkerId(0, 0L)
- val resource = Resource(1)
- val resourceRequest = ResourceRequest(resource, WorkerId.unspecified)
- val mockJar = AppJar("for_test", FilePath("PATH"))
- val emptyJvmConfig = ExecutorSystemJvmConfig(Array.empty, Array.empty, Some(mockJar), "")
- val start = StartExecutorSystems(Array(resourceRequest), emptyJvmConfig)
-
- implicit var system: ActorSystem = null
- var worker: TestProbe = null
- var workerInfo: WorkerInfo = null
- var masterProxy: TestProbe = null
- var launcher: TestProbe = null
- var client: TestProbe = null
-
- override def beforeEach(): Unit = {
- system = ActorSystem("test", TestUtil.DEFAULT_CONFIG)
- worker = TestProbe()
- workerInfo = WorkerInfo(workerId, worker.ref)
- masterProxy = TestProbe()
- launcher = TestProbe()
- client = TestProbe()
-
- val scheduler = system.actorOf(
- Props(new ExecutorSystemScheduler(appId, masterProxy.ref, (appId: Int, session: Session) => {
- Props(new MockExecutorSystemLauncher(launcher, session))
- })))
-
- client.send(scheduler, start)
- masterProxy.expectMsg(RequestResource(appId, resourceRequest))
- }
-
- override def afterEach(): Unit = {
- system.terminate()
- Await.result(system.whenTerminated, Duration.Inf)
- }
-
- private def launcherStarted(launcher: TestProbe): Option[ExecutorSystemLauncherStarted] = {
- val launcherStarted = launcher.receiveOne(15.seconds)
-
- launcherStarted match {
- case start: ExecutorSystemLauncherStarted => Some(start)
- case x =>
- assert(false, "ExecutorSystemLauncherStarted == false")
- None
- }
- }
-
- it should "schedule and launch an executor system on target worker successfully" in {
-
- masterProxy.reply(ResourceAllocated(Array(ResourceAllocation(resource, worker.ref, workerId))))
-
- val ExecutorSystemLauncherStarted(session) = launcherStarted(launcher).get
-
- var systemId = 0
- launcher.expectMsg(LaunchExecutorSystem(workerInfo, systemId, resource))
-
- val executorSystemProbe = TestProbe()
- val executorSystem =
- ExecutorSystem(systemId, null, executorSystemProbe.ref, resource, workerInfo)
- launcher.reply(LaunchExecutorSystemSuccess(executorSystem, session))
- client.expectMsg(ExecutorSystemStarted(executorSystem, Some(mockJar)))
- }
-
- it should "report failure when resource cannot be allocated" in {
- client.expectMsg(30.seconds, StartExecutorSystemTimeout)
- }
-
- it should "schedule new resouce on new worker " +
- "when target worker reject creating executor system" in {
- masterProxy.reply(ResourceAllocated(Array(ResourceAllocation(resource, worker.ref, workerId))))
- val ExecutorSystemLauncherStarted(session) = launcherStarted(launcher).get
-
- var systemId = 0
- launcher.expectMsg(LaunchExecutorSystem(workerInfo, systemId, resource))
- launcher.reply(LaunchExecutorSystemRejected(resource, "", session))
- masterProxy.expectMsg(RequestResource(appId, resourceRequest))
- }
-
- it should "report failure when resource is allocated, but timeout " +
- "when starting the executor system" in {
- masterProxy.reply(ResourceAllocated(Array(ResourceAllocation(resource, worker.ref, workerId))))
- val ExecutorSystemLauncherStarted(session) = launcherStarted(launcher).get
-
- var systemId = 0
- launcher.expectMsg(LaunchExecutorSystem(workerInfo, systemId, resource))
- launcher.reply(LaunchExecutorSystemTimeout(session))
- client.expectMsg(StartExecutorSystemTimeout)
- }
-}
-
-object ExecutorSystemSchedulerSpec {
- class MockExecutorSystemLauncher(forwardTo: TestProbe, session: Session) extends Actor {
- forwardTo.ref ! ExecutorSystemLauncherStarted(session)
-
- def receive: Receive = {
- case msg => forwardTo.ref forward msg
- }
- }
-
- case class ExecutorSystemLauncherStarted(session: Session)
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/io/gearpump/cluster/appmaster/MasterConnectionKeeperSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/io/gearpump/cluster/appmaster/MasterConnectionKeeperSpec.scala b/core/src/test/scala/io/gearpump/cluster/appmaster/MasterConnectionKeeperSpec.scala
deleted file mode 100644
index 3272b99..0000000
--- a/core/src/test/scala/io/gearpump/cluster/appmaster/MasterConnectionKeeperSpec.scala
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.appmaster
-
-import scala.concurrent.Await
-import scala.concurrent.duration._
-
-import akka.actor.{ActorRef, ActorSystem, Props}
-import akka.testkit.TestProbe
-import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
-
-import io.gearpump.cluster.AppMasterToMaster.RegisterAppMaster
-import io.gearpump.cluster.MasterToAppMaster.AppMasterRegistered
-import io.gearpump.cluster.TestUtil
-import io.gearpump.cluster.appmaster.MasterConnectionKeeper.MasterConnectionStatus.{MasterConnected, _}
-import io.gearpump.cluster.appmaster.MasterConnectionKeeperSpec.ConnectionKeeperTestEnv
-import io.gearpump.cluster.master.MasterProxy.WatchMaster
-
-class MasterConnectionKeeperSpec extends FlatSpec with Matchers with BeforeAndAfterAll {
-
- implicit var system: ActorSystem = null
- val register = RegisterAppMaster(null, null)
- val appId = 0
-
- override def beforeAll(): Unit = {
- system = ActorSystem("test", TestUtil.DEFAULT_CONFIG)
- }
-
- override def afterAll(): Unit = {
- system.terminate()
- Await.result(system.whenTerminated, Duration.Inf)
- }
-
- private def startMasterConnectionKeeper: ConnectionKeeperTestEnv = {
- val statusChangeSubscriber = TestProbe()
- val master = TestProbe()
-
- val keeper = system.actorOf(Props(
- new MasterConnectionKeeper(register, master.ref, statusChangeSubscriber.ref)))
- statusChangeSubscriber.watch(keeper)
-
- master.expectMsgType[WatchMaster]
-
- // Master is alive, response to RegisterAppMaster
- master.expectMsgType[RegisterAppMaster]
- master.reply(AppMasterRegistered(appId))
-
- // Notify listener that master is alive
- statusChangeSubscriber.expectMsg(MasterConnected)
- ConnectionKeeperTestEnv(master, keeper, statusChangeSubscriber)
- }
-
- it should "start correctly and notify listener that master is alive" in {
- startMasterConnectionKeeper
- }
-
- it should "re-register the appmaster when master is restarted" in {
- import io.gearpump.cluster.master.MasterProxy.MasterRestarted
- val ConnectionKeeperTestEnv(master, keeper, masterChangeListener) = startMasterConnectionKeeper
-
- // Master is restarted
- master.send(keeper, MasterRestarted)
- master.expectMsgType[RegisterAppMaster]
- master.reply(AppMasterRegistered(appId))
- masterChangeListener.expectMsg(MasterConnected)
-
- // Recovery from Master restart is transparent to listener
- masterChangeListener.expectNoMsg()
- }
-
- it should "notify listener and then shutdown itself when master is dead" in {
- val ConnectionKeeperTestEnv(master, keeper, masterChangeListener) = startMasterConnectionKeeper
-
- // Master is dead
- master.send(keeper, MasterStopped)
-
- // Keeper should tell the listener that master is stopped before shutting down itself
- masterChangeListener.expectMsg(MasterStopped)
- masterChangeListener.expectTerminated(keeper)
- }
-
- it should "mark the master as dead when timeout" in {
- val statusChangeSubscriber = TestProbe()
- val master = TestProbe()
-
- // MasterConnectionKeeper register itself to master by sending RegisterAppMaster
- val keeper = system.actorOf(Props(new MasterConnectionKeeper(register,
- master.ref, statusChangeSubscriber.ref)))
-
- // Master doesn't reply to keeper,
- statusChangeSubscriber.watch(keeper)
-
- // Timeout, keeper notify listener, and then make suicide
- statusChangeSubscriber.expectMsg(60.seconds, MasterStopped)
- statusChangeSubscriber.expectTerminated(keeper, 60.seconds)
- }
-}
-
-object MasterConnectionKeeperSpec {
- case class ConnectionKeeperTestEnv(
- master: TestProbe, keeper: ActorRef, masterChangeListener: TestProbe)
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/io/gearpump/cluster/main/ArgumentParserSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/io/gearpump/cluster/main/ArgumentParserSpec.scala b/core/src/test/scala/io/gearpump/cluster/main/ArgumentParserSpec.scala
deleted file mode 100644
index 7544f9a..0000000
--- a/core/src/test/scala/io/gearpump/cluster/main/ArgumentParserSpec.scala
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.main
-
-import org.scalatest.{FlatSpec, Matchers}
-
-class ArgumentParserSpec extends FlatSpec with Matchers {
- it should "parse arguments correctly" in {
-
- val parser = new ArgumentsParser {
- override val options = Array(
- "flag" -> CLIOption[Any]("", required = true),
- "opt1" -> CLIOption[Any]("", required = true),
- "opt2" -> CLIOption[Any]("", required = true))
- }
-
- val result = parser.parse(Array("-flag", "-opt1", "1", "-opt2", "2", "arg1", "arg2"))
- assert(result.getBoolean("flag"))
- assert(result.getInt("opt1") == 1)
- assert(result.getString("opt1") == "1")
- assert(result.getInt("opt2") == 2)
-
- assert(result.remainArgs(0) == "arg1")
- assert(result.remainArgs(1) == "arg2")
- }
-
- it should "handle interleaved options and remain args" in {
-
- val parser = new ArgumentsParser {
- override val options = Array(
- "opt1" -> CLIOption[Any]("", required = true))
- }
-
- val result = parser.parse(Array("-opt1", "1", "xx.MainClass", "-opt2", "2"))
- assert(result.getInt("opt1") == 1)
-
- assert(result.remainArgs.length == 3)
-
- intercept[Exception] {
- parser.parse(Array("-opt2"))
- }
-
- intercept[Exception] {
- parser.parse(Array("-opt2", "2", "-opt1"))
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/io/gearpump/cluster/master/AppMasterLauncherSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/io/gearpump/cluster/master/AppMasterLauncherSpec.scala b/core/src/test/scala/io/gearpump/cluster/master/AppMasterLauncherSpec.scala
deleted file mode 100644
index 2a8dba1..0000000
--- a/core/src/test/scala/io/gearpump/cluster/master/AppMasterLauncherSpec.scala
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.master
-
-import scala.util.Success
-
-import akka.actor._
-import akka.testkit.TestProbe
-import com.typesafe.config.Config
-import org.scalatest.{BeforeAndAfterEach, FlatSpec, Matchers}
-
-import io.gearpump.cluster.AppMasterToMaster.RequestResource
-import io.gearpump.cluster.AppMasterToWorker.{LaunchExecutor, ShutdownExecutor}
-import io.gearpump.cluster.MasterToAppMaster.ResourceAllocated
-import io.gearpump.cluster.MasterToClient.SubmitApplicationResult
-import io.gearpump.cluster.WorkerToAppMaster.ExecutorLaunchRejected
-import io.gearpump.cluster.scheduler.{Resource, ResourceAllocation, ResourceRequest}
-import io.gearpump.cluster.worker.WorkerId
-import io.gearpump.cluster.{MasterHarness, TestUtil}
-import io.gearpump.util.ActorSystemBooter._
-
-class AppMasterLauncherSpec extends FlatSpec with Matchers
- with BeforeAndAfterEach with MasterHarness {
-
- override def config: Config = TestUtil.DEFAULT_CONFIG
-
- val appId = 1
- val executorId = 2
- var master: TestProbe = null
- var client: TestProbe = null
- var worker: TestProbe = null
- var watcher: TestProbe = null
- var appMasterLauncher: ActorRef = null
-
- override def beforeEach(): Unit = {
- startActorSystem()
- master = createMockMaster()
- client = TestProbe()(getActorSystem)
- worker = TestProbe()(getActorSystem)
- watcher = TestProbe()(getActorSystem)
- appMasterLauncher = getActorSystem.actorOf(AppMasterLauncher.props(appId, executorId,
- TestUtil.dummyApp, None, "username", master.ref, Some(client.ref)))
- watcher watch appMasterLauncher
- master.expectMsg(RequestResource(appId, ResourceRequest(Resource(1), WorkerId.unspecified)))
- val resource = ResourceAllocated(
- Array(ResourceAllocation(Resource(1), worker.ref, WorkerId(0, 0L))))
- master.reply(resource)
- worker.expectMsgType[LaunchExecutor]
- }
-
- override def afterEach(): Unit = {
- shutdownActorSystem()
- }
-
- "AppMasterLauncher" should "launch appmaster correctly" in {
- worker.reply(RegisterActorSystem("systempath"))
- worker.expectMsgType[ActorSystemRegistered]
-
- worker.expectMsgType[CreateActor]
- worker.reply(ActorCreated(master.ref, "appmaster"))
-
- client.expectMsg(SubmitApplicationResult(Success(appId)))
- watcher.expectTerminated(appMasterLauncher)
- }
-
- "AppMasterLauncher" should "reallocate resource if executor launch rejected" in {
- worker.reply(ExecutorLaunchRejected(""))
- master.expectMsg(RequestResource(appId, ResourceRequest(Resource(1), WorkerId.unspecified)))
-
- val resource = ResourceAllocated(
- Array(ResourceAllocation(Resource(1), worker.ref, WorkerId(0, 0L))))
- master.reply(resource)
- worker.expectMsgType[LaunchExecutor]
-
- worker.reply(RegisterActorSystem("systempath"))
- worker.expectMsgType[ActorSystemRegistered]
-
- worker.expectMsgType[CreateActor]
- worker.reply(CreateActorFailed("", new Exception))
- worker.expectMsgType[ShutdownExecutor]
- assert(client.receiveN(1).head.asInstanceOf[SubmitApplicationResult].appId.isFailure)
- watcher.expectTerminated(appMasterLauncher)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/io/gearpump/cluster/master/ApplicationStateSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/io/gearpump/cluster/master/ApplicationStateSpec.scala b/core/src/test/scala/io/gearpump/cluster/master/ApplicationStateSpec.scala
deleted file mode 100644
index 99cfc37..0000000
--- a/core/src/test/scala/io/gearpump/cluster/master/ApplicationStateSpec.scala
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.master
-
-import org.scalatest.{BeforeAndAfterEach, FlatSpec, Matchers}
-
-import io.gearpump.cluster.appmaster.ApplicationState
-
-class ApplicationStateSpec extends FlatSpec with Matchers with BeforeAndAfterEach {
-
- "ApplicationState" should "check equal with respect to only appId and attemptId" in {
- val stateA = ApplicationState(0, "application0", 0, null, null, null, "A")
- val stateB = ApplicationState(0, "application0", 0, null, null, null, "B")
- val stateC = ApplicationState(0, "application1", 1, null, null, null, "A")
-
- assert(stateA == stateB)
- assert(stateA.hashCode == stateB.hashCode)
- assert(stateA != stateC)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/io/gearpump/cluster/master/MasterProxySpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/io/gearpump/cluster/master/MasterProxySpec.scala b/core/src/test/scala/io/gearpump/cluster/master/MasterProxySpec.scala
deleted file mode 100644
index b007120..0000000
--- a/core/src/test/scala/io/gearpump/cluster/master/MasterProxySpec.scala
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.master
-
-class MasterProxySpec {
-
- // Master proxy retries multiple times to find the master
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/io/gearpump/cluster/master/MasterSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/io/gearpump/cluster/master/MasterSpec.scala b/core/src/test/scala/io/gearpump/cluster/master/MasterSpec.scala
deleted file mode 100644
index e4122da..0000000
--- a/core/src/test/scala/io/gearpump/cluster/master/MasterSpec.scala
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.master
-
-class MasterSpec {
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/io/gearpump/metrics/MetricsSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/io/gearpump/metrics/MetricsSpec.scala b/core/src/test/scala/io/gearpump/metrics/MetricsSpec.scala
deleted file mode 100644
index 3b3265f..0000000
--- a/core/src/test/scala/io/gearpump/metrics/MetricsSpec.scala
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.metrics
-
-import org.mockito.Matchers._
-import org.mockito.Mockito._
-import org.scalatest.mock.MockitoSugar
-import org.scalatest.{FlatSpec, Matchers}
-
-import io.gearpump.codahale.metrics.{Counter => CodaHaleCounter, Histogram => CodaHaleHistogram, Meter => CodaHaleMeter}
-
-class MetricsSpec extends FlatSpec with Matchers with MockitoSugar {
-
- "Counter" should "handle sampleRate == 1" in {
-
- val mockBaseCounter = mock[CodaHaleCounter]
-
- val counter = new Counter("c", mockBaseCounter)
-
- counter.inc()
- counter.inc()
-
- verify(mockBaseCounter, times(2)).inc(1)
- }
-
- "Counter" should "handle sampleRate == 3" in {
-
- val mockBaseCounter = mock[CodaHaleCounter]
-
- val counter = new Counter("c", mockBaseCounter, 3)
-
- counter.inc(1)
- counter.inc(1)
- counter.inc(1)
- counter.inc(1)
- counter.inc(1)
- counter.inc(1)
-
- verify(mockBaseCounter, times(2)).inc(3)
- }
-
- "Histogram" should "handle sampleRate == 1" in {
-
- val mockBaseHistogram = mock[CodaHaleHistogram]
-
- val histogram = new Histogram("h", mockBaseHistogram)
-
- histogram.update(3)
- histogram.update(7)
- histogram.update(5)
- histogram.update(9)
-
- verify(mockBaseHistogram, times(4)).update(anyLong())
- }
-
- "Histogram" should "handle sampleRate > 1" in {
-
- val mockBaseHistogram = mock[CodaHaleHistogram]
-
- val histogram = new Histogram("h", mockBaseHistogram, 2)
-
- histogram.update(3)
- histogram.update(4)
- histogram.update(5)
- histogram.update(6)
-
- verify(mockBaseHistogram, times(1)).update(4L)
- verify(mockBaseHistogram, times(1)).update(6L)
- }
-
- "Meter" should "handle sampleRate == 1" in {
-
- val mockBaseMeter = mock[CodaHaleMeter]
-
- val meter = new Meter("m", mockBaseMeter)
-
- meter.mark()
- meter.mark(3)
-
- verify(mockBaseMeter, times(1)).mark(1L)
- verify(mockBaseMeter, times(1)).mark(3L)
- }
-
- "Meter" should "handle sampleRate > 1" in {
-
- val mockBaseMeter = mock[CodaHaleMeter]
-
- val meter = new Meter("m", mockBaseMeter, 2)
-
- meter.mark(1)
- meter.mark(3)
-
- meter.mark(5)
- meter.mark(7)
-
- verify(mockBaseMeter, times(1)).mark(4L)
- verify(mockBaseMeter, times(1)).mark(12L)
- }
-
- "Metrics" should "have a name" in {
- val metrics = new Metrics(3)
- assert(metrics.counter("counter").name == "counter")
- assert(metrics.histogram("histogram").name == "histogram")
- assert(metrics.meter("meter").name == "meter")
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/io/gearpump/partitioner/PartitionerSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/io/gearpump/partitioner/PartitionerSpec.scala b/core/src/test/scala/io/gearpump/partitioner/PartitionerSpec.scala
deleted file mode 100644
index 9509d94..0000000
--- a/core/src/test/scala/io/gearpump/partitioner/PartitionerSpec.scala
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.partitioner
-
-import org.scalatest.{FlatSpec, Matchers}
-
-import io.gearpump.Message
-
-class PartitionerSpec extends FlatSpec with Matchers {
- val NUM = 10
-
- "HashPartitioner" should "hash same key to same slots" in {
- val partitioner = new HashPartitioner
-
- val data = new Array[Byte](1000)
- (new java.util.Random()).nextBytes(data)
- val msg = Message(data)
-
- val partition = partitioner.getPartition(msg, NUM)
- assert(partition >= 0 && partition < NUM, "Partition Id should be >= 0")
-
- assert(partition == partitioner.getPartition(msg, NUM), "multiple run should return" +
- "consistent result")
- }
-
- "ShufflePartitioner" should "hash same key randomly" in {
- val partitioner = new ShufflePartitioner
-
- val data = new Array[Byte](1000)
- (new java.util.Random()).nextBytes(data)
- val msg = Message(data)
-
- val partition = partitioner.getPartition(msg, NUM)
- assert(partition >= 0 && partition < NUM, "Partition Id should be >= 0")
-
- assert(partition != partitioner.getPartition(msg, NUM), "multiple run should return" +
- "consistent result")
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/io/gearpump/security/ConfigFileBasedAuthenticatorSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/io/gearpump/security/ConfigFileBasedAuthenticatorSpec.scala b/core/src/test/scala/io/gearpump/security/ConfigFileBasedAuthenticatorSpec.scala
deleted file mode 100644
index c38a555..0000000
--- a/core/src/test/scala/io/gearpump/security/ConfigFileBasedAuthenticatorSpec.scala
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.security
-
-import scala.concurrent.Await
-import scala.concurrent.duration._
-
-import akka.actor.ActorSystem
-import org.scalatest.{FlatSpec, Matchers}
-
-import io.gearpump.cluster.TestUtil
-
-class ConfigFileBasedAuthenticatorSpec extends FlatSpec with Matchers {
- it should "authenticate correctly" in {
- val config = TestUtil.UI_CONFIG
- implicit val system = ActorSystem("ConfigFileBasedAuthenticatorSpec", config)
- implicit val ec = system.dispatcher
- val timeout = 30.seconds
-
- val authenticator = new ConfigFileBasedAuthenticator(config)
- val guest = Await.result(authenticator.authenticate("guest", "guest", ec), timeout)
- val admin = Await.result(authenticator.authenticate("admin", "admin", ec), timeout)
-
- val nonexist = Await.result(authenticator.authenticate("nonexist", "nonexist", ec), timeout)
-
- val failedGuest = Await.result(authenticator.authenticate("guest", "wrong", ec), timeout)
- val failedAdmin = Await.result(authenticator.authenticate("admin", "wrong", ec), timeout)
-
- assert(guest == Authenticator.Guest)
- assert(admin == Authenticator.Admin)
- assert(nonexist == Authenticator.UnAuthenticated)
- assert(failedGuest == Authenticator.UnAuthenticated)
- assert(failedAdmin == Authenticator.UnAuthenticated)
-
- system.terminate()
- Await.result(system.whenTerminated, Duration.Inf)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/io/gearpump/security/PasswordUtilSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/io/gearpump/security/PasswordUtilSpec.scala b/core/src/test/scala/io/gearpump/security/PasswordUtilSpec.scala
deleted file mode 100644
index 4a3963b..0000000
--- a/core/src/test/scala/io/gearpump/security/PasswordUtilSpec.scala
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.security
-
-import org.scalatest.{FlatSpec, Matchers}
-
-class PasswordUtilSpec extends FlatSpec with Matchers {
-
- it should "verify the credential correctly" in {
- val password = "password"
-
- val digest1 = PasswordUtil.hash(password)
- val digest2 = PasswordUtil.hash(password)
-
- // Uses different salt each time, thus creating different hash.
- assert(digest1 != digest2)
-
- // Both are valid hash.
- assert(PasswordUtil.verify(password, digest1))
- assert(PasswordUtil.verify(password, digest2))
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/io/gearpump/serializer/SerializerSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/io/gearpump/serializer/SerializerSpec.scala b/core/src/test/scala/io/gearpump/serializer/SerializerSpec.scala
deleted file mode 100644
index 3ed6ffa..0000000
--- a/core/src/test/scala/io/gearpump/serializer/SerializerSpec.scala
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.serializer
-
-import scala.collection.JavaConverters._
-import scala.concurrent.Await
-import scala.concurrent.duration.Duration
-
-import akka.actor.{ActorSystem, ExtendedActorSystem}
-import com.typesafe.config.{ConfigFactory, ConfigValueFactory}
-import org.scalatest.mock.MockitoSugar
-import org.scalatest.{FlatSpec, Matchers}
-
-import io.gearpump.cluster.TestUtil
-import io.gearpump.esotericsoftware.kryo.io.{Input, Output}
-import io.gearpump.esotericsoftware.kryo.{Kryo, Serializer => KryoSerializer}
-import io.gearpump.serializer.SerializerSpec._
-
-class SerializerSpec extends FlatSpec with Matchers with MockitoSugar {
- val config = ConfigFactory.empty.withValue("gearpump.serializers",
- ConfigValueFactory.fromAnyRef(Map(classOf[ClassA].getName -> classOf[ClassASerializer].getName,
- classOf[ClassB].getName -> classOf[ClassBSerializer].getName).asJava))
-
- "GearpumpSerialization" should "register custom serializers" in {
- val serialization = new GearpumpSerialization(config)
- val kryo = new Kryo
- serialization.customize(kryo)
-
- val forB = kryo.getRegistration(classOf[ClassB])
- assert(forB.getSerializer.isInstanceOf[ClassBSerializer])
-
- val forA = kryo.getRegistration(classOf[ClassA])
- assert(forA.getSerializer.isInstanceOf[ClassASerializer])
- }
-
- "FastKryoSerializer" should "serialize correctly" in {
- val myConfig = config.withFallback(TestUtil.DEFAULT_CONFIG.withoutPath("gearpump.serializers"))
- val system = ActorSystem("my", myConfig)
-
- val serializer = new FastKryoSerializer(system.asInstanceOf[ExtendedActorSystem])
-
- val bytes = serializer.serialize(new ClassA)
- val anotherA = serializer.deserialize(bytes)
-
- assert(anotherA.isInstanceOf[ClassA])
- system.terminate()
- Await.result(system.whenTerminated, Duration.Inf)
- }
-}
-
-object SerializerSpec {
-
- class ClassA {}
-
- class ClassASerializer extends KryoSerializer[ClassA] {
- override def write(kryo: Kryo, output: Output, `object`: ClassA): Unit = {
- output.writeString(classOf[ClassA].getName.toString)
- }
-
- override def read(kryo: Kryo, input: Input, `type`: Class[ClassA]): ClassA = {
- val className = input.readString()
- Class.forName(className).newInstance().asInstanceOf[ClassA]
- }
- }
-
- class ClassB {}
-
- class ClassBSerializer extends KryoSerializer[ClassA] {
- override def write(kryo: Kryo, output: Output, `object`: ClassA): Unit = {}
-
- override def read(kryo: Kryo, input: Input, `type`: Class[ClassA]): ClassA = {
- null
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/io/gearpump/transport/MockTransportSerializer.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/io/gearpump/transport/MockTransportSerializer.scala b/core/src/test/scala/io/gearpump/transport/MockTransportSerializer.scala
deleted file mode 100644
index 71b4218..0000000
--- a/core/src/test/scala/io/gearpump/transport/MockTransportSerializer.scala
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.transport
-
-import java.io.{DataInput, DataOutput}
-
-import io.gearpump.transport.MockTransportSerializer.NettyMessage
-import io.gearpump.transport.netty.ITransportMessageSerializer
-
-class MockTransportSerializer extends ITransportMessageSerializer {
- override def getLength(obj: scala.Any): Int = 4
-
- override def serialize(dataOutput: DataOutput, transportMessage: scala.Any): Unit = {
- transportMessage match {
- case msg: NettyMessage =>
- dataOutput.writeInt(msg.num)
- }
- }
-
- override def deserialize(dataInput: DataInput, length: Int): AnyRef = {
- NettyMessage(dataInput.readInt())
- }
-}
-
-object MockTransportSerializer {
- case class NettyMessage(num: Int)
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/io/gearpump/transport/NettySpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/io/gearpump/transport/NettySpec.scala b/core/src/test/scala/io/gearpump/transport/NettySpec.scala
deleted file mode 100644
index 6caf357..0000000
--- a/core/src/test/scala/io/gearpump/transport/NettySpec.scala
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.transport
-
-import java.util.concurrent.TimeUnit
-import scala.concurrent.Await
-import scala.concurrent.duration._
-
-import akka.actor.{ActorRef, ActorSystem}
-import akka.testkit.TestProbe
-import org.scalatest.mock.MockitoSugar
-import org.scalatest.{FlatSpec, Matchers}
-
-import io.gearpump.cluster.TestUtil
-import io.gearpump.transport.MockTransportSerializer.NettyMessage
-import io.gearpump.transport.netty.{Context, TaskMessage}
-import io.gearpump.util.Util
-
-class NettySpec extends FlatSpec with Matchers with MockitoSugar {
-
- "Netty Transport" should "send and receive message correctly " in {
- val conf = TestUtil.DEFAULT_CONFIG
- val system = ActorSystem("transport", conf)
- val context = new Context(system, conf)
- val serverActor = TestProbe()(system)
-
- val port = Util.findFreePort()
-
- import system.dispatcher
- system.scheduler.scheduleOnce(Duration(1, TimeUnit.SECONDS)) {
- context.bind("server", new ActorLookupById {
- override def lookupLocalActor(id: Long): Option[ActorRef] = Some(serverActor.ref)
- }, false, port.get)
- }
- val client = context.connect(HostPort("127.0.0.1", port.get))
-
- val data = NettyMessage(0)
- val msg = new TaskMessage(0, 1, 2, data)
- client ! msg
- serverActor.expectMsg(15.seconds, data)
-
- context.close()
- system.terminate()
- Await.result(system.whenTerminated, Duration.Inf)
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/io/gearpump/util/ActorSystemBooterSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/io/gearpump/util/ActorSystemBooterSpec.scala b/core/src/test/scala/io/gearpump/util/ActorSystemBooterSpec.scala
deleted file mode 100644
index 13530ed..0000000
--- a/core/src/test/scala/io/gearpump/util/ActorSystemBooterSpec.scala
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.util
-
-import scala.concurrent.Await
-import scala.concurrent.duration.Duration
-
-import akka.actor.{Actor, ActorSystem, Props}
-import akka.testkit.TestProbe
-import org.scalatest.mock.MockitoSugar
-import org.scalatest.{FlatSpec, Matchers}
-
-import io.gearpump.cluster.TestUtil
-import io.gearpump.util.ActorSystemBooter.{ActorCreated, RegisterActorSystem, _}
-import io.gearpump.util.ActorSystemBooterSpec._
-
-class ActorSystemBooterSpec extends FlatSpec with Matchers with MockitoSugar {
-
- "ActorSystemBooter" should "report its address back" in {
- val boot = bootSystem()
- boot.prob.expectMsgType[RegisterActorSystem]
- boot.shutdown()
- }
-
- "ActorSystemBooter" should "terminate itself when parent actor dies" in {
- val boot = bootSystem()
- boot.prob.expectMsgType[RegisterActorSystem]
-
- val dummy = boot.host.actorOf(Props(classOf[Dummy]), "dummy")
- boot.prob.reply(ActorSystemRegistered(boot.prob.ref))
- boot.prob.reply(BindLifeCycle(dummy))
- boot.host.stop(dummy)
- val terminated = retry(5)(boot.bootedSystem.whenTerminated.isCompleted)
- assert(terminated)
- boot.shutdown()
- }
-
- "ActorSystemBooter" should "create new actor" in {
- val boot = bootSystem()
- boot.prob.expectMsgType[RegisterActorSystem]
- boot.prob.reply(ActorSystemRegistered(boot.prob.ref))
- boot.prob.reply(CreateActor(Props(classOf[AcceptThreeArguments], 1, 2, 3), "three"))
- boot.prob.expectMsgType[ActorCreated]
-
- boot.prob.reply(CreateActor(Props(classOf[AcceptZeroArguments]), "zero"))
- boot.prob.expectMsgType[ActorCreated]
-
- boot.shutdown()
- }
-
- private def bootSystem(): Boot = {
- val booter = ActorSystemBooter(TestUtil.DEFAULT_CONFIG)
-
- val system = ActorSystem("reportback", TestUtil.DEFAULT_CONFIG)
-
- val receiver = TestProbe()(system)
- val address = ActorUtil.getFullPath(system, receiver.ref.path)
-
- val bootSystem = booter.boot("booter", address)
-
- Boot(system, receiver, bootSystem)
- }
-
- case class Boot(host: ActorSystem, prob: TestProbe, bootedSystem: ActorSystem) {
- def shutdown(): Unit = {
- host.terminate()
- bootedSystem.terminate()
- Await.result(host.whenTerminated, Duration.Inf)
- Await.result(bootedSystem.whenTerminated, Duration.Inf)
- }
- }
-
- def retry(seconds: Int)(fn: => Boolean): Boolean = {
- val result = fn
- if (result) {
- result
- } else {
- Thread.sleep(1000)
- retry(seconds - 1)(fn)
- }
- }
-}
-
-object ActorSystemBooterSpec {
- class Dummy extends Actor {
- def receive: Receive = {
- case _ =>
- }
- }
-
- class AcceptZeroArguments extends Actor {
- def receive: Receive = {
- case _ =>
- }
- }
-
- class AcceptThreeArguments(a: Int, b: Int, c: Int) extends Actor {
- def receive: Receive = {
- case _ =>
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/io/gearpump/util/ActorUtilSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/io/gearpump/util/ActorUtilSpec.scala b/core/src/test/scala/io/gearpump/util/ActorUtilSpec.scala
deleted file mode 100644
index 6ab5a2f..0000000
--- a/core/src/test/scala/io/gearpump/util/ActorUtilSpec.scala
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.util
-
-import org.scalatest.FlatSpec
-
-import io.gearpump.transport.HostPort
-
-class ActorUtilSpec extends FlatSpec {
- "masterActorPath" should "construct the ActorPath from HostPort" in {
- import io.gearpump.util.Constants.MASTER
-
- val host = "127.0.0.1"
- val port = 3000
- val master = HostPort("127.0.0.1", 3000)
- val masterPath = ActorUtil.getMasterActorPath(master)
- assert(masterPath.address.port == Some(port))
- assert(masterPath.address.system == MASTER)
- assert(masterPath.address.host == Some(host))
- assert(masterPath.address.protocol == "akka.tcp")
- assert(masterPath.toStringWithoutAddress == s"/user/$MASTER")
- }
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/io/gearpump/util/ConfigsSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/io/gearpump/util/ConfigsSpec.scala b/core/src/test/scala/io/gearpump/util/ConfigsSpec.scala
deleted file mode 100644
index 0c798f3..0000000
--- a/core/src/test/scala/io/gearpump/util/ConfigsSpec.scala
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.util
-
-import java.io.File
-import scala.concurrent.Await
-import scala.concurrent.duration.Duration
-
-import akka.actor.ActorSystem
-import org.scalatest.mock.MockitoSugar
-import org.scalatest.{FlatSpec, Matchers}
-
-import io.gearpump.cluster.{ClusterConfig, ClusterConfigSource, UserConfig}
-
-class ConfigsSpec extends FlatSpec with Matchers with MockitoSugar {
- "Typesafe Cluster Configs" should "follow the override rules" in {
-
- val conf =
- """
- gearpump {
- gear = "gearpump"
- }
-
- gearpump-master {
- conf = "master"
- }
- gearpump-worker {
- conf = "worker"
- }
- conf = "base"
- """
-
- val file = File.createTempFile("test", ".conf")
- FileUtils.write(file, conf)
-
- val raw = ClusterConfig.load(ClusterConfigSource(file.toString))
-
- assert(raw.master.getString("conf") == "master", "master > base")
- assert(raw.worker.getString("conf") == "worker", "worker > base")
- assert(raw.default.getString("conf") == "base", "application > base")
-
- file.delete()
- }
-
- "ClusterConfigSource" should "return empty for non-exist files" in {
- val source = ClusterConfigSource("non-exist")
- var config = source.getConfig
- assert(config.isEmpty)
-
- val nullCheck = ClusterConfigSource(null)
- config = nullCheck.getConfig
- assert(config.isEmpty)
- }
-
- "User Config" should "work" in {
-
- implicit val system = ActorSystem("forSerialization")
-
- val map = Map[String, String]("key1" -> "1", "key2" -> "value2")
-
- val user = new UserConfig(map)
- .withLong("key3", 2L)
- .withBoolean("key4", value = true)
- .withFloat("key5", 3.14F)
- .withDouble("key6", 2.718)
-
- assert(user.getInt("key1").get == 1)
- assert(user.getString("key1").get == "1")
- assert(user.getLong("key3").get == 2L)
- assert(user.getBoolean("key4").get == true)
- assert(user.getFloat("key5").get == 3.14F)
- assert(user.getDouble("key6").get == 2.718)
-
- val data = new ConfigsSpec.Data(3)
- assert(data == user.withValue("data", data).getValue[ConfigsSpec.Data]("data").get)
- system.terminate()
- Await.result(system.whenTerminated, Duration.Inf)
- }
-}
-
-object ConfigsSpec {
- case class Data(value: Int)
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/io/gearpump/util/FileUtilsSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/io/gearpump/util/FileUtilsSpec.scala b/core/src/test/scala/io/gearpump/util/FileUtilsSpec.scala
deleted file mode 100644
index 30e42c7..0000000
--- a/core/src/test/scala/io/gearpump/util/FileUtilsSpec.scala
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.util
-
-import java.io.File
-import java.util
-
-import org.scalatest.FlatSpec
-
-import io.gearpump.google.common.io.Files
-
-class FileUtilsSpec extends FlatSpec {
- val TXT =
- """
- |This is a multiple line
- |text
- |
- """.stripMargin
-
- it should "read/write string correctly" in {
- val file = File.createTempFile("fileutilspec", ".test")
- FileUtils.write(file, TXT)
- assert(FileUtils.read(file) == TXT)
- file.delete()
- }
-
- it should "read/write bytes array correctly" in {
- val file = File.createTempFile("fileutilspec", ".test")
- val bytes = TXT.toCharArray.map(_.toByte)
- FileUtils.writeByteArrayToFile(file, bytes)
- util.Arrays.equals(bytes, FileUtils.readFileToByteArray(file))
- file.delete()
- }
-
- it should "create directory and all parents" in {
- val temp = Files.createTempDir()
- val parent = new File(temp, "sub1")
- val child = new File(parent, "sub2" + File.separator)
- FileUtils.forceMkdir(child)
- assert(child.exists())
- assert(child.isDirectory)
- child.delete()
- parent.delete()
- temp.delete()
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/io/gearpump/util/GraphSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/io/gearpump/util/GraphSpec.scala b/core/src/test/scala/io/gearpump/util/GraphSpec.scala
deleted file mode 100644
index 20eab6d..0000000
--- a/core/src/test/scala/io/gearpump/util/GraphSpec.scala
+++ /dev/null
@@ -1,213 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.util
-
-import org.scalacheck.Gen
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{Matchers, PropSpec}
-
-import io.gearpump.util.Graph.{Node, Path}
-
-class GraphSpec extends PropSpec with PropertyChecks with Matchers {
-
- case class Vertex(id: Int)
- case class Edge(from: Int, to: Int)
-
- val vertexCount = 100
-
- property("Graph with no edges should be built correctly") {
- val vertexSet = Set("A", "B", "C")
- val graph = Graph(vertexSet.toSeq.map(Node): _*)
- graph.vertices.toSet shouldBe vertexSet
- }
-
- property("Graph with vertices and edges should be built correctly") {
- val vertices: Array[Vertex] = 0.until(vertexCount).map(Vertex).toArray
- val genEdge = for {
- from <- Gen.chooseNum[Int](0, vertexCount - 1)
- to <- Gen.chooseNum[Int](0, vertexCount - 1)
- } yield Edge(from, to)
-
- var graphElements = Array.empty[Path[Vertex, _ <: Edge]]
- val outDegrees = new Array[Int](vertices.length)
- val outGoingEdges = vertices.map(_ => Set.empty[(Vertex, Edge, Vertex)])
- val edgesOf = vertices.map(_ => Set.empty[(Vertex, Edge, Vertex)])
- vertices.foreach { v =>
- graphElements :+= Node(v)
- }
-
- forAll(genEdge) {
- e: Edge =>
- val from = vertices(e.from)
- val to = vertices(e.to)
- graphElements :+= from ~ e ~> to
- outDegrees(e.from) += 1
-
- val nodeEdgeNode = (from, e, to)
- outGoingEdges(e.from) += nodeEdgeNode
-
- edgesOf(e.from) += nodeEdgeNode
- edgesOf(e.to) += nodeEdgeNode
- }
-
- val graph: Graph[Vertex, Edge] = Graph(graphElements: _*)
- graph.vertices should contain theSameElementsAs vertices
-
- 0.until(vertices.size).foreach { i =>
- val v = vertices(i)
- graph.outgoingEdgesOf(v) should contain theSameElementsAs outGoingEdges(i)
- graph.edgesOf(v).sortBy(_._1.id)
- graph.edgesOf(v) should contain theSameElementsAs edgesOf(i)
- }
- }
-
- property("Check empty graph") {
- val graph = Graph.empty[String, String]
- assert(graph.isEmpty)
- }
-
- property("check level map for a graph") {
- val graph = Graph.empty[String, String]
-
- val defaultEdge = "edge"
-
- graph.addVertex("A")
- graph.addVertex("B")
- graph.addVertex("C")
-
- graph.addEdge("A", defaultEdge, "B")
- graph.addEdge("B", defaultEdge, "C")
- graph.addEdge("A", defaultEdge, "C")
-
- graph.addVertex("D")
- graph.addVertex("E")
- graph.addVertex("F")
-
- graph.addEdge("D", defaultEdge, "E")
- graph.addEdge("E", defaultEdge, "F")
- graph.addEdge("D", defaultEdge, "F")
-
- graph.addEdge("C", defaultEdge, "E")
-
- val levelMap = graph.vertexHierarchyLevelMap()
-
- // Check whether the rule holds: : if vertex A -> B, then level(A) < level(B)
- levelMap("A") < levelMap("B")
- levelMap("A") < levelMap("C")
- levelMap("B") < levelMap("C")
-
- levelMap("D") < levelMap("E")
- levelMap("D") < levelMap("F")
- levelMap("E") < levelMap("F")
-
- levelMap("C") < levelMap("F")
- }
-
- property("copy should return a immutalbe new Graph") {
- val graph = Graph.empty[String, String]
- val defaultEdge = "edge"
- graph.addVertex("A")
- graph.addVertex("B")
- graph.addEdge("A", defaultEdge, "B")
-
- val newGraph = graph.copy
- newGraph.addVertex("C")
-
- assert(!graph.vertices.toSet.contains("C"), "Graph should be immutable")
- }
-
- property("subGraph should return a sub-graph for certain vertex") {
- val graph = Graph.empty[String, String]
- val defaultEdge = "edge"
- graph.addVertex("A")
- graph.addVertex("B")
- graph.addVertex("C")
- graph.addEdge("A", defaultEdge, "B")
- graph.addEdge("B", defaultEdge, "C")
- graph.addEdge("A", defaultEdge, "C")
-
- val subGraph = graph.subGraph("C")
- assert(subGraph.outDegreeOf("A") != graph.outDegreeOf("A"))
- }
-
- property("replaceVertex should hold all upstream downstream relation for a vertex") {
- val graph = Graph.empty[String, String]
- val defaultEdge = "edge"
- graph.addVertex("A")
- graph.addVertex("B")
- graph.addVertex("C")
- graph.addEdge("A", defaultEdge, "B")
- graph.addEdge("B", defaultEdge, "C")
-
- val newGraph = graph.copy.replaceVertex("B", "D")
- assert(newGraph.inDegreeOf("D") == graph.inDegreeOf("B"))
- assert(newGraph.outDegreeOf("D") == graph.outDegreeOf("B"))
- }
-
- property("Cycle detecting should work properly") {
- val graph = Graph.empty[String, String]
- val defaultEdge = "edge"
- graph.addVertex("A")
- graph.addVertex("B")
- graph.addVertex("C")
- graph.addEdge("A", defaultEdge, "B")
- graph.addEdge("B", defaultEdge, "C")
-
- assert(!graph.hasCycle())
-
- graph.addEdge("C", defaultEdge, "B")
- assert(graph.hasCycle())
-
- graph.addEdge("C", defaultEdge, "A")
- assert(graph.hasCycle())
- }
-
- property("topologicalOrderIterator and topologicalOrderWithCirclesIterator method should " +
- "return equal order of graph with no circle") {
- val graph = Graph(1 ~> 2 ~> 3, 4 ~> 2, 2 ~> 5)
- val topoNoCircles = graph.topologicalOrderIterator
- val topoWithCircles = graph.topologicalOrderWithCirclesIterator
-
- assert(topoNoCircles.zip(topoWithCircles).forall(x => x._1 == x._2))
- }
-
- property("Topological sort of graph with circles should work properly") {
- val graph = Graph(0 ~> 1 ~> 3 ~> 4 ~> 6 ~> 5 ~> 7,
- 4 ~> 1, 1 ~> 2 ~> 4, 7 ~> 6, 8 ~> 2, 6 ~> 9, 4 ~> 10)
- val topoWithCircles = graph.topologicalOrderWithCirclesIterator
- val trueTopoWithCircles = Iterator[Int](0, 8, 1, 3, 4, 2, 6, 5, 7, 10, 9)
-
- assert(trueTopoWithCircles.zip(topoWithCircles).forall(x => x._1 == x._2))
- }
-
- property("Duplicated edges detecting should work properly") {
- val graph = Graph.empty[String, String]
- val defaultEdge = "edge"
- val anotherEdge = "edge2"
- graph.addVertex("A")
- graph.addVertex("B")
- graph.addEdge("A", defaultEdge, "B")
-
- assert(!graph.hasDuplicatedEdge())
-
- graph.addEdge("A", anotherEdge, "B")
-
- assert(graph.hasDuplicatedEdge())
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/io/gearpump/util/TimeOutSchedulerSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/io/gearpump/util/TimeOutSchedulerSpec.scala b/core/src/test/scala/io/gearpump/util/TimeOutSchedulerSpec.scala
deleted file mode 100644
index ef362ff..0000000
--- a/core/src/test/scala/io/gearpump/util/TimeOutSchedulerSpec.scala
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.util
-
-import scala.concurrent.duration._
-
-import akka.actor._
-import akka.testkit.{ImplicitSender, TestActorRef, TestKit, TestProbe}
-import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}
-import org.slf4j.Logger
-
-import io.gearpump.cluster.TestUtil
-
-class TimeOutSchedulerSpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
- with WordSpecLike with Matchers with BeforeAndAfterAll {
-
- def this() = this(ActorSystem("WorkerSpec", TestUtil.DEFAULT_CONFIG))
- val mockActor = TestProbe()
-
- override def afterAll {
- TestKit.shutdownActorSystem(system)
- }
-
- "The TimeOutScheduler" should {
- "handle the time out event" in {
- val testActorRef = TestActorRef(Props(classOf[TestActor], mockActor.ref))
- val testActor = testActorRef.underlyingActor.asInstanceOf[TestActor]
- testActor.sendMsgToIgnore()
- mockActor.expectMsg(30.seconds, MessageTimeOut)
- }
- }
-}
-
-case object Echo
-case object MessageTimeOut
-
-class TestActor(mock: ActorRef) extends Actor with TimeOutScheduler {
- private val LOG: Logger = LogUtil.getLogger(getClass)
-
- val target = context.actorOf(Props(classOf[EchoActor]))
-
- override def receive: Receive = {
- case _ =>
- }
-
- def sendMsgToIgnore(): Unit = {
- sendMsgWithTimeOutCallBack(target, Echo, 2000, sendMsgTimeOut())
- }
-
- private def sendMsgTimeOut(): Unit = {
- mock ! MessageTimeOut
- }
-}
-
-class EchoActor extends Actor {
- override def receive: Receive = {
- case _ =>
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/io/gearpump/util/UtilSpec.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/io/gearpump/util/UtilSpec.scala b/core/src/test/scala/io/gearpump/util/UtilSpec.scala
deleted file mode 100644
index b5bde04..0000000
--- a/core/src/test/scala/io/gearpump/util/UtilSpec.scala
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.util
-
-import org.scalatest.mock.MockitoSugar
-import org.scalatest.{FlatSpec, Matchers}
-
-import io.gearpump.transport.HostPort
-import io.gearpump.util.Util._
-
-class UtilSpec extends FlatSpec with Matchers with MockitoSugar {
- it should "work" in {
-
- assert(findFreePort().isSuccess)
-
- assert(randInt() != randInt())
-
- val hosts = parseHostList("host1:1,host2:2")
- assert(hosts(1) == HostPort("host2", 2))
-
- assert(Util.getCurrentClassPath.length > 0)
- }
-
- it should "check application name properly" in {
- assert(Util.validApplicationName("_application_1"))
- assert(Util.validApplicationName("application_1_"))
- assert(!Util.validApplicationName("0_application_1"))
- assert(!Util.validApplicationName("_applicat&&ion_1"))
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/org/apache/gearpump/TestProbeUtil.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/org/apache/gearpump/TestProbeUtil.scala b/core/src/test/scala/org/apache/gearpump/TestProbeUtil.scala
new file mode 100644
index 0000000..6ab7eed
--- /dev/null
+++ b/core/src/test/scala/org/apache/gearpump/TestProbeUtil.scala
@@ -0,0 +1,37 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump
+
+import scala.language.implicitConversions
+
+import akka.actor.{Actor, Props, Terminated}
+import akka.testkit.TestProbe
+
+object TestProbeUtil {
+ implicit def toProps(probe: TestProbe): Props = {
+ Props(new Actor {
+ val probeRef = probe.ref
+ context.watch(probeRef)
+ def receive: Receive = {
+ case Terminated(probeRef) => context.stop(self)
+ case x => probeRef.forward(x)
+ }
+ })
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/org/apache/gearpump/cluster/MasterHarness.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/org/apache/gearpump/cluster/MasterHarness.scala b/core/src/test/scala/org/apache/gearpump/cluster/MasterHarness.scala
new file mode 100644
index 0000000..f2f374e
--- /dev/null
+++ b/core/src/test/scala/org/apache/gearpump/cluster/MasterHarness.scala
@@ -0,0 +1,160 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster
+
+import java.io.File
+import java.net.{InetSocketAddress, Socket, SocketTimeoutException, URLClassLoader, UnknownHostException}
+import java.util.Properties
+import java.util.concurrent.{Executors, TimeUnit}
+import scala.collection.JavaConverters._
+import scala.concurrent.duration.Duration
+import scala.concurrent.{Await, ExecutionContext}
+
+import akka.actor.{Actor, ActorSystem, Address, Props}
+import akka.testkit.TestProbe
+import com.typesafe.config.{Config, ConfigFactory, ConfigParseOptions, ConfigValueFactory}
+
+import org.apache.gearpump.cluster.MasterHarness.MockMaster
+import org.apache.gearpump.util.Constants._
+import org.apache.gearpump.util.{ActorUtil, FileUtils, LogUtil}
+
+trait MasterHarness {
+ private val LOG = LogUtil.getLogger(getClass)
+
+ implicit val pool = MasterHarness.cachedPool
+
+ private var system: ActorSystem = null
+ private var systemAddress: Address = null
+ private var host: String = null
+ private var port: Int = 0
+ private var masterProperties = new Properties()
+ val PROCESS_BOOT_TIME = Duration(25, TimeUnit.SECONDS)
+
+ def getActorSystem: ActorSystem = system
+ def getHost: String = host
+ def getPort: Int = port
+
+ protected def config: Config
+
+ def startActorSystem(): Unit = {
+ val systemConfig = config
+ system = ActorSystem(MASTER, systemConfig)
+ systemAddress = ActorUtil.getSystemAddress(system)
+ host = systemAddress.host.get
+ port = systemAddress.port.get
+
+ masterProperties.put(s"${GEARPUMP_CLUSTER_MASTERS}.0", s"$getHost:$getPort")
+ masterProperties.put(s"${GEARPUMP_HOSTNAME}", s"$getHost")
+
+ LOG.info(s"Actor system is started, $host, $port")
+ }
+
+ def shutdownActorSystem(): Unit = {
+ system.terminate()
+ Await.result(system.whenTerminated, Duration.Inf)
+ LOG.info(s"Actor system is stopped, $host, $port")
+ }
+
+ def convertTestConf(host: String, port: Int): File = {
+ val test = ConfigFactory.parseResourcesAnySyntax("test.conf",
+ ConfigParseOptions.defaults.setAllowMissing(true))
+
+ val newConf = test.withValue(GEARPUMP_CLUSTER_MASTERS,
+ ConfigValueFactory.fromAnyRef(Array(s"$host:$port").toList.asJava))
+
+ val confFile = File.createTempFile("main", ".conf")
+ val serialized = newConf.root().render()
+ FileUtils.write(confFile, serialized)
+ confFile
+ }
+
+ def createMockMaster(): TestProbe = {
+ val masterReceiver = TestProbe()(system)
+ val master = system.actorOf(Props(classOf[MockMaster], masterReceiver), MASTER)
+ masterReceiver
+ }
+
+ def isPortUsed(host: String, port: Int): Boolean = {
+
+ var isPortUsed = true
+ val socket = new Socket()
+ try {
+ socket.setReuseAddress(true)
+ socket.connect(new InetSocketAddress(host, port), 1000)
+ socket.isConnected
+ } catch {
+ case ex: SocketTimeoutException =>
+ isPortUsed = false
+ case ex: UnknownHostException =>
+ isPortUsed = false
+ case ex: Throwable =>
+ // For other case, we think the port has been occupied.
+ isPortUsed = true
+ } finally {
+ socket.close()
+ }
+ isPortUsed
+ }
+
+ def getContextClassPath: Array[String] = {
+ val contextLoader = Thread.currentThread().getContextClassLoader()
+
+ val urlLoader = if (!contextLoader.isInstanceOf[URLClassLoader]) {
+ contextLoader.getParent.asInstanceOf[URLClassLoader]
+ } else {
+ contextLoader.asInstanceOf[URLClassLoader]
+ }
+
+ val urls = urlLoader.getURLs()
+ val classPath = urls.map { url =>
+ new File(url.getPath()).toString
+ }
+ classPath
+ }
+
+ /**
+ * Remove trailing $
+ */
+ def getMainClassName(mainObj: Any): String = {
+ mainObj.getClass.getName.dropRight(1)
+ }
+
+ def getMasterListOption(): Array[String] = {
+ masterProperties.asScala.toList.map { kv =>
+ s"-D${kv._1}=${kv._2}"
+ }.toArray
+ }
+
+ def masterConfig: Config = {
+ ConfigFactory.parseProperties(masterProperties).withFallback(system.settings.config)
+ }
+}
+
+object MasterHarness {
+
+ val cachedPool = ExecutionContext.fromExecutorService(Executors.newCachedThreadPool())
+
+ class MockMaster(receiver: TestProbe) extends Actor {
+ def receive: Receive = {
+ case msg => {
+ receiver.ref forward msg
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/org/apache/gearpump/cluster/TestUtil.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/org/apache/gearpump/cluster/TestUtil.scala b/core/src/test/scala/org/apache/gearpump/cluster/TestUtil.scala
new file mode 100644
index 0000000..5d8727e
--- /dev/null
+++ b/core/src/test/scala/org/apache/gearpump/cluster/TestUtil.scala
@@ -0,0 +1,36 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster
+
+import akka.actor._
+
+object TestUtil {
+ val DEFAULT_CONFIG = ClusterConfig.default("test.conf")
+ val MASTER_CONFIG = ClusterConfig.master("test.conf")
+ val UI_CONFIG = ClusterConfig.ui("test.conf")
+
+ class DummyAppMaster(context: AppMasterContext, app: AppDescription) extends ApplicationMaster {
+ context.masterProxy !(context, app)
+
+ def receive: Receive = null
+ }
+
+ val dummyApp: AppDescription =
+ AppDescription("dummy", classOf[DummyAppMaster].getName, UserConfig.empty)
+}
\ No newline at end of file
[35/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/test/scala/org/apache/gearpump/cluster/scheduler/PrioritySchedulerSpec.scala
----------------------------------------------------------------------
diff --git a/daemon/src/test/scala/org/apache/gearpump/cluster/scheduler/PrioritySchedulerSpec.scala b/daemon/src/test/scala/org/apache/gearpump/cluster/scheduler/PrioritySchedulerSpec.scala
new file mode 100644
index 0000000..e82dff3
--- /dev/null
+++ b/daemon/src/test/scala/org/apache/gearpump/cluster/scheduler/PrioritySchedulerSpec.scala
@@ -0,0 +1,232 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.cluster.scheduler
+
+import org.apache.gearpump.cluster.worker.WorkerId
+
+import scala.concurrent.duration._
+
+import akka.actor.{ActorSystem, Props}
+import akka.testkit.{ImplicitSender, TestKit, TestProbe}
+import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}
+
+import org.apache.gearpump.cluster.AppMasterToMaster.RequestResource
+import org.apache.gearpump.cluster.MasterToAppMaster.ResourceAllocated
+import org.apache.gearpump.cluster.MasterToWorker.{UpdateResourceFailed, WorkerRegistered}
+import org.apache.gearpump.cluster.TestUtil
+import org.apache.gearpump.cluster.WorkerToMaster.ResourceUpdate
+import org.apache.gearpump.cluster.master.Master.MasterInfo
+import org.apache.gearpump.cluster.scheduler.Priority.{HIGH, LOW, NORMAL}
+import org.apache.gearpump.cluster.scheduler.Scheduler.ApplicationFinished
+
+class PrioritySchedulerSpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
+ with WordSpecLike with Matchers with BeforeAndAfterAll{
+
+ def this() = this(ActorSystem("PrioritySchedulerSpec", TestUtil.DEFAULT_CONFIG))
+ val appId = 0
+ val workerId1: WorkerId = WorkerId(1, 0L)
+ val workerId2: WorkerId = WorkerId(2, 0L)
+ val mockAppMaster = TestProbe()
+ val mockWorker1 = TestProbe()
+ val mockWorker2 = TestProbe()
+
+ override def afterAll {
+ TestKit.shutdownActorSystem(system)
+ }
+
+ "The scheduler" should {
+ "update resource only when the worker is registered" in {
+ val scheduler = system.actorOf(Props(classOf[PriorityScheduler]))
+ scheduler ! ResourceUpdate(mockWorker1.ref, workerId1, Resource(100))
+ expectMsg(UpdateResourceFailed(s"ResourceUpdate failed! The worker $workerId1 has not been " +
+ s"registered into master"))
+ }
+
+ "drop application's resource requests when the application is removed" in {
+ val scheduler = system.actorOf(Props(classOf[PriorityScheduler]))
+ val request1 = ResourceRequest(Resource(40), WorkerId.unspecified, HIGH, Relaxation.ANY)
+ val request2 = ResourceRequest(Resource(20), WorkerId.unspecified, HIGH, Relaxation.ANY)
+ scheduler.tell(RequestResource(appId, request1), mockAppMaster.ref)
+ scheduler.tell(RequestResource(appId, request2), mockAppMaster.ref)
+ scheduler.tell(ApplicationFinished(appId), mockAppMaster.ref)
+ scheduler.tell(WorkerRegistered(workerId1, MasterInfo.empty), mockWorker1.ref)
+ scheduler.tell(ResourceUpdate(mockWorker1.ref, workerId1, Resource(100)), mockWorker1.ref)
+ mockAppMaster.expectNoMsg(5.seconds)
+ }
+ }
+
+ def sameElement(left: ResourceAllocated, right: ResourceAllocated): Boolean = {
+ left.allocations.sortBy(_.workerId).sameElements(right.allocations.sortBy(_.workerId))
+ }
+
+ "The resource request with higher priority" should {
+ "be handled first" in {
+ val scheduler = system.actorOf(Props(classOf[PriorityScheduler]))
+ val request1 = ResourceRequest(Resource(40), WorkerId.unspecified, LOW, Relaxation.ANY)
+ val request2 = ResourceRequest(Resource(20), WorkerId.unspecified, NORMAL, Relaxation.ANY)
+ val request3 = ResourceRequest(Resource(30), WorkerId.unspecified, HIGH, Relaxation.ANY)
+
+ scheduler.tell(RequestResource(appId, request1), mockAppMaster.ref)
+ scheduler.tell(RequestResource(appId, request1), mockAppMaster.ref)
+ scheduler.tell(RequestResource(appId, request2), mockAppMaster.ref)
+ scheduler.tell(RequestResource(appId, request3), mockAppMaster.ref)
+ scheduler.tell(WorkerRegistered(workerId1, MasterInfo.empty), mockWorker1.ref)
+ scheduler.tell(ResourceUpdate(mockWorker1.ref, workerId1, Resource(100)), mockWorker1.ref)
+
+ var expect = ResourceAllocated(
+ Array(ResourceAllocation(Resource(30), mockWorker1.ref, workerId1)))
+ mockAppMaster.expectMsgPF(5.seconds) {
+ case request: ResourceAllocated if sameElement(request, expect) => Unit
+ }
+
+ expect = ResourceAllocated(
+ Array(ResourceAllocation(Resource(20), mockWorker1.ref, workerId1)))
+ mockAppMaster.expectMsgPF(5.seconds) {
+ case request: ResourceAllocated if sameElement(request, expect) => Unit
+ }
+
+ expect = ResourceAllocated(
+ Array(ResourceAllocation(Resource(40), mockWorker1.ref, workerId1)))
+ mockAppMaster.expectMsgPF(5.seconds) {
+ case request: ResourceAllocated if sameElement(request, expect) => Unit
+ }
+
+ scheduler.tell(WorkerRegistered(workerId2, MasterInfo.empty), mockWorker2.ref)
+ scheduler.tell(ResourceUpdate(mockWorker1.ref, workerId1, Resource.empty), mockWorker1.ref)
+ scheduler.tell(ResourceUpdate(mockWorker2.ref, workerId2, Resource(100)), mockWorker2.ref)
+
+ expect = ResourceAllocated(
+ Array(ResourceAllocation(Resource(40), mockWorker2.ref, workerId2)))
+ mockAppMaster.expectMsgPF(5.seconds) {
+ case request: ResourceAllocated if sameElement(request, expect) => Unit
+ }
+ }
+ }
+
+ "The resource request which delivered earlier" should {
+ "be handled first if the priorities are the same" in {
+ val scheduler = system.actorOf(Props(classOf[PriorityScheduler]))
+ val request1 = ResourceRequest(Resource(40), WorkerId.unspecified, HIGH, Relaxation.ANY)
+ val request2 = ResourceRequest(Resource(20), WorkerId.unspecified, HIGH, Relaxation.ANY)
+ scheduler.tell(RequestResource(appId, request1), mockAppMaster.ref)
+ scheduler.tell(RequestResource(appId, request2), mockAppMaster.ref)
+ scheduler.tell(WorkerRegistered(workerId1, MasterInfo.empty), mockWorker1.ref)
+ scheduler.tell(ResourceUpdate(mockWorker1.ref, workerId1, Resource(100)), mockWorker1.ref)
+
+ var expect = ResourceAllocated(
+ Array(ResourceAllocation(Resource(40), mockWorker1.ref, workerId1)))
+ mockAppMaster.expectMsgPF(5.seconds) {
+ case request: ResourceAllocated if sameElement(request, expect) => Unit
+ }
+ expect = ResourceAllocated(
+ Array(ResourceAllocation(Resource(20), mockWorker1.ref, workerId1)))
+ mockAppMaster.expectMsgPF(5.seconds) {
+ case request: ResourceAllocated if sameElement(request, expect) => Unit
+ }
+ }
+ }
+
+ "The PriorityScheduler" should {
+ "handle the resource request with different relaxation" in {
+ val scheduler = system.actorOf(Props(classOf[PriorityScheduler]))
+ val request1 = ResourceRequest(Resource(40), workerId2, HIGH, Relaxation.SPECIFICWORKER)
+ val request2 = ResourceRequest(Resource(20), workerId1, NORMAL, Relaxation.SPECIFICWORKER)
+
+ scheduler.tell(RequestResource(appId, request1), mockAppMaster.ref)
+ scheduler.tell(RequestResource(appId, request2), mockAppMaster.ref)
+ scheduler.tell(WorkerRegistered(workerId1, MasterInfo.empty), mockWorker1.ref)
+ scheduler.tell(ResourceUpdate(mockWorker1.ref, workerId1, Resource(100)), mockWorker1.ref)
+
+ var expect = ResourceAllocated(
+ Array(ResourceAllocation(Resource(20), mockWorker1.ref, workerId1)))
+ mockAppMaster.expectMsgPF(5.seconds) {
+ case request: ResourceAllocated if sameElement(request, expect) => Unit
+ }
+
+ scheduler.tell(WorkerRegistered(workerId2, MasterInfo.empty), mockWorker2.ref)
+ scheduler.tell(ResourceUpdate(mockWorker2.ref, workerId2, Resource(100)), mockWorker2.ref)
+
+ expect = ResourceAllocated(
+ Array(ResourceAllocation(Resource(40), mockWorker2.ref, workerId2)))
+ mockAppMaster.expectMsgPF(5.seconds) {
+ case request: ResourceAllocated if sameElement(request, expect) => Unit
+ }
+
+ val request3 = ResourceRequest(
+ Resource(30), WorkerId.unspecified, NORMAL, Relaxation.ANY, executorNum = 2)
+ scheduler.tell(RequestResource(appId, request3), mockAppMaster.ref)
+
+ expect = ResourceAllocated(Array(
+ ResourceAllocation(Resource(15), mockWorker1.ref, workerId1),
+ ResourceAllocation(Resource(15), mockWorker2.ref, workerId2)))
+ mockAppMaster.expectMsgPF(5.seconds) {
+ case request: ResourceAllocated if sameElement(request, expect) => Unit
+ }
+
+ // We have to manually update the resource on each worker
+ scheduler.tell(ResourceUpdate(mockWorker1.ref, workerId1, Resource(65)), mockWorker1.ref)
+ scheduler.tell(ResourceUpdate(mockWorker2.ref, workerId2, Resource(45)), mockWorker2.ref)
+ val request4 = ResourceRequest(Resource(60), WorkerId(0, 0L), NORMAL, Relaxation.ONEWORKER)
+ scheduler.tell(RequestResource(appId, request4), mockAppMaster.ref)
+
+ expect = ResourceAllocated(
+ Array(ResourceAllocation(Resource(60), mockWorker1.ref, workerId1)))
+ mockAppMaster.expectMsgPF(5.seconds) {
+ case request: ResourceAllocated if sameElement(request, expect) => Unit
+ }
+ }
+ }
+
+ "The PriorityScheduler" should {
+ "handle the resource request with different executor number" in {
+ val scheduler = system.actorOf(Props(classOf[PriorityScheduler]))
+ scheduler.tell(WorkerRegistered(workerId1, MasterInfo.empty), mockWorker1.ref)
+ scheduler.tell(ResourceUpdate(mockWorker1.ref, workerId1, Resource(100)), mockWorker1.ref)
+ scheduler.tell(WorkerRegistered(workerId2, MasterInfo.empty), mockWorker2.ref)
+ scheduler.tell(ResourceUpdate(mockWorker2.ref, workerId2, Resource(100)), mockWorker2.ref)
+
+ // By default, the request requires only one executor
+ val request2 = ResourceRequest(Resource(20), WorkerId.unspecified)
+ scheduler.tell(RequestResource(appId, request2), mockAppMaster.ref)
+ val allocations2 = mockAppMaster.receiveN(1).head.asInstanceOf[ResourceAllocated]
+ assert(allocations2.allocations.length == 1)
+ assert(allocations2.allocations.head.resource == Resource(20))
+
+ val request3 = ResourceRequest(Resource(24), WorkerId.unspecified, executorNum = 3)
+ scheduler.tell(RequestResource(appId, request3), mockAppMaster.ref)
+ val allocations3 = mockAppMaster.receiveN(1).head.asInstanceOf[ResourceAllocated]
+ assert(allocations3.allocations.length == 3)
+ assert(allocations3.allocations.forall(_.resource == Resource(8)))
+
+ // The total available resource can not satisfy the requirements with executor number
+ scheduler.tell(ResourceUpdate(mockWorker1.ref, workerId1, Resource(30)), mockWorker1.ref)
+ scheduler.tell(ResourceUpdate(mockWorker2.ref, workerId2, Resource(30)), mockWorker2.ref)
+ val request4 = ResourceRequest(Resource(60), WorkerId.unspecified, executorNum = 3)
+ scheduler.tell(RequestResource(appId, request4), mockAppMaster.ref)
+ val allocations4 = mockAppMaster.receiveN(1).head.asInstanceOf[ResourceAllocated]
+ assert(allocations4.allocations.length == 2)
+ assert(allocations4.allocations.forall(_.resource == Resource(20)))
+
+ // When new resources are available, the remaining request will be satisfied
+ scheduler.tell(ResourceUpdate(mockWorker1.ref, workerId1, Resource(40)), mockWorker1.ref)
+ val allocations5 = mockAppMaster.receiveN(1).head.asInstanceOf[ResourceAllocated]
+ assert(allocations5.allocations.length == 1)
+ assert(allocations4.allocations.forall(_.resource == Resource(20)))
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/test/scala/org/apache/gearpump/cluster/worker/WorkerSpec.scala
----------------------------------------------------------------------
diff --git a/daemon/src/test/scala/org/apache/gearpump/cluster/worker/WorkerSpec.scala b/daemon/src/test/scala/org/apache/gearpump/cluster/worker/WorkerSpec.scala
new file mode 100644
index 0000000..bf25057
--- /dev/null
+++ b/daemon/src/test/scala/org/apache/gearpump/cluster/worker/WorkerSpec.scala
@@ -0,0 +1,129 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.cluster.worker
+
+import scala.concurrent.Await
+import scala.concurrent.duration._
+
+import akka.actor.{ActorSystem, PoisonPill, Props}
+import akka.testkit.TestProbe
+import com.typesafe.config.{Config, ConfigFactory}
+import org.scalatest._
+
+import org.apache.gearpump.cluster.AppMasterToWorker.{ChangeExecutorResource, LaunchExecutor, ShutdownExecutor}
+import org.apache.gearpump.cluster.MasterToWorker.{UpdateResourceFailed, WorkerRegistered}
+import org.apache.gearpump.cluster.WorkerToAppMaster.{ExecutorLaunchRejected, ShutdownExecutorFailed, ShutdownExecutorSucceed}
+import org.apache.gearpump.cluster.WorkerToMaster.{RegisterNewWorker, RegisterWorker, ResourceUpdate}
+import org.apache.gearpump.cluster.master.Master.MasterInfo
+import org.apache.gearpump.cluster.scheduler.Resource
+import org.apache.gearpump.cluster.{ExecutorJVMConfig, MasterHarness, TestUtil}
+import org.apache.gearpump.util.{ActorSystemBooter, ActorUtil, Constants}
+
+class WorkerSpec extends WordSpec with Matchers with BeforeAndAfterEach with MasterHarness {
+ override def config: Config = TestUtil.DEFAULT_CONFIG
+
+ val appId = 1
+ val workerId: WorkerId = WorkerId(1, 0L)
+ val executorId = 1
+ var masterProxy: TestProbe = null
+ var mockMaster: TestProbe = null
+ var client: TestProbe = null
+ val workerSlots = 50
+
+ override def beforeEach(): Unit = {
+ startActorSystem()
+ mockMaster = TestProbe()(getActorSystem)
+ masterProxy = TestProbe()(getActorSystem)
+ client = TestProbe()(getActorSystem)
+ }
+
+ override def afterEach(): Unit = {
+ shutdownActorSystem()
+ }
+
+ "The new started worker" should {
+ "kill itself if no response from Master after registering" in {
+ val worker = getActorSystem.actorOf(Props(classOf[Worker], mockMaster.ref))
+ mockMaster watch worker
+ mockMaster.expectMsg(RegisterNewWorker)
+ mockMaster.expectTerminated(worker, 60.seconds)
+ }
+ }
+
+ "Worker" should {
+ "init its resource from the gearpump config" in {
+ val config = ConfigFactory.parseString(s"${Constants.GEARPUMP_WORKER_SLOTS} = $workerSlots").
+ withFallback(TestUtil.DEFAULT_CONFIG)
+ val workerSystem = ActorSystem("WorkerSystem", config)
+ val worker = workerSystem.actorOf(Props(classOf[Worker], mockMaster.ref))
+ mockMaster watch worker
+ mockMaster.expectMsg(RegisterNewWorker)
+
+ worker.tell(WorkerRegistered(workerId, MasterInfo(mockMaster.ref)), mockMaster.ref)
+ mockMaster.expectMsg(ResourceUpdate(worker, workerId, Resource(workerSlots)))
+
+ worker.tell(
+ UpdateResourceFailed("Test resource update failed", new Exception()), mockMaster.ref)
+ mockMaster.expectTerminated(worker, 5.seconds)
+ workerSystem.terminate()
+ Await.result(workerSystem.whenTerminated, Duration.Inf)
+ }
+ }
+
+ "Worker" should {
+ "update its remaining resource when launching and shutting down executors" in {
+ val worker = getActorSystem.actorOf(Props(classOf[Worker], masterProxy.ref))
+ masterProxy.expectMsg(RegisterNewWorker)
+
+ worker.tell(WorkerRegistered(workerId, MasterInfo(mockMaster.ref)), mockMaster.ref)
+ mockMaster.expectMsg(ResourceUpdate(worker, workerId, Resource(100)))
+
+ val executorName = ActorUtil.actorNameForExecutor(appId, executorId)
+ // This is an actor path which the ActorSystemBooter will report back to,
+ // not needed in this test
+ val reportBack = "dummy"
+ val executionContext = ExecutorJVMConfig(Array.empty[String],
+ getActorSystem.settings.config.getString(Constants.GEARPUMP_APPMASTER_ARGS).split(" "),
+ classOf[ActorSystemBooter].getName, Array(executorName, reportBack), None,
+ username = "user")
+
+ // Test LaunchExecutor
+ worker.tell(LaunchExecutor(appId, executorId, Resource(101), executionContext),
+ mockMaster.ref)
+ mockMaster.expectMsg(ExecutorLaunchRejected("There is no free resource on this machine"))
+
+ worker.tell(LaunchExecutor(appId, executorId, Resource(5), executionContext), mockMaster.ref)
+ mockMaster.expectMsg(ResourceUpdate(worker, workerId, Resource(95)))
+
+ worker.tell(ChangeExecutorResource(appId, executorId, Resource(2)), client.ref)
+ mockMaster.expectMsg(ResourceUpdate(worker, workerId, Resource(98)))
+
+ // Test terminationWatch
+ worker.tell(ShutdownExecutor(appId, executorId, "Test shut down executor"), client.ref)
+ mockMaster.expectMsg(ResourceUpdate(worker, workerId, Resource(100)))
+ client.expectMsg(ShutdownExecutorSucceed(1, 1))
+
+ worker.tell(ShutdownExecutor(appId, executorId + 1, "Test shut down executor"), client.ref)
+ client.expectMsg(ShutdownExecutorFailed(
+ s"Can not find executor ${executorId + 1} for app $appId"))
+
+ mockMaster.ref ! PoisonPill
+ masterProxy.expectMsg(RegisterWorker(workerId))
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/test/scala/org/apache/gearpump/util/FileServerSpec.scala
----------------------------------------------------------------------
diff --git a/daemon/src/test/scala/org/apache/gearpump/util/FileServerSpec.scala b/daemon/src/test/scala/org/apache/gearpump/util/FileServerSpec.scala
new file mode 100644
index 0000000..b33c801
--- /dev/null
+++ b/daemon/src/test/scala/org/apache/gearpump/util/FileServerSpec.scala
@@ -0,0 +1,120 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.util
+
+import java.io.File
+import java.util.concurrent.TimeUnit
+import scala.concurrent.Await
+import scala.concurrent.duration.Duration
+
+import akka.actor.ActorSystem
+import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}
+
+import org.apache.gearpump.cluster.TestUtil
+import io.gearpump.google.common.io.Files
+import org.apache.gearpump.jarstore.FilePath
+import org.apache.gearpump.util.FileServer._
+
+class FileServerSpec extends WordSpecLike with Matchers with BeforeAndAfterAll {
+
+ implicit val timeout = akka.util.Timeout(25, TimeUnit.SECONDS)
+ val host = "localhost"
+ private val LOG = LogUtil.getLogger(getClass)
+
+ var system: ActorSystem = null
+
+ override def afterAll {
+ if (null != system) {
+ system.terminate()
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+ }
+
+ override def beforeAll {
+ val config = TestUtil.DEFAULT_CONFIG
+ system = ActorSystem("FileServerSpec", config)
+ }
+
+ private def save(client: Client, data: Array[Byte]): FilePath = {
+ val file = File.createTempFile("fileserverspec", "test")
+ FileUtils.writeByteArrayToFile(file, data)
+ val future = client.upload(file)
+ import scala.concurrent.duration._
+ val path = Await.result(future, 30.seconds)
+ file.delete()
+ path
+ }
+
+ private def get(client: Client, remote: FilePath): Array[Byte] = {
+ val file = File.createTempFile("fileserverspec", "test")
+ val future = client.download(remote, file)
+ import scala.concurrent.duration._
+ val data = Await.result(future, 10.seconds)
+
+ val bytes = FileUtils.readFileToByteArray(file)
+ file.delete()
+ bytes
+ }
+
+ "The file server" should {
+ "serve the data previously stored" in {
+
+ val rootDir = Files.createTempDir()
+
+ val server = new FileServer(system, host, 0, rootDir)
+ val port = Await.result((server.start), Duration(25, TimeUnit.SECONDS))
+
+ LOG.info("start test web server on port " + port)
+
+ val sizes = List(1, 100, 1000000, 50000000)
+ val client = new Client(system, host, port.port)
+
+ sizes.foreach { size =>
+ val bytes = randomBytes(size)
+ val url = s"http://$host:${port.port}/$size"
+ val remote = save(client, bytes)
+ val fetchedBytes = get(client, remote)
+ assert(fetchedBytes sameElements bytes, s"fetch data is coruppted, $url, $rootDir")
+ }
+ server.stop
+ rootDir.delete()
+ }
+ }
+
+ "The file server" should {
+ "handle missed file" in {
+
+ val rootDir = Files.createTempDir()
+
+ val server = new FileServer(system, host, 0, rootDir)
+ val port = Await.result((server.start), Duration(25, TimeUnit.SECONDS))
+
+ val client = new Client(system, host, port.port)
+ val fetchedBytes = get(client, FilePath("noexist"))
+ assert(fetchedBytes.length == 0)
+ rootDir.delete()
+ }
+ }
+
+ private def randomBytes(size: Int): Array[Byte] = {
+ val bytes = new Array[Byte](size)
+ (new java.util.Random()).nextBytes(bytes)
+ bytes
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/docs/deployment-configuration.md
----------------------------------------------------------------------
diff --git a/docs/deployment-configuration.md b/docs/deployment-configuration.md
index 70b5500..b651fed 100644
--- a/docs/deployment-configuration.md
+++ b/docs/deployment-configuration.md
@@ -76,7 +76,7 @@ This is the default configuration for `gear.conf`.
| gearpump.executor.vmargs | "-server -Xss1M -XX:+HeapDumpOnOutOfMemoryError -XX:+UseConcMarkSweepGC -XX:CMSInitiatingOccupancyFraction=80 -XX:+UseParNewGC -XX:NewRatio=3 -Djava.rmi.server.hostname=localhost" | JVM arguments for executor |
| gearpump.executor.extraClasspath | "" | JVM default class path for executor |
| gearpump.jarstore.rootpath | "jarstore/" | Define where the submitted jar file will be stored. This path follows the hadoop path schema. For HDFS, use `hdfs://host:port/path/`; if you want to store on master nodes, then use local directory. `jarstore.rootpath = "jarstore/"` will point to relative directory where master is started. `jarstore.rootpath = "/jarstore/"` will point to absolute directory on master server |
-| gearpump.scheduling.scheduler-class |"io.gearpump.cluster.scheduler.PriorityScheduler" | Class to schedule the applications. |
+| gearpump.scheduling.scheduler-class |"org.apache.gearpump.cluster.scheduler.PriorityScheduler" | Class to schedule the applications. |
| gearpump.services.host | "127.0.0.1" | dashboard UI host address |
| gearpump.services.port | 8090 | dashboard UI host port |
| gearpump.netty.buffer-size | 5242880 | netty connection buffer size |
@@ -88,4 +88,4 @@ This is the default configuration for `gear.conf`.
| gearpump.netty.dispatcher | "gearpump.shared-thread-pool-dispatcher" | default dispatcher for netty client and server |
| gearpump.shared-thread-pool-dispatcher | default Dispatcher with "fork-join-executor" | default shared thread pool dispatcher |
| gearpump.single-thread-dispatcher | PinnedDispatcher | default single thread dispatcher |
-| serialization-framework | "io.gearpump.serializer.FastKryoSerializationFramework" | Gearpump has built-in serialization framework using Kryo. Users are allowed to use a different serialization framework, like Protobuf. See `io.gearpump.serializer.FastKryoSerializationFramework` to find how a custom serialization framework can be defined |
+| serialization-framework | "org.apache.gearpump.serializer.FastKryoSerializationFramework" | Gearpump has built-in serialization framework using Kryo. Users are allowed to use a different serialization framework, like Protobuf. See `org.apache.gearpump.serializer.FastKryoSerializationFramework` to find how a custom serialization framework can be defined |
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/docs/deployment-resource-isolation.md
----------------------------------------------------------------------
diff --git a/docs/deployment-resource-isolation.md b/docs/deployment-resource-isolation.md
index 0cb3764..955b8dd 100644
--- a/docs/deployment-resource-isolation.md
+++ b/docs/deployment-resource-isolation.md
@@ -83,7 +83,7 @@ The following steps are supposed to be executed by root user.
2. Enter into Gearpump's home folder, edit gear.conf under folder ```${GEARPUMP_HOME}/conf/```
```
- gearpump.worker.executor-process-launcher = "io.gearpump.cluster.worker.CGroupProcessLauncher"
+ gearpump.worker.executor-process-launcher = "org.apache.gearpump.cluster.worker.CGroupProcessLauncher"
gearpump.cgroup.root = "gearpump"
```
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/docs/deployment-ui-authentication.md
----------------------------------------------------------------------
diff --git a/docs/deployment-ui-authentication.md b/docs/deployment-ui-authentication.md
index 872a857..614dc15 100644
--- a/docs/deployment-ui-authentication.md
+++ b/docs/deployment-ui-authentication.md
@@ -35,7 +35,7 @@ UI server admin can also choose to enable **auxiliary** OAuth2 authentication ch
Gearpump provides a built-in ConfigFileBasedAuthenticator which verify user name and password
against password hashcode stored in config files.
- However, developer can choose to extends the ```io.gearpump.security.Authenticator``` to provide a custom
+ However, developer can choose to extends the ```org.apache.gearpump.security.Authenticator``` to provide a custom
User-Password based authenticator, to support LDAP, Kerberos, and Database-based authentication...
### ConfigFileBasedAuthenticator: built-in User-Password Authenticator
@@ -59,7 +59,7 @@ Suppose we want to add user jerry as an administrator, here are the steps:
to generate the digest:
```
- bin/gear io.gearpump.security.PasswordUtil -password ilovegearpump
+ bin/gear org.apache.gearpump.security.PasswordUtil -password ilovegearpump
```
It will generate a digest value like this:
@@ -110,8 +110,8 @@ If developer choose to define his/her own User-Password based authenticator, it
modify configuration option:
```
-## Replace "io.gearpump.security.CustomAuthenticator" with your real authenticator class.
-gearpump.ui-security.authenticator = "io.gearpump.security.CustomAuthenticator"
+## Replace "org.apache.gearpump.security.CustomAuthenticator" with your real authenticator class.
+gearpump.ui-security.authenticator = "org.apache.gearpump.security.CustomAuthenticator"
```
Make sure CustomAuthenticator extends interface:
@@ -357,7 +357,7 @@ You can follow the Google OAuth2 example code to define a custom OAuth2Authentic
```
## name of this authenticator
"socialnetworkx" {
- "class" = "io.gearpump.services.security.oauth2.impl.SocialNetworkXAuthenticator"
+ "class" = "org.apache.gearpump.services.security.oauth2.impl.SocialNetworkXAuthenticator"
## Please make sure this URL matches the name
"callback" = "http://127.0.0.1:8090/login/oauth2/socialnetworkx/callback"
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/docs/dev-connectors.md
----------------------------------------------------------------------
diff --git a/docs/dev-connectors.md b/docs/dev-connectors.md
index 08ff023..2060c93 100644
--- a/docs/dev-connectors.md
+++ b/docs/dev-connectors.md
@@ -9,7 +9,7 @@ title: Gearpump Connectors
### DataSource
`DataSource` is the concept in Gearpump that without input and will output messages. So, basically, `DataSource` is the start point of a streaming processing flow.
-As Gearpump depends on `DataSource` to be replay-able to ensure at-least-once message delivery and exactly-once message delivery, for some data sources, we will need a `io.gearpump.streaming.transaction.api.OffsetStorageFactory` to store the offset (progress) of current `DataSource`. So that, when a replay is needed, Gearpump can guide `DataSource` to replay from certain offset.
+As Gearpump depends on `DataSource` to be replay-able to ensure at-least-once message delivery and exactly-once message delivery, for some data sources, we will need a `org.apache.gearpump.streaming.transaction.api.OffsetStorageFactory` to store the offset (progress) of current `DataSource`. So that, when a replay is needed, Gearpump can guide `DataSource` to replay from certain offset.
Currently Gearpump `DataSource` only support infinite stream. Finite stream support will be added in a near future release.
@@ -143,7 +143,7 @@ To implement your own `DataSource`, you need to implement two things:
2. a helper class to easy the usage in a DSL
### Implement your own `DataSource`
-You need to implement a class derived from `io.gearpump.streaming.transaction.api.TimeReplayableSource`.
+You need to implement a class derived from `org.apache.gearpump.streaming.transaction.api.TimeReplayableSource`.
### Implement DSL helper (Optional)
If you would like to have a DSL at hand you may start with this customized stream; it is better if you can implement your own DSL helper.
@@ -174,7 +174,7 @@ To implement your own `DataSink`, you need to implement two things:
2. a helper class to make it easy use in DSL
### Implement your own `DataSink`
-You need to implement a class derived from `io.gearpump.streaming.sink.DataSink`.
+You need to implement a class derived from `org.apache.gearpump.streaming.sink.DataSink`.
### Implement DSL helper (Optional)
If you would like to have a DSL at hand you may start with this customized stream; it is better if you can implement your own DSL helper.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/docs/dev-custom-serializer.md
----------------------------------------------------------------------
diff --git a/docs/dev-custom-serializer.md b/docs/dev-custom-serializer.md
index 5be0544..8e6ba46 100644
--- a/docs/dev-custom-serializer.md
+++ b/docs/dev-custom-serializer.md
@@ -15,10 +15,10 @@ To register a class, you need to change the configuration file gear.conf(or appl
gearpump {
serializers {
## We will use default FieldSerializer to serialize this class type
- "io.gearpump.UserMessage" = ""
+ "org.apache.gearpump.UserMessage" = ""
## we will use custom serializer to serialize this class type
- "io.gearpump.UserMessage2" = "io.gearpump.UserMessageSerializer"
+ "org.apache.gearpump.UserMessage2" = "org.apache.gearpump.UserMessageSerializer"
}
}
```
@@ -27,7 +27,7 @@ gearpump {
When you decide that you want to define a custom serializer, you can do this in two ways.
-Please note that Gearpump shaded the original Kryo dependency. The package name ```com.esotericsoftware``` was relocated to ```io.gearpump.esotericsoftware```. So in the following customization, you should import corresponding shaded classes, the example code will show that part.
+Please note that Gearpump shaded the original Kryo dependency. The package name ```com.esotericsoftware``` was relocated to ```org.apache.gearpump.esotericsoftware```. So in the following customization, you should import corresponding shaded classes, the example code will show that part.
In general you should use the shaded version of a library whenever possible in order to avoid binary incompatibilities, eg don't use:
@@ -38,7 +38,7 @@ In general you should use the shaded version of a library whenever possible in o
but rather
```scala
- import io.gearpump.google.common.io.Files
+ import org.apache.gearpump.google.common.io.Files
```
##### System Level Serializer
@@ -48,10 +48,10 @@ If the serializer is widely used, you can define a global serializer which is av
###### Step1: you first need to develop a java library which contains the custom serializer class. here is an example:
```scala
-package io.gearpump
+package org.apache.gearpump
-import io.gearpump.esotericsoftware.kryo.{Kryo, Serializer}
-import io.gearpump.esotericsoftware.kryo.io.{Input, Output}
+import org.apache.gearpump.esotericsoftware.kryo.{Kryo, Serializer}
+import org.apache.gearpump.esotericsoftware.kryo.io.{Input, Output}
class UserMessage(longField: Long, intField: Int)
@@ -78,7 +78,7 @@ Distribute the jar file to lib/ folder of every Gearpump installation in the clu
```
gearpump {
serializers {
- "io.gearpump.UserMessage" = "io.gearpump.UserMessageSerializer"
+ "org.apache.gearpump.UserMessage" = "org.apache.gearpump.UserMessageSerializer"
}
}
```
@@ -93,10 +93,10 @@ If all you want is to define an application level serializer, which is only visi
You should include the Serializer class in your application jar. Here is an example to define a custom serializer:
```scala
-package io.gearpump
+package org.apache.gearpump
-import io.gearpump.esotericsoftware.kryo.{Kryo, Serializer}
-import io.gearpump.esotericsoftware.kryo.io.{Input, Output}
+import org.apache.gearpump.esotericsoftware.kryo.{Kryo, Serializer}
+import org.apache.gearpump.esotericsoftware.kryo.io.{Input, Output}
class UserMessage(longField: Long, intField: Int)
@@ -120,7 +120,7 @@ class UserMessageSerializer extends Serializer[UserMessage] {
### content of application.conf
gearpump {
serializers {
- "io.gearpump.UserMessage" = "io.gearpump.UserMessageSerializer"
+ "org.apache.gearpump.UserMessage" = "org.apache.gearpump.UserMessageSerializer"
}
}
```
@@ -136,7 +136,7 @@ There are other serialization framework besides Kryo, like Protobuf. If user don
basically, user need to define in gear.conf(or application.conf for single application's scope) file like this:
```bash
-gearpump.serialization-framework = "io.gearpump.serializer.CustomSerializationFramework"
+gearpump.serialization-framework = "org.apache.gearpump.serializer.CustomSerializationFramework"
```
Please find an example in gearpump storm module, search "StormSerializationFramework" in source code.
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/docs/dev-non-streaming-example.md
----------------------------------------------------------------------
diff --git a/docs/dev-non-streaming-example.md b/docs/dev-non-streaming-example.md
index 1aec2d1..8b859dc 100644
--- a/docs/dev-non-streaming-example.md
+++ b/docs/dev-non-streaming-example.md
@@ -3,7 +3,7 @@ layout: global
title: Gearpump Non-Streaming Example
---
-We'll use [Distributed Shell](https://github.com/gearpump/gearpump/tree/master/examples/distributedshell/src/main/scala/io/gearpump/examples/distributedshell) as an example to illustrate how to do that.
+We'll use [Distributed Shell](https://github.com/gearpump/gearpump/tree/master/examples/distributedshell/src/main/scala/org.apache.gearpump/examples/distributedshell) as an example to illustrate how to do that.
What Distributed Shell do is that user send a shell command to the cluster and the command will the executed on each node, then the result will be return to user.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/docs/dev-rest-api.md
----------------------------------------------------------------------
diff --git a/docs/dev-rest-api.md b/docs/dev-rest-api.md
index 6243a89..161a09f 100644
--- a/docs/dev-rest-api.md
+++ b/docs/dev-rest-api.md
@@ -262,36 +262,36 @@ Sample Response:
:
[{
"time": "1450758725070",
- "value": {"$type": "io.gearpump.metrics.Metrics.Gauge", "name": "master:memory.heap.used", "value": "59764272"}
+ "value": {"$type": "org.apache.gearpump.metrics.Metrics.Gauge", "name": "master:memory.heap.used", "value": "59764272"}
}, {
"time": "1450758725070",
- "value": {"$type": "io.gearpump.metrics.Metrics.Gauge", "name": "master:thread.daemon.count", "value": "18"}
+ "value": {"$type": "org.apache.gearpump.metrics.Metrics.Gauge", "name": "master:thread.daemon.count", "value": "18"}
}, {
"time": "1450758725070",
"value": {
- "$type": "io.gearpump.metrics.Metrics.Gauge",
+ "$type": "org.apache.gearpump.metrics.Metrics.Gauge",
"name": "master:memory.total.committed",
"value": "210239488"
}
}, {
"time": "1450758725070",
- "value": {"$type": "io.gearpump.metrics.Metrics.Gauge", "name": "master:memory.heap.max", "value": "880017408"}
+ "value": {"$type": "org.apache.gearpump.metrics.Metrics.Gauge", "name": "master:memory.heap.max", "value": "880017408"}
}, {
"time": "1450758725070",
- "value": {"$type": "io.gearpump.metrics.Metrics.Gauge", "name": "master:memory.total.max", "value": "997457920"}
+ "value": {"$type": "org.apache.gearpump.metrics.Metrics.Gauge", "name": "master:memory.total.max", "value": "997457920"}
}, {
"time": "1450758725070",
"value": {
- "$type": "io.gearpump.metrics.Metrics.Gauge",
+ "$type": "org.apache.gearpump.metrics.Metrics.Gauge",
"name": "master:memory.heap.committed",
"value": "179830784"
}
}, {
"time": "1450758725070",
- "value": {"$type": "io.gearpump.metrics.Metrics.Gauge", "name": "master:memory.total.used", "value": "89117352"}
+ "value": {"$type": "org.apache.gearpump.metrics.Metrics.Gauge", "name": "master:memory.total.used", "value": "89117352"}
}, {
"time": "1450758725070",
- "value": {"$type": "io.gearpump.metrics.Metrics.Gauge", "name": "master:thread.count", "value": "28"}
+ "value": {"$type": "org.apache.gearpump.metrics.Metrics.Gauge", "name": "master:thread.count", "value": "28"}
}]
}
```
@@ -471,88 +471,88 @@ Sample Response:
[{
"time": "1450759137860",
"value": {
- "$type": "io.gearpump.metrics.Metrics.Gauge",
+ "$type": "org.apache.gearpump.metrics.Metrics.Gauge",
"name": "worker1:memory.total.used",
"value": "152931440"
}
}, {
"time": "1450759137860",
- "value": {"$type": "io.gearpump.metrics.Metrics.Gauge", "name": "worker1:thread.daemon.count", "value": "18"}
+ "value": {"$type": "org.apache.gearpump.metrics.Metrics.Gauge", "name": "worker1:thread.daemon.count", "value": "18"}
}, {
"time": "1450759137860",
"value": {
- "$type": "io.gearpump.metrics.Metrics.Gauge",
+ "$type": "org.apache.gearpump.metrics.Metrics.Gauge",
"name": "worker0:memory.heap.used",
"value": "123139640"
}
}, {
"time": "1450759137860",
"value": {
- "$type": "io.gearpump.metrics.Metrics.Gauge",
+ "$type": "org.apache.gearpump.metrics.Metrics.Gauge",
"name": "worker0:memory.total.max",
"value": "997457920"
}
}, {
"time": "1450759137860",
"value": {
- "$type": "io.gearpump.metrics.Metrics.Gauge",
+ "$type": "org.apache.gearpump.metrics.Metrics.Gauge",
"name": "worker0:memory.heap.committed",
"value": "179830784"
}
}, {
"time": "1450759137860",
- "value": {"$type": "io.gearpump.metrics.Metrics.Gauge", "name": "worker0:thread.count", "value": "28"}
+ "value": {"$type": "org.apache.gearpump.metrics.Metrics.Gauge", "name": "worker0:thread.count", "value": "28"}
}, {
"time": "1450759137860",
- "value": {"$type": "io.gearpump.metrics.Metrics.Gauge", "name": "worker0:memory.heap.max", "value": "880017408"}
+ "value": {"$type": "org.apache.gearpump.metrics.Metrics.Gauge", "name": "worker0:memory.heap.max", "value": "880017408"}
}, {
"time": "1450759137860",
- "value": {"$type": "io.gearpump.metrics.Metrics.Gauge", "name": "worker1:memory.heap.max", "value": "880017408"}
+ "value": {"$type": "org.apache.gearpump.metrics.Metrics.Gauge", "name": "worker1:memory.heap.max", "value": "880017408"}
}, {
"time": "1450759137860",
"value": {
- "$type": "io.gearpump.metrics.Metrics.Gauge",
+ "$type": "org.apache.gearpump.metrics.Metrics.Gauge",
"name": "worker0:memory.total.committed",
"value": "210239488"
}
}, {
"time": "1450759137860",
"value": {
- "$type": "io.gearpump.metrics.Metrics.Gauge",
+ "$type": "org.apache.gearpump.metrics.Metrics.Gauge",
"name": "worker0:memory.total.used",
"value": "152931440"
}
}, {
"time": "1450759137860",
- "value": {"$type": "io.gearpump.metrics.Metrics.Gauge", "name": "worker1:thread.count", "value": "28"}
+ "value": {"$type": "org.apache.gearpump.metrics.Metrics.Gauge", "name": "worker1:thread.count", "value": "28"}
}, {
"time": "1450759137860",
"value": {
- "$type": "io.gearpump.metrics.Metrics.Gauge",
+ "$type": "org.apache.gearpump.metrics.Metrics.Gauge",
"name": "worker1:memory.total.max",
"value": "997457920"
}
}, {
"time": "1450759137860",
"value": {
- "$type": "io.gearpump.metrics.Metrics.Gauge",
+ "$type": "org.apache.gearpump.metrics.Metrics.Gauge",
"name": "worker1:memory.heap.committed",
"value": "179830784"
}
}, {
"time": "1450759137860",
"value": {
- "$type": "io.gearpump.metrics.Metrics.Gauge",
+ "$type": "org.apache.gearpump.metrics.Metrics.Gauge",
"name": "worker1:memory.total.committed",
"value": "210239488"
}
}, {
"time": "1450759137860",
- "value": {"$type": "io.gearpump.metrics.Metrics.Gauge", "name": "worker0:thread.daemon.count", "value": "18"}
+ "value": {"$type": "org.apache.gearpump.metrics.Metrics.Gauge", "name": "worker0:thread.daemon.count", "value": "18"}
}, {
"time": "1450759137860",
"value": {
- "$type": "io.gearpump.metrics.Metrics.Gauge",
+ "$type": "org.apache.gearpump.metrics.Metrics.Gauge",
"name": "worker1:memory.heap.used",
"value": "123139640"
}
@@ -654,7 +654,7 @@ Sample Response:
0,
{
"id": 0,
- "taskClass": "io.gearpump.streaming.examples.wordcount.Split",
+ "taskClass": "org.apache.gearpump.streaming.examples.wordcount.Split",
"parallelism": 1,
"description": "",
"taskConf": {
@@ -681,7 +681,7 @@ Sample Response:
1,
{
"id": 1,
- "taskClass": "io.gearpump.streaming.examples.wordcount.Sum",
+ "taskClass": "org.apache.gearpump.streaming.examples.wordcount.Sum",
"parallelism": 1,
"description": "",
"taskConf": {
@@ -723,7 +723,7 @@ Sample Response:
"edgeList": [
[
0,
- "io.gearpump.partitioner.HashPartitioner",
+ "org.apache.gearpump.partitioner.HashPartitioner",
1
]
]
@@ -856,7 +856,7 @@ Sample Response:
},
"netty-dispatcher" : "akka.actor.default-dispatcher",
"scheduling" : {
- "scheduler-class" : "io.gearpump.cluster.scheduler.PriorityScheduler"
+ "scheduler-class" : "org.apache.gearpump.cluster.scheduler.PriorityScheduler"
},
"serializers" : {
"[B" : "",
@@ -868,11 +868,11 @@ Sample Response:
"[Ljava.lang.String;" : "",
"[S" : "",
"[Z" : "",
- "io.gearpump.Message" : "io.gearpump.streaming.MessageSerializer",
- "io.gearpump.streaming.task.Ack" : "io.gearpump.streaming.AckSerializer",
- "io.gearpump.streaming.task.AckRequest" : "io.gearpump.streaming.AckRequestSerializer",
- "io.gearpump.streaming.task.LatencyProbe" : "io.gearpump.streaming.LatencyProbeSerializer",
- "io.gearpump.streaming.task.TaskId" : "io.gearpump.streaming.TaskIdSerializer",
+ "org.apache.gearpump.Message" : "org.apache.gearpump.streaming.MessageSerializer",
+ "org.apache.gearpump.streaming.task.Ack" : "org.apache.gearpump.streaming.AckSerializer",
+ "org.apache.gearpump.streaming.task.AckRequest" : "org.apache.gearpump.streaming.AckRequestSerializer",
+ "org.apache.gearpump.streaming.task.LatencyProbe" : "org.apache.gearpump.streaming.LatencyProbeSerializer",
+ "org.apache.gearpump.streaming.task.TaskId" : "org.apache.gearpump.streaming.TaskIdSerializer",
"scala.Tuple1" : "",
"scala.Tuple2" : "",
"scala.Tuple3" : "",
@@ -910,7 +910,7 @@ aggregator points to a aggregator class, which will aggregate on the current met
Example:
```bash
-curl [--cookie outputAuthenticationCookie.txt] http://127.0.0.1:8090/api/v1.0/appmaster/1/metrics/app1?readLatest=true&aggregator=io.gearpump.streaming.metrics.ProcessorAggregator
+curl [--cookie outputAuthenticationCookie.txt] http://127.0.0.1:8090/api/v1.0/appmaster/1/metrics/app1?readLatest=true&aggregator=org.apache.gearpump.streaming.metrics.ProcessorAggregator
```
Sample Response:
@@ -924,88 +924,88 @@ Sample Response:
[{
"time": "1450759137860",
"value": {
- "$type": "io.gearpump.metrics.Metrics.Gauge",
+ "$type": "org.apache.gearpump.metrics.Metrics.Gauge",
"name": "worker1:memory.total.used",
"value": "152931440"
}
}, {
"time": "1450759137860",
- "value": {"$type": "io.gearpump.metrics.Metrics.Gauge", "name": "worker1:thread.daemon.count", "value": "18"}
+ "value": {"$type": "org.apache.gearpump.metrics.Metrics.Gauge", "name": "worker1:thread.daemon.count", "value": "18"}
}, {
"time": "1450759137860",
"value": {
- "$type": "io.gearpump.metrics.Metrics.Gauge",
+ "$type": "org.apache.gearpump.metrics.Metrics.Gauge",
"name": "worker0:memory.heap.used",
"value": "123139640"
}
}, {
"time": "1450759137860",
"value": {
- "$type": "io.gearpump.metrics.Metrics.Gauge",
+ "$type": "org.apache.gearpump.metrics.Metrics.Gauge",
"name": "worker0:memory.total.max",
"value": "997457920"
}
}, {
"time": "1450759137860",
"value": {
- "$type": "io.gearpump.metrics.Metrics.Gauge",
+ "$type": "org.apache.gearpump.metrics.Metrics.Gauge",
"name": "worker0:memory.heap.committed",
"value": "179830784"
}
}, {
"time": "1450759137860",
- "value": {"$type": "io.gearpump.metrics.Metrics.Gauge", "name": "worker0:thread.count", "value": "28"}
+ "value": {"$type": "org.apache.gearpump.metrics.Metrics.Gauge", "name": "worker0:thread.count", "value": "28"}
}, {
"time": "1450759137860",
- "value": {"$type": "io.gearpump.metrics.Metrics.Gauge", "name": "worker0:memory.heap.max", "value": "880017408"}
+ "value": {"$type": "org.apache.gearpump.metrics.Metrics.Gauge", "name": "worker0:memory.heap.max", "value": "880017408"}
}, {
"time": "1450759137860",
- "value": {"$type": "io.gearpump.metrics.Metrics.Gauge", "name": "worker1:memory.heap.max", "value": "880017408"}
+ "value": {"$type": "org.apache.gearpump.metrics.Metrics.Gauge", "name": "worker1:memory.heap.max", "value": "880017408"}
}, {
"time": "1450759137860",
"value": {
- "$type": "io.gearpump.metrics.Metrics.Gauge",
+ "$type": "org.apache.gearpump.metrics.Metrics.Gauge",
"name": "worker0:memory.total.committed",
"value": "210239488"
}
}, {
"time": "1450759137860",
"value": {
- "$type": "io.gearpump.metrics.Metrics.Gauge",
+ "$type": "org.apache.gearpump.metrics.Metrics.Gauge",
"name": "worker0:memory.total.used",
"value": "152931440"
}
}, {
"time": "1450759137860",
- "value": {"$type": "io.gearpump.metrics.Metrics.Gauge", "name": "worker1:thread.count", "value": "28"}
+ "value": {"$type": "org.apache.gearpump.metrics.Metrics.Gauge", "name": "worker1:thread.count", "value": "28"}
}, {
"time": "1450759137860",
"value": {
- "$type": "io.gearpump.metrics.Metrics.Gauge",
+ "$type": "org.apache.gearpump.metrics.Metrics.Gauge",
"name": "worker1:memory.total.max",
"value": "997457920"
}
}, {
"time": "1450759137860",
"value": {
- "$type": "io.gearpump.metrics.Metrics.Gauge",
+ "$type": "org.apache.gearpump.metrics.Metrics.Gauge",
"name": "worker1:memory.heap.committed",
"value": "179830784"
}
}, {
"time": "1450759137860",
"value": {
- "$type": "io.gearpump.metrics.Metrics.Gauge",
+ "$type": "org.apache.gearpump.metrics.Metrics.Gauge",
"name": "worker1:memory.total.committed",
"value": "210239488"
}
}, {
"time": "1450759137860",
- "value": {"$type": "io.gearpump.metrics.Metrics.Gauge", "name": "worker0:thread.daemon.count", "value": "18"}
+ "value": {"$type": "org.apache.gearpump.metrics.Metrics.Gauge", "name": "worker0:thread.daemon.count", "value": "18"}
}, {
"time": "1450759137860",
"value": {
- "$type": "io.gearpump.metrics.Metrics.Gauge",
+ "$type": "org.apache.gearpump.metrics.Metrics.Gauge",
"name": "worker1:memory.heap.used",
"value": "123139640"
}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/docs/dev-write-1st-app.md
----------------------------------------------------------------------
diff --git a/docs/dev-write-1st-app.md b/docs/dev-write-1st-app.md
index e768397..e125f3d 100644
--- a/docs/dev-write-1st-app.md
+++ b/docs/dev-write-1st-app.md
@@ -5,7 +5,7 @@ title: Write Your 1st Gearpump App
description: Write Your 1st Gearpump App
---
-We'll use [wordcount](https://github.com/gearpump/gearpump/blob/master/examples/streaming/wordcount/src/main/scala/io/gearpump/streaming/examples/wordcount/) as an example to illustrate how to write Gearpump applications.
+We'll use [wordcount](https://github.com/gearpump/gearpump/blob/master/examples/streaming/wordcount/src/main/scala/org.apache.gearpump/streaming/examples/wordcount/) as an example to illustrate how to write Gearpump applications.
### Maven/Sbt Settings
@@ -17,9 +17,9 @@ You can get your preferred IDE ready for Gearpump by following [this guide](dev-
### Decide which language and API to use for writing
Gearpump supports two level APIs:
-1. Low level API, which is more similar to Akka programming, operating on each event. The API document can be found at [Low Level API Doc](http://www.gearpump.io/releases/latest/api/scala/index.html#io.gearpump.streaming.package).
+1. Low level API, which is more similar to Akka programming, operating on each event. The API document can be found at [Low Level API Doc](http://www.gearpump.io/releases/latest/api/scala/index.html#org.apache.gearpump.streaming.package).
-2. High level API (aka DSL), which is operating on streaming instead of individual event. The API document can be found at [DSL API Doc](http://www.gearpump.io/releases/latest/api/scala/index.html#io.gearpump.streaming.dsl.package).
+2. High level API (aka DSL), which is operating on streaming instead of individual event. The API document can be found at [DSL API Doc](http://www.gearpump.io/releases/latest/api/scala/index.html#org.apache.gearpump.streaming.dsl.package).
And both APIs have their Java version and Scala version.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/docs/submit-your-1st-application.md
----------------------------------------------------------------------
diff --git a/docs/submit-your-1st-application.md b/docs/submit-your-1st-application.md
index b72329d..3bdb2f8 100644
--- a/docs/submit-your-1st-application.md
+++ b/docs/submit-your-1st-application.md
@@ -26,7 +26,7 @@ Open another shell,
```bash
### To run WordCount example
-bin/gear app -jar examples/wordcount-{{site.SCALA_BINARY_VERSION}}-{{site.GEARPUMP_VERSION}}-assembly.jar io.gearpump.streaming.examples.wordcount.WordCount
+bin/gear app -jar examples/wordcount-{{site.SCALA_BINARY_VERSION}}-{{site.GEARPUMP_VERSION}}-assembly.jar org.apache.gearpump.streaming.examples.wordcount.WordCount
```
### Step 2: Congratulations, you've submitted your first application.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/distributedshell/README.md
----------------------------------------------------------------------
diff --git a/examples/distributedshell/README.md b/examples/distributedshell/README.md
index f21e87e..437960a 100644
--- a/examples/distributedshell/README.md
+++ b/examples/distributedshell/README.md
@@ -8,10 +8,10 @@ In order to run the example:
2. Start the AppMaster:<br>
```bash
- target/pack/bin/gear app -jar target/pack/examples/gearpump-experiments-distributedshell_$VERSION.jar io.gearpump.examples.distributedshell.DistributedShell
+ target/pack/bin/gear app -jar target/pack/examples/gearpump-experiments-distributedshell_$VERSION.jar org.apache.gearpump.examples.distributedshell.DistributedShell
```
3. Submit the shell command:<br>
```bash
- target/pack/bin/gear app -verbose true -jar target/pack/examples/gearpump-experiments-distributedshell_$VERSION.jar io.gearpump.examples.distributedshell.DistributedShellClient -appid $APPID -command "ls /"
+ target/pack/bin/gear app -verbose true -jar target/pack/examples/gearpump-experiments-distributedshell_$VERSION.jar org.apache.gearpump.examples.distributedshell.DistributedShellClient -appid $APPID -command "ls /"
```
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/distributedshell/src/main/scala/io/gearpump/examples/distributedshell/DistShellAppMaster.scala
----------------------------------------------------------------------
diff --git a/examples/distributedshell/src/main/scala/io/gearpump/examples/distributedshell/DistShellAppMaster.scala b/examples/distributedshell/src/main/scala/io/gearpump/examples/distributedshell/DistShellAppMaster.scala
deleted file mode 100644
index 9b417c0..0000000
--- a/examples/distributedshell/src/main/scala/io/gearpump/examples/distributedshell/DistShellAppMaster.scala
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.examples.distributedshell
-
-import scala.concurrent.Future
-
-import akka.actor.{Deploy, Props}
-import akka.pattern.{ask, pipe}
-import akka.remote.RemoteScope
-import com.typesafe.config.Config
-import org.slf4j.Logger
-
-import io.gearpump.cluster.ClientToMaster.ShutdownApplication
-import io.gearpump.cluster.appmaster.ExecutorSystemScheduler.{ExecutorSystemJvmConfig, ExecutorSystemStarted, StartExecutorSystemTimeout}
-import io.gearpump.cluster.{AppDescription, AppMasterContext, ApplicationMaster, ExecutorContext}
-import io.gearpump.examples.distributedshell.DistShellAppMaster._
-import io.gearpump.util.{ActorUtil, Constants, LogUtil, Util}
-
-class DistShellAppMaster(appContext: AppMasterContext, app: AppDescription)
- extends ApplicationMaster {
-
- import appContext._
- import context.dispatcher
- implicit val timeout = Constants.FUTURE_TIMEOUT
- private val LOG: Logger = LogUtil.getLogger(getClass, app = appId)
- protected var currentExecutorId = 0
-
- override def preStart(): Unit = {
- LOG.info(s"Distributed Shell AppMaster started")
- ActorUtil.launchExecutorOnEachWorker(masterProxy, getExecutorJvmConfig, self)
- }
-
- override def receive: Receive = {
- case ExecutorSystemStarted(executorSystem, _) =>
- import executorSystem.{address, resource => executorResource, worker}
- val executorContext = ExecutorContext(currentExecutorId, worker, appId, app.name,
- self, executorResource)
- // Start executor
- val executor = context.actorOf(Props(classOf[ShellExecutor], executorContext, app.userConfig)
- .withDeploy(Deploy(scope = RemoteScope(address))), currentExecutorId.toString)
- executorSystem.bindLifeCycleWith(executor)
- currentExecutorId += 1
- case StartExecutorSystemTimeout =>
- LOG.error(s"Failed to allocate resource in time")
- masterProxy ! ShutdownApplication(appId)
- context.stop(self)
- case msg: ShellCommand =>
- Future.fold(context.children.map(_ ? msg))(new ShellCommandResultAggregator) {
- (aggregator, response) => {
- aggregator.aggregate(response.asInstanceOf[ShellCommandResult])
- }
- }.map(_.toString()) pipeTo sender
- }
-
- private def getExecutorJvmConfig: ExecutorSystemJvmConfig = {
- val config: Config = app.clusterConfig
- val jvmSetting = Util.resolveJvmSetting(config.withFallback(context.system.settings.config))
- .executor
- ExecutorSystemJvmConfig(jvmSetting.classPath, jvmSetting.vmargs,
- appJar, username, config)
- }
-}
-
-object DistShellAppMaster {
- case class ShellCommand(command: String)
-
- case class ShellCommandResult(executorId: Int, msg: Any)
-
- class ShellCommandResultAggregator {
- val result: StringBuilder = new StringBuilder
-
- def aggregate(response: ShellCommandResult): ShellCommandResultAggregator = {
- result.append(s"Execute results from executor ${response.executorId} : \n")
- result.append(response.msg + "\n")
- this
- }
-
- override def toString(): String = result.toString()
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/distributedshell/src/main/scala/io/gearpump/examples/distributedshell/DistributedShell.scala
----------------------------------------------------------------------
diff --git a/examples/distributedshell/src/main/scala/io/gearpump/examples/distributedshell/DistributedShell.scala b/examples/distributedshell/src/main/scala/io/gearpump/examples/distributedshell/DistributedShell.scala
deleted file mode 100644
index b7b3eb0..0000000
--- a/examples/distributedshell/src/main/scala/io/gearpump/examples/distributedshell/DistributedShell.scala
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.examples.distributedshell
-
-import org.slf4j.Logger
-
-import io.gearpump.cluster.client.ClientContext
-import io.gearpump.cluster.main.{ArgumentsParser, CLIOption}
-import io.gearpump.cluster.{Application, UserConfig}
-import io.gearpump.util.{AkkaApp, LogUtil}
-
-/** Demo application to distribute and execute shell command on all machines of the cluster */
-object DistributedShell extends AkkaApp with ArgumentsParser {
- private val LOG: Logger = LogUtil.getLogger(getClass)
-
- override val options: Array[(String, CLIOption[Any])] = Array.empty
-
- override def main(akkaConf: Config, args: Array[String]): Unit = {
- LOG.info(s"Distributed shell submitting application...")
- val context = ClientContext(akkaConf)
- val appId = context.submit(Application[DistShellAppMaster]("DistributedShell",
- UserConfig.empty))
- context.close()
- LOG.info(s"Distributed Shell Application started with appId $appId !")
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/distributedshell/src/main/scala/io/gearpump/examples/distributedshell/DistributedShellClient.scala
----------------------------------------------------------------------
diff --git a/examples/distributedshell/src/main/scala/io/gearpump/examples/distributedshell/DistributedShellClient.scala b/examples/distributedshell/src/main/scala/io/gearpump/examples/distributedshell/DistributedShellClient.scala
deleted file mode 100644
index cd6f943..0000000
--- a/examples/distributedshell/src/main/scala/io/gearpump/examples/distributedshell/DistributedShellClient.scala
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.examples.distributedshell
-
-import java.util.concurrent.TimeUnit
-import scala.concurrent.Await
-import scala.concurrent.duration.Duration
-
-import akka.pattern.ask
-import org.slf4j.{Logger, LoggerFactory}
-
-import io.gearpump.cluster.client.ClientContext
-import io.gearpump.cluster.main.{ArgumentsParser, CLIOption}
-import io.gearpump.examples.distributedshell.DistShellAppMaster.ShellCommand
-import io.gearpump.util.{AkkaApp, Constants}
-
-/** Client to DistributedShell to input "shell command" */
-object DistributedShellClient extends AkkaApp with ArgumentsParser {
- implicit val timeout = Constants.FUTURE_TIMEOUT
- private val LOG: Logger = LoggerFactory.getLogger(getClass)
-
- override val options: Array[(String, CLIOption[Any])] = Array(
- "appid" -> CLIOption[Int]("<the distributed shell appid>", required = true),
- "command" -> CLIOption[String]("<shell command>", required = true)
- )
-
- override def main(akkaConf: Config, args: Array[String]): Unit = {
- val config = parse(args)
- val context = ClientContext(akkaConf)
- implicit val system = context.system
- implicit val dispatcher = system.dispatcher
- val appid = config.getInt("appid")
- val command = config.getString("command")
- val appMaster = context.resolveAppID(appid)
- LOG.info(s"Resolved appMaster $appid address $appMaster, sending command $command")
- val future = (appMaster ? ShellCommand(command)).map { result =>
- LOG.info(s"Result: \n$result")
- context.close()
- }
- Await.ready(future, Duration(60, TimeUnit.SECONDS))
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/distributedshell/src/main/scala/io/gearpump/examples/distributedshell/ShellExecutor.scala
----------------------------------------------------------------------
diff --git a/examples/distributedshell/src/main/scala/io/gearpump/examples/distributedshell/ShellExecutor.scala b/examples/distributedshell/src/main/scala/io/gearpump/examples/distributedshell/ShellExecutor.scala
deleted file mode 100644
index 2d0fd06..0000000
--- a/examples/distributedshell/src/main/scala/io/gearpump/examples/distributedshell/ShellExecutor.scala
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.examples.distributedshell
-
-import scala.sys.process._
-import scala.util.{Failure, Success, Try}
-
-import akka.actor.Actor
-import org.slf4j.Logger
-
-import io.gearpump.cluster.{ExecutorContext, UserConfig}
-import io.gearpump.examples.distributedshell.DistShellAppMaster.{ShellCommand, ShellCommandResult}
-import io.gearpump.util.LogUtil
-
-/** Executor actor on remote machine */
-class ShellExecutor(executorContext: ExecutorContext, userConf: UserConfig) extends Actor {
- import executorContext._
- private val LOG: Logger = LogUtil.getLogger(getClass, executor = executorId, app = appId)
-
- LOG.info(s"ShellExecutor started!")
-
- override def receive: Receive = {
- case ShellCommand(command) =>
- val process = Try(s"$command".!!)
- val result = process match {
- case Success(msg) => msg
- case Failure(ex) => ex.getMessage
- }
- sender ! ShellCommandResult(executorId, result)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/distributedshell/src/main/scala/org/apache/gearpump/examples/distributedshell/DistShellAppMaster.scala
----------------------------------------------------------------------
diff --git a/examples/distributedshell/src/main/scala/org/apache/gearpump/examples/distributedshell/DistShellAppMaster.scala b/examples/distributedshell/src/main/scala/org/apache/gearpump/examples/distributedshell/DistShellAppMaster.scala
new file mode 100644
index 0000000..cd0b18b
--- /dev/null
+++ b/examples/distributedshell/src/main/scala/org/apache/gearpump/examples/distributedshell/DistShellAppMaster.scala
@@ -0,0 +1,95 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.examples.distributedshell
+
+import scala.concurrent.Future
+
+import akka.actor.{Deploy, Props}
+import akka.pattern.{ask, pipe}
+import akka.remote.RemoteScope
+import com.typesafe.config.Config
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.ClientToMaster.ShutdownApplication
+import org.apache.gearpump.cluster.appmaster.ExecutorSystemScheduler.{ExecutorSystemJvmConfig, ExecutorSystemStarted, StartExecutorSystemTimeout}
+import org.apache.gearpump.cluster.{AppDescription, AppMasterContext, ApplicationMaster, ExecutorContext}
+import org.apache.gearpump.examples.distributedshell.DistShellAppMaster._
+import org.apache.gearpump.util.{ActorUtil, Constants, LogUtil, Util}
+
+class DistShellAppMaster(appContext: AppMasterContext, app: AppDescription)
+ extends ApplicationMaster {
+
+ import appContext._
+ import context.dispatcher
+ implicit val timeout = Constants.FUTURE_TIMEOUT
+ private val LOG: Logger = LogUtil.getLogger(getClass, app = appId)
+ protected var currentExecutorId = 0
+
+ override def preStart(): Unit = {
+ LOG.info(s"Distributed Shell AppMaster started")
+ ActorUtil.launchExecutorOnEachWorker(masterProxy, getExecutorJvmConfig, self)
+ }
+
+ override def receive: Receive = {
+ case ExecutorSystemStarted(executorSystem, _) =>
+ import executorSystem.{address, resource => executorResource, worker}
+ val executorContext = ExecutorContext(currentExecutorId, worker, appId, app.name,
+ self, executorResource)
+ // Start executor
+ val executor = context.actorOf(Props(classOf[ShellExecutor], executorContext, app.userConfig)
+ .withDeploy(Deploy(scope = RemoteScope(address))), currentExecutorId.toString)
+ executorSystem.bindLifeCycleWith(executor)
+ currentExecutorId += 1
+ case StartExecutorSystemTimeout =>
+ LOG.error(s"Failed to allocate resource in time")
+ masterProxy ! ShutdownApplication(appId)
+ context.stop(self)
+ case msg: ShellCommand =>
+ Future.fold(context.children.map(_ ? msg))(new ShellCommandResultAggregator) {
+ (aggregator, response) => {
+ aggregator.aggregate(response.asInstanceOf[ShellCommandResult])
+ }
+ }.map(_.toString()) pipeTo sender
+ }
+
+ private def getExecutorJvmConfig: ExecutorSystemJvmConfig = {
+ val config: Config = app.clusterConfig
+ val jvmSetting = Util.resolveJvmSetting(config.withFallback(context.system.settings.config))
+ .executor
+ ExecutorSystemJvmConfig(jvmSetting.classPath, jvmSetting.vmargs,
+ appJar, username, config)
+ }
+}
+
+object DistShellAppMaster {
+ case class ShellCommand(command: String)
+
+ case class ShellCommandResult(executorId: Int, msg: Any)
+
+ class ShellCommandResultAggregator {
+ val result: StringBuilder = new StringBuilder
+
+ def aggregate(response: ShellCommandResult): ShellCommandResultAggregator = {
+ result.append(s"Execute results from executor ${response.executorId} : \n")
+ result.append(response.msg + "\n")
+ this
+ }
+
+ override def toString(): String = result.toString()
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/distributedshell/src/main/scala/org/apache/gearpump/examples/distributedshell/DistributedShell.scala
----------------------------------------------------------------------
diff --git a/examples/distributedshell/src/main/scala/org/apache/gearpump/examples/distributedshell/DistributedShell.scala b/examples/distributedshell/src/main/scala/org/apache/gearpump/examples/distributedshell/DistributedShell.scala
new file mode 100644
index 0000000..c4eec07
--- /dev/null
+++ b/examples/distributedshell/src/main/scala/org/apache/gearpump/examples/distributedshell/DistributedShell.scala
@@ -0,0 +1,41 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.examples.distributedshell
+
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.client.ClientContext
+import org.apache.gearpump.cluster.main.{ArgumentsParser, CLIOption}
+import org.apache.gearpump.cluster.{Application, UserConfig}
+import org.apache.gearpump.util.{AkkaApp, LogUtil}
+
+/** Demo application to distribute and execute shell command on all machines of the cluster */
+object DistributedShell extends AkkaApp with ArgumentsParser {
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+
+ override val options: Array[(String, CLIOption[Any])] = Array.empty
+
+ override def main(akkaConf: Config, args: Array[String]): Unit = {
+ LOG.info(s"Distributed shell submitting application...")
+ val context = ClientContext(akkaConf)
+ val appId = context.submit(Application[DistShellAppMaster]("DistributedShell",
+ UserConfig.empty))
+ context.close()
+ LOG.info(s"Distributed Shell Application started with appId $appId !")
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/distributedshell/src/main/scala/org/apache/gearpump/examples/distributedshell/DistributedShellClient.scala
----------------------------------------------------------------------
diff --git a/examples/distributedshell/src/main/scala/org/apache/gearpump/examples/distributedshell/DistributedShellClient.scala b/examples/distributedshell/src/main/scala/org/apache/gearpump/examples/distributedshell/DistributedShellClient.scala
new file mode 100644
index 0000000..8a7efa5
--- /dev/null
+++ b/examples/distributedshell/src/main/scala/org/apache/gearpump/examples/distributedshell/DistributedShellClient.scala
@@ -0,0 +1,57 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.examples.distributedshell
+
+import java.util.concurrent.TimeUnit
+import scala.concurrent.Await
+import scala.concurrent.duration.Duration
+
+import akka.pattern.ask
+import org.slf4j.{Logger, LoggerFactory}
+
+import org.apache.gearpump.cluster.client.ClientContext
+import org.apache.gearpump.cluster.main.{ArgumentsParser, CLIOption}
+import org.apache.gearpump.examples.distributedshell.DistShellAppMaster.ShellCommand
+import org.apache.gearpump.util.{AkkaApp, Constants}
+
+/** Client to DistributedShell to input "shell command" */
+object DistributedShellClient extends AkkaApp with ArgumentsParser {
+ implicit val timeout = Constants.FUTURE_TIMEOUT
+ private val LOG: Logger = LoggerFactory.getLogger(getClass)
+
+ override val options: Array[(String, CLIOption[Any])] = Array(
+ "appid" -> CLIOption[Int]("<the distributed shell appid>", required = true),
+ "command" -> CLIOption[String]("<shell command>", required = true)
+ )
+
+ override def main(akkaConf: Config, args: Array[String]): Unit = {
+ val config = parse(args)
+ val context = ClientContext(akkaConf)
+ implicit val system = context.system
+ implicit val dispatcher = system.dispatcher
+ val appid = config.getInt("appid")
+ val command = config.getString("command")
+ val appMaster = context.resolveAppID(appid)
+ LOG.info(s"Resolved appMaster $appid address $appMaster, sending command $command")
+ val future = (appMaster ? ShellCommand(command)).map { result =>
+ LOG.info(s"Result: \n$result")
+ context.close()
+ }
+ Await.ready(future, Duration(60, TimeUnit.SECONDS))
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/distributedshell/src/main/scala/org/apache/gearpump/examples/distributedshell/ShellExecutor.scala
----------------------------------------------------------------------
diff --git a/examples/distributedshell/src/main/scala/org/apache/gearpump/examples/distributedshell/ShellExecutor.scala b/examples/distributedshell/src/main/scala/org/apache/gearpump/examples/distributedshell/ShellExecutor.scala
new file mode 100644
index 0000000..fc394d8
--- /dev/null
+++ b/examples/distributedshell/src/main/scala/org/apache/gearpump/examples/distributedshell/ShellExecutor.scala
@@ -0,0 +1,47 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.examples.distributedshell
+
+import scala.sys.process._
+import scala.util.{Failure, Success, Try}
+
+import akka.actor.Actor
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.{ExecutorContext, UserConfig}
+import org.apache.gearpump.examples.distributedshell.DistShellAppMaster.{ShellCommand, ShellCommandResult}
+import org.apache.gearpump.util.LogUtil
+
+/** Executor actor on remote machine */
+class ShellExecutor(executorContext: ExecutorContext, userConf: UserConfig) extends Actor {
+ import executorContext._
+ private val LOG: Logger = LogUtil.getLogger(getClass, executor = executorId, app = appId)
+
+ LOG.info(s"ShellExecutor started!")
+
+ override def receive: Receive = {
+ case ShellCommand(command) =>
+ val process = Try(s"$command".!!)
+ val result = process match {
+ case Success(msg) => msg
+ case Failure(ex) => ex.getMessage
+ }
+ sender ! ShellCommandResult(executorId, result)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/distributedshell/src/test/scala/io/gearpump/examples/distributedshell/DistShellAppMasterSpec.scala
----------------------------------------------------------------------
diff --git a/examples/distributedshell/src/test/scala/io/gearpump/examples/distributedshell/DistShellAppMasterSpec.scala b/examples/distributedshell/src/test/scala/io/gearpump/examples/distributedshell/DistShellAppMasterSpec.scala
deleted file mode 100644
index 2d63734..0000000
--- a/examples/distributedshell/src/test/scala/io/gearpump/examples/distributedshell/DistShellAppMasterSpec.scala
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.examples.distributedshell
-
-import scala.concurrent.Await
-import scala.concurrent.duration.Duration
-
-import akka.actor.ActorSystem
-import akka.testkit.{TestActorRef, TestProbe}
-import org.scalatest.{BeforeAndAfter, Matchers, WordSpec}
-
-import io.gearpump.cluster.AppMasterToMaster.{GetAllWorkers, RegisterAppMaster, RequestResource}
-import io.gearpump.cluster.AppMasterToWorker.LaunchExecutor
-import io.gearpump.cluster.MasterToAppMaster.{AppMasterRegistered, ResourceAllocated, WorkerList}
-import io.gearpump.cluster._
-import io.gearpump.cluster.appmaster.{AppMasterRuntimeEnvironment, AppMasterRuntimeInfo}
-import io.gearpump.cluster.scheduler.{Relaxation, Resource, ResourceAllocation, ResourceRequest}
-import io.gearpump.cluster.worker.WorkerId
-import io.gearpump.util.ActorSystemBooter.RegisterActorSystem
-import io.gearpump.util.ActorUtil
-
-class DistShellAppMasterSpec extends WordSpec with Matchers with BeforeAndAfter {
- implicit val system = ActorSystem("AppMasterSpec", TestUtil.DEFAULT_CONFIG)
- val mockMaster = TestProbe()(system)
- val mockWorker1 = TestProbe()(system)
- val masterProxy = mockMaster.ref
- val appId = 0
- val userName = "test"
- val masterExecutorId = 0
- val workerList = List(WorkerId(1, 0L), WorkerId(2, 0L), WorkerId(3, 0L))
- val resource = Resource(1)
- val appJar = None
- val appDescription = AppDescription("app0", classOf[DistShellAppMaster].getName, UserConfig.empty)
-
- "DistributedShell AppMaster" should {
- "launch one ShellTask on each worker" in {
- val appMasterInfo = AppMasterRuntimeInfo(appId, appName = appId.toString)
- val appMasterContext = AppMasterContext(appId, userName, resource, null, appJar,
- masterProxy, appMasterInfo)
- TestActorRef[DistShellAppMaster](
- AppMasterRuntimeEnvironment.props(List(masterProxy.path), appDescription, appMasterContext))
- mockMaster.expectMsgType[RegisterAppMaster]
- mockMaster.reply(AppMasterRegistered(appId))
- // The DistributedShell AppMaster asks for worker list from Master.
- mockMaster.expectMsg(GetAllWorkers)
- mockMaster.reply(WorkerList(workerList))
- // After worker list is ready, DistributedShell AppMaster requests resource on each worker
- workerList.foreach { workerId =>
- mockMaster.expectMsg(RequestResource(appId, ResourceRequest(Resource(1), workerId,
- relaxation = Relaxation.SPECIFICWORKER)))
- }
- mockMaster.reply(ResourceAllocated(
- Array(ResourceAllocation(resource, mockWorker1.ref, WorkerId(1, 0L)))))
- mockWorker1.expectMsgClass(classOf[LaunchExecutor])
- mockWorker1.reply(RegisterActorSystem(ActorUtil.getSystemAddress(system).toString))
- }
- }
-
- after {
- system.terminate()
- Await.result(system.whenTerminated, Duration.Inf)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/distributedshell/src/test/scala/io/gearpump/examples/distributedshell/DistributedShellClientSpec.scala
----------------------------------------------------------------------
diff --git a/examples/distributedshell/src/test/scala/io/gearpump/examples/distributedshell/DistributedShellClientSpec.scala b/examples/distributedshell/src/test/scala/io/gearpump/examples/distributedshell/DistributedShellClientSpec.scala
deleted file mode 100644
index 973b3b3..0000000
--- a/examples/distributedshell/src/test/scala/io/gearpump/examples/distributedshell/DistributedShellClientSpec.scala
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.examples.distributedshell
-
-import scala.concurrent.Future
-import scala.util.{Success, Try}
-
-import akka.testkit.TestProbe
-import org.scalatest.{BeforeAndAfter, Matchers, PropSpec}
-
-import io.gearpump.cluster.ClientToMaster.ResolveAppId
-import io.gearpump.cluster.MasterToClient.ResolveAppIdResult
-import io.gearpump.cluster.{MasterHarness, TestUtil}
-import io.gearpump.examples.distributedshell.DistShellAppMaster.ShellCommand
-import io.gearpump.util.LogUtil
-
-class DistributedShellClientSpec
- extends PropSpec with Matchers with BeforeAndAfter with MasterHarness {
-
- private val LOG = LogUtil.getLogger(getClass)
-
- before {
- startActorSystem()
- }
-
- after {
- shutdownActorSystem()
- }
-
- protected override def config = TestUtil.DEFAULT_CONFIG
-
- property("DistributedShellClient should succeed to submit application with required arguments") {
- val command = "ls /"
- val requiredArgs = Array("-appid", "0", "-command", command)
- val masterReceiver = createMockMaster()
-
- assert(Try(DistributedShellClient.main(Array.empty[String])).isFailure,
- "missing required arguments, print usage")
-
- Future {
- DistributedShellClient.main(masterConfig, requiredArgs)
- }
-
- masterReceiver.expectMsg(PROCESS_BOOT_TIME, ResolveAppId(0))
- val mockAppMaster = TestProbe()(getActorSystem)
- masterReceiver.reply(ResolveAppIdResult(Success(mockAppMaster.ref)))
- LOG.info(s"Reply back ResolveAppIdResult, current actorRef: ${mockAppMaster.ref.path.toString}")
- mockAppMaster.expectMsg(PROCESS_BOOT_TIME, ShellCommand(command))
- mockAppMaster.reply("result")
- }
-}
[12/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/test/scala/org/apache/gearpump/services/security/oauth2/GoogleOAuth2AuthenticatorSpec.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/test/scala/org/apache/gearpump/services/security/oauth2/GoogleOAuth2AuthenticatorSpec.scala b/services/jvm/src/test/scala/org/apache/gearpump/services/security/oauth2/GoogleOAuth2AuthenticatorSpec.scala
new file mode 100644
index 0000000..610f0c7
--- /dev/null
+++ b/services/jvm/src/test/scala/org/apache/gearpump/services/security/oauth2/GoogleOAuth2AuthenticatorSpec.scala
@@ -0,0 +1,163 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.services.security.oauth2
+
+import scala.collection.JavaConverters._
+import scala.concurrent.Await
+import scala.concurrent.duration._
+
+import akka.actor.ActorSystem
+import akka.http.scaladsl.model.HttpEntity.Strict
+import akka.http.scaladsl.model.MediaTypes._
+import akka.http.scaladsl.model.Uri.{Path, Query}
+import akka.http.scaladsl.model._
+import akka.http.scaladsl.testkit.ScalatestRouteTest
+import com.typesafe.config.ConfigFactory
+import org.scalatest.FlatSpec
+
+import org.apache.gearpump.security.Authenticator
+// NOTE: This cannot be removed!!!
+import org.apache.gearpump.services.util.UpickleUtil._
+import org.apache.gearpump.services.security.oauth2.GoogleOAuth2AuthenticatorSpec.MockGoogleAuthenticator
+import org.apache.gearpump.services.security.oauth2.impl.GoogleOAuth2Authenticator
+
+class GoogleOAuth2AuthenticatorSpec extends FlatSpec with ScalatestRouteTest {
+
+ implicit val actorSystem: ActorSystem = system
+ private val server = new MockOAuth2Server(system, null)
+ server.start()
+ private val serverHost = s"http://127.0.0.1:${server.port}"
+
+ val configMap = Map(
+ "class" -> "org.apache.gearpump.services.security.oauth2.impl.GoogleOAuth2Authenticator",
+ "callback" -> s"$serverHost/login/oauth2/google/callback",
+ "clientid" -> "170234147043-a1tag68jtq6ab4bi11jvsj7vbaqcmhkt.apps.googleusercontent.com",
+ "clientsecret" -> "ioeWLLDipz2S7aTDXym2-obe",
+ "default-userrole" -> "guest",
+ "icon" -> "/icons/google.png")
+
+ val configString = ConfigFactory.parseMap(configMap.asJava)
+
+ private lazy val google = {
+ val google = new MockGoogleAuthenticator(serverHost)
+ google.init(configString, system.dispatcher)
+ google
+ }
+
+ it should "generate the correct authorization request" in {
+ val parameters = Uri(google.getAuthorizationUrl()).query().toMap
+ assert(parameters("response_type") == "code")
+ assert(parameters("client_id") == configMap("clientid"))
+ assert(parameters("redirect_uri") == configMap("callback"))
+ assert(parameters("scope") == GoogleOAuth2Authenticator.Scope)
+ }
+
+ it should "authenticate the authorization code and return the correct profile" in {
+ val code = Map("code" -> "4/PME0pfxjiBA42SukR-OTGl7fpFzTWzvZPf1TbkpXL4M#")
+ val accessToken = "e2922002-0218-4513-a62d-1da2ba64ee4c"
+ val refreshToken = "eyJhbGciOiJSUzI1NiJ9.eyJqdGkiOiI2Nm"
+ val mail = "test@gearpump.io"
+
+ def accessTokenEndpoint(request: HttpRequest): HttpResponse = {
+
+ assert(request.entity.contentType.mediaType.value == "application/x-www-form-urlencoded")
+
+ val body = request.entity.asInstanceOf[Strict].data.decodeString("UTF-8")
+ val form = Uri./.withQuery(Query(body)).query().toMap
+
+ assert(form("client_id") == configMap("clientid"))
+ assert(form("client_secret") == configMap("clientsecret"))
+ assert(form("grant_type") == "authorization_code")
+ assert(form("code") == code("code"))
+ assert(form("redirect_uri") == configMap("callback"))
+ assert(form("scope") == GoogleOAuth2Authenticator.Scope)
+
+ // scalastyle:off line.size.limit
+ val response =
+ s"""
+ |{
+ | "access_token": "$accessToken",
+ | "token_type": "Bearer",
+ | "expires_in": 3591,
+ | "id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6ImY1NjQyYzY2MzdhYWQyOTJiOThlOGIwN2MwMzIxN2QwMzBmOTdkODkifQ.eyJpc3"
+ |}
+ """.stripMargin
+ // scalastyle:on line.size.limit
+
+ HttpResponse(entity = HttpEntity(ContentType(`application/json`), response))
+ }
+
+ def protectedResourceEndpoint(request: HttpRequest): HttpResponse = {
+ assert(request.getUri().query().get("access_token").get == accessToken)
+ val response =
+ s"""
+ |{
+ | "kind": "plus#person",
+ | "etag": "4OZ_Kt6ujOh1jaML_U6RM6APqoE/mZ57HcMOYXaNXYXS5XEGJ9yVsI8",
+ | "nickname": "gearpump",
+ | "gender": "female",
+ | "emails": [
+ | {
+ | "value": "$mail",
+ | "type": "account"
+ | }
+ | ]
+ | }
+ """.stripMargin
+ HttpResponse(entity = HttpEntity(ContentType(`application/json`), response))
+ }
+
+ server.requestHandler = (request: HttpRequest) => {
+ if (request.uri.path.startsWith(Path("/oauth2/v4/token"))) {
+ accessTokenEndpoint(request)
+ } else if (request.uri.path.startsWith(Path("/plus/v1/people/me"))) {
+ protectedResourceEndpoint(request)
+ } else {
+ fail("Unexpected access to " + request.uri.toString())
+ }
+ }
+
+ val userFuture = google.authenticate(code)
+ val user = Await.result(userFuture, 30.seconds)
+ assert(user.user == mail)
+ assert(user.permissionLevel == Authenticator.Guest.permissionLevel)
+ }
+
+ override def cleanUp(): Unit = {
+ server.stop()
+ google.close()
+ super.cleanUp()
+ }
+}
+
+object GoogleOAuth2AuthenticatorSpec {
+ class MockGoogleAuthenticator(host: String) extends GoogleOAuth2Authenticator {
+ protected override def authorizeUrl: String = {
+ super.authorizeUrl.replace("https://accounts.google.com", host)
+ }
+
+ protected override def accessTokenEndpoint: String = {
+ super.accessTokenEndpoint.replace("https://www.googleapis.com", host)
+ }
+
+ protected override def protectedResourceUrl: String = {
+ super.protectedResourceUrl.replace("https://www.googleapis.com", host)
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/test/scala/org/apache/gearpump/services/security/oauth2/MockOAuth2Server.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/test/scala/org/apache/gearpump/services/security/oauth2/MockOAuth2Server.scala b/services/jvm/src/test/scala/org/apache/gearpump/services/security/oauth2/MockOAuth2Server.scala
new file mode 100644
index 0000000..d656361
--- /dev/null
+++ b/services/jvm/src/test/scala/org/apache/gearpump/services/security/oauth2/MockOAuth2Server.scala
@@ -0,0 +1,65 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.services.security.oauth2
+
+import scala.concurrent.{Await, Future}
+
+import akka.actor.ActorSystem
+import akka.http.scaladsl.Http
+import akka.http.scaladsl.Http.ServerBinding
+import akka.http.scaladsl.model.{HttpRequest, HttpResponse}
+import akka.stream.ActorMaterializer
+import akka.stream.scaladsl.Sink
+
+import org.apache.gearpump.util.Util
+// NOTE: This cannot be removed!!
+import org.apache.gearpump.services.util.UpickleUtil._
+
+/**
+ * Serves as a fake OAuth2 server.
+ */
+class MockOAuth2Server(
+ actorSystem: ActorSystem,
+ var requestHandler: HttpRequest => HttpResponse) {
+
+ implicit val system: ActorSystem = actorSystem
+ implicit val materializer = ActorMaterializer()
+ implicit val ec = system.dispatcher
+
+ private var _port: Int = 0
+ private var bindingFuture: Future[ServerBinding] = null
+
+ def port: Int = _port
+
+ def start(): Unit = {
+ _port = Util.findFreePort().get
+
+ val serverSource = Http().bind(interface = "127.0.0.1", port = _port)
+ bindingFuture = {
+ serverSource.to(Sink.foreach { connection =>
+ connection handleWithSyncHandler requestHandler
+ }).run()
+ }
+ }
+
+ def stop(): Unit = {
+ import scala.concurrent.duration._
+ Await.result(bindingFuture.map(_.unbind()), 120.seconds)
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/test/scala/org/apache/gearpump/services/util/UpickleSpec.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/test/scala/org/apache/gearpump/services/util/UpickleSpec.scala b/services/jvm/src/test/scala/org/apache/gearpump/services/util/UpickleSpec.scala
new file mode 100644
index 0000000..2bf6b6b
--- /dev/null
+++ b/services/jvm/src/test/scala/org/apache/gearpump/services/util/UpickleSpec.scala
@@ -0,0 +1,67 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.services.util
+
+import org.scalatest.{BeforeAndAfterEach, FlatSpec, Matchers}
+import upickle.default.{read, write}
+
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.metrics.Metrics.{Counter, MetricType}
+import org.apache.gearpump.services.util.UpickleUtil._
+import org.apache.gearpump.streaming.ProcessorId
+import org.apache.gearpump.streaming.appmaster.{ProcessorSummary, StreamAppMasterSummary}
+import org.apache.gearpump.util.Graph
+
+class UpickleSpec extends FlatSpec with Matchers with BeforeAndAfterEach {
+
+ "UserConfig" should "serialize and deserialize with upickle correctly" in {
+ val conf = UserConfig.empty.withString("key", "value")
+ val serialized = write(conf)
+ val deserialized = read[UserConfig](serialized)
+ assert(deserialized.getString("key") == Some("value"))
+ }
+
+ "Graph" should "be able to serialize/deserialize correctly" in {
+ val graph = new Graph[Int, String](List(0, 1), List((0, "edge", 1)))
+ val serialized = write(graph)
+
+ val deserialized = read[Graph[Int, String]](serialized)
+
+ graph.vertices.toSet shouldBe deserialized.vertices.toSet
+ graph.edges.toSet shouldBe deserialized.edges.toSet
+ }
+
+ "MetricType" should "be able to serialize/deserialize correctly" in {
+ val metric: MetricType = Counter("counter", 100L)
+ val serialized = write(metric)
+ val deserialized = read[MetricType](serialized)
+ metric shouldBe deserialized
+ }
+
+ "StreamingAppMasterDataDetail" should "serialize and deserialize with upickle correctly" in {
+ val app = new StreamAppMasterSummary(appId = 0,
+ processors = Map.empty[ProcessorId, ProcessorSummary],
+ processorLevels = Map.empty[ProcessorId, Int]
+ )
+
+ val serialized = write(app)
+ val deserialized = read[StreamAppMasterSummary](serialized)
+ assert(deserialized == app)
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/java/io/gearpump/streaming/javaapi/Graph.java
----------------------------------------------------------------------
diff --git a/streaming/src/main/java/io/gearpump/streaming/javaapi/Graph.java b/streaming/src/main/java/io/gearpump/streaming/javaapi/Graph.java
deleted file mode 100644
index dbae1c4..0000000
--- a/streaming/src/main/java/io/gearpump/streaming/javaapi/Graph.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.javaapi;
-
-import io.gearpump.partitioner.Partitioner;
-import io.gearpump.streaming.Processor;
-import io.gearpump.streaming.task.Task;
-
-/**
- * Java version of Graph
- *
- * See {@link io.gearpump.util.Graph}
- */
-public class Graph extends io.gearpump.util.Graph<Processor<? extends Task>, Partitioner> {
-
- public Graph() {
- super(null, null);
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/java/io/gearpump/streaming/javaapi/Processor.java
----------------------------------------------------------------------
diff --git a/streaming/src/main/java/io/gearpump/streaming/javaapi/Processor.java b/streaming/src/main/java/io/gearpump/streaming/javaapi/Processor.java
deleted file mode 100644
index 974183e..0000000
--- a/streaming/src/main/java/io/gearpump/streaming/javaapi/Processor.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.javaapi;
-
-import akka.actor.ActorSystem;
-import io.gearpump.cluster.UserConfig;
-import io.gearpump.streaming.sink.DataSink;
-import io.gearpump.streaming.sink.DataSinkProcessor;
-import io.gearpump.streaming.sink.DataSinkTask;
-import io.gearpump.streaming.source.DataSource;
-import io.gearpump.streaming.source.DataSourceProcessor;
-import io.gearpump.streaming.source.DataSourceTask;
-
-/**
- * Java version of Processor
- *
- * See {@link io.gearpump.streaming.Processor}
- */
-public class Processor<T extends io.gearpump.streaming.task.Task> implements io.gearpump.streaming.Processor<T> {
- private Class<T> _taskClass;
- private int _parallelism = 1;
- private String _description = "";
- private UserConfig _userConf = UserConfig.empty();
-
- public Processor(Class<T> taskClass) {
- this._taskClass = taskClass;
- }
-
- public Processor(Class<T> taskClass, int parallelism) {
- this._taskClass = taskClass;
- this._parallelism = parallelism;
- }
-
- /**
- * Creates a Sink Processor
- *
- * @param dataSink the data sink itself
- * @param parallelism the parallelism of this processor
- * @param description the description for this processor
- * @param taskConf the configuration for this processor
- * @param system actor system
- * @return the new created sink processor
- */
- public static Processor<DataSinkTask> sink(DataSink dataSink, int parallelism, String description, UserConfig taskConf, ActorSystem system) {
- io.gearpump.streaming.Processor<DataSinkTask> p = DataSinkProcessor.apply(dataSink, parallelism, description, taskConf, system);
- return new Processor(p);
- }
-
- /**
- * Creates a Source Processor
- *
- * @param source the data source itself
- * @param parallelism the parallelism of this processor
- * @param description the description of this processor
- * @param taskConf the configuration of this processor
- * @param system actor system
- * @return the new created source processor
- */
- public static Processor<DataSourceTask> source(DataSource source, int parallelism, String description, UserConfig taskConf, ActorSystem system) {
- io.gearpump.streaming.Processor<DataSourceTask> p = DataSourceProcessor.apply(source, parallelism, description, taskConf, system);
- return new Processor(p);
- }
-
- public Processor(io.gearpump.streaming.Processor<T> processor) {
- this._taskClass = (Class) (processor.taskClass());
- this._parallelism = processor.parallelism();
- this._description = processor.description();
- this._userConf = processor.taskConf();
- }
-
- /**
- * Creates a general processor with user specified task logic.
- *
- * @param taskClass task implementation class of this processor (shall be a derived class from {@link Task}
- * @param parallelism, how many initial tasks you want to use
- * @param description, some text to describe this processor
- * @param taskConf, Processor specific configuration
- */
- public Processor(Class<T> taskClass, int parallelism, String description, UserConfig taskConf) {
- this._taskClass = taskClass;
- this._parallelism = parallelism;
- this._description = description;
- this._userConf = taskConf;
- }
-
- public Processor<T> withParallelism(int parallel) {
- return new Processor<T>(_taskClass, parallel, _description, _userConf);
- }
-
- public Processor<T> withDescription(String desc) {
- return new Processor<T>(_taskClass, _parallelism, desc, _userConf);
- }
-
- public Processor<T> withConfig(UserConfig conf) {
- return new Processor<T>(_taskClass, _parallelism, _description, conf);
- }
-
- @Override
- public int parallelism() {
- return _parallelism;
- }
-
- @Override
- public UserConfig taskConf() {
- return _userConf;
- }
-
- @Override
- public String description() {
- return _description;
- }
-
- @Override
- public Class<? extends io.gearpump.streaming.task.Task> taskClass() {
- return _taskClass;
- }
-
- /**
- * reference equal
- */
- @Override
- public boolean equals(Object obj) {
- return (this == obj);
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/java/io/gearpump/streaming/javaapi/StreamApplication.java
----------------------------------------------------------------------
diff --git a/streaming/src/main/java/io/gearpump/streaming/javaapi/StreamApplication.java b/streaming/src/main/java/io/gearpump/streaming/javaapi/StreamApplication.java
deleted file mode 100644
index 150a26f..0000000
--- a/streaming/src/main/java/io/gearpump/streaming/javaapi/StreamApplication.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.javaapi;
-
-import akka.actor.ActorSystem;
-import io.gearpump.cluster.Application;
-import io.gearpump.cluster.ApplicationMaster;
-import io.gearpump.cluster.UserConfig;
-
-/**
- * Java version of StreamApplication.
- *
- * Also see {@link io.gearpump.streaming.StreamApplication}
- */
-public class StreamApplication implements Application {
- private io.gearpump.streaming.StreamApplication app;
- /**
- * Creates a streaming application
- *
- * @param name Name of the application
- * @param conf User configuration
- * @param graph The DAG
- */
- public StreamApplication(String name, UserConfig conf, Graph graph) {
- //by pass the tricky type check in scala 2.10
- io.gearpump.util.Graph untypedGraph = graph;
- this.app = io.gearpump.streaming.StreamApplication.apply(
- name, untypedGraph, conf);
- }
-
- @Override
- public String name() {
- return app.name();
- }
-
- @Override
- public UserConfig userConfig(ActorSystem system) {
- return app.userConfig(system);
- }
-
- @Override
- public Class<? extends ApplicationMaster> appMaster() {
- return app.appMaster();
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/java/io/gearpump/streaming/javaapi/Task.java
----------------------------------------------------------------------
diff --git a/streaming/src/main/java/io/gearpump/streaming/javaapi/Task.java b/streaming/src/main/java/io/gearpump/streaming/javaapi/Task.java
deleted file mode 100644
index 45fae19..0000000
--- a/streaming/src/main/java/io/gearpump/streaming/javaapi/Task.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.javaapi;
-
-import akka.actor.ActorRef;
-import io.gearpump.Message;
-import io.gearpump.cluster.UserConfig;
-import io.gearpump.streaming.task.StartTime;
-import io.gearpump.streaming.task.TaskContext;
-
-/**
- * Java version of Task.
- *
- * See {@link io.gearpump.streaming.task.Task}
- */
-public class Task extends io.gearpump.streaming.task.Task {
- protected TaskContext context;
- protected UserConfig userConf;
-
- public Task(TaskContext taskContext, UserConfig userConf) {
- super(taskContext, userConf);
- this.context = taskContext;
- this.userConf = userConf;
- }
-
- @Override
- final public ActorRef self() {
- return context.self();
- }
-
- @Override
- public void onStart(StartTime startTime) {
- }
-
- @Override
- public void onNext(Message msg) {
- }
-
- @Override
- public void onStop() {
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/java/io/gearpump/streaming/javaapi/dsl/functions/FilterFunction.java
----------------------------------------------------------------------
diff --git a/streaming/src/main/java/io/gearpump/streaming/javaapi/dsl/functions/FilterFunction.java b/streaming/src/main/java/io/gearpump/streaming/javaapi/dsl/functions/FilterFunction.java
deleted file mode 100644
index bb97442..0000000
--- a/streaming/src/main/java/io/gearpump/streaming/javaapi/dsl/functions/FilterFunction.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.javaapi.dsl.functions;
-
-import java.io.Serializable;
-
-/**
- * Filter function
- *
- * @param <T> Message of type T
- */
-public interface FilterFunction<T> extends Serializable {
- boolean apply(T t);
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/java/io/gearpump/streaming/javaapi/dsl/functions/FlatMapFunction.java
----------------------------------------------------------------------
diff --git a/streaming/src/main/java/io/gearpump/streaming/javaapi/dsl/functions/FlatMapFunction.java b/streaming/src/main/java/io/gearpump/streaming/javaapi/dsl/functions/FlatMapFunction.java
deleted file mode 100644
index 3e18cf1..0000000
--- a/streaming/src/main/java/io/gearpump/streaming/javaapi/dsl/functions/FlatMapFunction.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.javaapi.dsl.functions;
-
-import java.io.Serializable;
-import java.util.Iterator;
-
-/**
- * Function that converts a value of type T to a iterator of values of type R.
- *
- * @param <T> Input value type
- * @param <R> Return value type
- */
-public interface FlatMapFunction<T, R> extends Serializable {
- Iterator<R> apply(T t);
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/java/io/gearpump/streaming/javaapi/dsl/functions/GroupByFunction.java
----------------------------------------------------------------------
diff --git a/streaming/src/main/java/io/gearpump/streaming/javaapi/dsl/functions/GroupByFunction.java b/streaming/src/main/java/io/gearpump/streaming/javaapi/dsl/functions/GroupByFunction.java
deleted file mode 100644
index 2ba524e..0000000
--- a/streaming/src/main/java/io/gearpump/streaming/javaapi/dsl/functions/GroupByFunction.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.javaapi.dsl.functions;
-
-import java.io.Serializable;
-
-/**
- * GroupBy function which assign value of type T to groups
- *
- * @param <T> Input value type
- * @param <Group> Group Type
- */
-public interface GroupByFunction<T, Group> extends Serializable {
- Group apply(T t);
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/java/io/gearpump/streaming/javaapi/dsl/functions/MapFunction.java
----------------------------------------------------------------------
diff --git a/streaming/src/main/java/io/gearpump/streaming/javaapi/dsl/functions/MapFunction.java b/streaming/src/main/java/io/gearpump/streaming/javaapi/dsl/functions/MapFunction.java
deleted file mode 100644
index b4bd6ac..0000000
--- a/streaming/src/main/java/io/gearpump/streaming/javaapi/dsl/functions/MapFunction.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.javaapi.dsl.functions;
-
-import java.io.Serializable;
-
-/**
- * Function that map a value of type T to value of type R
- *
- * @param <T> Input value type
- * @param <R> Output value type
- */
-public interface MapFunction<T, R> extends Serializable {
- R apply(T t);
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/java/io/gearpump/streaming/javaapi/dsl/functions/ReduceFunction.java
----------------------------------------------------------------------
diff --git a/streaming/src/main/java/io/gearpump/streaming/javaapi/dsl/functions/ReduceFunction.java b/streaming/src/main/java/io/gearpump/streaming/javaapi/dsl/functions/ReduceFunction.java
deleted file mode 100644
index f439c0a..0000000
--- a/streaming/src/main/java/io/gearpump/streaming/javaapi/dsl/functions/ReduceFunction.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.javaapi.dsl.functions;
-
-import java.io.Serializable;
-
-/**
- * Function that applies reduce operation
- *
- * @param <T> Input value type
- */
-public interface ReduceFunction<T> extends Serializable {
- T apply(T t1, T t2);
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/Graph.java
----------------------------------------------------------------------
diff --git a/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/Graph.java b/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/Graph.java
new file mode 100644
index 0000000..8f85aa3
--- /dev/null
+++ b/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/Graph.java
@@ -0,0 +1,35 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.javaapi;
+
+import org.apache.gearpump.partitioner.Partitioner;
+import org.apache.gearpump.streaming.Processor;
+import org.apache.gearpump.streaming.task.Task;
+
+/**
+ * Java version of Graph
+ *
+ * See {@link org.apache.gearpump.util.Graph}
+ */
+public class Graph extends org.apache.gearpump.util.Graph<Processor<? extends Task>, Partitioner> {
+
+ public Graph() {
+ super(null, null);
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/Processor.java
----------------------------------------------------------------------
diff --git a/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/Processor.java b/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/Processor.java
new file mode 100644
index 0000000..8757081
--- /dev/null
+++ b/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/Processor.java
@@ -0,0 +1,141 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.javaapi;
+
+import akka.actor.ActorSystem;
+import org.apache.gearpump.cluster.UserConfig;
+import org.apache.gearpump.streaming.sink.DataSink;
+import org.apache.gearpump.streaming.sink.DataSinkProcessor;
+import org.apache.gearpump.streaming.sink.DataSinkTask;
+import org.apache.gearpump.streaming.source.DataSource;
+import org.apache.gearpump.streaming.source.DataSourceProcessor;
+import org.apache.gearpump.streaming.source.DataSourceTask;
+
+/**
+ * Java version of Processor
+ *
+ * See {@link org.apache.gearpump.streaming.Processor}
+ */
+public class Processor<T extends org.apache.gearpump.streaming.task.Task> implements org.apache.gearpump.streaming.Processor<T> {
+ private Class<T> _taskClass;
+ private int _parallelism = 1;
+ private String _description = "";
+ private UserConfig _userConf = UserConfig.empty();
+
+ public Processor(Class<T> taskClass) {
+ this._taskClass = taskClass;
+ }
+
+ public Processor(Class<T> taskClass, int parallelism) {
+ this._taskClass = taskClass;
+ this._parallelism = parallelism;
+ }
+
+ /**
+ * Creates a Sink Processor
+ *
+ * @param dataSink the data sink itself
+ * @param parallelism the parallelism of this processor
+ * @param description the description for this processor
+ * @param taskConf the configuration for this processor
+ * @param system actor system
+ * @return the new created sink processor
+ */
+ public static Processor<DataSinkTask> sink(DataSink dataSink, int parallelism, String description, UserConfig taskConf, ActorSystem system) {
+ org.apache.gearpump.streaming.Processor<DataSinkTask> p = DataSinkProcessor.apply(dataSink, parallelism, description, taskConf, system);
+ return new Processor(p);
+ }
+
+ /**
+ * Creates a Source Processor
+ *
+ * @param source the data source itself
+ * @param parallelism the parallelism of this processor
+ * @param description the description of this processor
+ * @param taskConf the configuration of this processor
+ * @param system actor system
+ * @return the new created source processor
+ */
+ public static Processor<DataSourceTask> source(DataSource source, int parallelism, String description, UserConfig taskConf, ActorSystem system) {
+ org.apache.gearpump.streaming.Processor<DataSourceTask> p = DataSourceProcessor.apply(source, parallelism, description, taskConf, system);
+ return new Processor(p);
+ }
+
+ public Processor(org.apache.gearpump.streaming.Processor<T> processor) {
+ this._taskClass = (Class) (processor.taskClass());
+ this._parallelism = processor.parallelism();
+ this._description = processor.description();
+ this._userConf = processor.taskConf();
+ }
+
+ /**
+ * Creates a general processor with user specified task logic.
+ *
+ * @param taskClass task implementation class of this processor (shall be a derived class from {@link Task}
+ * @param parallelism, how many initial tasks you want to use
+ * @param description, some text to describe this processor
+ * @param taskConf, Processor specific configuration
+ */
+ public Processor(Class<T> taskClass, int parallelism, String description, UserConfig taskConf) {
+ this._taskClass = taskClass;
+ this._parallelism = parallelism;
+ this._description = description;
+ this._userConf = taskConf;
+ }
+
+ public Processor<T> withParallelism(int parallel) {
+ return new Processor<T>(_taskClass, parallel, _description, _userConf);
+ }
+
+ public Processor<T> withDescription(String desc) {
+ return new Processor<T>(_taskClass, _parallelism, desc, _userConf);
+ }
+
+ public Processor<T> withConfig(UserConfig conf) {
+ return new Processor<T>(_taskClass, _parallelism, _description, conf);
+ }
+
+ @Override
+ public int parallelism() {
+ return _parallelism;
+ }
+
+ @Override
+ public UserConfig taskConf() {
+ return _userConf;
+ }
+
+ @Override
+ public String description() {
+ return _description;
+ }
+
+ @Override
+ public Class<? extends org.apache.gearpump.streaming.task.Task> taskClass() {
+ return _taskClass;
+ }
+
+ /**
+ * reference equal
+ */
+ @Override
+ public boolean equals(Object obj) {
+ return (this == obj);
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/StreamApplication.java
----------------------------------------------------------------------
diff --git a/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/StreamApplication.java b/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/StreamApplication.java
new file mode 100644
index 0000000..b15685e
--- /dev/null
+++ b/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/StreamApplication.java
@@ -0,0 +1,61 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.javaapi;
+
+import akka.actor.ActorSystem;
+import org.apache.gearpump.cluster.Application;
+import org.apache.gearpump.cluster.ApplicationMaster;
+import org.apache.gearpump.cluster.UserConfig;
+
+/**
+ * Java version of StreamApplication.
+ *
+ * Also see {@link org.apache.gearpump.streaming.StreamApplication}
+ */
+public class StreamApplication implements Application {
+ private org.apache.gearpump.streaming.StreamApplication app;
+ /**
+ * Creates a streaming application
+ *
+ * @param name Name of the application
+ * @param conf User configuration
+ * @param graph The DAG
+ */
+ public StreamApplication(String name, UserConfig conf, Graph graph) {
+ //by pass the tricky type check in scala 2.10
+ org.apache.gearpump.util.Graph untypedGraph = graph;
+ this.app = org.apache.gearpump.streaming.StreamApplication.apply(
+ name, untypedGraph, conf);
+ }
+
+ @Override
+ public String name() {
+ return app.name();
+ }
+
+ @Override
+ public UserConfig userConfig(ActorSystem system) {
+ return app.userConfig(system);
+ }
+
+ @Override
+ public Class<? extends ApplicationMaster> appMaster() {
+ return app.appMaster();
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/Task.java
----------------------------------------------------------------------
diff --git a/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/Task.java b/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/Task.java
new file mode 100644
index 0000000..2efce45
--- /dev/null
+++ b/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/Task.java
@@ -0,0 +1,58 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.javaapi;
+
+import akka.actor.ActorRef;
+import org.apache.gearpump.Message;
+import org.apache.gearpump.cluster.UserConfig;
+import org.apache.gearpump.streaming.task.StartTime;
+import org.apache.gearpump.streaming.task.TaskContext;
+
+/**
+ * Java version of Task.
+ *
+ * See {@link org.apache.gearpump.streaming.task.Task}
+ */
+public class Task extends org.apache.gearpump.streaming.task.Task {
+ protected TaskContext context;
+ protected UserConfig userConf;
+
+ public Task(TaskContext taskContext, UserConfig userConf) {
+ super(taskContext, userConf);
+ this.context = taskContext;
+ this.userConf = userConf;
+ }
+
+ @Override
+ final public ActorRef self() {
+ return context.self();
+ }
+
+ @Override
+ public void onStart(StartTime startTime) {
+ }
+
+ @Override
+ public void onNext(Message msg) {
+ }
+
+ @Override
+ public void onStop() {
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/dsl/functions/FilterFunction.java
----------------------------------------------------------------------
diff --git a/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/dsl/functions/FilterFunction.java b/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/dsl/functions/FilterFunction.java
new file mode 100644
index 0000000..f07ceff
--- /dev/null
+++ b/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/dsl/functions/FilterFunction.java
@@ -0,0 +1,30 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.javaapi.dsl.functions;
+
+import java.io.Serializable;
+
+/**
+ * Filter function
+ *
+ * @param <T> Message of type T
+ */
+public interface FilterFunction<T> extends Serializable {
+ boolean apply(T t);
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/dsl/functions/FlatMapFunction.java
----------------------------------------------------------------------
diff --git a/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/dsl/functions/FlatMapFunction.java b/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/dsl/functions/FlatMapFunction.java
new file mode 100644
index 0000000..9788dd2
--- /dev/null
+++ b/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/dsl/functions/FlatMapFunction.java
@@ -0,0 +1,32 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.javaapi.dsl.functions;
+
+import java.io.Serializable;
+import java.util.Iterator;
+
+/**
+ * Function that converts a value of type T to a iterator of values of type R.
+ *
+ * @param <T> Input value type
+ * @param <R> Return value type
+ */
+public interface FlatMapFunction<T, R> extends Serializable {
+ Iterator<R> apply(T t);
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/dsl/functions/GroupByFunction.java
----------------------------------------------------------------------
diff --git a/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/dsl/functions/GroupByFunction.java b/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/dsl/functions/GroupByFunction.java
new file mode 100644
index 0000000..6c71280
--- /dev/null
+++ b/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/dsl/functions/GroupByFunction.java
@@ -0,0 +1,31 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.javaapi.dsl.functions;
+
+import java.io.Serializable;
+
+/**
+ * GroupBy function which assign value of type T to groups
+ *
+ * @param <T> Input value type
+ * @param <Group> Group Type
+ */
+public interface GroupByFunction<T, Group> extends Serializable {
+ Group apply(T t);
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/dsl/functions/MapFunction.java
----------------------------------------------------------------------
diff --git a/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/dsl/functions/MapFunction.java b/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/dsl/functions/MapFunction.java
new file mode 100644
index 0000000..e1fc821
--- /dev/null
+++ b/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/dsl/functions/MapFunction.java
@@ -0,0 +1,31 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.javaapi.dsl.functions;
+
+import java.io.Serializable;
+
+/**
+ * Function that map a value of type T to value of type R
+ *
+ * @param <T> Input value type
+ * @param <R> Output value type
+ */
+public interface MapFunction<T, R> extends Serializable {
+ R apply(T t);
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/dsl/functions/ReduceFunction.java
----------------------------------------------------------------------
diff --git a/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/dsl/functions/ReduceFunction.java b/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/dsl/functions/ReduceFunction.java
new file mode 100644
index 0000000..2bcac60
--- /dev/null
+++ b/streaming/src/main/java/org/apache/gearpump/streaming/javaapi/dsl/functions/ReduceFunction.java
@@ -0,0 +1,30 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.javaapi.dsl.functions;
+
+import java.io.Serializable;
+
+/**
+ * Function that applies reduce operation
+ *
+ * @param <T> Input value type
+ */
+public interface ReduceFunction<T> extends Serializable {
+ T apply(T t1, T t2);
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/resources/geardefault.conf
----------------------------------------------------------------------
diff --git a/streaming/src/main/resources/geardefault.conf b/streaming/src/main/resources/geardefault.conf
index 219543e..a484f3c 100644
--- a/streaming/src/main/resources/geardefault.conf
+++ b/streaming/src/main/resources/geardefault.conf
@@ -21,11 +21,11 @@ gearpump {
### Whitelist for Metrics Aggregator class.
### See class [[MetricsAggregator]] for more information.
metrics-aggregator-class {
- "io.gearpump.streaming.metrics.TaskFilterAggregator" = ""
- "io.gearpump.streaming.metrics.ProcessorAggregator" = ""
+ "org.apache.gearpump.streaming.metrics.TaskFilterAggregator" = ""
+ "org.apache.gearpump.streaming.metrics.ProcessorAggregator" = ""
}
}
}
- transport.serializer = "io.gearpump.streaming.task.StreamingTransportSerializer"
+ transport.serializer = "org.apache.gearpump.streaming.task.StreamingTransportSerializer"
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/ClusterMessage.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/ClusterMessage.scala b/streaming/src/main/scala/io/gearpump/streaming/ClusterMessage.scala
deleted file mode 100644
index 06cf022..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/ClusterMessage.scala
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming
-
-import scala.language.existentials
-
-import akka.actor.ActorRef
-
-import io.gearpump.TimeStamp
-import io.gearpump.cluster.appmaster.WorkerInfo
-import io.gearpump.cluster.scheduler.Resource
-import io.gearpump.streaming.appmaster.TaskRegistry.TaskLocations
-import io.gearpump.streaming.task.{Subscriber, TaskId}
-import io.gearpump.transport.HostPort
-
-object AppMasterToExecutor {
- case class LaunchTasks(
- taskId: List[TaskId], dagVersion: Int, processorDescription: ProcessorDescription,
- subscribers: List[Subscriber])
-
- case object TasksLaunched
-
- /**
- * dagVersion, life, and subscribers will be changed on target task list.
- */
- case class ChangeTasks(
- taskId: List[TaskId], dagVersion: Int, life: LifeTime, subscribers: List[Subscriber])
-
- case class TasksChanged(taskIds: List[TaskId])
-
- case class ChangeTask(
- taskId: TaskId, dagVersion: Int, life: LifeTime, subscribers: List[Subscriber])
-
- case class TaskChanged(taskId: TaskId, dagVersion: Int)
-
- case class StartTask(taskId: TaskId)
-
- case class StopTask(taskId: TaskId)
-
- case class TaskLocationsReady(taskLocations: TaskLocations, dagVersion: Int)
-
- case class TaskLocationsReceived(dagVersion: Int, executorId: ExecutorId)
-
- case class TaskLocationsRejected(
- dagVersion: Int, executorId: ExecutorId, reason: String, ex: Throwable)
-
- case class StartAllTasks(dagVersion: Int)
-
- case class StartDynamicDag(dagVersion: Int)
- case class TaskRegistered(taskId: TaskId, sessionId: Int, startClock: TimeStamp)
- case class TaskRejected(taskId: TaskId)
-
- case object RestartClockService
- class MsgLostException extends Exception
-}
-
-object ExecutorToAppMaster {
- case class RegisterExecutor(
- executor: ActorRef, executorId: Int, resource: Resource, worker : WorkerInfo)
-
- case class RegisterTask(taskId: TaskId, executorId: Int, task: HostPort)
- case class UnRegisterTask(taskId: TaskId, executorId: Int)
-
- case class MessageLoss(executorId: Int, taskId: TaskId, cause: String)
-}
-
-object AppMasterToMaster {
- case class StallingTasks(tasks: List[TaskId])
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/Constants.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/Constants.scala b/streaming/src/main/scala/io/gearpump/streaming/Constants.scala
deleted file mode 100644
index becf31a..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/Constants.scala
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming
-
-object Constants {
-
- val GEARPUMP_STREAMING_OPERATOR = "gearpump.streaming.dsl.operator"
- val GEARPUMP_STREAMING_SOURCE = "gearpump.streaming.dsl.source"
- val GEARPUMP_STREAMING_SINK = "gearpump.streaming.dsl.sink"
- val GEARPUMP_STREAMING_GROUPBY_FUNCTION = "gearpump.streaming.dsl.groupby-function"
-
- val GEARPUMP_STREAMING_LOCALITIES = "gearpump.streaming.localities"
-
- val GEARPUMP_STREAMING_REGISTER_TASK_TIMEOUT_MS = "gearpump.streaming.register-task-timeout-ms"
-
- val GEARPUMP_STREAMING_MAX_PENDING_MESSAGE_COUNT =
- "gearpump.streaming.max-pending-message-count-per-connection"
-
- val GEARPUMP_STREAMING_ACK_ONCE_EVERY_MESSAGE_COUNT =
- "gearpump.streaming.ack-once-every-message-count"
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/DAG.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/DAG.scala b/streaming/src/main/scala/io/gearpump/streaming/DAG.scala
deleted file mode 100644
index a73fd48..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/DAG.scala
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming
-
-import io.gearpump.partitioner.PartitionerDescription
-import io.gearpump.streaming.task.TaskId
-import io.gearpump.util.Graph
-
-/**
- * DAG is wrapper for [[io.gearpump.util.Graph]] for streaming applications.
- */
-case class DAG(version: Int, processors : Map[ProcessorId, ProcessorDescription],
- graph : Graph[ProcessorId, PartitionerDescription])
- extends Serializable {
-
- def isEmpty: Boolean = {
- processors.isEmpty
- }
-
- def taskCount: Int = {
- processors.foldLeft(0) { (count, task) =>
- count + task._2.parallelism
- }
- }
-
- def tasks: List[TaskId] = {
- processors.flatMap { pair =>
- val (processorId, processor) = pair
- (0 until processor.parallelism).map(TaskId(processorId, _))
- }.toList
- }
-}
-
-object DAG {
- def apply(graph: Graph[ProcessorDescription, PartitionerDescription], version: Int = 0): DAG = {
- val processors = graph.vertices.map { processorDescription =>
- (processorDescription.id, processorDescription)
- }.toMap
- val dag = graph.mapVertex { processor =>
- processor.id
- }
- new DAG(version, processors, dag)
- }
-
- def empty: DAG = apply(Graph.empty[ProcessorDescription, PartitionerDescription])
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/MessageSerializer.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/MessageSerializer.scala b/streaming/src/main/scala/io/gearpump/streaming/MessageSerializer.scala
deleted file mode 100644
index 8eb866d..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/MessageSerializer.scala
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming
-
-import java.io.{DataInput, DataOutput}
-
-import io.gearpump.streaming.task._
-
-class TaskIdSerializer extends TaskMessageSerializer[TaskId] {
- override def getLength(obj: TaskId): Int = 8
-
- override def write(dataOutput: DataOutput, obj: TaskId): Unit = {
- dataOutput.writeInt(obj.processorId)
- dataOutput.writeInt(obj.index)
- }
-
- override def read(dataInput: DataInput): TaskId = {
- val processorId = dataInput.readInt()
- val index = dataInput.readInt()
- new TaskId(processorId, index)
- }
-}
-
-class AckSerializer extends TaskMessageSerializer[Ack] {
- val taskIdSerializer = new TaskIdSerializer
-
- override def getLength(obj: Ack): Int = taskIdSerializer.getLength(obj.taskId) + 8
-
- override def write(dataOutput: DataOutput, obj: Ack): Unit = {
- taskIdSerializer.write(dataOutput, obj.taskId)
- dataOutput.writeShort(obj.seq)
- dataOutput.writeShort(obj.actualReceivedNum)
- dataOutput.writeInt(obj.sessionId)
- }
-
- override def read(dataInput: DataInput): Ack = {
- val taskId = taskIdSerializer.read(dataInput)
- val seq = dataInput.readShort()
- val actualReceivedNum = dataInput.readShort()
- val sessionId = dataInput.readInt()
- Ack(taskId, seq, actualReceivedNum, sessionId)
- }
-}
-
-class InitialAckRequestSerializer extends TaskMessageSerializer[InitialAckRequest] {
- val taskIdSerialzer = new TaskIdSerializer()
-
- override def getLength(obj: InitialAckRequest): Int = taskIdSerialzer.getLength(obj.taskId) + 4
-
- override def write(dataOutput: DataOutput, obj: InitialAckRequest): Unit = {
- taskIdSerialzer.write(dataOutput, obj.taskId)
- dataOutput.writeInt(obj.sessionId)
- }
-
- override def read(dataInput: DataInput): InitialAckRequest = {
- val taskId = taskIdSerialzer.read(dataInput)
- val sessionId = dataInput.readInt()
- InitialAckRequest(taskId, sessionId)
- }
-}
-
-class AckRequestSerializer extends TaskMessageSerializer[AckRequest] {
- val taskIdSerializer = new TaskIdSerializer
-
- override def getLength(obj: AckRequest): Int = taskIdSerializer.getLength(obj.taskId) + 6
-
- override def write(dataOutput: DataOutput, obj: AckRequest): Unit = {
- taskIdSerializer.write(dataOutput, obj.taskId)
- dataOutput.writeShort(obj.seq)
- dataOutput.writeInt(obj.sessionId)
- }
-
- override def read(dataInput: DataInput): AckRequest = {
- val taskId = taskIdSerializer.read(dataInput)
- val seq = dataInput.readShort()
- val sessionId = dataInput.readInt()
- AckRequest(taskId, seq, sessionId)
- }
-}
-
-class LatencyProbeSerializer extends TaskMessageSerializer[LatencyProbe] {
- override def getLength(obj: LatencyProbe): Int = 8
-
- override def write(dataOutput: DataOutput, obj: LatencyProbe): Unit = {
- dataOutput.writeLong(obj.timestamp)
- }
-
- override def read(dataInput: DataInput): LatencyProbe = {
- val timestamp = dataInput.readLong()
- LatencyProbe(timestamp)
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/StreamApplication.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/StreamApplication.scala b/streaming/src/main/scala/io/gearpump/streaming/StreamApplication.scala
deleted file mode 100644
index 0ca4d92..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/StreamApplication.scala
+++ /dev/null
@@ -1,170 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming
-
-import scala.language.implicitConversions
-import scala.reflect.ClassTag
-
-import akka.actor.ActorSystem
-
-import io.gearpump.TimeStamp
-import io.gearpump.cluster._
-import io.gearpump.partitioner.{HashPartitioner, Partitioner, PartitionerDescription, PartitionerObject}
-import io.gearpump.streaming.appmaster.AppMaster
-import io.gearpump.streaming.task.Task
-import io.gearpump.util.{Graph, LogUtil, ReferenceEqual}
-
-/**
- * Processor is the blueprint for tasks.
- */
-trait Processor[+T <: Task] extends ReferenceEqual {
-
- /**
- * How many tasks you want to use for this processor.
- */
- def parallelism: Int
-
- /**
- * The custom [[io.gearpump.cluster.UserConfig]], it is used to initialize a task in runtime.
- */
- def taskConf: UserConfig
-
- /**
- * Some description text for this processor.
- */
- def description: String
-
- /**
- * The task class, should be a subtype of Task.
- *
- * Each runtime instance of this class is a task.
- */
- def taskClass: Class[_ <: Task]
-}
-
-object Processor {
- def ProcessorToProcessorDescription(id: ProcessorId, processor: Processor[_ <: Task])
- : ProcessorDescription = {
- import processor._
- ProcessorDescription(id, taskClass.getName, parallelism, description, taskConf)
- }
-
- def apply[T<: Task](
- parallelism : Int, description: String = "",
- taskConf: UserConfig = UserConfig.empty)(implicit classtag: ClassTag[T])
- : DefaultProcessor[T] = {
- new DefaultProcessor[T](parallelism, description, taskConf,
- classtag.runtimeClass.asInstanceOf[Class[T]])
- }
-
- def apply[T<: Task](
- taskClazz: Class[T], parallelism : Int, description: String, taskConf: UserConfig)
- : DefaultProcessor[T] = {
- new DefaultProcessor[T](parallelism, description, taskConf, taskClazz)
- }
-
- case class DefaultProcessor[T<: Task](
- parallelism : Int, description: String, taskConf: UserConfig, taskClass: Class[T])
- extends Processor[T] {
-
- def withParallelism(parallel: Int): DefaultProcessor[T] = {
- new DefaultProcessor[T](parallel, description, taskConf, taskClass)
- }
-
- def withDescription(desc: String): DefaultProcessor[T] = {
- new DefaultProcessor[T](parallelism, desc, taskConf, taskClass)
- }
-
- def withConfig(conf: UserConfig): DefaultProcessor[T] = {
- new DefaultProcessor[T](parallelism, description, conf, taskClass)
- }
- }
-}
-
-/**
- * Each processor has a LifeTime.
- *
- * When input message's timestamp is beyond current processor's lifetime,
- * then it will not be processed by this processor.
- */
-case class LifeTime(birth: TimeStamp, death: TimeStamp) {
- def contains(timestamp: TimeStamp): Boolean = {
- timestamp >= birth && timestamp < death
- }
-
- def cross(another: LifeTime): LifeTime = {
- LifeTime(Math.max(birth, another.birth), Math.min(death, another.death))
- }
-}
-
-object LifeTime {
- val Immortal = LifeTime(0L, Long.MaxValue)
-}
-
-/**
- * Represent a streaming application
- */
-class StreamApplication(
- override val name: String, val inputUserConfig: UserConfig,
- val dag: Graph[ProcessorDescription, PartitionerDescription])
- extends Application {
-
- require(!dag.hasDuplicatedEdge(), "Graph should not have duplicated edges")
-
- override def appMaster: Class[_ <: ApplicationMaster] = classOf[AppMaster]
- override def userConfig(implicit system: ActorSystem): UserConfig = {
- inputUserConfig.withValue(StreamApplication.DAG, dag)
- }
-}
-
-case class ProcessorDescription(
- id: ProcessorId,
- taskClass: String,
- parallelism : Int,
- description: String = "",
- taskConf: UserConfig = null,
- life: LifeTime = LifeTime.Immortal,
- jar: AppJar = null) extends ReferenceEqual
-
-object StreamApplication {
-
- private val hashPartitioner = new HashPartitioner()
- private val LOG = LogUtil.getLogger(getClass)
-
- def apply[T <: Processor[Task], P <: Partitioner](
- name: String, dag: Graph[T, P], userConfig: UserConfig): StreamApplication = {
- import io.gearpump.streaming.Processor._
-
- if (dag.hasCycle()) {
- LOG.warn(s"Detected cycles in DAG of application $name!")
- }
-
- val indices = dag.topologicalOrderWithCirclesIterator.toList.zipWithIndex.toMap
- val graph = dag.mapVertex { processor =>
- val updatedProcessor = ProcessorToProcessorDescription(indices(processor), processor)
- updatedProcessor
- }.mapEdge { (node1, edge, node2) =>
- PartitionerDescription(new PartitionerObject(
- Option(edge).getOrElse(StreamApplication.hashPartitioner)))
- }
- new StreamApplication(name, userConfig, graph)
- }
-
- val DAG = "DAG"
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/appmaster/AppMaster.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/appmaster/AppMaster.scala b/streaming/src/main/scala/io/gearpump/streaming/appmaster/AppMaster.scala
deleted file mode 100644
index df85017..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/appmaster/AppMaster.scala
+++ /dev/null
@@ -1,362 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.appmaster
-
-import java.lang.management.ManagementFactory
-import scala.concurrent.Future
-
-import akka.actor._
-import org.slf4j.Logger
-
-import io.gearpump._
-import io.gearpump.cluster.ClientToMaster.{GetLastFailure, GetStallingTasks, QueryHistoryMetrics, ShutdownApplication}
-import io.gearpump.cluster.MasterToAppMaster.{AppMasterDataDetailRequest, ReplayFromTimestampWindowTrailingEdge}
-import io.gearpump.cluster.MasterToClient.{HistoryMetrics, HistoryMetricsItem, LastFailure}
-import io.gearpump.cluster._
-import io.gearpump.cluster.worker.WorkerId
-import io.gearpump.metrics.Metrics.ReportMetrics
-import io.gearpump.metrics.{JvmMetricsSet, Metrics, MetricsReporterService}
-import io.gearpump.partitioner.PartitionerDescription
-import io.gearpump.streaming.ExecutorToAppMaster.{MessageLoss, RegisterExecutor, RegisterTask, UnRegisterTask}
-import io.gearpump.streaming._
-import io.gearpump.streaming.appmaster.AppMaster._
-import io.gearpump.streaming.appmaster.DagManager.{GetLatestDAG, LatestDAG, ReplaceProcessor}
-import io.gearpump.streaming.appmaster.ExecutorManager.{ExecutorInfo, GetExecutorInfo}
-import io.gearpump.streaming.appmaster.TaskManager.{FailedToRecover, GetTaskList, TaskList}
-import io.gearpump.streaming.executor.Executor.{ExecutorConfig, ExecutorSummary, GetExecutorSummary, QueryExecutorConfig}
-import io.gearpump.streaming.storage.InMemoryAppStoreOnMaster
-import io.gearpump.streaming.task._
-import io.gearpump.streaming.util.ActorPathUtil
-import io.gearpump.util.Constants.{APPMASTER_DEFAULT_EXECUTOR_ID, _}
-import io.gearpump.util.HistoryMetricsService.HistoryMetricsConfig
-import io.gearpump.util._
-
-/**
- * AppMaster is the head of a streaming application.
- *
- * It contains:
- * 1. ExecutorManager to manage all executors.
- * 2. TaskManager to manage all tasks,
- * 3. ClockService to track the global clock for this streaming application.
- * 4. Scheduler to decide which a task should be scheduled to.
- */
-class AppMaster(appContext: AppMasterContext, app: AppDescription) extends ApplicationMaster {
- import app.userConfig
- import appContext.{appId, masterProxy, username}
-
- private implicit val actorSystem = context.system
- private implicit val timeOut = FUTURE_TIMEOUT
-
- import akka.pattern.ask
- private implicit val dispatcher = context.dispatcher
-
- private val startTime: TimeStamp = System.currentTimeMillis()
-
- private val LOG: Logger = LogUtil.getLogger(getClass, app = appId)
- LOG.info(s"AppMaster[$appId] is launched by $username, app: $app xxxxxxxxxxxxxxxxx")
- LOG.info(s"AppMaster actor path: ${ActorUtil.getFullPath(context.system, self.path)}")
-
- private val address = ActorUtil.getFullPath(context.system, self.path)
-
- private val store = new InMemoryAppStoreOnMaster(appId, appContext.masterProxy)
- private val dagManager = context.actorOf(Props(new DagManager(appContext.appId, userConfig, store,
- Some(getUpdatedDAG()))))
-
- private var taskManager: Option[ActorRef] = None
- private var clockService: Option[ActorRef] = None
- private val systemConfig = context.system.settings.config
- private var lastFailure = LastFailure(0L, null)
-
- private val appMasterBrief = ExecutorBrief(APPMASTER_DEFAULT_EXECUTOR_ID,
- self.path.toString,
- Option(appContext.workerInfo).map(_.workerId).getOrElse(WorkerId.unspecified), "active")
-
- private val getHistoryMetricsConfig = HistoryMetricsConfig(systemConfig)
-
- private val metricsEnabled = systemConfig.getBoolean(GEARPUMP_METRIC_ENABLED)
-
- private val userDir = System.getProperty("user.dir")
- private val logFile = LogUtil.applicationLogDir(actorSystem.settings.config)
-
- private val appMasterExecutorSummary = ExecutorSummary(
- APPMASTER_DEFAULT_EXECUTOR_ID,
- Option(appContext.workerInfo).map(_.workerId).getOrElse(WorkerId.unspecified),
- self.path.toString,
- logFile.getAbsolutePath,
- status = "Active",
- taskCount = 0,
- tasks = Map.empty[ProcessorId, List[TaskId]],
- jvmName = ManagementFactory.getRuntimeMXBean().getName()
- )
-
- private val historyMetricsService = if (metricsEnabled) {
- // Registers jvm metrics
- Metrics(context.system).register(new JvmMetricsSet(
- s"app${appId}.executor${APPMASTER_DEFAULT_EXECUTOR_ID}"))
-
- val historyMetricsService = context.actorOf(Props(new HistoryMetricsService(
- s"app$appId", getHistoryMetricsConfig)))
-
- val metricsReportService = context.actorOf(Props(
- new MetricsReporterService(Metrics(context.system))))
- historyMetricsService.tell(ReportMetrics, metricsReportService)
-
- Some(historyMetricsService)
- } else {
- None
- }
-
- private val executorManager: ActorRef =
- context.actorOf(ExecutorManager.props(userConfig, appContext, app.clusterConfig, app.name),
- ActorPathUtil.executorManagerActorName)
-
- for (dag <- getDAG) {
- clockService = Some(context.actorOf(Props(new ClockService(dag, store))))
- val jarScheduler = new JarScheduler(appId, app.name, systemConfig, context)
-
- taskManager = Some(context.actorOf(Props(new TaskManager(appContext.appId, dagManager,
- jarScheduler, executorManager, clockService.get, self, app.name))))
- }
-
- override def receive: Receive = {
- taskMessageHandler orElse
- executorMessageHandler orElse
- recover orElse
- appMasterService orElse
- ActorUtil.defaultMsgHandler(self)
- }
-
- /** Handles messages from Tasks */
- def taskMessageHandler: Receive = {
- case clock: ClockEvent =>
- taskManager.foreach(_ forward clock)
- case register: RegisterTask =>
- taskManager.foreach(_ forward register)
- case unRegister: UnRegisterTask =>
- taskManager.foreach(_ forward unRegister)
- // Checks whether this processor dead, if it is, then we should remove it from clockService.
- clockService.foreach(_ forward CheckProcessorDeath(unRegister.taskId.processorId))
- case replay: ReplayFromTimestampWindowTrailingEdge =>
- taskManager.foreach(_ forward replay)
- case messageLoss: MessageLoss =>
- lastFailure = LastFailure(System.currentTimeMillis(), messageLoss.cause)
- taskManager.foreach(_ forward messageLoss)
- case lookupTask: LookupTaskActorRef =>
- taskManager.foreach(_ forward lookupTask)
- case checkpoint: ReportCheckpointClock =>
- clockService.foreach(_ forward checkpoint)
- case GetDAG =>
- val task = sender
- getDAG.foreach {
- dag => task ! dag
- }
- case GetCheckpointClock =>
- clockService.foreach(_ forward GetCheckpointClock)
- }
-
- /** Handles messages from Executors */
- def executorMessageHandler: Receive = {
- case register: RegisterExecutor =>
- executorManager forward register
- case ReportMetrics =>
- historyMetricsService.foreach(_ forward ReportMetrics)
- }
-
- /** Handles messages from AppMaster */
- def appMasterService: Receive = {
- case appMasterDataDetailRequest: AppMasterDataDetailRequest =>
- LOG.debug(s"AppMaster got AppMasterDataDetailRequest for $appId ")
-
- val executorsFuture = executorBrief
- val clockFuture = getMinClock
- val taskFuture = getTaskList
- val dagFuture = getDAG
-
- val appMasterDataDetail = for {
- executors <- executorsFuture
- clock <- clockFuture
- tasks <- taskFuture
- dag <- dagFuture
- } yield {
- val graph = dag.graph
-
- val executorToTasks = tasks.tasks.groupBy(_._2).mapValues {
- _.keys.toList
- }
-
- val processors = dag.processors.map { kv =>
- val processor = kv._2
- import processor._
- val tasks = executorToTasks.map { kv =>
- (kv._1, TaskCount(kv._2.count(_.processorId == id)))
- }.filter(_._2.count != 0)
- (id,
- ProcessorSummary(id, taskClass, parallelism, description, taskConf, life,
- tasks.keys.toList, tasks))
- }
-
- StreamAppMasterSummary(
- appId = appId,
- appName = app.name,
- actorPath = address,
- clock = clock,
- status = MasterToAppMaster.AppMasterActive,
- startTime = startTime,
- uptime = System.currentTimeMillis() - startTime,
- user = username,
- homeDirectory = userDir,
- logFile = logFile.getAbsolutePath,
- processors = processors,
- processorLevels = graph.vertexHierarchyLevelMap(),
- dag = graph.mapEdge { (node1, edge, node2) =>
- edge.partitionerFactory.name
- },
- executors = executors,
- historyMetricsConfig = getHistoryMetricsConfig
- )
- }
-
- val client = sender()
-
- appMasterDataDetail.map { appData =>
- client ! appData
- }
- // TODO: WebSocket is buggy and disabled.
- // case appMasterMetricsRequest: AppMasterMetricsRequest =>
- // val client = sender()
- // actorSystem.eventStream.subscribe(client, classOf[MetricType])
- case query: QueryHistoryMetrics =>
- if (historyMetricsService.isEmpty) {
- // Returns empty metrics so that we don't hang the UI
- sender ! HistoryMetrics(query.path, List.empty[HistoryMetricsItem])
- } else {
- historyMetricsService.get forward query
- }
- case getStalling: GetStallingTasks =>
- clockService.foreach(_ forward getStalling)
- case replaceDAG: ReplaceProcessor =>
- dagManager forward replaceDAG
- case GetLastFailure(_) =>
- sender ! lastFailure
- case get@GetExecutorSummary(executorId) =>
- val client = sender
- if (executorId == APPMASTER_DEFAULT_EXECUTOR_ID) {
- client ! appMasterExecutorSummary
- } else {
- ActorUtil.askActor[Map[ExecutorId, ExecutorInfo]](executorManager, GetExecutorInfo)
- .map { map =>
- map.get(executorId).foreach { executor =>
- executor.executor.tell(get, client)
- }
- }
- }
- case query@QueryExecutorConfig(executorId) =>
- val client = sender
- if (executorId == -1) {
- val systemConfig = context.system.settings.config
- sender ! ExecutorConfig(ClusterConfig.filterOutDefaultConfig(systemConfig))
- } else {
- ActorUtil.askActor[Map[ExecutorId, ExecutorInfo]](executorManager, GetExecutorInfo)
- .map { map =>
- map.get(executorId).foreach { executor =>
- executor.executor.tell(query, client)
- }
- }
- }
- }
-
- /** Error handling */
- def recover: Receive = {
- case FailedToRecover(errorMsg) =>
- if (context.children.toList.contains(sender())) {
- LOG.error(errorMsg)
- masterProxy ! ShutdownApplication(appId)
- }
- case AllocateResourceTimeOut =>
- LOG.error(s"Failed to allocate resource in time, shutdown application $appId")
- masterProxy ! ShutdownApplication(appId)
- context.stop(self)
- }
-
- private def getMinClock: Future[TimeStamp] = {
- clockService match {
- case Some(clockService) =>
- (clockService ? GetLatestMinClock).asInstanceOf[Future[LatestMinClock]].map(_.clock)
- case None =>
- Future.failed(new ServiceNotAvailableException("clock service not ready"))
- }
- }
-
- private def executorBrief: Future[List[ExecutorBrief]] = {
- ActorUtil.askActor[Map[ExecutorId, ExecutorInfo]](executorManager, GetExecutorInfo)
- .map { infos =>
- infos.values.map { info =>
- ExecutorBrief(info.executorId,
- info.executor.path.toSerializationFormat,
- info.worker.workerId,
- "active")
- }.toList :+ appMasterBrief
- }
- }
-
- private def getTaskList: Future[TaskList] = {
- taskManager match {
- case Some(taskManager) =>
- (taskManager ? GetTaskList).asInstanceOf[Future[TaskList]]
- case None =>
- Future.failed(new ServiceNotAvailableException("task manager not ready"))
- }
- }
-
- private def getDAG: Future[DAG] = {
- (dagManager ? GetLatestDAG).asInstanceOf[Future[LatestDAG]].map(_.dag)
- }
-
- private def getUpdatedDAG(): DAG = {
- val dag = DAG(userConfig.getValue[Graph[ProcessorDescription,
- PartitionerDescription]](StreamApplication.DAG).get)
- val updated = dag.processors.map { idAndProcessor =>
- val (id, oldProcessor) = idAndProcessor
- val newProcessor = if (oldProcessor.jar == null) {
- oldProcessor.copy(jar = appContext.appJar.getOrElse(null))
- } else {
- oldProcessor
- }
- (id, newProcessor)
- }
- DAG(dag.version, updated, dag.graph)
- }
-}
-
-object AppMaster {
-
- /** Master node doesn't return resource in time */
- case object AllocateResourceTimeOut
-
- /** Query task ActorRef by providing the taskId */
- case class LookupTaskActorRef(taskId: TaskId)
-
- case class TaskActorRef(task: ActorRef)
-
- class ServiceNotAvailableException(reason: String) extends Exception(reason)
-
- case class ExecutorBrief(
- executorId: ExecutorId, executor: String, workerId: WorkerId, status: String)
-
-}
\ No newline at end of file
[23/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/producer/StormSpoutOutputCollectorSpec.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/producer/StormSpoutOutputCollectorSpec.scala b/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/producer/StormSpoutOutputCollectorSpec.scala
new file mode 100644
index 0000000..49afe05
--- /dev/null
+++ b/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/producer/StormSpoutOutputCollectorSpec.scala
@@ -0,0 +1,50 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.storm.producer
+
+import java.util.{List => JList}
+
+import backtype.storm.spout.ISpout
+import backtype.storm.utils.Utils
+import org.apache.gearpump.experiments.storm.util.StormOutputCollector
+import org.mockito.Mockito._
+import org.scalacheck.Gen
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{Matchers, PropSpec}
+
+import scala.collection.JavaConverters._
+
+class StormSpoutOutputCollectorSpec
+ extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
+
+ property("StormSpoutOutputCollector should call StormOutputCollector") {
+ val valGen = Gen.oneOf(Gen.alphaStr, Gen.alphaChar, Gen.chooseNum[Int](0, 1000))
+ val valuesGen = Gen.listOf[AnyRef](valGen)
+
+ forAll(valuesGen) { (values: List[AnyRef]) =>
+ val collector = mock[StormOutputCollector]
+ val spout = mock[ISpout]
+ val streamId = Utils.DEFAULT_STREAM_ID
+ val spoutCollector = new StormSpoutOutputCollector(collector, spout, false)
+ spoutCollector.emit(streamId, values.asJava, null)
+ verify(collector).emit(streamId, values.asJava)
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/topology/GearpumpStormComponentSpec.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/topology/GearpumpStormComponentSpec.scala b/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/topology/GearpumpStormComponentSpec.scala
new file mode 100644
index 0000000..bdea50c
--- /dev/null
+++ b/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/topology/GearpumpStormComponentSpec.scala
@@ -0,0 +1,124 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.experiments.storm.topology
+
+import java.util.{Map => JMap}
+
+import akka.actor.ActorRef
+import backtype.storm.spout.{ISpout, SpoutOutputCollector}
+import backtype.storm.task.{GeneralTopologyContext, IBolt, OutputCollector, TopologyContext}
+import backtype.storm.tuple.Tuple
+import org.apache.gearpump.experiments.storm.producer.StormSpoutOutputCollector
+import org.apache.gearpump.experiments.storm.topology.GearpumpStormComponent.{GearpumpBolt, GearpumpSpout}
+import org.apache.gearpump.experiments.storm.util.StormOutputCollector
+import org.apache.gearpump.streaming.task.{StartTime, TaskContext, TaskId}
+import org.apache.gearpump.streaming.{DAG, MockUtil}
+import org.apache.gearpump.{Message, TimeStamp}
+import org.mockito.Matchers.{anyObject, eq => mockitoEq}
+import org.mockito.Mockito._
+import org.scalacheck.Gen
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{Matchers, PropSpec}
+
+class GearpumpStormComponentSpec
+ extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
+
+ property("GearpumpSpout lifecycle") {
+ val config = mock[JMap[AnyRef, AnyRef]]
+ val spout = mock[ISpout]
+ val taskContext = MockUtil.mockTaskContext
+ val appMaster = mock[ActorRef]
+ when(taskContext.appMaster).thenReturn(appMaster)
+ val getDAG = mock[ActorRef => DAG]
+ val dag = mock[DAG]
+ when(getDAG(appMaster)).thenReturn(dag)
+ val getTopologyContext = mock[(DAG, TaskId) => TopologyContext]
+ val topologyContext = mock[TopologyContext]
+ when(getTopologyContext(dag, taskContext.taskId)).thenReturn(topologyContext)
+ val getOutputCollector = mock[(TaskContext, TopologyContext) => StormSpoutOutputCollector]
+ val outputCollector = mock[StormSpoutOutputCollector]
+ when(getOutputCollector(taskContext, topologyContext)).thenReturn(outputCollector)
+
+ val gearpumpSpout = GearpumpSpout(config, spout, getDAG, getTopologyContext,
+ getOutputCollector, ackEnabled = false, taskContext)
+
+ // Start
+ val startTime = mock[StartTime]
+ gearpumpSpout.start(startTime)
+
+ verify(spout).open(mockitoEq(config), mockitoEq(topologyContext),
+ anyObject[SpoutOutputCollector])
+
+ // Next
+ val message = mock[Message]
+ gearpumpSpout.next(message)
+
+ verify(spout).nextTuple()
+ }
+
+ property("GearpumpBolt lifecycle") {
+ val timestampGen = Gen.chooseNum[Long](0L, 1000L)
+ val freqGen = Gen.chooseNum[Int](1, 100)
+ forAll(timestampGen, freqGen) { (timestamp: TimeStamp, freq: Int) =>
+ val config = mock[JMap[AnyRef, AnyRef]]
+ val bolt = mock[IBolt]
+ val taskContext = MockUtil.mockTaskContext
+ val appMaster = mock[ActorRef]
+ when(taskContext.appMaster).thenReturn(appMaster)
+ val getDAG = mock[ActorRef => DAG]
+ val dag = mock[DAG]
+ when(getDAG(appMaster)).thenReturn(dag)
+ val getTopologyContext = mock[(DAG, TaskId) => TopologyContext]
+ val topologyContext = mock[TopologyContext]
+ when(getTopologyContext(dag, taskContext.taskId)).thenReturn(topologyContext)
+ val getGeneralTopologyContext = mock[DAG => GeneralTopologyContext]
+ val generalTopologyContext = mock[GeneralTopologyContext]
+ when(getGeneralTopologyContext(dag)).thenReturn(generalTopologyContext)
+ val getOutputCollector = mock[(TaskContext, TopologyContext) => StormOutputCollector]
+ val stormOutputCollector = mock[StormOutputCollector]
+ when(getOutputCollector(taskContext, topologyContext)).thenReturn(stormOutputCollector)
+ val getTickTuple = mock[(GeneralTopologyContext, Int) => Tuple]
+ val tickTuple = mock[Tuple]
+ when(getTickTuple(mockitoEq(generalTopologyContext), anyObject[Int]())).thenReturn(tickTuple)
+ val gearpumpBolt = GearpumpBolt(config, bolt, getDAG, getTopologyContext,
+ getGeneralTopologyContext, getOutputCollector, getTickTuple, taskContext)
+
+ // Start
+ val startTime = mock[StartTime]
+ gearpumpBolt.start(startTime)
+
+ verify(bolt).prepare(mockitoEq(config), mockitoEq(topologyContext),
+ anyObject[OutputCollector])
+
+ // Next
+ val gearpumpTuple = mock[GearpumpTuple]
+ val tuple = mock[Tuple]
+ when(gearpumpTuple.toTuple(generalTopologyContext, timestamp)).thenReturn(tuple)
+ val message = Message(gearpumpTuple, timestamp)
+ gearpumpBolt.next(message)
+
+ verify(stormOutputCollector).setTimestamp(timestamp)
+ verify(bolt).execute(tuple)
+
+ // Tick
+ gearpumpBolt.tick(freq)
+ verify(bolt).execute(tickTuple)
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/topology/GearpumpStormTopologySpec.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/topology/GearpumpStormTopologySpec.scala b/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/topology/GearpumpStormTopologySpec.scala
new file mode 100644
index 0000000..ef383ad
--- /dev/null
+++ b/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/topology/GearpumpStormTopologySpec.scala
@@ -0,0 +1,104 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.storm.topology
+
+import java.util.{HashMap => JHashMap, Map => JMap}
+
+import backtype.storm.Config
+import org.apache.gearpump.experiments.storm.processor.StormProcessor
+import org.apache.gearpump.experiments.storm.producer.StormProducer
+import org.apache.gearpump.experiments.storm.util.TopologyUtil
+import org.apache.gearpump.streaming.MockUtil
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.{Matchers, WordSpec}
+
+import scala.collection.JavaConverters._
+
+class GearpumpStormTopologySpec extends WordSpec with Matchers with MockitoSugar {
+ import org.apache.gearpump.experiments.storm.topology.GearpumpStormTopologySpec._
+
+ "GearpumpStormTopology" should {
+ "merge configs with defined priority" in {
+ val stormTopology = TopologyUtil.getTestTopology
+ val name = "name"
+ val sysVal = "sys"
+ val sysConfig = newJavaConfig(name, sysVal)
+ val appVal = "app"
+ val appConfig = newJavaConfig(name, appVal)
+
+ implicit val system = MockUtil.system
+ val topology1 = new GearpumpStormTopology("topology1", stormTopology, newEmptyConfig,
+ newEmptyConfig)
+ topology1.getStormConfig.get(Config.TOPOLOGY_NAME) shouldBe "topology1"
+ topology1.getStormConfig should not contain name
+
+ val topology2 = new GearpumpStormTopology("topology2", stormTopology, sysConfig,
+ newEmptyConfig)
+ topology2.getStormConfig.get(Config.TOPOLOGY_NAME) shouldBe "topology2"
+ topology2.getStormConfig.get(name) shouldBe sysVal
+
+ val topology3 = new GearpumpStormTopology("topology3", stormTopology, sysConfig, appConfig)
+ topology3.getStormConfig.get(Config.TOPOLOGY_NAME) shouldBe "topology3"
+ topology3.getStormConfig.get(name) shouldBe appVal
+ }
+
+ "create Gearpump processors from Storm topology" in {
+ val stormTopology = TopologyUtil.getTestTopology
+ implicit val system = MockUtil.system
+ val gearpumpStormTopology =
+ GearpumpStormTopology("app", stormTopology, null)
+ val processors = gearpumpStormTopology.getProcessors
+ stormTopology.get_spouts().asScala.foreach { case (spoutId, _) =>
+ val processor = processors(spoutId)
+ processor.taskClass shouldBe classOf[StormProducer]
+ processor.description shouldBe spoutId
+ }
+ stormTopology.get_bolts().asScala.foreach { case (boltId, _) =>
+ val processor = processors(boltId)
+ processor.taskClass shouldBe classOf[StormProcessor]
+ processor.description shouldBe boltId
+ }
+ }
+
+ "get target processors from source id" in {
+ val stormTopology = TopologyUtil.getTestTopology
+ implicit val system = MockUtil.system
+ val sysConfig = new JHashMap[AnyRef, AnyRef]
+ val gearpumpStormTopology =
+ GearpumpStormTopology("app", stormTopology, null)
+ val targets0 = gearpumpStormTopology.getTargets("1")
+ targets0 should contain key "3"
+ targets0 should contain key "4"
+ val targets1 = gearpumpStormTopology.getTargets("2")
+ targets1 should contain key "3"
+ }
+ }
+}
+
+object GearpumpStormTopologySpec {
+ def newEmptyConfig: JMap[AnyRef, AnyRef] = {
+ new JHashMap[AnyRef, AnyRef]
+ }
+
+ def newJavaConfig(key: AnyRef, value: AnyRef): JMap[AnyRef, AnyRef] = {
+ val config = new JHashMap[AnyRef, AnyRef]
+ config.put(key, value)
+ config
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/topology/GearpumpTupleSpec.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/topology/GearpumpTupleSpec.scala b/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/topology/GearpumpTupleSpec.scala
new file mode 100644
index 0000000..f12e54f
--- /dev/null
+++ b/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/topology/GearpumpTupleSpec.scala
@@ -0,0 +1,63 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.experiments.storm.topology
+
+import java.util.{List => JList}
+
+import backtype.storm.task.GeneralTopologyContext
+import backtype.storm.tuple.Fields
+import org.apache.gearpump.TimeStamp
+import org.mockito.Mockito._
+import org.scalacheck.Gen
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{Matchers, PropSpec}
+
+import scala.collection.JavaConverters._
+
+class GearpumpTupleSpec extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
+
+ property("GearpumpTuple should create Storm Tuple") {
+ val tupleGen = for {
+ values <- Gen.listOf[String](Gen.alphaStr).map(_.distinct.asJava.asInstanceOf[JList[AnyRef]])
+ sourceTaskId <- Gen.chooseNum[Int](0, Int.MaxValue)
+ sourceStreamId <- Gen.alphaStr
+ } yield new GearpumpTuple(values, new Integer(sourceTaskId), sourceStreamId, null)
+
+ forAll(tupleGen, Gen.alphaStr, Gen.chooseNum[Long](0, Long.MaxValue)) {
+ (gearpumpTuple: GearpumpTuple, componentId: String, timestamp: TimeStamp) =>
+ val topologyContext = mock[GeneralTopologyContext]
+ val fields = new Fields(gearpumpTuple.values.asScala.map(_.asInstanceOf[String]): _*)
+ when(topologyContext.getComponentId(gearpumpTuple.sourceTaskId)).thenReturn(componentId)
+ when(topologyContext.getComponentOutputFields(
+ componentId, gearpumpTuple.sourceStreamId)).thenReturn(fields)
+
+ val tuple = gearpumpTuple.toTuple(topologyContext, timestamp)
+
+ tuple shouldBe a[TimedTuple]
+ val timedTuple = tuple.asInstanceOf[TimedTuple]
+ timedTuple.getValues shouldBe gearpumpTuple.values
+ timedTuple.getSourceTask shouldBe gearpumpTuple.sourceTaskId
+ timedTuple.getSourceComponent shouldBe componentId
+ timedTuple.getSourceStreamId shouldBe gearpumpTuple.sourceStreamId
+ timedTuple.getMessageId shouldBe null
+ timedTuple.getFields shouldBe fields
+ timedTuple.timestamp shouldBe timestamp
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/util/GraphBuilderSpec.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/util/GraphBuilderSpec.scala b/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/util/GraphBuilderSpec.scala
new file mode 100644
index 0000000..9cf5009
--- /dev/null
+++ b/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/util/GraphBuilderSpec.scala
@@ -0,0 +1,55 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.storm.util
+
+import org.mockito.Mockito._
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.{Matchers, WordSpec}
+
+import org.apache.gearpump.experiments.storm.partitioner.StormPartitioner
+import org.apache.gearpump.experiments.storm.topology.GearpumpStormTopology
+import org.apache.gearpump.streaming.Processor
+import org.apache.gearpump.streaming.task.Task
+
+class GraphBuilderSpec extends WordSpec with Matchers with MockitoSugar {
+
+ "GraphBuilder" should {
+ "build Graph from Storm topology" in {
+ val topology = mock[GearpumpStormTopology]
+
+ val sourceId = "source"
+ val sourceProcessor = mock[Processor[Task]]
+ val targetId = "target"
+ val targetProcessor = mock[Processor[Task]]
+
+ when(topology.getProcessors).thenReturn(
+ Map(sourceId -> sourceProcessor, targetId -> targetProcessor))
+ when(topology.getTargets(sourceId)).thenReturn(Map(targetId -> targetProcessor))
+ when(topology.getTargets(targetId)).thenReturn(Map.empty[String, Processor[Task]])
+
+ val graph = GraphBuilder.build(topology)
+
+ graph.edges.size shouldBe 1
+ val (from, edge, to) = graph.edges.head
+ from shouldBe sourceProcessor
+ edge shouldBe a[StormPartitioner]
+ to shouldBe targetProcessor
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/util/GrouperSpec.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/util/GrouperSpec.scala b/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/util/GrouperSpec.scala
new file mode 100644
index 0000000..c1cdb3b
--- /dev/null
+++ b/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/util/GrouperSpec.scala
@@ -0,0 +1,131 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.storm.util
+
+import java.util.{List => JList}
+import scala.collection.JavaConverters._
+
+import backtype.storm.generated.GlobalStreamId
+import backtype.storm.grouping.CustomStreamGrouping
+import backtype.storm.task.TopologyContext
+import backtype.storm.tuple.Fields
+import org.mockito.Mockito._
+import org.scalacheck.Gen
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{Matchers, PropSpec}
+
+import org.apache.gearpump.experiments.storm.util.GrouperSpec.Value
+
+class GrouperSpec extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
+
+ val taskIdGen = Gen.chooseNum[Int](0, 1000)
+ val valuesGen = Gen.listOf[String](Gen.alphaStr)
+ .map(_.asJava.asInstanceOf[JList[AnyRef]])
+ val numTasksGen = Gen.chooseNum[Int](1, 1000)
+
+ property("GlobalGrouper should always return partition 0") {
+ forAll(taskIdGen, valuesGen) { (taskId: Int, values: JList[AnyRef]) =>
+ val grouper = new GlobalGrouper
+ grouper.getPartitions(taskId, values) shouldBe List(0)
+ }
+ }
+
+ property("NoneGrouper should returns partition in the range [0, numTasks)") {
+ forAll(taskIdGen, valuesGen, numTasksGen) {
+ (taskId: Int, values: JList[AnyRef], numTasks: Int) =>
+ val grouper = new NoneGrouper(numTasks)
+ val partitions = grouper.getPartitions(taskId, values)
+ partitions.size shouldBe 1
+ partitions.head should (be >= 0 and be < numTasks)
+ }
+ }
+
+ property("ShuffleGrouper should return partition in the range [0, numTasks)") {
+ forAll(taskIdGen, valuesGen, numTasksGen) {
+ (taskId: Int, values: JList[AnyRef], numTasks: Int) =>
+ val grouper = new ShuffleGrouper(numTasks)
+ val partitions = grouper.getPartitions(taskId, values)
+ partitions.size shouldBe 1
+ partitions.head should (be >= 0 and be < numTasks)
+ }
+ }
+
+ property("FieldsGrouper should return partition according to fields") {
+ forAll(taskIdGen, numTasksGen) {
+ (taskId: Int, numTasks: Int) =>
+ val values = 0.until(numTasks).map(i => new Value(i))
+ val fields = values.map(_.toString)
+ val outFields = new Fields(fields: _*)
+ values.flatMap { v =>
+ val groupFields = new Fields(v.toString)
+ val grouper = new FieldsGrouper(outFields, groupFields, numTasks)
+ grouper.getPartitions(taskId,
+ values.toList.asJava.asInstanceOf[JList[AnyRef]])
+ }.distinct.size shouldBe numTasks
+ }
+ }
+
+ property("AllGrouper should return all partitions") {
+ forAll(taskIdGen, numTasksGen, valuesGen) {
+ (taskId: Int, numTasks: Int, values: JList[AnyRef]) =>
+ val grouper = new AllGrouper(numTasks)
+ val partitions = grouper.getPartitions(taskId, values)
+ partitions.distinct.size shouldBe numTasks
+ partitions.min shouldBe 0
+ partitions.max shouldBe (numTasks - 1)
+ }
+ }
+
+ property("CustomGrouper should return partitions specified by user") {
+ val grouping = mock[CustomStreamGrouping]
+ val grouper = new CustomGrouper(grouping)
+ val topologyContext = mock[TopologyContext]
+ val globalStreamId = mock[GlobalStreamId]
+ val sourceTasks = mock[JList[Integer]]
+
+ grouper.prepare(topologyContext, globalStreamId, sourceTasks)
+
+ verify(grouping).prepare(topologyContext, globalStreamId, sourceTasks)
+
+ forAll(taskIdGen, valuesGen, numTasksGen) {(taskId: Int, values: JList[AnyRef], taskNum: Int) =>
+ 0.until(taskNum).foreach { i =>
+ when(grouping.chooseTasks(taskId, values)).thenReturn(List(new Integer(i)).asJava)
+ grouper.getPartitions(taskId, values) shouldBe List(i)
+ }
+ }
+ }
+}
+
+object GrouperSpec {
+ class Value(val i: Int) extends AnyRef {
+
+ override def toString: String = s"$i"
+
+ override def hashCode(): Int = i
+
+ override def equals(other: Any): Boolean = {
+ if (other.isInstanceOf[Value]) {
+ this.i == other.asInstanceOf[Value].i
+ } else {
+ false
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/util/StormOutputCollectorSpec.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/util/StormOutputCollectorSpec.scala b/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/util/StormOutputCollectorSpec.scala
new file mode 100644
index 0000000..e0e9e61
--- /dev/null
+++ b/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/util/StormOutputCollectorSpec.scala
@@ -0,0 +1,109 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.experiments.storm.util
+
+import java.util.{List => JList, Map => JMap}
+import scala.collection.JavaConverters._
+
+import backtype.storm.generated.Grouping
+import org.mockito.Matchers._
+import org.mockito.Mockito._
+import org.scalacheck.Gen
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{Matchers, PropSpec}
+
+import org.apache.gearpump._
+import org.apache.gearpump.experiments.storm.topology.GearpumpTuple
+import org.apache.gearpump.streaming.MockUtil
+
+class StormOutputCollectorSpec
+ extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
+
+ val stormTaskId = 0
+ val streamIdGen = Gen.alphaStr
+ val valuesGen = Gen.listOf[String](Gen.alphaStr).map(_.asJava.asInstanceOf[JList[AnyRef]])
+ val timestampGen = Gen.chooseNum[Long](0L, 1000L)
+
+ property("StormOutputCollector emits tuple values into a stream") {
+ forAll(timestampGen, streamIdGen, valuesGen) {
+ (timestamp: TimeStamp, streamId: String, values: JList[AnyRef]) =>
+ val targets = mock[JMap[String, JMap[String, Grouping]]]
+ val taskToComponent = mock[JMap[Integer, String]]
+ val getTargetPartitionsFn = mock[(String, JList[AnyRef]) =>
+ (Map[String, Array[Int]], JList[Integer])]
+ val targetPartitions = mock[Map[String, Array[Int]]]
+ val targetStormTaskIds = mock[JList[Integer]]
+ when(getTargetPartitionsFn(streamId, values)).thenReturn((targetPartitions,
+ targetStormTaskIds))
+ val taskContext = MockUtil.mockTaskContext
+ val stormOutputCollector = new StormOutputCollector(stormTaskId, taskToComponent,
+ targets, getTargetPartitionsFn, taskContext, LatestTime)
+
+ when(targets.containsKey(streamId)).thenReturn(false)
+ stormOutputCollector.emit(streamId, values) shouldBe StormOutputCollector.EMPTY_LIST
+ verify(taskContext, times(0)).output(anyObject[Message])
+
+ when(targets.containsKey(streamId)).thenReturn(true)
+ stormOutputCollector.setTimestamp(timestamp)
+ stormOutputCollector.emit(streamId, values) shouldBe targetStormTaskIds
+ verify(taskContext, times(1)).output(MockUtil.argMatch[Message]({
+ case Message(tuple: GearpumpTuple, t) =>
+ val expected = new GearpumpTuple(values, stormTaskId, streamId, targetPartitions)
+ tuple == expected && t == timestamp
+ }))
+ }
+ }
+
+ property("StormOutputCollector emit direct to a task") {
+ val idGen = Gen.chooseNum[Int](0, 1000)
+ val targetGen = Gen.alphaStr
+ forAll(idGen, targetGen, timestampGen, streamIdGen, valuesGen) {
+ (id: Int, target: String, timestamp: Long, streamId: String, values: JList[AnyRef]) =>
+ val targets = mock[JMap[String, JMap[String, Grouping]]]
+ val taskToComponent = mock[JMap[Integer, String]]
+ when(taskToComponent.get(id)).thenReturn(target)
+ val getTargetPartitionsFn = mock[(String, JList[AnyRef]) =>
+ (Map[String, Array[Int]], JList[Integer])]
+ val targetPartitions = mock[Map[String, Array[Int]]]
+ val targetStormTaskIds = mock[JList[Integer]]
+ when(getTargetPartitionsFn(streamId, values)).thenReturn((targetPartitions,
+ targetStormTaskIds))
+ val taskContext = MockUtil.mockTaskContext
+ val stormOutputCollector = new StormOutputCollector(stormTaskId, taskToComponent,
+ targets, getTargetPartitionsFn, taskContext, LatestTime)
+
+ when(targets.containsKey(streamId)).thenReturn(false)
+ verify(taskContext, times(0)).output(anyObject[Message])
+
+ when(targets.containsKey(streamId)).thenReturn(true)
+ stormOutputCollector.setTimestamp(timestamp)
+ stormOutputCollector.emitDirect(id, streamId, values)
+ val partitions = Array(StormUtil.stormTaskIdToGearpump(id).index)
+ verify(taskContext, times(1)).output(MockUtil.argMatch[Message]({
+ case Message(tuple: GearpumpTuple, t) => {
+ val expected = new GearpumpTuple(values, stormTaskId, streamId,
+ Map(target -> partitions))
+
+ val result = tuple == expected && t == timestamp
+ result
+ }
+ }))
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/util/StormSerializerPoolSpec.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/util/StormSerializerPoolSpec.scala b/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/util/StormSerializerPoolSpec.scala
new file mode 100644
index 0000000..e787c3d
--- /dev/null
+++ b/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/util/StormSerializerPoolSpec.scala
@@ -0,0 +1,63 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.storm.util
+
+import java.util.{HashMap => JHashMap, List => JList, Map => JMap}
+import scala.collection.JavaConverters._
+
+import akka.actor.ExtendedActorSystem
+import backtype.storm.utils.Utils
+import com.esotericsoftware.kryo.Kryo
+import org.scalacheck.Gen
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{Matchers, PropSpec}
+
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.experiments.storm.topology.GearpumpTuple
+import org.apache.gearpump.experiments.storm.util.StormConstants._
+import org.apache.gearpump.streaming.MockUtil
+
+class StormSerializerPoolSpec extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
+
+ property("StormSerializerPool should create and manage StormSerializer") {
+ val taskContext = MockUtil.mockTaskContext
+ val serializerPool = new StormSerializationFramework
+ val system = taskContext.system.asInstanceOf[ExtendedActorSystem]
+ implicit val actorSystem = system
+ val stormConfig = Utils.readDefaultConfig.asInstanceOf[JMap[AnyRef, AnyRef]]
+ val config = UserConfig.empty.withValue[JMap[AnyRef, AnyRef]](STORM_CONFIG, stormConfig)
+ serializerPool.init(system, config)
+ serializerPool.get shouldBe a[StormSerializer]
+ }
+
+ property("StormSerializer should serialize and deserialize GearpumpTuple") {
+ val tupleGen = for {
+ values <- Gen.listOf[String](Gen.alphaStr).map(_.asJava.asInstanceOf[JList[AnyRef]])
+ sourceTaskId <- Gen.chooseNum[Int](0, Int.MaxValue)
+ sourceStreamId <- Gen.alphaStr
+ } yield new GearpumpTuple(values, new Integer(sourceTaskId), sourceStreamId, null)
+
+ val kryo = new Kryo
+ forAll(tupleGen) { (tuple: GearpumpTuple) =>
+ val serializer = new StormSerializer(kryo)
+ serializer.deserialize(serializer.serialize(tuple)) shouldBe tuple
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/util/StormUtilSpec.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/util/StormUtilSpec.scala b/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/util/StormUtilSpec.scala
new file mode 100644
index 0000000..36d84cb
--- /dev/null
+++ b/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/util/StormUtilSpec.scala
@@ -0,0 +1,157 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.storm.util
+
+import java.lang.{Boolean => JBoolean, Long => JLong}
+import java.util.{HashMap => JHashMap, Map => JMap}
+import scala.collection.JavaConverters._
+
+import backtype.storm.Config
+import backtype.storm.generated.StormTopology
+import org.apache.storm.shade.org.json.simple.JSONValue
+import org.scalacheck.Gen
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{Matchers, PropSpec}
+
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.experiments.storm.topology.GearpumpStormComponent.{GearpumpBolt, GearpumpSpout}
+import org.apache.gearpump.experiments.storm.util.StormConstants._
+import org.apache.gearpump.experiments.storm.util.StormUtil._
+import org.apache.gearpump.streaming.MockUtil
+import org.apache.gearpump.streaming.task.TaskId
+
+class StormUtilSpec extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
+
+ property("convert Storm task ids to gearpump TaskIds and back") {
+ val idGen = Gen.chooseNum[Int](0, Int.MaxValue)
+ forAll(idGen) { (stormTaskId: Int) =>
+ gearpumpTaskIdToStorm(stormTaskIdToGearpump(stormTaskId)) shouldBe stormTaskId
+ }
+
+ val processorIdGen = Gen.chooseNum[Int](0, Int.MaxValue >> 16)
+ val indexGen = Gen.chooseNum[Int](0, Int.MaxValue >> 16)
+ forAll(processorIdGen, indexGen) { (processorId: Int, index: Int) =>
+ val taskId = TaskId(processorId, index)
+ stormTaskIdToGearpump(gearpumpTaskIdToStorm(taskId)) shouldBe taskId
+ }
+ }
+
+ property("get GearpumpStormComponent from user config") {
+ val taskContext = MockUtil.mockTaskContext
+ val topology = TopologyUtil.getTestTopology
+ implicit val actorSystem = taskContext.system
+ val userConfig = UserConfig.empty
+ .withValue[StormTopology](STORM_TOPOLOGY, topology)
+ .withValue[JMap[AnyRef, AnyRef]](STORM_CONFIG, new JHashMap[AnyRef, AnyRef])
+ topology.get_spouts.asScala.foreach { case (spoutId, _) =>
+ val config = userConfig.withString(STORM_COMPONENT, spoutId)
+ val component = getGearpumpStormComponent(taskContext, config)(taskContext.system)
+ component shouldBe a[GearpumpSpout]
+ }
+ topology.get_bolts.asScala.foreach { case (boltId, _) =>
+ val config = userConfig.withString(STORM_COMPONENT, boltId)
+ val component = getGearpumpStormComponent(taskContext, config)(taskContext.system)
+ component shouldBe a[GearpumpBolt]
+ }
+ }
+
+ property("parse json to map") {
+ val mapGen = Gen.listOf[String](Gen.alphaStr)
+ .map(_.map(s => (s, s)).toMap.asJava.asInstanceOf[JMap[AnyRef, AnyRef]])
+
+ forAll(mapGen) { (map: JMap[AnyRef, AnyRef]) =>
+ parseJsonStringToMap(JSONValue.toJSONString(map)) shouldBe map
+ }
+
+ val invalidJsonGen: Gen[String] = Gen.oneOf(null, "", "1")
+ forAll(invalidJsonGen) { (invalidJson: String) =>
+ val map = parseJsonStringToMap(invalidJson)
+ map shouldBe empty
+ map shouldBe a[JMap[_, _]]
+ }
+ }
+
+ property("get int from config") {
+ val name = "int"
+ val conf: JMap[AnyRef, AnyRef] = new JHashMap[AnyRef, AnyRef]
+ getInt(conf, name) shouldBe None
+ conf.put(name, null)
+ getInt(conf, name) shouldBe None
+
+ forAll(Gen.chooseNum[Int](Int.MinValue, Int.MaxValue)) { (int: Int) =>
+ conf.put(name, new Integer(int))
+ getInt(conf, name) shouldBe Some(int)
+ }
+
+ forAll(Gen.chooseNum[Long](Int.MinValue, Int.MaxValue)) { (long: Long) =>
+ conf.put(name, new JLong(long))
+ getInt(conf, name) shouldBe Some(long)
+ }
+
+ forAll(Gen.alphaStr) { (s: String) =>
+ conf.put(name, s)
+ an[IllegalArgumentException] should be thrownBy getInt(conf, name)
+ }
+ }
+
+ property("get boolean from config") {
+ val name = "boolean"
+ val conf: JMap[AnyRef, AnyRef] = new JHashMap[AnyRef, AnyRef]
+ getBoolean(conf, name) shouldBe None
+ conf.put(name, null)
+ getBoolean(conf, name) shouldBe None
+
+ forAll(Gen.oneOf(true, false)) { (boolean: Boolean) =>
+ conf.put(name, new JBoolean(boolean))
+ getBoolean(conf, name) shouldBe Some(boolean)
+ }
+
+ forAll(Gen.alphaStr) { (s: String) =>
+ conf.put(name, s)
+ an[IllegalArgumentException] should be thrownBy getBoolean(conf, name)
+ }
+ }
+
+ property("mod should be correct") {
+ mod(10, 5) shouldBe 0
+ mod(10, 6) shouldBe 4
+ mod(10, -3) shouldBe -2
+ mod(-2, 5) shouldBe 3
+ mod(-1, -2) shouldBe -1
+ }
+
+ property("get whether ack enabled") {
+ val conf: JMap[AnyRef, AnyRef] = new JHashMap[AnyRef, AnyRef]
+ ackEnabled(conf) shouldBe false
+ conf.put(Config.TOPOLOGY_ACKER_EXECUTORS, new Integer(0))
+ ackEnabled(conf) shouldBe false
+ conf.put(Config.TOPOLOGY_ACKER_EXECUTORS, null)
+ ackEnabled(conf) shouldBe true
+ forAll(Gen.chooseNum[Int](Int.MinValue, Int.MaxValue)) {
+ (ackers: Int) =>
+ conf.put(Config.TOPOLOGY_ACKER_EXECUTORS, new Integer(ackers))
+ if (ackers == 0) {
+ ackEnabled(conf) shouldBe false
+ } else {
+ ackEnabled(conf) shouldBe true
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/util/TopologyUtil.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/util/TopologyUtil.scala b/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/util/TopologyUtil.scala
new file mode 100644
index 0000000..886013c
--- /dev/null
+++ b/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/util/TopologyUtil.scala
@@ -0,0 +1,41 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.storm.util
+
+import backtype.storm.generated.StormTopology
+import backtype.storm.testing.{TestGlobalCount, TestWordCounter, TestWordSpout}
+import backtype.storm.topology.TopologyBuilder
+import backtype.storm.tuple.Fields
+import backtype.storm.utils.Utils
+
+object TopologyUtil {
+ val DEFAULT_STREAM_ID = Utils.DEFAULT_STREAM_ID
+ val DEFAULT_COMPONENT_ID = "component"
+
+ def getTestTopology: StormTopology = {
+ val topologyBuilder = new TopologyBuilder
+ topologyBuilder.setSpout("1", new TestWordSpout(true), 5)
+ topologyBuilder.setSpout("2", new TestWordSpout(true), 3)
+ topologyBuilder.setBolt("3", new TestWordCounter(), 3)
+ .fieldsGrouping("1", new Fields("word"))
+ .fieldsGrouping("2", new Fields("word"))
+ topologyBuilder.setBolt("4", new TestGlobalCount()).globalGrouping("1")
+ topologyBuilder.createTopology()
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/Constants.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/Constants.scala b/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/Constants.scala
deleted file mode 100644
index 6618b48..0000000
--- a/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/Constants.scala
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.yarn
-
-object Constants {
- val APPMASTER_NAME = "gearpump.yarn.applicationmaster.name"
- val APPMASTER_COMMAND = "gearpump.yarn.applicationmaster.command"
- val APPMASTER_MEMORY = "gearpump.yarn.applicationmaster.memory"
- val APPMASTER_VCORES = "gearpump.yarn.applicationmaster.vcores"
- val APPMASTER_QUEUE = "gearpump.yarn.applicationmaster.queue"
-
- val PACKAGE_PATH = "gearpump.yarn.client.package-path"
- val CONFIG_PATH = "gearpump.yarn.client.config-path"
-
- val MASTER_COMMAND = "gearpump.yarn.master.command"
- val MASTER_MEMORY = "gearpump.yarn.master.memory"
- val MASTER_VCORES = "gearpump.yarn.master.vcores"
-
- val WORKER_COMMAND = "gearpump.yarn.worker.command"
- val WORKER_CONTAINERS = "gearpump.yarn.worker.containers"
- val WORKER_MEMORY = "gearpump.yarn.worker.memory"
- val WORKER_VCORES = "gearpump.yarn.worker.vcores"
-
- val SERVICES_ENABLED = "gearpump.yarn.services.enabled"
-
- val LOCAL_DIRS = org.apache.hadoop.yarn.api.ApplicationConstants.Environment.LOCAL_DIRS.$$()
- val CONTAINER_ID = org.apache.hadoop.yarn.api.ApplicationConstants.Environment.CONTAINER_ID.$$()
- val LOG_DIR_EXPANSION_VAR = org.apache.hadoop.yarn.api.ApplicationConstants.LOG_DIR_EXPANSION_VAR
- val NODEMANAGER_HOST = org.apache.hadoop.yarn.api.ApplicationConstants.Environment.NM_HOST.$$()
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/appmaster/Command.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/appmaster/Command.scala b/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/appmaster/Command.scala
deleted file mode 100644
index af871ab..0000000
--- a/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/appmaster/Command.scala
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.yarn.appmaster
-
-import com.typesafe.config.Config
-
-import io.gearpump.cluster.main.{Master, Worker}
-import io.gearpump.experiments.yarn.Constants._
-import io.gearpump.transport.HostPort
-import io.gearpump.util.Constants
-
-/** Command to start a YARN container */
-trait Command {
- def get: String
- override def toString: String = get
-}
-
-abstract class AbstractCommand extends Command {
- protected def config: Config
- def version: String
- def classPath: Array[String] = {
- Array(
- s"conf",
- s"pack/$version/conf",
- s"pack/$version/lib/daemon/*",
- s"pack/$version/lib/*"
- )
- }
-
- protected def buildCommand(
- java: String, properties: Array[String], mainClazz: String, cliOpts: Array[String])
- : String = {
- val exe = config.getString(java)
-
- s"$exe -cp ${classPath.mkString(":")}:" +
- "$CLASSPATH " + properties.mkString(" ") +
- s" $mainClazz ${cliOpts.mkString(" ")} 2>&1 | /usr/bin/tee -a ${LOG_DIR_EXPANSION_VAR}/stderr"
- }
-
- protected def clazz(any: AnyRef): String = {
- val name = any.getClass.getName
- if (name.endsWith("$")) {
- name.dropRight(1)
- } else {
- name
- }
- }
-}
-
-case class MasterCommand(config: Config, version: String, masterAddr: HostPort)
- extends AbstractCommand {
-
- def get: String = {
- val masterArguments = Array(s"-ip ${masterAddr.host}", s"-port ${masterAddr.port}")
-
- val properties = Array(
- s"-D${Constants.GEARPUMP_CLUSTER_MASTERS}.0=${masterAddr.host}:${masterAddr.port}",
- s"-D${Constants.GEARPUMP_HOSTNAME}=${masterAddr.host}",
- s"-D${Constants.GEARPUMP_MASTER_RESOURCE_MANAGER_CONTAINER_ID}=${CONTAINER_ID}",
- s"-D${Constants.GEARPUMP_HOME}=${LOCAL_DIRS}/${CONTAINER_ID}/pack/$version",
- s"-D${Constants.GEARPUMP_LOG_DAEMON_DIR}=${LOG_DIR_EXPANSION_VAR}",
- s"-D${Constants.GEARPUMP_LOG_APPLICATION_DIR}=${LOG_DIR_EXPANSION_VAR}")
-
- buildCommand(MASTER_COMMAND, properties, clazz(Master), masterArguments)
- }
-}
-
-case class WorkerCommand(config: Config, version: String, masterAddr: HostPort, workerHost: String)
- extends AbstractCommand {
-
- def get: String = {
- val properties = Array(
- s"-D${Constants.GEARPUMP_CLUSTER_MASTERS}.0=${masterAddr.host}:${masterAddr.port}",
- s"-D${Constants.GEARPUMP_LOG_DAEMON_DIR}=${LOG_DIR_EXPANSION_VAR}",
- s"-D${Constants.GEARPUMP_WORKER_RESOURCE_MANAGER_CONTAINER_ID}=${CONTAINER_ID}",
- s"-D${Constants.GEARPUMP_HOME}=${LOCAL_DIRS}/${CONTAINER_ID}/pack/$version",
- s"-D${Constants.GEARPUMP_LOG_APPLICATION_DIR}=${LOG_DIR_EXPANSION_VAR}",
- s"-D${Constants.GEARPUMP_HOSTNAME}=$workerHost")
-
- buildCommand(WORKER_COMMAND, properties, clazz(Worker), Array.empty[String])
- }
-}
-
-case class AppMasterCommand(config: Config, version: String, args: Array[String])
- extends AbstractCommand {
-
- override val classPath = Array(
- "conf",
- s"pack/$version/conf",
- s"pack/$version/dashboard",
- s"pack/$version/lib/*",
- s"pack/$version/lib/daemon/*",
- s"pack/$version/lib/services/*",
- s"pack/$version/lib/yarn/*"
- )
-
- def get: String = {
- val properties = Array(
- s"-D${Constants.GEARPUMP_HOME}=${LOCAL_DIRS}/${CONTAINER_ID}/pack/$version",
- s"-D${Constants.GEARPUMP_FULL_SCALA_VERSION}=$version",
- s"-D${Constants.GEARPUMP_LOG_DAEMON_DIR}=${LOG_DIR_EXPANSION_VAR}",
- s"-D${Constants.GEARPUMP_LOG_APPLICATION_DIR}=${LOG_DIR_EXPANSION_VAR}",
- s"-D${Constants.GEARPUMP_HOSTNAME}=${NODEMANAGER_HOST}")
-
- val arguments = Array(s"") ++ args
-
- buildCommand(APPMASTER_COMMAND, properties, clazz(YarnAppMaster),
- arguments)
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/appmaster/UIService.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/appmaster/UIService.scala b/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/appmaster/UIService.scala
deleted file mode 100644
index 6dd5011..0000000
--- a/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/appmaster/UIService.scala
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.yarn.appmaster
-
-import scala.concurrent.Future
-
-import akka.actor._
-import com.typesafe.config.{ConfigFactory, ConfigValueFactory}
-
-import io.gearpump.cluster.ClusterConfig
-import io.gearpump.services.main.Services
-import io.gearpump.transport.HostPort
-import io.gearpump.util.{ActorUtil, Constants, LogUtil}
-
-trait UIFactory {
- def props(masters: List[HostPort], host: String, port: Int): Props
-}
-
-/** Wrapper of UI server */
-class UIService(masters: List[HostPort], host: String, port: Int) extends Actor {
- private val LOG = LogUtil.getLogger(getClass)
-
- private val supervisor = ActorUtil.getFullPath(context.system, context.parent.path)
- private var configFile: java.io.File = null
-
- private implicit val dispatcher = context.dispatcher
-
- override def postStop(): Unit = {
- if (configFile != null) {
- configFile.delete()
- configFile = null
- }
-
- // TODO: fix this
- // Hack around to Kill the UI server
- Services.kill()
- }
-
- override def preStart(): Unit = {
- Future(start())
- }
-
- def start(): Unit = {
- val mastersArg = masters.mkString(",")
- LOG.info(s"Launching services -master $mastersArg")
-
- configFile = java.io.File.createTempFile("uiserver", ".conf")
-
- val config = context.system.settings.config.
- withValue(Constants.GEARPUMP_SERVICE_HOST, ConfigValueFactory.fromAnyRef(host)).
- withValue(Constants.GEARPUMP_SERVICE_HTTP, ConfigValueFactory.fromAnyRef(port.toString)).
- withValue(Constants.NETTY_TCP_HOSTNAME, ConfigValueFactory.fromAnyRef(host))
-
- ClusterConfig.saveConfig(config, configFile)
-
- val master = masters.head
-
- ConfigFactory.invalidateCaches()
- launch(supervisor, master.host, master.port, configFile.toString)
- }
-
- // Launch the UI server
- def launch(supervisor: String, masterHost: String, masterPort: Int, configFile: String): Unit = {
- Services.main(Array("-supervisor", supervisor, "-master", s"$masterHost:$masterPort"
- , "-conf", configFile))
- }
-
- override def receive: Receive = {
- case _ =>
- LOG.error(s"Unknown message received")
- }
-}
-
-object UIService extends UIFactory {
- override def props(masters: List[HostPort], host: String, port: Int): Props = {
- Props(new UIService(masters, host, port))
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/appmaster/YarnAppMaster.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/appmaster/YarnAppMaster.scala b/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/appmaster/YarnAppMaster.scala
deleted file mode 100644
index 1df7fb9..0000000
--- a/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/appmaster/YarnAppMaster.scala
+++ /dev/null
@@ -1,385 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.yarn.appmaster
-
-import java.io.IOException
-import java.util.concurrent.TimeUnit
-import scala.collection.JavaConverters._
-import scala.concurrent.Await
-import scala.concurrent.duration.Duration
-
-import akka.actor._
-import akka.util.Timeout
-import com.typesafe.config.ConfigValueFactory
-import org.apache.commons.httpclient.HttpClient
-import org.apache.commons.httpclient.methods.GetMethod
-import org.slf4j.Logger
-
-import io.gearpump.cluster.ClientToMaster._
-import io.gearpump.cluster.ClusterConfig
-import io.gearpump.cluster.main.{ArgumentsParser, CLIOption}
-import io.gearpump.experiments.yarn.Constants._
-import io.gearpump.experiments.yarn.glue.Records._
-import io.gearpump.experiments.yarn.glue.{NMClient, RMClient, YarnConfig}
-import io.gearpump.transport.HostPort
-import io.gearpump.util._
-
-/**
- * YARN AppMaster. YARN AppMaster is responsible to start Gearpump masters, workers, UI server as
- * YARN containers.
- *
- * NOTE: It is different with Gearpump AppMaster. Gearpump AppMaster is a sub-process of worker.
- */
-class YarnAppMaster(rmClient: RMClient, nmClient: NMClient,
- packagePath: String, hdfsConfDir: String,
- uiFactory: UIFactory)
- extends Actor {
-
- private val LOG: Logger = LogUtil.getLogger(getClass)
- private val akkaConf = context.system.settings.config
- private val servicesEnabled = akkaConf.getString(SERVICES_ENABLED).toBoolean
- private var uiStarted = false
- private val host = akkaConf.getString(Constants.GEARPUMP_HOSTNAME)
-
- private val port = Util.findFreePort().get
-
- private val trackingURL = "http://" + host + ":" + port
-
- // TODO: for now, only one master is supported.
- private val masterCount = 1
- private val masterMemory = akkaConf.getString(MASTER_MEMORY).toInt
- private val masterVCores = akkaConf.getString(MASTER_VCORES).toInt
-
- private var workerCount = akkaConf.getString(WORKER_CONTAINERS).toInt
- private val workerMemory = akkaConf.getString(WORKER_MEMORY).toInt
- private val workerVCores = akkaConf.getString(WORKER_VCORES).toInt
-
- val rootPath = System.getProperty(Constants.GEARPUMP_FULL_SCALA_VERSION)
-
- rmClient.start(self)
- nmClient.start(self)
-
- def receive: Receive = null
-
- private def registerAppMaster(): Unit = {
- val target = host + ":" + port
- rmClient.registerAppMaster(host, port, trackingURL)
- }
-
- registerAppMaster
- context.become(waitForAppMasterRegistered)
-
- import io.gearpump.experiments.yarn.appmaster.YarnAppMaster._
-
- def waitForAppMasterRegistered: Receive = {
- case AppMasterRegistered =>
- LOG.info("YarnAppMaster registration completed")
- requestMasterContainers(masterCount)
- context.become(startingMasters(remain = masterCount, List.empty[MasterInfo]))
- }
-
- private def startingMasters(remain: Int, masters: List[MasterInfo]): Receive = box {
- case ContainersAllocated(containers) =>
- LOG.info(s"ContainersAllocated: containers allocated for master(remain=$remain), count: "
- + containers.size)
- val count = Math.min(containers.length, remain)
- val newMasters = (0 until count).toList.map { index =>
- val container = containers(index)
- MasterInfo(container.getId, container.getNodeId, launchMaster(container))
- }
-
- // Stops un-used containers
- containers.drop(count).map { container =>
- nmClient.stopContainer(container.getId, container.getNodeId)
- }
-
- context.become(startingMasters(remain, newMasters ++ masters))
- case ContainerStarted(containerId) =>
- LOG.info(s"ContainerStarted: container ${containerId} started for master(remain=$remain) ")
- if (remain > 1) {
- context.become(startingMasters(remain - 1, masters))
- } else {
- requestWorkerContainers(workerCount)
- context.become(startingWorkers(workerCount, masters, List.empty[WorkerInfo]))
- }
- }
-
- private def box(receive: Receive): Receive = {
- onError orElse receive orElse unHandled
- }
-
- private def startingWorkers(remain: Int, masters: List[MasterInfo], workers: List[WorkerInfo])
- : Receive = {
- box {
- case ContainersAllocated(containers) =>
- LOG.info(s"ContainersAllocated: containers allocated for workers(remain=$remain), " +
- s"count: " + containers.size)
-
- val count = Math.min(containers.length, remain)
- val newWorkers = (0 until count).toList.map { index =>
- val container = containers(index)
- launchWorker(container, masters)
- WorkerInfo(container.getId, container.getNodeId)
- }
-
- // Stops un-used containers
- containers.drop(count).map { container =>
- nmClient.stopContainer(container.getId, container.getNodeId)
- }
- context.become(startingWorkers(remain, masters, workers ++ newWorkers))
- case ContainerStarted(containerId) =>
- LOG.info(s"ContainerStarted: container $containerId started for worker(remain=$remain)")
- // The last one
- if (remain > 1) {
- context.become(startingWorkers(remain - 1, masters, workers))
- } else {
- if (servicesEnabled && !uiStarted) {
- context.actorOf(uiFactory.props(masters.map(_.host), host, port))
- uiStarted = true
- }
- context.become(service(effectiveConfig(masters.map(_.host)), masters, workers))
- }
- }
- }
-
- private def effectiveConfig(masters: List[HostPort]): Config = {
- val masterList = masters.map(pair => s"${pair.host}:${pair.port}")
- val config = context.system.settings.config
- config.withValue(Constants.GEARPUMP_CLUSTER_MASTERS,
- ConfigValueFactory.fromIterable(masterList.asJava))
- }
-
- private def onError: Receive = {
- case ContainersCompleted(containers) =>
- // TODO: we should recover the failed container from this...
- containers.foreach { status =>
- if (status.getExitStatus != 0) {
- LOG.error(s"ContainersCompleted: container ${status.getContainerId}" +
- s" failed with exit code ${status.getExitStatus}, msg: ${status.getDiagnostics}")
- } else {
- LOG.info(s"ContainersCompleted: container ${status.getContainerId} completed")
- }
- }
- case ShutdownApplication =>
- LOG.error("ShutdownApplication")
- nmClient.stop()
- rmClient.shutdownApplication()
- context.stop(self)
- case ResourceManagerException(ex) =>
- LOG.error("ResourceManagerException: " + ex.getMessage, ex)
- nmClient.stop()
- rmClient.failApplication(ex)
- context.stop(self)
- case Kill =>
- LOG.info("Kill: User asked to shutdown the application")
- sender ! CommandResult(success = true)
- self ! ShutdownApplication
- }
-
- private def service(config: Config, masters: List[MasterInfo], workers: List[WorkerInfo])
- : Receive = box {
- case GetActiveConfig(clientHost) =>
- LOG.info("GetActiveConfig: Get active configuration for client: " + clientHost)
- val filtered = ClusterConfig.filterOutDefaultConfig(
- config.withValue(Constants.GEARPUMP_HOSTNAME,
- ConfigValueFactory.fromAnyRef(clientHost)))
- sender ! ActiveConfig(filtered)
- case QueryVersion =>
- LOG.info("QueryVersion")
- sender ! Version(Util.version)
- case QueryClusterInfo =>
- LOG.info("QueryClusterInfo")
- val masterContainers = masters.map { master =>
- master.id.toString + s"(${master.nodeId.toString})"
- }
-
- val workerContainers = workers.map { worker =>
- worker.id.toString + s"(${worker.nodeId.toString})"
- }
- sender ! ClusterInfo(masterContainers, workerContainers)
- case AddMaster =>
- sender ! CommandResult(success = false, "Not Implemented")
- case RemoveMaster(masterId) =>
- sender ! CommandResult(success = false, "Not Implemented")
- case AddWorker(count) =>
- if (count == 0) {
- sender ! CommandResult(success = true)
- } else {
- LOG.info("AddWorker: Start to add new workers, count: " + count)
- workerCount += count
- requestWorkerContainers(count)
- context.become(startingWorkers(count, masters, workers))
- sender ! CommandResult(success = true)
- }
- case RemoveWorker(worker) =>
- val workerId = ContainerId.fromString(worker)
- LOG.info(s"RemoveWorker: remove worker $workerId")
- val info = workers.find(_.id.toString == workerId.toString)
- if (info.isDefined) {
- nmClient.stopContainer(info.get.id, info.get.nodeId)
- sender ! CommandResult(success = true)
- val remainWorkers = workers.filter(_.id != info.get.id)
- context.become(service(config, masters, remainWorkers))
- } else {
- sender ! CommandResult(success = false, "failed to find worker " + worker)
- }
- }
-
- private def unHandled: Receive = {
- case other =>
- LOG.info(s"Received unknown message $other")
- }
-
- private def requestMasterContainers(masters: Int) = {
- LOG.info(s"Request resource for masters($masters)")
- val containers = (1 to masters).map(
- i => Resource.newInstance(masterMemory, masterVCores)
- ).toList
- rmClient.requestContainers(containers)
- }
-
- private def launchMaster(container: Container): HostPort = {
- LOG.info(s"Launch Master on container " + container.getNodeHttpAddress)
- val host = container.getNodeId.getHost
-
- val port = Util.findFreePort().get
-
- LOG.info("=============PORT" + port)
- val masterCommand = MasterCommand(akkaConf, rootPath, HostPort(host, port))
- nmClient.launchCommand(container, masterCommand.get, packagePath, hdfsConfDir)
- HostPort(host, port)
- }
-
- private def requestWorkerContainers(workers: Int): Unit = {
- LOG.info(s"Request resource for workers($workers)")
- val containers = (1 to workers).map(
- i => Resource.newInstance(workerMemory, workerVCores)
- ).toList
-
- rmClient.requestContainers(containers)
- }
-
- private def launchWorker(container: Container, masters: List[MasterInfo]): Unit = {
- LOG.info(s"Launch Worker on container " + container.getNodeHttpAddress)
- val workerHost = container.getNodeId.getHost
- val workerCommand = WorkerCommand(akkaConf, rootPath, masters.head.host, workerHost)
- nmClient.launchCommand(container, workerCommand.get, packagePath, hdfsConfDir)
- }
-}
-
-object YarnAppMaster extends AkkaApp with ArgumentsParser {
- val LOG: Logger = LogUtil.getLogger(getClass)
-
- override val options: Array[(String, CLIOption[Any])] = Array(
- "conf" -> CLIOption[String]("<Gearpump configuration directory on HDFS>", required = true),
- "package" -> CLIOption[String]("<Gearpump package path on HDFS>", required = true)
- )
-
- override def akkaConfig: Config = {
- ClusterConfig.ui()
- }
-
- override def main(akkaConf: Config, args: Array[String]): Unit = {
- implicit val timeout = Timeout(5, TimeUnit.SECONDS)
- implicit val system = ActorSystem("GearpumpAM", akkaConf)
-
- val yarnConf = new YarnConfig()
-
- val confDir = parse(args).getString("conf")
- val packagePath = parse(args).getString("package")
-
- LOG.info("HADOOP_CONF_DIR: " + System.getenv("HADOOP_CONF_DIR"))
- LOG.info("YARN Resource Manager: " + yarnConf.resourceManager)
-
- val rmClient = new RMClient(yarnConf)
- val nmClient = new NMClient(yarnConf, akkaConf)
- val appMaster = system.actorOf(Props(new YarnAppMaster(rmClient,
- nmClient, packagePath, confDir, UIService)))
-
- val daemon = system.actorOf(Props(new Daemon(appMaster)))
- Await.result(system.whenTerminated, Duration.Inf)
- LOG.info("YarnAppMaster is shutdown")
- }
-
- class Daemon(appMaster: ActorRef) extends Actor {
- context.watch(appMaster)
-
- override def receive: Actor.Receive = {
- case Terminated(actor) =>
- if (actor.compareTo(appMaster) == 0) {
- LOG.info(s"YarnAppMaster ${appMaster.path.toString} is terminated, " +
- s"shutting down current ActorSystem")
- context.system.terminate()
- context.stop(self)
- }
- }
- }
-
- case class ResourceManagerException(throwable: Throwable)
- case object ShutdownApplication
- case class ContainersRequest(containers: List[Resource])
- case class ContainersAllocated(containers: List[Container])
- case class ContainersCompleted(containers: List[ContainerStatus])
- case class ContainerStarted(containerId: ContainerId)
- case object AppMasterRegistered
-
- case class GetActiveConfig(clientHost: String)
-
- case object QueryClusterInfo
- case class ClusterInfo(masters: List[String], workers: List[String]) {
- override def toString: String = {
- val separator = "\n"
- val masterSection = "masters: " + separator + masters.mkString("\n") + "\n"
-
- val workerSection = "workers: " + separator + workers.mkString("\n") + "\n"
- masterSection + workerSection
- }
- }
-
- case object Kill
- case class ActiveConfig(config: Config)
-
- case object QueryVersion
-
- case class Version(version: String)
-
- case class MasterInfo(id: ContainerId, nodeId: NodeId, host: HostPort)
-
- case class WorkerInfo(id: ContainerId, nodeId: NodeId)
-
- def getAppMaster(report: ApplicationReport, system: ActorSystem): ActorRef = {
- val client = new HttpClient()
- val appMasterPath = s"${report.getOriginalTrackingUrl}/supervisor-actor-path"
- val get = new GetMethod(appMasterPath)
- var status = client.executeMethod(get)
-
- if (status != 200) {
- // Sleeps a little bit, and try again
- Thread.sleep(3000)
- status = client.executeMethod(get)
- }
-
- if (status == 200) {
- AkkaHelper.actorFor(system, get.getResponseBodyAsString)
- } else {
- throw new IOException("Fail to resolve AppMaster address, please make sure " +
- s"${report.getOriginalTrackingUrl} is accessible...")
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/client/AppMasterResolver.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/client/AppMasterResolver.scala b/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/client/AppMasterResolver.scala
deleted file mode 100644
index 49ec3a0..0000000
--- a/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/client/AppMasterResolver.scala
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.yarn.client
-
-import java.io.IOException
-import scala.util.Try
-
-import akka.actor.{ActorRef, ActorSystem}
-import org.apache.commons.httpclient.HttpClient
-import org.apache.commons.httpclient.methods.GetMethod
-
-import io.gearpump.experiments.yarn.glue.Records.ApplicationId
-import io.gearpump.experiments.yarn.glue.YarnClient
-import io.gearpump.util.{AkkaHelper, LogUtil}
-
-/**
- * Resolves AppMaster ActorRef
- */
-class AppMasterResolver(yarnClient: YarnClient, system: ActorSystem) {
- val LOG = LogUtil.getLogger(getClass)
- val RETRY_INTERVAL_MS = 3000 // ms
-
- def resolve(appId: ApplicationId, timeoutSeconds: Int = 30): ActorRef = {
- val appMaster = retry(connect(appId), 1 + timeoutSeconds * 1000 / RETRY_INTERVAL_MS)
- appMaster
- }
-
- private def connect(appId: ApplicationId): ActorRef = {
- val report = yarnClient.getApplicationReport(appId)
- val client = new HttpClient()
- val appMasterPath = s"${report.getOriginalTrackingUrl}/supervisor-actor-path"
- LOG.info(s"appMasterPath=$appMasterPath")
- val get = new GetMethod(appMasterPath)
- val status = client.executeMethod(get)
- if (status == 200) {
- val response = get.getResponseBodyAsString
- LOG.info("Successfully resolved AppMaster address: " + response)
- AkkaHelper.actorFor(system, response)
- } else {
- throw new IOException("Fail to resolve AppMaster address, please make sure " +
- s"${report.getOriginalTrackingUrl} is accessible...")
- }
- }
-
- private def retry(fun: => ActorRef, times: Int): ActorRef = {
- var index = 0
- var result: ActorRef = null
- while (index < times && result == null) {
- Thread.sleep(RETRY_INTERVAL_MS)
- index += 1
- val tryConnect = Try(fun)
- if (tryConnect.isFailure) {
- LOG.error(s"Failed to connect YarnAppMaster(tried $index)... " +
- tryConnect.failed.get.getMessage)
- } else {
- result = tryConnect.get
- }
- }
- result
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/client/Client.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/client/Client.scala b/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/client/Client.scala
deleted file mode 100644
index 7c3bc38..0000000
--- a/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/client/Client.scala
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.experiments.yarn.client
-import org.slf4j.Logger
-
-import io.gearpump.util.LogUtil
-
-/** Command line tool to launch a Gearpump cluster on YARN, and also to manage Gearpump cluster */
-object Client {
-
- private val LOG: Logger = LogUtil.getLogger(getClass)
- val LAUNCH = "launch"
-
- val commands = Map(LAUNCH -> LaunchCluster) ++
- ManageCluster.commands.map(key => (key, ManageCluster)).toMap
-
- def usage(): Unit = {
- val keys = commands.keys.toList.sorted
- // scalastyle:off println
- Console.err.println("Usage: " + "<" + keys.mkString("|") + ">")
- // scalastyle:on println
- }
-
- def main(args: Array[String]): Unit = {
- if (args.length == 0) {
- usage()
- } else {
- val key = args(0)
- val command = commands.get(key)
- command match {
- case Some(command) =>
- if (key == LAUNCH) {
- val remainArgs = args.drop(1)
- command.main(remainArgs)
- } else {
- val commandArg = Array("-" + ManageCluster.COMMAND, key)
- val remainArgs = args.drop(1)
- val updatedArgs = commandArg ++ args.drop(1)
- command.main(updatedArgs)
- }
- case None =>
- usage
- }
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/client/LaunchCluster.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/client/LaunchCluster.scala b/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/client/LaunchCluster.scala
deleted file mode 100644
index ea5e707..0000000
--- a/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/client/LaunchCluster.scala
+++ /dev/null
@@ -1,221 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.experiments.yarn.client
-
-import java.io.{File, IOException, OutputStreamWriter}
-import java.net.InetAddress
-import java.util.zip.ZipInputStream
-import scala.concurrent.duration.Duration
-import scala.concurrent.{Await, Future}
-
-import akka.actor.ActorSystem
-import com.typesafe.config.{Config, ConfigValueFactory}
-import org.slf4j.Logger
-
-import io.gearpump.cluster.ClusterConfig
-import io.gearpump.cluster.main.{ArgumentsParser, CLIOption, ParseResult}
-import io.gearpump.experiments.yarn
-import io.gearpump.experiments.yarn.Constants
-import io.gearpump.experiments.yarn.appmaster.AppMasterCommand
-import io.gearpump.experiments.yarn.appmaster.YarnAppMaster.{ActiveConfig, GetActiveConfig}
-import io.gearpump.experiments.yarn.glue.Records.{ApplicationId, Resource}
-import io.gearpump.experiments.yarn.glue.{FileSystem, YarnClient, YarnConfig}
-import io.gearpump.util.ActorUtil.askActor
-import io.gearpump.util.{AkkaApp, LogUtil, Util}
-
-/**
- * Launch Gearpump on YARN
- */
-class LaunchCluster(
- akka: Config,
- yarnConf: YarnConfig,
- yarnClient: YarnClient,
- fs: FileSystem,
- actorSystem: ActorSystem,
- appMasterResolver: AppMasterResolver,
- version: String = Util.version) {
-
- import io.gearpump.experiments.yarn.Constants._
- private implicit val dispatcher = actorSystem.dispatcher
-
- private val LOG: Logger = LogUtil.getLogger(getClass)
- private val host = InetAddress.getLocalHost.getHostName
- private val queue = akka.getString(APPMASTER_QUEUE)
- private val memory = akka.getString(APPMASTER_MEMORY).toInt
- private val vcore = akka.getString(APPMASTER_VCORES).toInt
-
- def submit(appName: String, packagePath: String): ApplicationId = {
- LOG.info("Starting AM")
-
- // First step, check the version, to make sure local version matches remote version
- if (!packagePath.endsWith(".zip")) {
- throw new IOException(s"YarnClient only support .zip distribution package," +
- s" now it is ${packagePath}. Please download the zip " +
- "package from website or use sbt assembly packArchiveZip to build one.")
- }
-
- if (!fs.exists(packagePath)) {
- throw new IOException(s"Cannot find package ${packagePath} on HDFS ${fs.name}. ")
- }
-
- val rootEntry = rootEntryPath(zip = packagePath)
-
- if (!rootEntry.contains(version)) {
- throw new IOException(s"Check version failed! Local gearpump binary" +
- s" version $version doesn't match with remote path $packagePath")
- }
-
- val resource = Resource.newInstance(memory, vcore)
- val appId = yarnClient.createApplication
-
- // uploads the configs to HDFS home directory of current user.
- val configPath = uploadConfigToHDFS(appId)
-
- val command = AppMasterCommand(akka, rootEntry, Array(s"-conf $configPath",
- s"-package $packagePath"))
-
- yarnClient.submit(appName, appId, command.get, resource, queue, packagePath, configPath)
-
- LOG.info("Waiting application to finish...")
- val report = yarnClient.awaitApplication(appId, LaunchCluster.TIMEOUT_MILLISECONDS)
- LOG.info(s"Application $appId finished with state ${report.getYarnApplicationState} " +
- s"at ${report.getFinishTime}, info: ${report.getDiagnostics}")
-
- // scalastyle:off println
- Console.println("================================================")
- Console.println("==Application Id: " + appId)
- // scalastyle:on println
- appId
- }
-
- def saveConfig(appId: ApplicationId, output: String): Future[File] = {
- LOG.info(s"Trying to download active configuration to output path: " + output)
- LOG.info(s"Resolving YarnAppMaster ActorRef for application " + appId)
- val appMaster = appMasterResolver.resolve(appId)
- LOG.info(s"appMaster=${appMaster.path} host=$host")
- val future = askActor[ActiveConfig](appMaster, GetActiveConfig(host)).map(_.config)
- future.map { config =>
- val out = new File(output)
- ClusterConfig.saveConfig(config, out)
- out
- }
- }
-
- private def uploadConfigToHDFS(appId: ApplicationId): String = {
- // Uses personal home directory so that it will not conflict with other users
- // conf path pattern: /user/<userid>/.gearpump_application_<timestamp>_<id>/conf
- val confDir = s"${fs.getHomeDirectory}/.gearpump_${appId}/conf/"
- LOG.info(s"Uploading configuration files to remote HDFS(under $confDir)...")
-
- // Copies config from local to remote.
- val remoteConfFile = s"$confDir/gear.conf"
- var out = fs.create(remoteConfFile)
- var writer = new OutputStreamWriter(out)
-
- val cleanedConfig = ClusterConfig.filterOutDefaultConfig(akka)
-
- writer.write(cleanedConfig.root().render())
- writer.close()
-
- // Saves yarn-site.xml to remote
- val yarn_site_xml = s"$confDir/yarn-site.xml"
- out = fs.create(yarn_site_xml)
- writer = new OutputStreamWriter(out)
- yarnConf.writeXml(writer)
- writer.close()
-
- // Saves log4j.properties to remote
- val log4j_properties = s"$confDir/log4j.properties"
- val log4j = LogUtil.loadConfiguration
- out = fs.create(log4j_properties)
- writer = new OutputStreamWriter(out)
- log4j.store(writer, "gearpump on yarn")
- writer.close()
- confDir.toString
- }
-
- private def rootEntryPath(zip: String): String = {
- val stream = new ZipInputStream(fs.open(zip))
- val entry = stream.getNextEntry()
- val name = entry.getName
- name.substring(0, entry.getName.indexOf("/"))
- }
-}
-
-object LaunchCluster extends AkkaApp with ArgumentsParser {
-
- val PACKAGE = "package"
- val NAME = "name"
- val VERBOSE = "verbose"
- val OUTPUT = "output"
-
- override protected def akkaConfig: Config = {
- ClusterConfig.default()
- }
-
- override val options: Array[(String, CLIOption[Any])] = Array(
- PACKAGE -> CLIOption[String]("<Please specify the gearpump.zip package path on HDFS. " +
- "If not specified, we will use default value /user/gearpump/gearpump.zip>", required = false),
- NAME -> CLIOption[String]("<Application name showed in YARN>", required = false,
- defaultValue = Some("Gearpump")),
- VERBOSE -> CLIOption("<print verbose log on console>", required = false,
- defaultValue = Some(false)),
- OUTPUT -> CLIOption("<output path for configuration file>", required = false,
- defaultValue = None)
- )
- private val TIMEOUT_MILLISECONDS = 30 * 1000
-
- override def main(inputAkkaConf: Config, args: Array[String]): Unit = {
- val parsed = parse(args)
- if (parsed.getBoolean(VERBOSE)) {
- LogUtil.verboseLogToConsole()
- }
-
- val yarnConfig = new YarnConfig()
- val fs = new FileSystem(yarnConfig)
- val yarnClient = new YarnClient(yarnConfig)
- val akkaConf = updateConf(inputAkkaConf, parsed)
- val actorSystem = ActorSystem("launchCluster", akkaConf)
- val appMasterResolver = new AppMasterResolver(yarnClient, actorSystem)
-
- val client = new LaunchCluster(akkaConf, yarnConfig, yarnClient, fs,
- actorSystem, appMasterResolver)
-
- val name = parsed.getString(NAME)
- val appId = client.submit(name, akkaConf.getString(Constants.PACKAGE_PATH))
-
- if (parsed.exists(OUTPUT)) {
- import scala.concurrent.duration._
- Await.result(client.saveConfig(appId, parsed.getString(OUTPUT)),
- TIMEOUT_MILLISECONDS.milliseconds)
- }
-
- yarnClient.stop()
- actorSystem.terminate()
- Await.result(actorSystem.whenTerminated, Duration.Inf)
- }
-
- private def updateConf(akka: Config, parsed: ParseResult): Config = {
- if (parsed.exists(PACKAGE)) {
- akka.withValue(Constants.PACKAGE_PATH,
- ConfigValueFactory.fromAnyRef(parsed.getString(PACKAGE)))
- } else {
- akka
- }
- }
-}
\ No newline at end of file
[49/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
fix GEARPUMP-118 change package name to org.apache
Author: huafengw <fv...@gmail.com>
Closes #14 from huafengw/rename.
Project: http://git-wip-us.apache.org/repos/asf/incubator-gearpump/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-gearpump/commit/83b36ef7
Tree: http://git-wip-us.apache.org/repos/asf/incubator-gearpump/tree/83b36ef7
Diff: http://git-wip-us.apache.org/repos/asf/incubator-gearpump/diff/83b36ef7
Branch: refs/heads/master
Commit: 83b36ef76de786534fe92a6d75149d4d561915f4
Parents: 9bb9ca5
Author: huafengw <fv...@gmail.com>
Authored: Tue May 10 10:41:43 2016 +0800
Committer: manuzhang <ow...@gmail.com>
Committed: Tue May 10 10:41:43 2016 +0800
----------------------------------------------------------------------
conf/gear.conf | 28 +-
conf/log4j.properties | 4 +-
.../netty/ITransportMessageSerializer.java | 31 -
.../gearpump/transport/netty/MessageBatch.java | 152 -----
.../transport/netty/MessageDecoder.java | 104 ----
.../transport/netty/MessageEncoder.java | 34 --
.../netty/NettyRenameThreadFactory.java | 53 --
.../gearpump/transport/netty/TaskMessage.java | 56 --
.../transport/netty/WrappedChannelBuffer.java | 116 ----
.../main/java/io/gearpump/util/AkkaHelper.java | 40 --
.../io/gearpump/util/HadoopFSLogAppender.java | 28 -
.../util/RecreateRollingFileAppender.java | 64 --
.../netty/ITransportMessageSerializer.java | 31 +
.../gearpump/transport/netty/MessageBatch.java | 152 +++++
.../transport/netty/MessageDecoder.java | 104 ++++
.../transport/netty/MessageEncoder.java | 34 ++
.../netty/NettyRenameThreadFactory.java | 53 ++
.../gearpump/transport/netty/TaskMessage.java | 56 ++
.../transport/netty/WrappedChannelBuffer.java | 116 ++++
.../org/apache/gearpump/util/AkkaHelper.java | 40 ++
.../gearpump/util/HadoopFSLogAppender.java | 28 +
.../util/RecreateRollingFileAppender.java | 64 ++
core/src/main/resources/geardefault.conf | 34 +-
core/src/main/resources/log4j.properties | 4 +-
core/src/main/scala/io/gearpump/Message.scala | 32 -
.../io/gearpump/cluster/AppDescription.scala | 145 -----
.../io/gearpump/cluster/ClusterConfig.scala | 184 ------
.../gearpump/cluster/ClusterConfigSource.scala | 63 --
.../io/gearpump/cluster/ClusterMessage.scala | 287 ---------
.../scala/io/gearpump/cluster/UserConfig.scala | 162 ------
.../appmaster/AppMasterRuntimeEnvironment.scala | 195 -------
.../appmaster/AppMasterRuntimeInfo.scala | 38 --
.../cluster/appmaster/ApplicationState.scala | 47 --
.../cluster/appmaster/ExecutorSystem.scala | 43 --
.../appmaster/ExecutorSystemLauncher.scala | 114 ----
.../appmaster/ExecutorSystemScheduler.scala | 190 ------
.../appmaster/MasterConnectionKeeper.scala | 98 ----
.../gearpump/cluster/client/ClientContext.scala | 185 ------
.../gearpump/cluster/client/MasterClient.scala | 81 ---
.../gearpump/cluster/main/ArgumentsParser.scala | 139 -----
.../cluster/master/AppMasterLauncher.scala | 147 -----
.../gearpump/cluster/master/MasterProxy.scala | 134 -----
.../gearpump/cluster/master/MasterSummary.scala | 51 --
.../gearpump/cluster/scheduler/Resource.scala | 80 ---
.../worker/ExecutorProcessLauncher.scala | 56 --
.../io/gearpump/cluster/worker/WorkerId.scala | 63 --
.../gearpump/cluster/worker/WorkerSummary.scala | 47 --
.../io/gearpump/jarstore/JarStoreService.scala | 86 ---
.../io/gearpump/metrics/AkkaReporter.scala | 78 ---
.../scala/io/gearpump/metrics/Counter.scala | 42 --
.../scala/io/gearpump/metrics/Histogram.scala | 43 --
.../io/gearpump/metrics/JvmMetricsSet.scala | 43 --
.../main/scala/io/gearpump/metrics/Meter.scala | 44 --
.../scala/io/gearpump/metrics/Metrics.scala | 160 -----
.../io/gearpump/metrics/MetricsAggregator.scala | 32 -
.../metrics/MetricsReporterService.scala | 109 ----
core/src/main/scala/io/gearpump/package.scala | 24 -
.../partitioner/BroadcastPartitioner.scala | 36 --
.../partitioner/CoLocationPartitioner.scala | 31 -
.../gearpump/partitioner/HashPartitioner.scala | 32 -
.../io/gearpump/partitioner/Partitioner.scala | 109 ----
.../ShuffleGroupingPartitioner.scala | 45 --
.../partitioner/ShufflePartitioner.scala | 44 --
.../io/gearpump/security/Authenticator.scala | 68 ---
.../security/ConfigFileBasedAuthenticator.scala | 120 ----
.../io/gearpump/security/PasswordUtil.scala | 101 ----
.../FastKryoSerializationFramework.scala | 46 --
.../serializer/FastKryoSerializer.scala | 83 ---
.../serializer/GearpumpSerialization.scala | 60 --
.../serializer/SerializationFramework.scala | 47 --
.../io/gearpump/serializer/Serializer.scala | 28 -
.../scala/io/gearpump/transport/Express.scala | 135 -----
.../scala/io/gearpump/transport/HostPort.scala | 32 -
.../io/gearpump/transport/netty/Client.scala | 248 --------
.../io/gearpump/transport/netty/Context.scala | 113 ----
.../io/gearpump/transport/netty/IContext.scala | 41 --
.../gearpump/transport/netty/NettyConfig.scala | 39 --
.../io/gearpump/transport/netty/NettyUtil.scala | 67 ---
.../io/gearpump/transport/netty/Server.scala | 134 -----
.../io/gearpump/util/ActorSystemBooter.scala | 152 -----
.../main/scala/io/gearpump/util/ActorUtil.scala | 130 -----
.../main/scala/io/gearpump/util/AkkaApp.scala | 45 --
.../main/scala/io/gearpump/util/Constants.scala | 177 ------
.../main/scala/io/gearpump/util/FileUtils.scala | 53 --
.../src/main/scala/io/gearpump/util/Graph.scala | 497 ----------------
.../gearpump/util/HistoryMetricsService.scala | 404 -------------
.../main/scala/io/gearpump/util/LogUtil.scala | 125 ----
.../io/gearpump/util/ProcessLogRedirector.scala | 53 --
.../scala/io/gearpump/util/ReferenceEqual.scala | 33 --
.../scala/io/gearpump/util/RestartPolicy.scala | 41 --
.../scala/io/gearpump/util/RichProcess.scala | 33 --
.../io/gearpump/util/TimeOutScheduler.scala | 43 --
core/src/main/scala/io/gearpump/util/Util.scala | 181 ------
.../scala/org/apache/gearpump/Message.scala | 32 +
.../gearpump/cluster/AppDescription.scala | 145 +++++
.../apache/gearpump/cluster/ClusterConfig.scala | 180 ++++++
.../gearpump/cluster/ClusterConfigSource.scala | 63 ++
.../gearpump/cluster/ClusterMessage.scala | 288 +++++++++
.../apache/gearpump/cluster/UserConfig.scala | 162 ++++++
.../appmaster/AppMasterRuntimeEnvironment.scala | 195 +++++++
.../appmaster/AppMasterRuntimeInfo.scala | 38 ++
.../cluster/appmaster/ApplicationState.scala | 47 ++
.../cluster/appmaster/ExecutorSystem.scala | 43 ++
.../appmaster/ExecutorSystemLauncher.scala | 114 ++++
.../appmaster/ExecutorSystemScheduler.scala | 191 ++++++
.../appmaster/MasterConnectionKeeper.scala | 98 ++++
.../gearpump/cluster/client/ClientContext.scala | 185 ++++++
.../gearpump/cluster/client/MasterClient.scala | 81 +++
.../gearpump/cluster/main/ArgumentsParser.scala | 139 +++++
.../cluster/master/AppMasterLauncher.scala | 148 +++++
.../gearpump/cluster/master/MasterProxy.scala | 134 +++++
.../gearpump/cluster/master/MasterSummary.scala | 51 ++
.../gearpump/cluster/scheduler/Resource.scala | 79 +++
.../worker/ExecutorProcessLauncher.scala | 56 ++
.../gearpump/cluster/worker/WorkerId.scala | 63 ++
.../gearpump/cluster/worker/WorkerSummary.scala | 47 ++
.../gearpump/jarstore/JarStoreService.scala | 86 +++
.../apache/gearpump/metrics/AkkaReporter.scala | 78 +++
.../org/apache/gearpump/metrics/Counter.scala | 42 ++
.../org/apache/gearpump/metrics/Histogram.scala | 43 ++
.../apache/gearpump/metrics/JvmMetricsSet.scala | 43 ++
.../org/apache/gearpump/metrics/Meter.scala | 44 ++
.../org/apache/gearpump/metrics/Metrics.scala | 160 +++++
.../gearpump/metrics/MetricsAggregator.scala | 32 +
.../metrics/MetricsReporterService.scala | 109 ++++
.../scala/org/apache/gearpump/package.scala | 24 +
.../partitioner/BroadcastPartitioner.scala | 36 ++
.../partitioner/CoLocationPartitioner.scala | 31 +
.../gearpump/partitioner/HashPartitioner.scala | 32 +
.../gearpump/partitioner/Partitioner.scala | 109 ++++
.../ShuffleGroupingPartitioner.scala | 45 ++
.../partitioner/ShufflePartitioner.scala | 44 ++
.../gearpump/security/Authenticator.scala | 68 +++
.../security/ConfigFileBasedAuthenticator.scala | 120 ++++
.../apache/gearpump/security/PasswordUtil.scala | 102 ++++
.../FastKryoSerializationFramework.scala | 46 ++
.../serializer/FastKryoSerializer.scala | 83 +++
.../serializer/GearpumpSerialization.scala | 60 ++
.../serializer/SerializationFramework.scala | 44 ++
.../apache/gearpump/serializer/Serializer.scala | 28 +
.../org/apache/gearpump/transport/Express.scala | 135 +++++
.../apache/gearpump/transport/HostPort.scala | 32 +
.../gearpump/transport/netty/Client.scala | 249 ++++++++
.../gearpump/transport/netty/Context.scala | 114 ++++
.../gearpump/transport/netty/IContext.scala | 41 ++
.../gearpump/transport/netty/NettyConfig.scala | 39 ++
.../gearpump/transport/netty/NettyUtil.scala | 67 +++
.../gearpump/transport/netty/Server.scala | 135 +++++
.../gearpump/util/ActorSystemBooter.scala | 152 +++++
.../org/apache/gearpump/util/ActorUtil.scala | 131 +++++
.../org/apache/gearpump/util/AkkaApp.scala | 45 ++
.../org/apache/gearpump/util/Constants.scala | 177 ++++++
.../org/apache/gearpump/util/FileUtils.scala | 53 ++
.../scala/org/apache/gearpump/util/Graph.scala | 496 ++++++++++++++++
.../gearpump/util/HistoryMetricsService.scala | 404 +++++++++++++
.../org/apache/gearpump/util/LogUtil.scala | 125 ++++
.../gearpump/util/ProcessLogRedirector.scala | 53 ++
.../apache/gearpump/util/ReferenceEqual.scala | 33 ++
.../apache/gearpump/util/RestartPolicy.scala | 41 ++
.../org/apache/gearpump/util/RichProcess.scala | 33 ++
.../apache/gearpump/util/TimeOutScheduler.scala | 43 ++
.../scala/org/apache/gearpump/util/Util.scala | 181 ++++++
core/src/test/resources/log4j.properties | 4 +-
core/src/test/resources/test.conf | 6 +-
.../test/scala/io/gearpump/TestProbeUtil.scala | 37 --
.../io/gearpump/cluster/MasterHarness.scala | 160 -----
.../scala/io/gearpump/cluster/TestUtil.scala | 36 --
.../AppMasterRuntimeEnvironmentSpec.scala | 140 -----
.../appmaster/ExecutorSystemLauncherSpec.scala | 105 ----
.../appmaster/ExecutorSystemSchedulerSpec.scala | 140 -----
.../appmaster/MasterConnectionKeeperSpec.scala | 118 ----
.../cluster/main/ArgumentParserSpec.scala | 63 --
.../cluster/master/AppMasterLauncherSpec.scala | 100 ----
.../cluster/master/ApplicationStateSpec.scala | 36 --
.../cluster/master/MasterProxySpec.scala | 24 -
.../io/gearpump/cluster/master/MasterSpec.scala | 22 -
.../scala/io/gearpump/metrics/MetricsSpec.scala | 122 ----
.../gearpump/partitioner/PartitionerSpec.scala | 55 --
.../ConfigFileBasedAuthenticatorSpec.scala | 54 --
.../io/gearpump/security/PasswordUtilSpec.scala | 38 --
.../io/gearpump/serializer/SerializerSpec.scala | 91 ---
.../transport/MockTransportSerializer.scala | 43 --
.../scala/io/gearpump/transport/NettySpec.scala | 62 --
.../gearpump/util/ActorSystemBooterSpec.scala | 118 ----
.../scala/io/gearpump/util/ActorUtilSpec.scala | 40 --
.../scala/io/gearpump/util/ConfigsSpec.scala | 99 ----
.../scala/io/gearpump/util/FileUtilsSpec.scala | 62 --
.../test/scala/io/gearpump/util/GraphSpec.scala | 213 -------
.../io/gearpump/util/TimeOutSchedulerSpec.scala | 75 ---
.../test/scala/io/gearpump/util/UtilSpec.scala | 46 --
.../org/apache/gearpump/TestProbeUtil.scala | 37 ++
.../apache/gearpump/cluster/MasterHarness.scala | 160 +++++
.../org/apache/gearpump/cluster/TestUtil.scala | 36 ++
.../AppMasterRuntimeEnvironmentSpec.scala | 140 +++++
.../appmaster/ExecutorSystemLauncherSpec.scala | 106 ++++
.../appmaster/ExecutorSystemSchedulerSpec.scala | 141 +++++
.../appmaster/MasterConnectionKeeperSpec.scala | 118 ++++
.../cluster/main/ArgumentParserSpec.scala | 63 ++
.../cluster/master/AppMasterLauncherSpec.scala | 101 ++++
.../cluster/master/ApplicationStateSpec.scala | 36 ++
.../cluster/master/MasterProxySpec.scala | 24 +
.../gearpump/cluster/master/MasterSpec.scala | 22 +
.../apache/gearpump/metrics/MetricsSpec.scala | 122 ++++
.../gearpump/partitioner/PartitionerSpec.scala | 55 ++
.../ConfigFileBasedAuthenticatorSpec.scala | 54 ++
.../gearpump/security/PasswordUtilSpec.scala | 38 ++
.../gearpump/serializer/SerializerSpec.scala | 91 +++
.../transport/MockTransportSerializer.scala | 42 ++
.../apache/gearpump/transport/NettySpec.scala | 63 ++
.../gearpump/util/ActorSystemBooterSpec.scala | 118 ++++
.../apache/gearpump/util/ActorUtilSpec.scala | 40 ++
.../org/apache/gearpump/util/ConfigsSpec.scala | 99 ++++
.../apache/gearpump/util/FileUtilsSpec.scala | 62 ++
.../org/apache/gearpump/util/GraphSpec.scala | 213 +++++++
.../gearpump/util/TimeOutSchedulerSpec.scala | 75 +++
.../org/apache/gearpump/util/UtilSpec.scala | 46 ++
.../io.gearpump.jarstore.JarStoreService | 20 -
...org.apache.gearpump.jarstore.JarStoreService | 20 +
.../io/gearpump/cluster/DaemonMessage.scala | 51 --
.../cluster/embedded/EmbeddedCluster.scala | 95 ---
.../io/gearpump/cluster/main/AppSubmitter.scala | 106 ----
.../scala/io/gearpump/cluster/main/Gear.scala | 81 ---
.../scala/io/gearpump/cluster/main/Info.scala | 53 --
.../scala/io/gearpump/cluster/main/Kill.scala | 50 --
.../scala/io/gearpump/cluster/main/Local.scala | 90 ---
.../io/gearpump/cluster/main/MainRunner.scala | 43 --
.../scala/io/gearpump/cluster/main/Master.scala | 236 --------
.../scala/io/gearpump/cluster/main/Replay.scala | 48 --
.../scala/io/gearpump/cluster/main/Worker.scala | 71 ---
.../io/gearpump/cluster/master/AppManager.scala | 341 -----------
.../cluster/master/InMemoryKVService.scala | 122 ----
.../io/gearpump/cluster/master/Master.scala | 313 ----------
.../cluster/scheduler/PriorityScheduler.scala | 155 -----
.../gearpump/cluster/scheduler/Scheduler.scala | 78 ---
.../worker/DefaultExecutorProcessLauncher.scala | 41 --
.../io/gearpump/cluster/worker/Worker.scala | 580 ------------------
.../jarstore/dfs/DFSJarStoreService.scala | 76 ---
.../gearpump/jarstore/local/LocalJarStore.scala | 64 --
.../jarstore/local/LocalJarStoreService.scala | 81 ---
.../scala/io/gearpump/util/FileDirective.scala | 140 -----
.../scala/io/gearpump/util/FileServer.scala | 167 ------
.../apache/gearpump/cluster/DaemonMessage.scala | 51 ++
.../cluster/embedded/EmbeddedCluster.scala | 95 +++
.../gearpump/cluster/main/AppSubmitter.scala | 106 ++++
.../org/apache/gearpump/cluster/main/Gear.scala | 81 +++
.../org/apache/gearpump/cluster/main/Info.scala | 53 ++
.../org/apache/gearpump/cluster/main/Kill.scala | 50 ++
.../apache/gearpump/cluster/main/Local.scala | 90 +++
.../gearpump/cluster/main/MainRunner.scala | 43 ++
.../apache/gearpump/cluster/main/Master.scala | 236 ++++++++
.../apache/gearpump/cluster/main/Replay.scala | 48 ++
.../apache/gearpump/cluster/main/Worker.scala | 71 +++
.../gearpump/cluster/master/AppManager.scala | 341 +++++++++++
.../cluster/master/InMemoryKVService.scala | 122 ++++
.../apache/gearpump/cluster/master/Master.scala | 314 ++++++++++
.../cluster/scheduler/PriorityScheduler.scala | 156 +++++
.../gearpump/cluster/scheduler/Scheduler.scala | 79 +++
.../worker/DefaultExecutorProcessLauncher.scala | 41 ++
.../apache/gearpump/cluster/worker/Worker.scala | 581 +++++++++++++++++++
.../jarstore/dfs/DFSJarStoreService.scala | 76 +++
.../gearpump/jarstore/local/LocalJarStore.scala | 64 ++
.../jarstore/local/LocalJarStoreService.scala | 81 +++
.../apache/gearpump/util/FileDirective.scala | 140 +++++
.../org/apache/gearpump/util/FileServer.scala | 167 ++++++
.../io.gearpump.jarstore.JarStoreService | 20 -
...org.apache.gearpump.jarstore.JarStoreService | 20 +
.../scala/io/gearpump/cluster/MiniCluster.scala | 74 ---
.../io/gearpump/cluster/main/MainSpec.scala | 189 ------
.../cluster/main/MasterWatcherSpec.scala | 44 --
.../cluster/master/AppManagerSpec.scala | 181 ------
.../cluster/master/InMemoryKVServiceSpec.scala | 69 ---
.../scheduler/PrioritySchedulerSpec.scala | 231 --------
.../io/gearpump/cluster/worker/WorkerSpec.scala | 129 ----
.../scala/io/gearpump/util/FileServerSpec.scala | 120 ----
.../apache/gearpump/cluster/MiniCluster.scala | 74 +++
.../apache/gearpump/cluster/main/MainSpec.scala | 189 ++++++
.../cluster/main/MasterWatcherSpec.scala | 44 ++
.../cluster/master/AppManagerSpec.scala | 181 ++++++
.../cluster/master/InMemoryKVServiceSpec.scala | 69 +++
.../scheduler/PrioritySchedulerSpec.scala | 232 ++++++++
.../gearpump/cluster/worker/WorkerSpec.scala | 129 ++++
.../apache/gearpump/util/FileServerSpec.scala | 120 ++++
docs/deployment-configuration.md | 4 +-
docs/deployment-resource-isolation.md | 2 +-
docs/deployment-ui-authentication.md | 10 +-
docs/dev-connectors.md | 6 +-
docs/dev-custom-serializer.md | 26 +-
docs/dev-non-streaming-example.md | 2 +-
docs/dev-rest-api.md | 100 ++--
docs/dev-write-1st-app.md | 6 +-
docs/submit-your-1st-application.md | 2 +-
examples/distributedshell/README.md | 4 +-
.../distributedshell/DistShellAppMaster.scala | 95 ---
.../distributedshell/DistributedShell.scala | 41 --
.../DistributedShellClient.scala | 57 --
.../distributedshell/ShellExecutor.scala | 47 --
.../distributedshell/DistShellAppMaster.scala | 95 +++
.../distributedshell/DistributedShell.scala | 41 ++
.../DistributedShellClient.scala | 57 ++
.../distributedshell/ShellExecutor.scala | 47 ++
.../DistShellAppMasterSpec.scala | 78 ---
.../DistributedShellClientSpec.scala | 66 ---
.../distributedshell/DistributedShellSpec.scala | 56 --
.../ShellCommandResultAggregatorSpec.scala | 38 --
.../distributedshell/ShellExecutorSpec.scala | 66 ---
.../DistShellAppMasterSpec.scala | 78 +++
.../DistributedShellClientSpec.scala | 66 +++
.../distributedshell/DistributedShellSpec.scala | 56 ++
.../ShellCommandResultAggregatorSpec.scala | 38 ++
.../distributedshell/ShellExecutorSpec.scala | 66 +++
examples/distributeservice/README.md | 4 +-
.../DistServiceAppMaster.scala | 100 ----
.../distributeservice/DistServiceExecutor.scala | 89 ---
.../distributeservice/DistributeService.scala | 41 --
.../DistributeServiceClient.scala | 90 ---
.../distributeservice/FileServer.scala | 138 -----
.../DistServiceAppMaster.scala | 100 ++++
.../distributeservice/DistServiceExecutor.scala | 89 +++
.../distributeservice/DistributeService.scala | 41 ++
.../DistributeServiceClient.scala | 90 +++
.../distributeservice/FileServer.scala | 138 +++++
.../DistServiceAppMasterSpec.scala | 87 ---
.../DistServiceAppMasterSpec.scala | 87 +++
examples/pagerank/README.md | 2 +-
.../src/main/resources/geardefault.conf | 6 +-
.../pagerank/PageRankApplication.scala | 77 ---
.../pagerank/PageRankController.scala | 79 ---
.../experiments/pagerank/PageRankWorker.scala | 83 ---
.../pagerank/example/PageRankExample.scala | 42 --
.../pagerank/PageRankApplication.scala | 77 +++
.../pagerank/PageRankController.scala | 79 +++
.../experiments/pagerank/PageRankWorker.scala | 83 +++
.../pagerank/example/PageRankExample.scala | 42 ++
.../streaming/examples/complexdag/Dag.scala | 113 ----
.../streaming/examples/complexdag/Node.scala | 34 --
.../streaming/examples/complexdag/Sink.scala | 45 --
.../streaming/examples/complexdag/Source.scala | 38 --
.../streaming/examples/complexdag/Dag.scala | 113 ++++
.../streaming/examples/complexdag/Node.scala | 34 ++
.../streaming/examples/complexdag/Sink.scala | 45 ++
.../streaming/examples/complexdag/Source.scala | 38 ++
.../streaming/examples/complexdag/DagSpec.scala | 56 --
.../examples/complexdag/NodeSpec.scala | 42 --
.../examples/complexdag/SinkSpec.scala | 43 --
.../examples/complexdag/SourceSpec.scala | 45 --
.../streaming/examples/complexdag/DagSpec.scala | 55 ++
.../examples/complexdag/NodeSpec.scala | 41 ++
.../examples/complexdag/SinkSpec.scala | 43 ++
.../examples/complexdag/SourceSpec.scala | 44 ++
examples/streaming/fsio/README.md | 2 +-
.../streaming/examples/fsio/HadoopConfig.scala | 61 --
.../examples/fsio/SeqFileStreamProcessor.scala | 96 ---
.../examples/fsio/SeqFileStreamProducer.scala | 68 ---
.../examples/fsio/SequenceFileIO.scala | 67 ---
.../streaming/examples/fsio/HadoopConfig.scala | 61 ++
.../examples/fsio/SeqFileStreamProcessor.scala | 96 +++
.../examples/fsio/SeqFileStreamProducer.scala | 68 +++
.../examples/fsio/SequenceFileIO.scala | 67 +++
.../examples/fsio/HadoopConfigSpec.scala | 40 --
.../fsio/SeqFileStreamProcessorSpec.scala | 94 ---
.../fsio/SeqFileStreamProducerSpec.scala | 87 ---
.../examples/fsio/SequenceFileIOSpec.scala | 83 ---
.../examples/fsio/HadoopConfigSpec.scala | 40 ++
.../fsio/SeqFileStreamProcessorSpec.scala | 94 +++
.../fsio/SeqFileStreamProducerSpec.scala | 87 +++
.../examples/fsio/SequenceFileIOSpec.scala | 83 +++
examples/streaming/kafka/README.md | 2 +-
.../examples/kafka/KafkaReadWrite.scala | 80 ---
.../kafka/wordcount/KafkaWordCount.scala | 79 ---
.../examples/kafka/wordcount/Split.scala | 38 --
.../examples/kafka/wordcount/Sum.scala | 43 --
.../examples/kafka/KafkaReadWrite.scala | 80 +++
.../kafka/wordcount/KafkaWordCount.scala | 79 +++
.../examples/kafka/wordcount/Split.scala | 38 ++
.../examples/kafka/wordcount/Sum.scala | 43 ++
.../kafka/wordcount/KafkaWordCountSpec.scala | 71 ---
.../examples/kafka/wordcount/SplitSpec.scala | 40 --
.../examples/kafka/wordcount/SumSpec.scala | 58 --
.../kafka/wordcount/KafkaWordCountSpec.scala | 71 +++
.../examples/kafka/wordcount/SplitSpec.scala | 40 ++
.../examples/kafka/wordcount/SumSpec.scala | 58 ++
examples/streaming/sol/README.md | 2 +-
.../gearpump/streaming/examples/sol/SOL.scala | 68 ---
.../examples/sol/SOLStreamProcessor.scala | 66 ---
.../examples/sol/SOLStreamProducer.scala | 78 ---
.../gearpump/streaming/examples/sol/SOL.scala | 68 +++
.../examples/sol/SOLStreamProcessor.scala | 66 +++
.../examples/sol/SOLStreamProducer.scala | 78 +++
.../streaming/examples/sol/SOLSpec.scala | 70 ---
.../examples/sol/SOLStreamProcessorSpec.scala | 42 --
.../examples/sol/SOLStreamProducerSpec.scala | 43 --
.../streaming/examples/sol/SOLSpec.scala | 70 +++
.../examples/sol/SOLStreamProcessorSpec.scala | 42 ++
.../examples/sol/SOLStreamProducerSpec.scala | 43 ++
.../state/src/main/resources/state.conf | 2 +-
.../examples/state/MessageCountApp.scala | 100 ----
.../examples/state/WindowAverageApp.scala | 72 ---
.../state/processor/CountProcessor.scala | 41 --
.../processor/NumberGeneratorProcessor.scala | 42 --
.../processor/WindowAverageProcessor.scala | 54 --
.../examples/state/MessageCountApp.scala | 100 ++++
.../examples/state/WindowAverageApp.scala | 72 +++
.../state/processor/CountProcessor.scala | 41 ++
.../processor/NumberGeneratorProcessor.scala | 42 ++
.../processor/WindowAverageProcessor.scala | 54 ++
.../examples/state/MessageCountAppSpec.scala | 79 ---
.../examples/state/WindowAverageAppSpec.scala | 76 ---
.../state/processor/CountProcessorSpec.scala | 84 ---
.../NumberGeneratorProcessorSpec.scala | 61 --
.../processor/WindowAverageProcessorSpec.scala | 86 ---
.../examples/state/MessageCountAppSpec.scala | 79 +++
.../examples/state/WindowAverageAppSpec.scala | 76 +++
.../state/processor/CountProcessorSpec.scala | 84 +++
.../NumberGeneratorProcessorSpec.scala | 61 ++
.../processor/WindowAverageProcessorSpec.scala | 86 +++
examples/streaming/stockcrawler/README.md | 4 +-
.../src/main/resources/geardefault.conf | 2 +-
.../streaming/examples/stock/Analyzer.scala | 170 ------
.../streaming/examples/stock/Crawler.scala | 60 --
.../streaming/examples/stock/Data.scala | 61 --
.../streaming/examples/stock/QueryServer.scala | 134 -----
.../streaming/examples/stock/StockMarket.scala | 155 -----
.../streaming/examples/stock/main/Stock.scala | 86 ---
.../streaming/examples/stock/Analyzer.scala | 170 ++++++
.../streaming/examples/stock/Crawler.scala | 60 ++
.../streaming/examples/stock/Data.scala | 61 ++
.../streaming/examples/stock/QueryServer.scala | 134 +++++
.../streaming/examples/stock/StockMarket.scala | 155 +++++
.../streaming/examples/stock/main/Stock.scala | 86 +++
.../src/main/resources/geardefault.conf | 4 +-
.../streaming/examples/transport/Data.scala | 32 -
.../examples/transport/DataSource.scala | 56 --
.../examples/transport/QueryServer.scala | 154 -----
.../examples/transport/Transport.scala | 69 ---
.../examples/transport/VelocityInspector.scala | 123 ----
.../examples/transport/generator/MockCity.scala | 88 ---
.../generator/PassRecordGenerator.scala | 69 ---
.../streaming/examples/transport/Data.scala | 32 +
.../examples/transport/DataSource.scala | 56 ++
.../examples/transport/QueryServer.scala | 154 +++++
.../examples/transport/Transport.scala | 69 +++
.../examples/transport/VelocityInspector.scala | 123 ++++
.../examples/transport/generator/MockCity.scala | 88 +++
.../generator/PassRecordGenerator.scala | 69 +++
.../examples/transport/DataSourceSpec.scala | 45 --
.../examples/transport/TransportSpec.scala | 69 ---
.../transport/generator/MockCitySpec.scala | 31 -
.../generator/PassRecordGeneratorSpec.scala | 34 --
.../examples/transport/DataSourceSpec.scala | 45 ++
.../examples/transport/TransportSpec.scala | 69 +++
.../transport/generator/MockCitySpec.scala | 31 +
.../generator/PassRecordGeneratorSpec.scala | 34 ++
.../streaming/examples/wordcountjava/Split.java | 54 --
.../streaming/examples/wordcountjava/Sum.java | 54 --
.../examples/wordcountjava/WordCount.java | 91 ---
.../examples/wordcountjava/dsl/WordCount.java | 84 ---
.../streaming/examples/wordcountjava/Split.java | 54 ++
.../streaming/examples/wordcountjava/Sum.java | 54 ++
.../examples/wordcountjava/WordCount.java | 91 +++
.../examples/wordcountjava/dsl/WordCount.java | 85 +++
.../examples/wordcountjava/WordCountSpec.scala | 59 --
.../examples/wordcountjava/WordCountSpec.scala | 59 ++
.../streaming/examples/wordcount/Split.scala | 66 ---
.../streaming/examples/wordcount/Sum.scala | 66 ---
.../examples/wordcount/WordCount.scala | 86 ---
.../examples/wordcount/dsl/WordCount.scala | 45 --
.../streaming/examples/wordcount/Split.scala | 66 +++
.../streaming/examples/wordcount/Sum.scala | 66 +++
.../examples/wordcount/WordCount.scala | 86 +++
.../examples/wordcount/dsl/WordCount.scala | 45 ++
.../examples/wordcount/SplitSpec.scala | 62 --
.../streaming/examples/wordcount/SumSpec.scala | 56 --
.../examples/wordcount/WordCountSpec.scala | 69 ---
.../examples/wordcount/SplitSpec.scala | 62 ++
.../streaming/examples/wordcount/SumSpec.scala | 56 ++
.../examples/wordcount/WordCountSpec.scala | 69 +++
.../main/scala/akka/stream/ModuleGraph.scala | 4 +-
.../akka/stream/gearpump/example/Test3.scala | 2 +-
.../akka/stream/gearpump/example/Test4.scala | 2 +-
.../akka/stream/gearpump/example/Test6.scala | 2 +-
.../stream/gearpump/example/WikipediaApp.scala | 4 +-
.../stream/gearpump/graph/GraphCutter.scala | 2 +-
.../akka/stream/gearpump/graph/LocalGraph.scala | 2 +-
.../stream/gearpump/graph/RemoteGraph.scala | 8 +-
.../akka/stream/gearpump/graph/SubGraph.scala | 2 +-
.../materializer/LocalMaterializer.scala | 2 +-
.../materializer/LocalMaterializerImpl.scala | 2 +-
.../materializer/RemoteMaterializerImpl.scala | 10 +-
.../gearpump/module/GearpumpTaskModule.scala | 8 +-
.../akka/stream/gearpump/scaladsl/Api.scala | 12 +-
.../akka/stream/gearpump/task/BalanceTask.scala | 6 +-
.../stream/gearpump/task/BroadcastTask.scala | 6 +-
.../akka/stream/gearpump/task/GraphTask.scala | 8 +-
.../stream/gearpump/task/SinkBridgeTask.scala | 14 +-
.../stream/gearpump/task/SourceBridgeTask.scala | 12 +-
.../akka/stream/gearpump/task/UnZip2Task.scala | 6 +-
.../gearpump/cluster/cgroup/CGroupResource.java | 68 ---
.../gearpump/cluster/cgroup/CgroupCenter.java | 212 -------
.../gearpump/cluster/cgroup/CgroupCommon.java | 220 -------
.../cluster/cgroup/CgroupCommonOperation.java | 46 --
.../cluster/cgroup/CgroupCoreFactory.java | 42 --
.../cluster/cgroup/CgroupOperation.java | 43 --
.../io/gearpump/cluster/cgroup/CgroupUtils.java | 160 -----
.../io/gearpump/cluster/cgroup/Constants.java | 29 -
.../io/gearpump/cluster/cgroup/Hierarchy.java | 106 ----
.../gearpump/cluster/cgroup/ResourceType.java | 30 -
.../cluster/cgroup/core/CgroupCore.java | 25 -
.../gearpump/cluster/cgroup/core/CpuCore.java | 59 --
.../gearpump/cluster/utils/SystemOperation.java | 63 --
.../gearpump/cluster/cgroup/CGroupResource.java | 68 +++
.../gearpump/cluster/cgroup/CgroupCenter.java | 212 +++++++
.../gearpump/cluster/cgroup/CgroupCommon.java | 220 +++++++
.../cluster/cgroup/CgroupCommonOperation.java | 46 ++
.../cluster/cgroup/CgroupCoreFactory.java | 42 ++
.../cluster/cgroup/CgroupOperation.java | 43 ++
.../gearpump/cluster/cgroup/CgroupUtils.java | 160 +++++
.../gearpump/cluster/cgroup/Constants.java | 29 +
.../gearpump/cluster/cgroup/Hierarchy.java | 106 ++++
.../gearpump/cluster/cgroup/ResourceType.java | 30 +
.../cluster/cgroup/core/CgroupCore.java | 25 +
.../gearpump/cluster/cgroup/core/CpuCore.java | 59 ++
.../gearpump/cluster/utils/SystemOperation.java | 63 ++
.../gearpump/cluster/worker/CGroupManager.scala | 125 ----
.../cluster/worker/CGroupProcessLauncher.scala | 63 --
.../gearpump/cluster/worker/CGroupManager.scala | 125 ++++
.../cluster/worker/CGroupProcessLauncher.scala | 63 ++
.../storm/util/TimeCacheMapWrapper.java | 42 --
.../storm/util/TimeCacheMapWrapper.java | 42 ++
.../storm/src/main/resources/geardefault.conf | 2 +-
.../experiments/storm/StormRunner.scala | 55 --
.../experiments/storm/main/GearpumpNimbus.scala | 289 ---------
.../storm/main/GearpumpStormClient.scala | 74 ---
.../storm/partitioner/StormPartitioner.scala | 48 --
.../processor/StormBoltOutputCollector.scala | 76 ---
.../storm/processor/StormProcessor.scala | 71 ---
.../storm/producer/StormProducer.scala | 91 ---
.../producer/StormSpoutOutputCollector.scala | 105 ----
.../storm/topology/GearpumpStormComponent.scala | 388 -------------
.../storm/topology/GearpumpStormTopology.scala | 321 ----------
.../storm/topology/GearpumpTuple.scala | 69 ---
.../experiments/storm/util/GraphBuilder.scala | 46 --
.../experiments/storm/util/Grouper.scala | 142 -----
.../experiments/storm/util/StormConstants.scala | 33 --
.../storm/util/StormOutputCollector.scala | 221 -------
.../util/StormSerializationFramework.scala | 82 ---
.../experiments/storm/util/StormUtil.scala | 136 -----
.../experiments/storm/StormRunner.scala | 54 ++
.../experiments/storm/main/GearpumpNimbus.scala | 289 +++++++++
.../storm/main/GearpumpStormClient.scala | 73 +++
.../storm/partitioner/StormPartitioner.scala | 49 ++
.../processor/StormBoltOutputCollector.scala | 75 +++
.../storm/processor/StormProcessor.scala | 71 +++
.../storm/producer/StormProducer.scala | 91 +++
.../producer/StormSpoutOutputCollector.scala | 104 ++++
.../storm/topology/GearpumpStormComponent.scala | 385 ++++++++++++
.../storm/topology/GearpumpStormTopology.scala | 320 ++++++++++
.../storm/topology/GearpumpTuple.scala | 69 +++
.../experiments/storm/util/GraphBuilder.scala | 46 ++
.../experiments/storm/util/Grouper.scala | 142 +++++
.../experiments/storm/util/StormConstants.scala | 33 ++
.../storm/util/StormOutputCollector.scala | 221 +++++++
.../util/StormSerializationFramework.scala | 82 +++
.../experiments/storm/util/StormUtil.scala | 136 +++++
.../partitioner/StormPartitionerSpec.scala | 67 ---
.../StormBoltOutputCollectorSpec.scala | 56 --
.../storm/processor/StormProcessorSpec.scala | 66 ---
.../storm/producer/StormProducerSpec.scala | 73 ---
.../StormSpoutOutputCollectorSpec.scala | 50 --
.../topology/GearpumpStormComponentSpec.scala | 125 ----
.../topology/GearpumpStormTopologySpec.scala | 104 ----
.../storm/topology/GearpumpTupleSpec.scala | 63 --
.../storm/util/GraphBuilderSpec.scala | 55 --
.../experiments/storm/util/GrouperSpec.scala | 131 -----
.../storm/util/StormOutputCollectorSpec.scala | 109 ----
.../storm/util/StormSerializerPoolSpec.scala | 63 --
.../experiments/storm/util/StormUtilSpec.scala | 157 -----
.../experiments/storm/util/TopologyUtil.scala | 41 --
.../partitioner/StormPartitionerSpec.scala | 67 +++
.../StormBoltOutputCollectorSpec.scala | 56 ++
.../storm/processor/StormProcessorSpec.scala | 65 +++
.../storm/producer/StormProducerSpec.scala | 72 +++
.../StormSpoutOutputCollectorSpec.scala | 50 ++
.../topology/GearpumpStormComponentSpec.scala | 124 ++++
.../topology/GearpumpStormTopologySpec.scala | 104 ++++
.../storm/topology/GearpumpTupleSpec.scala | 63 ++
.../storm/util/GraphBuilderSpec.scala | 55 ++
.../experiments/storm/util/GrouperSpec.scala | 131 +++++
.../storm/util/StormOutputCollectorSpec.scala | 109 ++++
.../storm/util/StormSerializerPoolSpec.scala | 63 ++
.../experiments/storm/util/StormUtilSpec.scala | 157 +++++
.../experiments/storm/util/TopologyUtil.scala | 41 ++
.../gearpump/experiments/yarn/Constants.scala | 46 --
.../experiments/yarn/appmaster/Command.scala | 126 ----
.../experiments/yarn/appmaster/UIService.scala | 94 ---
.../yarn/appmaster/YarnAppMaster.scala | 385 ------------
.../yarn/client/AppMasterResolver.scala | 77 ---
.../experiments/yarn/client/Client.scala | 61 --
.../experiments/yarn/client/LaunchCluster.scala | 221 -------
.../experiments/yarn/client/ManageCluster.scala | 156 -----
.../yarn/glue/ContainerLaunchContext.scala | 99 ----
.../experiments/yarn/glue/FileSystem.scala | 73 ---
.../experiments/yarn/glue/NMClient.scala | 100 ----
.../experiments/yarn/glue/RMClient.scala | 128 ----
.../experiments/yarn/glue/Records.scala | 219 -------
.../experiments/yarn/glue/YarnClient.scala | 105 ----
.../experiments/yarn/glue/YarnConfig.scala | 33 --
.../experiments/yarn/glue/package.scala | 26 -
.../gearpump/experiments/yarn/Constants.scala | 46 ++
.../experiments/yarn/appmaster/Command.scala | 126 ++++
.../experiments/yarn/appmaster/UIService.scala | 93 +++
.../yarn/appmaster/YarnAppMaster.scala | 385 ++++++++++++
.../yarn/client/AppMasterResolver.scala | 77 +++
.../experiments/yarn/client/Client.scala | 61 ++
.../experiments/yarn/client/LaunchCluster.scala | 220 +++++++
.../experiments/yarn/client/ManageCluster.scala | 156 +++++
.../yarn/glue/ContainerLaunchContext.scala | 99 ++++
.../experiments/yarn/glue/FileSystem.scala | 73 +++
.../experiments/yarn/glue/NMClient.scala | 99 ++++
.../experiments/yarn/glue/RMClient.scala | 127 ++++
.../experiments/yarn/glue/Records.scala | 219 +++++++
.../experiments/yarn/glue/YarnClient.scala | 103 ++++
.../experiments/yarn/glue/YarnConfig.scala | 33 ++
.../experiments/yarn/glue/package.scala | 25 +
.../yarn/appmaster/CommandSpec.scala | 95 ---
.../yarn/appmaster/UIServiceSpec.scala | 85 ---
.../yarn/appmaster/YarnAppMasterSpec.scala | 221 -------
.../yarn/client/LaunchClusterSpec.scala | 232 --------
.../yarn/client/ManageClusterSpec.scala | 142 -----
.../yarn/appmaster/CommandSpec.scala | 95 +++
.../yarn/appmaster/UIServiceSpec.scala | 84 +++
.../yarn/appmaster/YarnAppMasterSpec.scala | 220 +++++++
.../yarn/client/LaunchClusterSpec.scala | 232 ++++++++
.../yarn/client/ManageClusterSpec.scala | 141 +++++
.../hadoop/HadoopCheckpointStore.scala | 164 ------
.../hadoop/HadoopCheckpointStoreFactory.scala | 61 --
.../streaming/hadoop/SequenceFileSink.scala | 110 ----
.../lib/HadoopCheckpointStoreReader.scala | 72 ---
.../lib/HadoopCheckpointStoreWriter.scala | 40 --
.../streaming/hadoop/lib/HadoopUtil.scala | 80 ---
.../lib/format/DefaultSequenceFormatter.scala | 32 -
.../hadoop/lib/format/OutputFormatter.scala | 32 -
.../hadoop/lib/rotation/FileSizeRotation.scala | 37 --
.../hadoop/lib/rotation/Rotation.scala | 27 -
.../hadoop/HadoopCheckpointStore.scala | 164 ++++++
.../hadoop/HadoopCheckpointStoreFactory.scala | 61 ++
.../streaming/hadoop/SequenceFileSink.scala | 110 ++++
.../lib/HadoopCheckpointStoreReader.scala | 72 +++
.../lib/HadoopCheckpointStoreWriter.scala | 40 ++
.../streaming/hadoop/lib/HadoopUtil.scala | 80 +++
.../lib/format/DefaultSequenceFormatter.scala | 32 +
.../hadoop/lib/format/OutputFormatter.scala | 32 +
.../hadoop/lib/rotation/FileSizeRotation.scala | 37 ++
.../hadoop/lib/rotation/Rotation.scala | 27 +
.../HadoopCheckpointStoreIntegrationSpec.scala | 86 ---
.../lib/rotation/FileSizeRotationSpec.scala | 44 --
.../HadoopCheckpointStoreIntegrationSpec.scala | 86 +++
.../lib/rotation/FileSizeRotationSpec.scala | 44 ++
.../io/gearpump/external/hbase/HBaseSink.scala | 139 -----
.../external/hbase/dsl/HBaseDSLSink.scala | 47 --
.../gearpump/external/hbase/HBaseSink.scala | 139 +++++
.../external/hbase/dsl/HBaseDSLSink.scala | 47 ++
.../gearpump/external/hbase/HBaseSinkSpec.scala | 41 --
.../gearpump/external/hbase/HBaseSinkSpec.scala | 41 ++
.../io/gearpump/streaming/kafka/KafkaSink.scala | 80 ---
.../gearpump/streaming/kafka/KafkaSource.scala | 195 -------
.../gearpump/streaming/kafka/KafkaStorage.scala | 148 -----
.../streaming/kafka/dsl/KafkaDSLSink.scala | 53 --
.../streaming/kafka/dsl/KafkaDSLUtil.scala | 88 ---
.../kafka/lib/DefaultMessageDecoder.scala | 41 --
.../kafka/lib/KafkaOffsetManager.scala | 66 ---
.../streaming/kafka/lib/KafkaSourceConfig.scala | 175 ------
.../streaming/kafka/lib/KafkaUtil.scala | 167 ------
.../consumer/ExponentialBackoffSleeper.scala | 55 --
.../kafka/lib/consumer/FetchThread.scala | 139 -----
.../kafka/lib/consumer/KafkaConsumer.scala | 103 ----
.../kafka/lib/consumer/KafkaMessage.scala | 38 --
.../kafka/lib/grouper/KafkaDefaultGrouper.scala | 38 --
.../kafka/lib/grouper/KafkaGrouper.scala | 30 -
.../gearpump/streaming/kafka/KafkaSink.scala | 80 +++
.../gearpump/streaming/kafka/KafkaSource.scala | 195 +++++++
.../gearpump/streaming/kafka/KafkaStorage.scala | 148 +++++
.../streaming/kafka/dsl/KafkaDSLSink.scala | 53 ++
.../streaming/kafka/dsl/KafkaDSLUtil.scala | 88 +++
.../kafka/lib/DefaultMessageDecoder.scala | 41 ++
.../kafka/lib/KafkaOffsetManager.scala | 66 +++
.../streaming/kafka/lib/KafkaSourceConfig.scala | 178 ++++++
.../streaming/kafka/lib/KafkaUtil.scala | 167 ++++++
.../consumer/ExponentialBackoffSleeper.scala | 55 ++
.../kafka/lib/consumer/FetchThread.scala | 139 +++++
.../kafka/lib/consumer/KafkaConsumer.scala | 103 ++++
.../kafka/lib/consumer/KafkaMessage.scala | 38 ++
.../kafka/lib/grouper/KafkaDefaultGrouper.scala | 38 ++
.../kafka/lib/grouper/KafkaGrouper.scala | 30 +
.../streaming/kafka/KafkaSinkSpec.scala | 63 --
.../streaming/kafka/KafkaSourceSpec.scala | 167 ------
.../kafka/lib/DefaultMessageDecoderSpec.scala | 44 --
.../kafka/lib/KafkaOffsetManagerSpec.scala | 117 ----
.../streaming/kafka/lib/KafkaStorageSpec.scala | 187 ------
.../streaming/kafka/lib/KafkaUtilSpec.scala | 107 ----
.../ExponentialBackoffSleeperSpec.scala | 68 ---
.../kafka/lib/consumer/FetchThreadSpec.scala | 113 ----
.../kafka/lib/consumer/KafkaConsumerSpec.scala | 88 ---
.../lib/grouper/KafkaDefaultGrouperSpec.scala | 42 --
.../kafka/util/KafkaServerHarness.scala | 69 ---
.../streaming/kafka/util/ZookeeperHarness.scala | 43 --
.../streaming/kafka/KafkaSinkSpec.scala | 63 ++
.../streaming/kafka/KafkaSourceSpec.scala | 167 ++++++
.../kafka/lib/DefaultMessageDecoderSpec.scala | 44 ++
.../kafka/lib/KafkaOffsetManagerSpec.scala | 117 ++++
.../streaming/kafka/lib/KafkaStorageSpec.scala | 187 ++++++
.../streaming/kafka/lib/KafkaUtilSpec.scala | 107 ++++
.../ExponentialBackoffSleeperSpec.scala | 68 +++
.../kafka/lib/consumer/FetchThreadSpec.scala | 113 ++++
.../kafka/lib/consumer/KafkaConsumerSpec.scala | 88 +++
.../lib/grouper/KafkaDefaultGrouperSpec.scala | 42 ++
.../kafka/util/KafkaServerHarness.scala | 69 +++
.../streaming/kafka/util/ZookeeperHarness.scala | 43 ++
.../streaming/monoid/AlgebirdMonoid.scala | 37 --
.../streaming/monoid/AlgebirdMonoid.scala | 36 ++
.../streaming/serializer/ChillSerializer.scala | 33 --
.../streaming/serializer/ChillSerializer.scala | 32 +
integrationtest/README.md | 6 +-
.../integrationtest/MiniClusterProvider.scala | 4 +-
.../gearpump/integrationtest/TestSpecBase.scala | 8 +-
.../checklist/CommandLineSpec.scala | 6 +-
.../checklist/ConnectorKafkaSpec.scala | 10 +-
.../checklist/DynamicDagSpec.scala | 18 +-
.../integrationtest/checklist/ExampleSpec.scala | 12 +-
.../checklist/MessageDeliverySpec.scala | 12 +-
.../checklist/RestServiceSpec.scala | 10 +-
.../checklist/StabilitySpec.scala | 10 +-
.../checklist/StormCompatibilitySpec.scala | 12 +-
.../suites/StandaloneModeSuite.scala | 8 +-
.../io/gearpump/integrationtest/Docker.scala | 2 +-
.../io/gearpump/integrationtest/ShellExec.scala | 2 +-
.../io/gearpump/integrationtest/Util.scala | 2 +-
.../integrationtest/hadoop/HadoopCluster.scala | 4 +-
.../integrationtest/kafka/KafkaCluster.scala | 6 +-
.../kafka/NumericalDataProducer.scala | 4 +-
.../integrationtest/kafka/ResultVerifier.scala | 2 +-
.../kafka/SimpleKafkaReader.scala | 4 +-
.../minicluster/BaseContainer.scala | 4 +-
.../minicluster/CommandLineClient.scala | 6 +-
.../minicluster/MiniCluster.scala | 4 +-
.../minicluster/RestClient.scala | 34 +-
.../integrationtest/storm/StormClient.scala | 6 +-
.../integrationtest/storm/Adaptor.scala | 2 +-
.../storm/Storm010KafkaTopology.scala | 4 +-
.../integrationtest/storm/Adaptor.scala | 2 +-
.../storm/Storm09KafkaTopology.scala | 4 +-
project/Build.scala | 7 +-
project/BuildExample.scala | 24 +-
project/Pack.scala | 14 +-
services/README.md | 2 +-
services/dashboard/dashboard.js | 2 +-
services/dashboard/services/models/dag.js | 2 +-
services/dashboard/services/models/metrics.js | 8 +-
.../services/models/metrics_provider.js | 2 +-
services/dashboard/services/models/models.js | 6 +-
.../services/models/streamingapp_dag.js | 2 +-
.../models/streamingapp_metrics_provider.js | 2 +-
services/dashboard/services/restapi.js | 2 +-
.../io/gearpump/dashboard/DashboardApp.scala | 28 -
.../gearpump/dashboard/DashboardApp.scala | 28 +
.../io/gearpump/services/AdminService.scala | 53 --
.../io/gearpump/services/AppMasterService.scala | 226 --------
.../io/gearpump/services/BasicService.scala | 71 ---
.../io/gearpump/services/MasterService.scala | 350 -----------
.../io/gearpump/services/RestServices.scala | 105 ----
.../io/gearpump/services/SecurityService.scala | 290 ---------
.../io/gearpump/services/StaticService.scala | 70 ---
.../gearpump/services/SupervisorService.scala | 116 ----
.../io/gearpump/services/WorkerService.scala | 79 ---
.../io/gearpump/services/main/Services.scala | 148 -----
.../scala/io/gearpump/services/package.scala | 22 -
.../security/oauth2/OAuth2Authenticator.scala | 152 -----
.../oauth2/impl/BaseOAuth2Authenticator.scala | 231 --------
.../CloudFoundryUAAOAuth2Authenticator.scala | 244 --------
.../oauth2/impl/GoogleOAuth2Authenticator.scala | 106 ----
.../io/gearpump/services/util/UpickleUtil.scala | 49 --
.../apache/gearpump/services/AdminService.scala | 53 ++
.../gearpump/services/AppMasterService.scala | 226 ++++++++
.../apache/gearpump/services/BasicService.scala | 71 +++
.../gearpump/services/MasterService.scala | 350 +++++++++++
.../apache/gearpump/services/RestServices.scala | 105 ++++
.../gearpump/services/SecurityService.scala | 290 +++++++++
.../gearpump/services/StaticService.scala | 70 +++
.../gearpump/services/SupervisorService.scala | 116 ++++
.../gearpump/services/WorkerService.scala | 79 +++
.../gearpump/services/main/Services.scala | 148 +++++
.../org/apache/gearpump/services/package.scala | 22 +
.../security/oauth2/OAuth2Authenticator.scala | 152 +++++
.../oauth2/impl/BaseOAuth2Authenticator.scala | 232 ++++++++
.../CloudFoundryUAAOAuth2Authenticator.scala | 244 ++++++++
.../oauth2/impl/GoogleOAuth2Authenticator.scala | 108 ++++
.../gearpump/services/util/UpickleUtil.scala | 49 ++
.../io/gearpump/services/AdminServiceSpec.scala | 53 --
.../services/AppMasterServiceSpec.scala | 167 ------
.../gearpump/services/MasterServiceSpec.scala | 217 -------
.../gearpump/services/SecurityServiceSpec.scala | 162 ------
.../gearpump/services/StaticServiceSpec.scala | 63 --
.../gearpump/services/WorkerServiceSpec.scala | 121 ----
...CloudFoundryUAAOAuth2AuthenticatorSpec.scala | 139 -----
.../oauth2/GoogleOAuth2AuthenticatorSpec.scala | 163 ------
.../security/oauth2/MockOAuth2Server.scala | 65 ---
.../io/gearpump/services/util/UpickleSpec.scala | 67 ---
.../gearpump/services/AdminServiceSpec.scala | 53 ++
.../services/AppMasterServiceSpec.scala | 167 ++++++
.../gearpump/services/MasterServiceSpec.scala | 217 +++++++
.../gearpump/services/SecurityServiceSpec.scala | 162 ++++++
.../gearpump/services/StaticServiceSpec.scala | 63 ++
.../gearpump/services/WorkerServiceSpec.scala | 121 ++++
...CloudFoundryUAAOAuth2AuthenticatorSpec.scala | 140 +++++
.../oauth2/GoogleOAuth2AuthenticatorSpec.scala | 163 ++++++
.../security/oauth2/MockOAuth2Server.scala | 65 +++
.../gearpump/services/util/UpickleSpec.scala | 67 +++
.../io/gearpump/streaming/javaapi/Graph.java | 35 --
.../gearpump/streaming/javaapi/Processor.java | 141 -----
.../streaming/javaapi/StreamApplication.java | 61 --
.../io/gearpump/streaming/javaapi/Task.java | 58 --
.../javaapi/dsl/functions/FilterFunction.java | 30 -
.../javaapi/dsl/functions/FlatMapFunction.java | 32 -
.../javaapi/dsl/functions/GroupByFunction.java | 31 -
.../javaapi/dsl/functions/MapFunction.java | 31 -
.../javaapi/dsl/functions/ReduceFunction.java | 30 -
.../gearpump/streaming/javaapi/Graph.java | 35 ++
.../gearpump/streaming/javaapi/Processor.java | 141 +++++
.../streaming/javaapi/StreamApplication.java | 61 ++
.../apache/gearpump/streaming/javaapi/Task.java | 58 ++
.../javaapi/dsl/functions/FilterFunction.java | 30 +
.../javaapi/dsl/functions/FlatMapFunction.java | 32 +
.../javaapi/dsl/functions/GroupByFunction.java | 31 +
.../javaapi/dsl/functions/MapFunction.java | 31 +
.../javaapi/dsl/functions/ReduceFunction.java | 30 +
streaming/src/main/resources/geardefault.conf | 6 +-
.../io/gearpump/streaming/ClusterMessage.scala | 85 ---
.../scala/io/gearpump/streaming/Constants.scala | 37 --
.../main/scala/io/gearpump/streaming/DAG.scala | 62 --
.../gearpump/streaming/MessageSerializer.scala | 108 ----
.../gearpump/streaming/StreamApplication.scala | 170 ------
.../streaming/appmaster/AppMaster.scala | 362 ------------
.../streaming/appmaster/ClockService.scala | 447 --------------
.../streaming/appmaster/DagManager.scala | 182 ------
.../streaming/appmaster/ExecutorManager.scala | 209 -------
.../streaming/appmaster/JarScheduler.scala | 176 ------
.../appmaster/StreamAppMasterSummary.scala | 61 --
.../streaming/appmaster/TaskLocator.scala | 99 ----
.../streaming/appmaster/TaskManager.scala | 497 ----------------
.../streaming/appmaster/TaskRegistry.scala | 143 -----
.../streaming/appmaster/TaskSchedulerImpl.scala | 178 ------
.../io/gearpump/streaming/dsl/Stream.scala | 230 --------
.../io/gearpump/streaming/dsl/StreamApp.scala | 124 ----
.../streaming/dsl/javaapi/JavaStream.scala | 77 ---
.../streaming/dsl/javaapi/JavaStreamApp.scala | 47 --
.../scala/io/gearpump/streaming/dsl/op/OP.scala | 109 ----
.../dsl/partitioner/GroupbyPartitioner.scala | 46 --
.../streaming/dsl/plan/OpTranslator.scala | 296 ----------
.../gearpump/streaming/dsl/plan/Planner.scala | 96 ---
.../gearpump/streaming/executor/Executor.scala | 476 ---------------
.../executor/ExecutorRestartPolicy.scala | 64 --
.../streaming/executor/TaskLauncher.scala | 83 ---
.../streaming/metrics/ProcessorAggregator.scala | 301 ----------
.../metrics/TaskFilterAggregator.scala | 157 -----
.../scala/io/gearpump/streaming/package.scala | 25 -
.../io/gearpump/streaming/sink/DataSink.scala | 65 ---
.../streaming/sink/DataSinkProcessor.scala | 49 --
.../gearpump/streaming/sink/DataSinkTask.scala | 50 --
.../gearpump/streaming/source/DataSource.scala | 70 ---
.../streaming/source/DataSourceConfig.scala | 25 -
.../streaming/source/DataSourceProcessor.scala | 49 --
.../streaming/source/DataSourceTask.scala | 65 ---
.../source/DefaultTimeStampFilter.scala | 31 -
.../gearpump/streaming/state/api/Monoid.scala | 28 -
.../streaming/state/api/MonoidState.scala | 52 --
.../streaming/state/api/PersistentState.scala | 61 --
.../streaming/state/api/PersistentTask.scala | 114 ----
.../streaming/state/api/Serializer.scala | 26 -
.../state/impl/CheckpointManager.scala | 64 --
.../state/impl/InMemoryCheckpointStore.scala | 50 --
.../streaming/state/impl/NonWindowState.scala | 53 --
.../state/impl/PersistentStateConfig.scala | 28 -
.../gearpump/streaming/state/impl/Window.scala | 54 --
.../streaming/state/impl/WindowConfig.scala | 25 -
.../streaming/state/impl/WindowState.scala | 165 ------
.../streaming/storage/AppDataStore.scala | 30 -
.../storage/InMemoryAppStoreOnMaster.scala | 48 --
.../streaming/task/ExpressTransport.scala | 75 ---
.../streaming/task/SerializedMessage.scala | 42 --
.../streaming/task/SerializerResolver.scala | 47 --
.../io/gearpump/streaming/task/StartTime.scala | 24 -
.../task/StreamingTransportSerializer.scala | 68 ---
.../io/gearpump/streaming/task/Subscriber.scala | 58 --
.../gearpump/streaming/task/Subscription.scala | 235 --------
.../scala/io/gearpump/streaming/task/Task.scala | 189 ------
.../io/gearpump/streaming/task/TaskActor.scala | 397 -------------
.../streaming/task/TaskContextData.scala | 32 -
.../streaming/task/TaskControlMessage.scala | 72 ---
.../io/gearpump/streaming/task/TaskId.scala | 28 -
.../streaming/task/TaskMessageSerializer.scala | 28 -
.../io/gearpump/streaming/task/TaskUtil.scala | 33 --
.../gearpump/streaming/task/TaskWrapper.scala | 133 -----
.../transaction/api/CheckpointStore.scala | 42 --
.../transaction/api/MessageDecoder.scala | 29 -
.../transaction/api/OffsetManager.scala | 44 --
.../transaction/api/OffsetStorage.scala | 66 ---
.../transaction/api/TimeReplayableSource.scala | 30 -
.../transaction/api/TimeStampFilter.scala | 29 -
.../gearpump/streaming/util/ActorPathUtil.scala | 41 --
.../gearpump/streaming/ClusterMessage.scala | 85 +++
.../apache/gearpump/streaming/Constants.scala | 36 ++
.../org/apache/gearpump/streaming/DAG.scala | 62 ++
.../gearpump/streaming/MessageSerializer.scala | 108 ++++
.../gearpump/streaming/StreamApplication.scala | 171 ++++++
.../streaming/appmaster/AppMaster.scala | 362 ++++++++++++
.../streaming/appmaster/ClockService.scala | 447 ++++++++++++++
.../streaming/appmaster/DagManager.scala | 181 ++++++
.../streaming/appmaster/ExecutorManager.scala | 209 +++++++
.../streaming/appmaster/JarScheduler.scala | 175 ++++++
.../appmaster/StreamAppMasterSummary.scala | 61 ++
.../streaming/appmaster/TaskLocator.scala | 97 ++++
.../streaming/appmaster/TaskManager.scala | 496 ++++++++++++++++
.../streaming/appmaster/TaskRegistry.scala | 142 +++++
.../streaming/appmaster/TaskSchedulerImpl.scala | 177 ++++++
.../apache/gearpump/streaming/dsl/Stream.scala | 229 ++++++++
.../gearpump/streaming/dsl/StreamApp.scala | 123 ++++
.../streaming/dsl/javaapi/JavaStream.scala | 77 +++
.../streaming/dsl/javaapi/JavaStreamApp.scala | 47 ++
.../apache/gearpump/streaming/dsl/op/OP.scala | 109 ++++
.../dsl/partitioner/GroupbyPartitioner.scala | 46 ++
.../streaming/dsl/plan/OpTranslator.scala | 296 ++++++++++
.../gearpump/streaming/dsl/plan/Planner.scala | 96 +++
.../gearpump/streaming/executor/Executor.scala | 476 +++++++++++++++
.../executor/ExecutorRestartPolicy.scala | 64 ++
.../streaming/executor/TaskLauncher.scala | 83 +++
.../streaming/metrics/ProcessorAggregator.scala | 301 ++++++++++
.../metrics/TaskFilterAggregator.scala | 157 +++++
.../org/apache/gearpump/streaming/package.scala | 25 +
.../gearpump/streaming/sink/DataSink.scala | 65 +++
.../streaming/sink/DataSinkProcessor.scala | 49 ++
.../gearpump/streaming/sink/DataSinkTask.scala | 50 ++
.../gearpump/streaming/source/DataSource.scala | 70 +++
.../streaming/source/DataSourceConfig.scala | 25 +
.../streaming/source/DataSourceProcessor.scala | 49 ++
.../streaming/source/DataSourceTask.scala | 66 +++
.../source/DefaultTimeStampFilter.scala | 31 +
.../gearpump/streaming/state/api/Monoid.scala | 28 +
.../streaming/state/api/MonoidState.scala | 52 ++
.../streaming/state/api/PersistentState.scala | 61 ++
.../streaming/state/api/PersistentTask.scala | 114 ++++
.../streaming/state/api/Serializer.scala | 26 +
.../state/impl/CheckpointManager.scala | 64 ++
.../state/impl/InMemoryCheckpointStore.scala | 50 ++
.../streaming/state/impl/NonWindowState.scala | 53 ++
.../state/impl/PersistentStateConfig.scala | 28 +
.../gearpump/streaming/state/impl/Window.scala | 54 ++
.../streaming/state/impl/WindowConfig.scala | 25 +
.../streaming/state/impl/WindowState.scala | 165 ++++++
.../streaming/storage/AppDataStore.scala | 30 +
.../storage/InMemoryAppStoreOnMaster.scala | 48 ++
.../streaming/task/ExpressTransport.scala | 75 +++
.../streaming/task/SerializedMessage.scala | 42 ++
.../streaming/task/SerializerResolver.scala | 47 ++
.../gearpump/streaming/task/StartTime.scala | 24 +
.../task/StreamingTransportSerializer.scala | 68 +++
.../gearpump/streaming/task/Subscriber.scala | 58 ++
.../gearpump/streaming/task/Subscription.scala | 235 ++++++++
.../apache/gearpump/streaming/task/Task.scala | 189 ++++++
.../gearpump/streaming/task/TaskActor.scala | 397 +++++++++++++
.../streaming/task/TaskContextData.scala | 32 +
.../streaming/task/TaskControlMessage.scala | 72 +++
.../apache/gearpump/streaming/task/TaskId.scala | 28 +
.../streaming/task/TaskMessageSerializer.scala | 28 +
.../gearpump/streaming/task/TaskUtil.scala | 33 ++
.../gearpump/streaming/task/TaskWrapper.scala | 134 +++++
.../transaction/api/CheckpointStore.scala | 42 ++
.../transaction/api/MessageDecoder.scala | 29 +
.../transaction/api/OffsetManager.scala | 44 ++
.../transaction/api/OffsetStorage.scala | 66 +++
.../transaction/api/TimeReplayableSource.scala | 30 +
.../transaction/api/TimeStampFilter.scala | 29 +
.../gearpump/streaming/util/ActorPathUtil.scala | 41 ++
.../scala/io/gearpump/streaming/DAGSpec.scala | 45 --
.../streaming/MessageSerializerSpec.scala | 78 ---
.../scala/io/gearpump/streaming/MockUtil.scala | 48 --
.../gearpump/streaming/StreamingTestUtil.scala | 49 --
.../streaming/appmaster/AppMasterSpec.scala | 238 --------
.../streaming/appmaster/ClockServiceSpec.scala | 241 --------
.../streaming/appmaster/DagManagerSpec.scala | 108 ----
.../appmaster/ExecutorManagerSpec.scala | 151 -----
.../appmaster/ExecutorRestartPolicySpec.scala | 47 --
.../appmaster/HistoryMetricsServiceSpec.scala | 197 -------
.../streaming/appmaster/JarSchedulerSpec.scala | 96 ---
.../streaming/appmaster/TaskLocatorSpec.scala | 35 --
.../streaming/appmaster/TaskManagerSpec.scala | 276 ---------
.../streaming/appmaster/TaskRegistrySpec.scala | 64 --
.../streaming/appmaster/TaskSchedulerSpec.scala | 130 -----
.../gearpump/streaming/dsl/StreamAppSpec.scala | 94 ---
.../io/gearpump/streaming/dsl/StreamSpec.scala | 126 ----
.../partitioner/GroupByPartitionerSpec.scala | 44 --
.../streaming/dsl/plan/OpTranslatorSpec.scala | 143 -----
.../streaming/executor/ExecutorSpec.scala | 110 ----
.../executor/TaskArgumentStoreSpec.scala | 45 --
.../streaming/executor/TaskLauncherSpec.scala | 78 ---
.../metrics/ProcessorAggregatorSpec.scala | 261 ---------
.../metrics/TaskFilterAggregatorSpec.scala | 80 ---
.../source/DefaultTimeStampFilterSpec.scala | 48 --
.../state/impl/CheckpointManagerSpec.scala | 89 ---
.../impl/InMemoryCheckpointStoreSpec.scala | 37 --
.../state/impl/NonWindowStateSpec.scala | 132 -----
.../streaming/state/impl/WindowSpec.scala | 61 --
.../streaming/state/impl/WindowStateSpec.scala | 239 --------
.../storage/InMemoryAppStoreOnMasterSpec.scala | 62 --
.../streaming/task/SubscriberSpec.scala | 51 --
.../streaming/task/SubscriptionSpec.scala | 142 -----
.../gearpump/streaming/task/TaskActorSpec.scala | 123 ----
.../org/apache/gearpump/streaming/DAGSpec.scala | 44 ++
.../streaming/MessageSerializerSpec.scala | 78 +++
.../apache/gearpump/streaming/MockUtil.scala | 47 ++
.../gearpump/streaming/StreamingTestUtil.scala | 48 ++
.../streaming/appmaster/AppMasterSpec.scala | 237 ++++++++
.../streaming/appmaster/ClockServiceSpec.scala | 240 ++++++++
.../streaming/appmaster/DagManagerSpec.scala | 107 ++++
.../appmaster/ExecutorManagerSpec.scala | 150 +++++
.../appmaster/ExecutorRestartPolicySpec.scala | 46 ++
.../appmaster/HistoryMetricsServiceSpec.scala | 196 +++++++
.../streaming/appmaster/JarSchedulerSpec.scala | 95 +++
.../streaming/appmaster/TaskLocatorSpec.scala | 34 ++
.../streaming/appmaster/TaskManagerSpec.scala | 275 +++++++++
.../streaming/appmaster/TaskRegistrySpec.scala | 63 ++
.../streaming/appmaster/TaskSchedulerSpec.scala | 129 ++++
.../gearpump/streaming/dsl/StreamAppSpec.scala | 93 +++
.../gearpump/streaming/dsl/StreamSpec.scala | 125 ++++
.../partitioner/GroupByPartitionerSpec.scala | 44 ++
.../streaming/dsl/plan/OpTranslatorSpec.scala | 143 +++++
.../streaming/executor/ExecutorSpec.scala | 110 ++++
.../executor/TaskArgumentStoreSpec.scala | 45 ++
.../streaming/executor/TaskLauncherSpec.scala | 78 +++
.../metrics/ProcessorAggregatorSpec.scala | 261 +++++++++
.../metrics/TaskFilterAggregatorSpec.scala | 80 +++
.../source/DefaultTimeStampFilterSpec.scala | 48 ++
.../state/impl/CheckpointManagerSpec.scala | 89 +++
.../impl/InMemoryCheckpointStoreSpec.scala | 37 ++
.../state/impl/NonWindowStateSpec.scala | 132 +++++
.../streaming/state/impl/WindowSpec.scala | 61 ++
.../streaming/state/impl/WindowStateSpec.scala | 239 ++++++++
.../storage/InMemoryAppStoreOnMasterSpec.scala | 62 ++
.../streaming/task/SubscriberSpec.scala | 51 ++
.../streaming/task/SubscriptionSpec.scala | 142 +++++
.../gearpump/streaming/task/TaskActorSpec.scala | 123 ++++
1049 files changed, 46925 insertions(+), 46957 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/conf/gear.conf
----------------------------------------------------------------------
diff --git a/conf/gear.conf b/conf/gear.conf
index b21f59a..30eacd2 100644
--- a/conf/gear.conf
+++ b/conf/gear.conf
@@ -31,11 +31,11 @@ gearpump {
worker.slots = 1000
## The class responsable for launching the executor process.
- ## User can switch to "io.gearpump.cluster.worker.CGroupProcessLauncher" to enable CGroup support.
- worker.executor-process-launcher = "io.gearpump.cluster.worker.DefaultExecutorProcessLauncher"
+ ## User can switch to "org.apache.gearpump.cluster.worker.CGroupProcessLauncher" to enable CGroup support.
+ worker.executor-process-launcher = "org.apache.gearpump.cluster.worker.DefaultExecutorProcessLauncher"
## To enable worker use cgroup to make resource isolation,
- ## set gearpump.worker.executor-process-launcher = "io.gearpump.cluster.worker.CGroupProcessLauncher"
+ ## set gearpump.worker.executor-process-launcher = "org.apache.gearpump.cluster.worker.CGroupProcessLauncher"
##
## Before enable it, you should also make sure:
## 1. Linux version (>= 2.6.18)
@@ -144,7 +144,7 @@ gearpump {
### Whitelist for Metrics Aggregator class.
### See class [[MetricsAggregator]] for more information.
metrics-aggregator-class {
- ## Format io.gearpump.KeyFullClassName = ""
+ ## Format org.apache.gearpump.KeyFullClassName = ""
}
}
}
@@ -171,9 +171,9 @@ gearpump {
### Gearpump has built-in serialization framework using Kryo.
### User are allowed to use a different serialization framework, like Protobuf
- ### See [io.gearpump.serializer.FastKryoSerializationFramework] to find how
+ ### See [org.apache.gearpump.serializer.FastKryoSerializationFramework] to find how
### a custom serialization framework can be defined.
- serialization-framework = "io.gearpump.serializer.FastKryoSerializationFramework"
+ serialization-framework = "org.apache.gearpump.serializer.FastKryoSerializationFramework"
### Define where the submitted jar file will be stored at
@@ -190,7 +190,7 @@ gearpump {
### If you don't know what is this about, don't change it
#########################
scheduling {
- scheduler-class = "io.gearpump.cluster.scheduler.PriorityScheduler"
+ scheduler-class = "org.apache.gearpump.cluster.scheduler.PriorityScheduler"
}
#############################################
@@ -388,15 +388,15 @@ gearpump-ui {
## authentication channel like OAuth2.
##
## User can replace this with a custom User-Password based authenticator,
- ## which implements interface io.gearpump.security.Authenticator
+ ## which implements interface org.apache.gearpump.security.Authenticator
##
- authenticator = "io.gearpump.security.ConfigFileBasedAuthenticator"
+ authenticator = "org.apache.gearpump.security.ConfigFileBasedAuthenticator"
- ## Configuration options for authenticator io.gearpump.security.ConfigFileBasedAuthenticator
+ ## Configuration options for authenticator org.apache.gearpump.security.ConfigFileBasedAuthenticator
config-file-based-authenticator = {
## Format: username = "password_hash_value"
## password_hash_value can be generated by running shell tool:
- ## bin/gear io.gearpump.security.PasswordUtil -password <your raw password>
+ ## bin/gear org.apache.gearpump.security.PasswordUtil -password <your raw password>
## Admin users have super permission to do everything
admins = {
@@ -447,7 +447,7 @@ gearpump-ui {
## For steps to enable OAuth2 Authentication on Google, please view docs/deployment-ui-authentication.md
##
"google" {
- "class" = "io.gearpump.services.security.oauth2.impl.GoogleOAuth2Authenticator"
+ "class" = "org.apache.gearpump.services.security.oauth2.impl.GoogleOAuth2Authenticator"
## Please replace "127.0.0.1:8090" with your address of UI service.
"callback" = "http://127.0.0.1:8090/login/oauth2/google/callback"
@@ -478,7 +478,7 @@ gearpump-ui {
## For steps to enable OAuth2 Authentication for UAA, please view docs/deployment-ui-authentication.md
##
"cloudfoundryuaa" {
- "class" = "io.gearpump.services.security.oauth2.impl.CloudFoundryUAAOAuth2Authenticator"
+ "class" = "org.apache.gearpump.services.security.oauth2.impl.CloudFoundryUAAOAuth2Authenticator"
## Please replace "127.0.0.1:8090" with your address of UI service.
"callback" = "http://127.0.0.1:8090/login/oauth2/cloudfoundryuaa/callback"
@@ -516,7 +516,7 @@ gearpump-ui {
## Define how to do additional authorization check. The class should implement
## interface CloudFoundryUAAOAuth2Authenticator.AdditionalAuthenticator
additional-authenticator = {
- "class" = "io.gearpump.services.security.oauth2.impl.CloudFoundryUAAOAuth2Authenticator$OrganizationAccessChecker"
+ "class" = "org.apache.gearpump.services.security.oauth2.impl.CloudFoundryUAAOAuth2Authenticator$OrganizationAccessChecker"
## Please fill the Cloud Foundry API endpoint and organization GUID
"organization-url" = "http://<cloud foundry api endpoint>/v2/organizations/<organization-guid>"
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/conf/log4j.properties
----------------------------------------------------------------------
diff --git a/conf/log4j.properties b/conf/log4j.properties
index 7175778..32638e4 100644
--- a/conf/log4j.properties
+++ b/conf/log4j.properties
@@ -77,7 +77,7 @@ log4j.threshhold=ALL
#
# Rolling File Appender
#
-log4j.appender.RollingFileAppender=io.gearpump.util.RecreateRollingFileAppender
+log4j.appender.RollingFileAppender=org.apache.gearpump.util.RecreateRollingFileAppender
log4j.appender.RollingFileAppender.File=${gearpump.log.dir}/${gearpump.log.file}
log4j.appender.RollingFileAppender.checkFileInterval=60
log4j.appender.RollingFileAppender.layout=org.apache.log4j.PatternLayout
@@ -98,7 +98,7 @@ log4j.appender.console.layout.ConversionPattern=[%c{1}] %m%n
#
# Application Log Appender
#
-log4j.appender.ApplicationLogAppender=io.gearpump.util.RecreateRollingFileAppender
+log4j.appender.ApplicationLogAppender=org.apache.gearpump.util.RecreateRollingFileAppender
log4j.appender.ApplicationLogAppender.File=${gearpump.application.log.dir}/${gearpump.application.log.file}
log4j.appender.ApplicationLogAppender.checkFileInterval=60
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/java/io/gearpump/transport/netty/ITransportMessageSerializer.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/io/gearpump/transport/netty/ITransportMessageSerializer.java b/core/src/main/java/io/gearpump/transport/netty/ITransportMessageSerializer.java
deleted file mode 100644
index c01135e..0000000
--- a/core/src/main/java/io/gearpump/transport/netty/ITransportMessageSerializer.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.transport.netty;
-
-import java.io.DataInput;
-import java.io.DataOutput;
-
-public interface ITransportMessageSerializer {
-
- int getLength(Object obj);
-
- void serialize(DataOutput dataOutput, Object transportMessage);
-
- Object deserialize(DataInput dataInput, int length);
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/java/io/gearpump/transport/netty/MessageBatch.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/io/gearpump/transport/netty/MessageBatch.java b/core/src/main/java/io/gearpump/transport/netty/MessageBatch.java
deleted file mode 100644
index f556161..0000000
--- a/core/src/main/java/io/gearpump/transport/netty/MessageBatch.java
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.transport.netty;
-
-import io.gearpump.google.common.io.Closeables;
-import org.jboss.netty.buffer.ChannelBuffer;
-import org.jboss.netty.buffer.ChannelBufferOutputStream;
-import org.jboss.netty.buffer.ChannelBuffers;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Netty message on the wire is wrapped as MessageBatch
- */
-public class MessageBatch {
- private static final Logger log = LoggerFactory.getLogger(MessageBatch.class);
-
- private int buffer_size;
- private List<TaskMessage> messages;
- private int encoded_length;
- private ITransportMessageSerializer serializer;
-
- MessageBatch(int buffer_size, ITransportMessageSerializer serializer) {
- this.buffer_size = buffer_size;
- messages = new ArrayList<TaskMessage>();
- encoded_length = 0;
- this.serializer = serializer;
- }
-
- void add(TaskMessage taskMessage) {
- if (taskMessage == null) {
- throw new RuntimeException("null object forbidden in a message batch");
- }
-
- messages.add(taskMessage);
- encoded_length += msgEncodeLength(taskMessage);
- }
-
- TaskMessage get(int index) {
- return messages.get(index);
- }
-
- /**
- * try to add a TaskMessage to a batch
- *
- * @param taskMsg - {@link io.gearpump.transport.netty.TaskMessage}
- * @return false if the msg could not be added due to buffer size limit; true otherwise
- */
- boolean tryAdd(TaskMessage taskMsg) {
- if ((encoded_length + msgEncodeLength(taskMsg)) <= buffer_size) {
- add(taskMsg);
- return true;
- }
- return false;
- }
-
- private int msgEncodeLength(TaskMessage taskMsg) {
- int size = 0;
- if (taskMsg != null) {
- size = 24; //sessionId(INT) + sourceTask(LONG) + targetTask(LONG) + messageLength(INT)
- if (taskMsg.message() != null) {
- size += serializer.getLength(taskMsg.message());
- }
- }
- return size;
- }
-
- /**
- * @return true, if allowed buffer is Full
- */
- boolean isFull() {
- return encoded_length >= buffer_size;
- }
-
- /**
- * @return true, if no messages in this batch
- */
- boolean isEmpty() {
- return messages.isEmpty();
- }
-
- /**
- * @return number of messages available in this batch
- */
- int size() {
- return messages.size();
- }
-
- /**
- * create a buffer containing the encoding of this batch
- */
- ChannelBuffer buffer() throws IOException {
- ChannelBufferOutputStream bout =
- new ChannelBufferOutputStream(ChannelBuffers.directBuffer(encoded_length));
-
- try {
- for (TaskMessage msg : messages) {
- writeTaskMessage(bout, msg);
- }
- return bout.buffer();
- } catch (IOException e) {
- log.error("Error while writing Tasks to Channel Buffer - {}", e.getMessage());
- } finally {
- Closeables.close(bout, false);
- }
- return null;
- }
-
- /**
- * write a TaskMessage into a stream
- * <p>
- * Each TaskMessage is encoded as:
- * sessionId ... int(4)
- * source task ... Long(8)
- * target task ... long(8)
- * len ... int(4)
- * payload ... byte[] *
- */
- private void writeTaskMessage(ChannelBufferOutputStream bout,
- TaskMessage message) throws IOException {
- long target_id = message.targetTask();
- long source_id = message.sourceTask();
- int sessionId = message.sessionId();
- int msgLength = serializer.getLength(message.message());
-
- bout.writeInt(sessionId);
- bout.writeLong(target_id);
- bout.writeLong(source_id);
- bout.writeInt(msgLength);
- serializer.serialize(bout, message.message());
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/java/io/gearpump/transport/netty/MessageDecoder.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/io/gearpump/transport/netty/MessageDecoder.java b/core/src/main/java/io/gearpump/transport/netty/MessageDecoder.java
deleted file mode 100644
index 7566014..0000000
--- a/core/src/main/java/io/gearpump/transport/netty/MessageDecoder.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.transport.netty;
-
-import org.jboss.netty.buffer.ChannelBuffer;
-import org.jboss.netty.channel.Channel;
-import org.jboss.netty.channel.ChannelHandlerContext;
-import org.jboss.netty.handler.codec.frame.FrameDecoder;
-
-import java.util.ArrayList;
-import java.util.List;
-
-public class MessageDecoder extends FrameDecoder {
- private ITransportMessageSerializer serializer;
- private WrappedChannelBuffer dataInput = new WrappedChannelBuffer();
-
- public MessageDecoder(ITransportMessageSerializer serializer) {
- this.serializer = serializer;
- }
-
- /*
- * Each TaskMessage is encoded as:
- * sessionId ... int(4)
- * source task ... long(8)
- * target task ... long(8)
- * len ... int(4)
- * payload ... byte[] *
- */
- protected List<TaskMessage> decode(ChannelHandlerContext ctx, Channel channel,
- ChannelBuffer buf) {
- this.dataInput.setChannelBuffer(buf);
-
- final int SESION_LENGTH = 4; //int
- final int SOURCE_TASK_LENGTH = 8; //long
- final int TARGET_TASK_LENGTH = 8; //long
- final int MESSAGE_LENGTH = 4; //int
- final int HEADER_LENGTH = SESION_LENGTH + SOURCE_TASK_LENGTH + TARGET_TASK_LENGTH + MESSAGE_LENGTH;
-
- // Make sure that we have received at least a short message
- long available = buf.readableBytes();
- if (available < HEADER_LENGTH) {
- //need more data
- return null;
- }
-
- List<TaskMessage> taskMessageList = new ArrayList<TaskMessage>();
-
- // Use while loop, try to decode as more messages as possible in single call
- while (available >= HEADER_LENGTH) {
-
- // Mark the current buffer position before reading task/len field
- // because the whole frame might not be in the buffer yet.
- // We will reset the buffer position to the marked position if
- // there's not enough bytes in the buffer.
- buf.markReaderIndex();
-
- int sessionId = buf.readInt();
- long targetTask = buf.readLong();
- long sourceTask = buf.readLong();
- // Read the length field.
- int length = buf.readInt();
-
- available -= HEADER_LENGTH;
-
- if (length <= 0) {
- taskMessageList.add(new TaskMessage(sessionId, targetTask, sourceTask, null));
- break;
- }
-
- // Make sure if there's enough bytes in the buffer.
- if (available < length) {
- // The whole bytes were not received yet - return null.
- buf.resetReaderIndex();
- break;
- }
- available -= length;
-
- // There's enough bytes in the buffer. Read it.
- Object message = serializer.deserialize(dataInput, length);
-
- // Successfully decoded a frame.
- // Return a TaskMessage object
- taskMessageList.add(new TaskMessage(sessionId, targetTask, sourceTask, message));
- }
-
- return taskMessageList.size() == 0 ? null : taskMessageList;
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/java/io/gearpump/transport/netty/MessageEncoder.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/io/gearpump/transport/netty/MessageEncoder.java b/core/src/main/java/io/gearpump/transport/netty/MessageEncoder.java
deleted file mode 100644
index 674e96f..0000000
--- a/core/src/main/java/io/gearpump/transport/netty/MessageEncoder.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.transport.netty;
-
-import org.jboss.netty.channel.Channel;
-import org.jboss.netty.channel.ChannelHandlerContext;
-import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;
-
-public class MessageEncoder extends OneToOneEncoder {
- @Override
- protected Object encode(ChannelHandlerContext ctx, Channel channel, Object obj) throws Exception {
- if (obj instanceof MessageBatch) {
- return ((MessageBatch) obj).buffer();
- }
-
- throw new RuntimeException("Unsupported encoding of object of class " + obj.getClass().getName());
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/java/io/gearpump/transport/netty/NettyRenameThreadFactory.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/io/gearpump/transport/netty/NettyRenameThreadFactory.java b/core/src/main/java/io/gearpump/transport/netty/NettyRenameThreadFactory.java
deleted file mode 100644
index 026684e..0000000
--- a/core/src/main/java/io/gearpump/transport/netty/NettyRenameThreadFactory.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.transport.netty;
-
-import org.jboss.netty.util.ThreadNameDeterminer;
-import org.jboss.netty.util.ThreadRenamingRunnable;
-
-import java.util.concurrent.ThreadFactory;
-import java.util.concurrent.atomic.AtomicInteger;
-
-public class NettyRenameThreadFactory implements ThreadFactory {
-
- static {
- //Rename Netty threads
- ThreadRenamingRunnable.setThreadNameDeterminer(ThreadNameDeterminer.CURRENT);
- }
-
- final ThreadGroup group;
- final AtomicInteger index = new AtomicInteger(1);
- final String name;
-
- NettyRenameThreadFactory(String name) {
- SecurityManager s = System.getSecurityManager();
- group = (s != null) ? s.getThreadGroup() :
- Thread.currentThread().getThreadGroup();
- this.name = name;
- }
-
- public Thread newThread(Runnable r) {
- Thread t = new Thread(group, r, name + "-" + index.getAndIncrement(), 0);
- if (t.isDaemon())
- t.setDaemon(false);
- if (t.getPriority() != Thread.NORM_PRIORITY)
- t.setPriority(Thread.NORM_PRIORITY);
- return t;
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/java/io/gearpump/transport/netty/TaskMessage.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/io/gearpump/transport/netty/TaskMessage.java b/core/src/main/java/io/gearpump/transport/netty/TaskMessage.java
deleted file mode 100644
index 243d3f0..0000000
--- a/core/src/main/java/io/gearpump/transport/netty/TaskMessage.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.transport.netty;
-
-public class TaskMessage {
-
- // When network partition happen, there may be several task instances of
- // same taskId co-existing for a short period of time. When they send messages
- // to same target task, it may cause confusion.
- // With sessionId, we can know which messages are from an old session, and which
- // are from new session. Messages of old sesson will be dropped.
-
- private int _sessionId;
- private long _targetTask;
- private long _sourceTask;
- private Object _message;
-
- public TaskMessage(int sessionId, long targetTask, long sourceTask, Object message) {
- _sessionId = sessionId;
- _targetTask = targetTask;
- _sourceTask = sourceTask;
- _message = message;
- }
-
- public int sessionId() {
- return _sessionId;
- }
-
- public long targetTask() {
- return _targetTask;
- }
-
- public long sourceTask() {
- return _sourceTask;
- }
-
- public Object message() {
- return _message;
- }
-}
[43/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/metrics/JvmMetricsSet.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/metrics/JvmMetricsSet.scala b/core/src/main/scala/org/apache/gearpump/metrics/JvmMetricsSet.scala
new file mode 100644
index 0000000..87db442
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/metrics/JvmMetricsSet.scala
@@ -0,0 +1,43 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.metrics
+
+import java.util
+import scala.collection.JavaConverters._
+
+import io.gearpump.codahale.metrics.jvm.{MemoryUsageGaugeSet, ThreadStatesGaugeSet}
+import io.gearpump.codahale.metrics.{Metric, MetricSet}
+
+class JvmMetricsSet(name: String) extends MetricSet {
+
+ override def getMetrics: util.Map[String, Metric] = {
+ val memoryMetrics = new MemoryUsageGaugeSet().getMetrics.asScala
+ val threadMetrics = new ThreadStatesGaugeSet().getMetrics.asScala
+ Map(
+ s"$name:memory.total.used" -> memoryMetrics("total.used"),
+ s"$name:memory.total.committed" -> memoryMetrics("total.committed"),
+ s"$name:memory.total.max" -> memoryMetrics("total.max"),
+ s"$name:memory.heap.used" -> memoryMetrics("heap.used"),
+ s"$name:memory.heap.committed" -> memoryMetrics("heap.committed"),
+ s"$name:memory.heap.max" -> memoryMetrics("heap.max"),
+ s"$name:thread.count" -> threadMetrics("count"),
+ s"$name:thread.daemon.count" -> threadMetrics("daemon.count")
+ ).asJava
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/metrics/Meter.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/metrics/Meter.scala b/core/src/main/scala/org/apache/gearpump/metrics/Meter.scala
new file mode 100644
index 0000000..6d89456
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/metrics/Meter.scala
@@ -0,0 +1,44 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.metrics
+
+import io.gearpump.codahale.metrics.{Meter => CodaHaleMeter}
+
+/** See org.apache.gearpump.codahale.metrics.Meter */
+class Meter(val name: String, meter: CodaHaleMeter, sampleRate: Int = 1) {
+ private var sampleCount = 0L
+ private var toBeMarked = 0L
+
+ def mark() {
+ meter.mark(1)
+ }
+
+ def mark(n: Long) {
+ toBeMarked += n
+ sampleCount += 1
+ if (null != meter && sampleCount % sampleRate == 0) {
+ meter.mark(toBeMarked)
+ toBeMarked = 0
+ }
+ }
+
+ def getOneMinuteRate(): Double = {
+ meter.getOneMinuteRate
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/metrics/Metrics.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/metrics/Metrics.scala b/core/src/main/scala/org/apache/gearpump/metrics/Metrics.scala
new file mode 100644
index 0000000..54d8c6a
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/metrics/Metrics.scala
@@ -0,0 +1,160 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.metrics
+
+import scala.collection.JavaConverters._
+
+import akka.actor._
+import org.slf4j.Logger
+
+import io.gearpump.codahale.metrics._
+import org.apache.gearpump.metrics
+import org.apache.gearpump.util.LogUtil
+
+/** Metric objects registry */
+class Metrics(sampleRate: Int) extends Extension {
+
+ val registry = new MetricRegistry()
+
+ def meter(name: String): metrics.Meter = {
+ new metrics.Meter(name, registry.meter(name), sampleRate)
+ }
+
+ def histogram(name: String): Histogram = {
+ new Histogram(name, registry.histogram(name), sampleRate)
+ }
+
+ def histogram(name: String, sampleRate: Int): Histogram = {
+ new Histogram(name, registry.histogram(name), sampleRate)
+ }
+
+ def counter(name: String): Counter = {
+ new Counter(name, registry.counter(name), sampleRate)
+ }
+
+ def register(set: MetricSet): Unit = {
+ val names = registry.getNames
+ val metrics = set.getMetrics.asScala.filterKeys { key => !names.contains(key) }
+ metrics.foreach { kv =>
+ registry.register(kv._1, kv._2)
+ }
+ }
+}
+
+object Metrics extends ExtensionId[Metrics] with ExtensionIdProvider {
+
+ val LOG: Logger = LogUtil.getLogger(getClass)
+ import org.apache.gearpump.util.Constants._
+
+ sealed trait MetricType {
+ def name: String
+ }
+
+ object MetricType {
+ def unapply(obj: MetricType): Option[(Histogram, Counter, Meter, Timer, Gauge)] = {
+ obj match {
+ case x: Histogram => Some((x, null, null, null, null))
+ case x: Counter => Some((null, x, null, null, null))
+ case x: Meter => Some((null, null, x, null, null))
+ case x: Timer => Some((null, null, null, x, null))
+ case g: Gauge => Some((null, null, null, null, g))
+ }
+ }
+
+ def apply(h: Histogram, c: Counter, m: Meter, t: Timer, g: Gauge): MetricType = {
+ val result =
+ if (h != null) h
+ else if (c != null) c
+ else if (m != null) m
+ else if (t != null) t
+ else if (g != null) g
+ else null
+ result
+ }
+ }
+
+ case class Histogram (
+ name: String, mean: Double,
+ stddev: Double, median: Double,
+ p95: Double, p99: Double, p999: Double)
+ extends MetricType
+
+ case class Counter(name: String, value: Long) extends MetricType
+
+ case class Meter(
+ name: String, count: Long, meanRate: Double,
+ m1: Double, rateUnit: String)
+ extends MetricType
+
+ case class Timer(
+ name: String, count: Long, min: Double, max: Double,
+ mean: Double, stddev: Double, median: Double,
+ p75: Double, p95: Double, p98: Double,
+ p99: Double, p999: Double, meanRate: Double,
+ m1: Double, m5: Double, m15: Double,
+ rateUnit: String, durationUnit: String)
+ extends MetricType
+
+ case class Gauge(name: String, value: Long) extends MetricType
+
+ case object ReportMetrics
+
+ case class DemandMoreMetrics(subscriber: ActorRef)
+
+ override def get(system: ActorSystem): Metrics = super.get(system)
+
+ override def lookup: ExtensionId[Metrics] = Metrics
+
+ override def createExtension(system: ExtendedActorSystem): Metrics = {
+ val metricsEnabled = system.settings.config.getBoolean(GEARPUMP_METRIC_ENABLED)
+ LOG.info(s"Metrics is enabled..., $metricsEnabled")
+ val sampleRate = system.settings.config.getInt(GEARPUMP_METRIC_SAMPLE_RATE)
+ if (metricsEnabled) {
+ val meters = new Metrics(sampleRate)
+ meters
+ } else {
+ new DummyMetrics
+ }
+ }
+
+ class DummyMetrics extends Metrics(1) {
+ override def register(set: MetricSet): Unit = Unit
+
+ private val meter = new metrics.Meter("", null) {
+ override def mark(): Unit = Unit
+ override def mark(n: Long): Unit = Unit
+ override def getOneMinuteRate(): Double = 0
+ }
+
+ private val histogram = new metrics.Histogram("", null) {
+ override def update(value: Long): Unit = Unit
+ override def getMean(): Double = 0
+ override def getStdDev(): Double = 0
+ }
+
+ private val counter = new metrics.Counter("", null) {
+ override def inc(): Unit = Unit
+ override def inc(n: Long): Unit = Unit
+ }
+
+ override def meter(name: String): metrics.Meter = meter
+ override def histogram(name: String): metrics.Histogram = histogram
+ override def counter(name: String): metrics.Counter = counter
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/metrics/MetricsAggregator.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/metrics/MetricsAggregator.scala b/core/src/main/scala/org/apache/gearpump/metrics/MetricsAggregator.scala
new file mode 100644
index 0000000..08dad57
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/metrics/MetricsAggregator.scala
@@ -0,0 +1,32 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.metrics
+
+import org.apache.gearpump.cluster.MasterToClient.HistoryMetricsItem
+
+/**
+ * Aggregates a larger set of metrics into a smaller set
+ *
+ * Sub Class must implement a constructor with signature like this:
+ * MetricsAggregator(config: Config)
+ */
+trait MetricsAggregator {
+ def aggregate(options: Map[String, String], inputs: Iterator[HistoryMetricsItem])
+ : List[HistoryMetricsItem]
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/metrics/MetricsReporterService.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/metrics/MetricsReporterService.scala b/core/src/main/scala/org/apache/gearpump/metrics/MetricsReporterService.scala
new file mode 100644
index 0000000..9b506af
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/metrics/MetricsReporterService.scala
@@ -0,0 +1,109 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.metrics
+
+import java.net.InetSocketAddress
+import java.util.concurrent.TimeUnit
+import scala.concurrent.duration._
+
+import akka.actor.{Actor, ActorRef}
+
+import io.gearpump.codahale.metrics.graphite.{Graphite, GraphiteReporter}
+import io.gearpump.codahale.metrics.{MetricFilter, Slf4jReporter}
+import org.apache.gearpump.metrics.Metrics.{DemandMoreMetrics, ReportMetrics}
+import org.apache.gearpump.metrics.MetricsReporterService.ReportTo
+import org.apache.gearpump.util.Constants._
+import org.apache.gearpump.util.LogUtil
+
+/**
+ * Reports the metrics data to some where, like Ganglia, remote Akka actor, log files...
+ *
+ * @param metrics Holds a list of metrics object.
+ */
+class MetricsReporterService(metrics: Metrics) extends Actor {
+
+ private val LOG = LogUtil.getLogger(getClass)
+ private implicit val system = context.system
+
+ private val reportInterval = system.settings.config.getInt(GEARPUMP_METRIC_REPORT_INTERVAL)
+ private val reporter = getReporter
+ implicit val dispatcher = context.dispatcher
+
+ def receive: Receive = {
+ // The subscriber is demanding more messages.
+ case DemandMoreMetrics(subscriber) => {
+ reporter.report(subscriber)
+ context.system.scheduler.scheduleOnce(reportInterval.milliseconds,
+ subscriber, ReportMetrics)
+ }
+ }
+
+ def startGraphiteReporter(): ReportTo = {
+ val graphiteHost = system.settings.config.getString(GEARPUMP_METRIC_GRAPHITE_HOST)
+ val graphitePort = system.settings.config.getInt(GEARPUMP_METRIC_GRAPHITE_PORT)
+
+ val graphite = new Graphite(new InetSocketAddress(graphiteHost, graphitePort))
+ LOG.info(s"reporting to $graphiteHost, $graphitePort")
+ new ReportTo {
+ private val reporter = GraphiteReporter.forRegistry(metrics.registry)
+ .convertRatesTo(TimeUnit.SECONDS)
+ .convertDurationsTo(TimeUnit.MILLISECONDS)
+ .filter(MetricFilter.ALL)
+ .build(graphite)
+
+ override def report(to: ActorRef): Unit = reporter.report()
+ }
+ }
+
+ def startSlf4jReporter(): ReportTo = {
+ new ReportTo {
+ val reporter = Slf4jReporter.forRegistry(metrics.registry)
+ .convertRatesTo(TimeUnit.SECONDS)
+ .convertDurationsTo(TimeUnit.MILLISECONDS)
+ .filter(MetricFilter.ALL)
+ .outputTo(LOG)
+ .build()
+
+ override def report(to: ActorRef): Unit = reporter.report()
+ }
+ }
+
+ def startAkkaReporter(): ReportTo = {
+ new AkkaReporter(system, metrics.registry)
+ }
+
+ def getReporter: ReportTo = {
+ val reporterType = system.settings.config.getString(GEARPUMP_METRIC_REPORTER)
+ LOG.info(s"Metrics reporter is enabled, using $reporterType reporter")
+ val reporter = reporterType match {
+ case "graphite" => startGraphiteReporter()
+ case "logfile" => startSlf4jReporter()
+ case "akka" => startAkkaReporter()
+ }
+ reporter
+ }
+}
+
+object MetricsReporterService {
+
+ /** Target where user want to report the metrics data to */
+ trait ReportTo {
+ def report(to: ActorRef): Unit
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/package.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/package.scala b/core/src/main/scala/org/apache/gearpump/package.scala
new file mode 100644
index 0000000..b1118d3
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/package.scala
@@ -0,0 +1,24 @@
+/*
+ * 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.
+ */
+
+package org.apache
+
+package object gearpump {
+ type TimeStamp = Long
+ val LatestTime = -1
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/partitioner/BroadcastPartitioner.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/partitioner/BroadcastPartitioner.scala b/core/src/main/scala/org/apache/gearpump/partitioner/BroadcastPartitioner.scala
new file mode 100644
index 0000000..99cbcb6
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/partitioner/BroadcastPartitioner.scala
@@ -0,0 +1,36 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.partitioner
+
+import org.apache.gearpump.Message
+
+/** Used by storm module to broadcast message to all downstream tasks */
+class BroadcastPartitioner extends MulticastPartitioner {
+ private var lastPartitionNum = -1
+ private var partitions = Array.empty[Int]
+
+ override def getPartitions(
+ msg: Message, partitionNum: Int, currentPartitionId: Int): Array[Int] = {
+ if (partitionNum != lastPartitionNum) {
+ partitions = (0 until partitionNum).toArray
+ lastPartitionNum = partitionNum
+ }
+ partitions
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/partitioner/CoLocationPartitioner.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/partitioner/CoLocationPartitioner.scala b/core/src/main/scala/org/apache/gearpump/partitioner/CoLocationPartitioner.scala
new file mode 100644
index 0000000..5a3eec4
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/partitioner/CoLocationPartitioner.scala
@@ -0,0 +1,31 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.partitioner
+
+import org.apache.gearpump.Message
+
+/**
+ * Will have the same parallelism with last processor
+ * And each task in current processor will co-locate with task of last processor
+ */
+class CoLocationPartitioner extends UnicastPartitioner {
+ override def getPartition(msg: Message, partitionNum: Int, currentPartitionId: Int): Int = {
+ currentPartitionId
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/partitioner/HashPartitioner.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/partitioner/HashPartitioner.scala b/core/src/main/scala/org/apache/gearpump/partitioner/HashPartitioner.scala
new file mode 100644
index 0000000..ee684a9
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/partitioner/HashPartitioner.scala
@@ -0,0 +1,32 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.partitioner
+
+import org.apache.gearpump.Message
+
+/**
+ * Only make sense when the message has implemented the hashCode()
+ * Otherwise, it will use Object.hashCode(), which will not return
+ * same hash code after serialization and deserialization.
+ */
+class HashPartitioner extends UnicastPartitioner {
+ override def getPartition(msg: Message, partitionNum: Int, currentPartitionId: Int): Int = {
+ (msg.msg.hashCode() & Integer.MAX_VALUE) % partitionNum
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/partitioner/Partitioner.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/partitioner/Partitioner.scala b/core/src/main/scala/org/apache/gearpump/partitioner/Partitioner.scala
new file mode 100644
index 0000000..d68fa65
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/partitioner/Partitioner.scala
@@ -0,0 +1,109 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.partitioner
+
+import scala.reflect.ClassTag
+
+import org.apache.commons.lang.SerializationUtils
+
+import org.apache.gearpump.Message
+
+/**
+ * For processor chain: A (3 tasks) {@literal ->} B (3 tasks), partitioner decide how ONE task
+ * of upstream processor A send to several tasks of downstream processor B.
+ */
+sealed trait Partitioner extends Serializable
+
+/**
+ * For processor chain: A (3 tasks) {@literal ->} B (3 tasks), UnicastPartitioner does
+ * ONE-task {@literal ->} ONE-task mapping.
+ */
+trait UnicastPartitioner extends Partitioner {
+
+ /**
+ * Gets the SINGLE downstream processor task index to send message to.
+ *
+ * @param msg Message you want to send
+ * @param partitionNum How many tasks does the downstream processor have.
+ * @param upstreamTaskIndex Upstream task's task index who trigger the getPartition() call.
+ *
+ * @return ONE task index of downstream processor.
+ */
+ def getPartition(msg: Message, partitionNum: Int, upstreamTaskIndex: Int): Int
+
+ def getPartition(msg: Message, partitionNum: Int): Int = {
+ getPartition(msg, partitionNum, Partitioner.UNKNOWN_PARTITION_ID)
+ }
+}
+
+trait MulticastPartitioner extends Partitioner {
+
+ /**
+ * Gets a list of downstream processor task indexes to send message to.
+ *
+ * @param upstreamTaskIndex Current sender task's task index.
+ *
+ */
+ def getPartitions(msg: Message, partitionNum: Int, upstreamTaskIndex: Int): Array[Int]
+
+ def getPartitions(msg: Message, partitionNum: Int): Array[Int] = {
+ getPartitions(msg, partitionNum, Partitioner.UNKNOWN_PARTITION_ID)
+ }
+}
+
+sealed trait PartitionerFactory {
+
+ def name: String
+
+ def partitioner: Partitioner
+}
+
+/** Stores the Partitioner in an object. To use it, user need to deserialize the object */
+class PartitionerObject(private[this] val _partitioner: Partitioner)
+ extends PartitionerFactory with Serializable {
+
+ override def name: String = partitioner.getClass.getName
+
+ override def partitioner: Partitioner = {
+ SerializationUtils.clone(_partitioner).asInstanceOf[Partitioner]
+ }
+}
+
+/** Store the partitioner in class Name, the user need to instantiate a new class */
+class PartitionerByClassName(partitionerClass: String)
+ extends PartitionerFactory with Serializable {
+
+ override def name: String = partitionerClass
+ override def partitioner: Partitioner = {
+ Class.forName(partitionerClass).newInstance().asInstanceOf[Partitioner]
+ }
+}
+
+/**
+ * @param partitionerFactory How we construct a Partitioner.
+ */
+case class PartitionerDescription(partitionerFactory: PartitionerFactory)
+
+object Partitioner {
+ val UNKNOWN_PARTITION_ID = -1
+
+ def apply[T <: Partitioner](implicit clazz: ClassTag[T]): PartitionerDescription = {
+ PartitionerDescription(new PartitionerByClassName(clazz.runtimeClass.getName))
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/partitioner/ShuffleGroupingPartitioner.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/partitioner/ShuffleGroupingPartitioner.scala b/core/src/main/scala/org/apache/gearpump/partitioner/ShuffleGroupingPartitioner.scala
new file mode 100644
index 0000000..55ef614
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/partitioner/ShuffleGroupingPartitioner.scala
@@ -0,0 +1,45 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.partitioner
+
+import scala.util.Random
+
+import org.apache.gearpump.Message
+
+/**
+ * The idea of ShuffleGroupingPartitioner is derived from Storm.
+ * Messages are randomly distributed across the downstream's tasks in a way such that
+ * each task is guaranteed to get an equal number of messages.
+ */
+class ShuffleGroupingPartitioner extends UnicastPartitioner {
+ private val random = new Random
+ private var index = -1
+ private var partitions = List.empty[Int]
+ override def getPartition(msg: Message, partitionNum: Int, currentPartitionId: Int): Int = {
+ index += 1
+ if (partitions.isEmpty) {
+ partitions = 0.until(partitionNum).toList
+ partitions = random.shuffle(partitions)
+ } else if (index >= partitionNum) {
+ index = 0
+ partitions = random.shuffle(partitions)
+ }
+ partitions(index)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/partitioner/ShufflePartitioner.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/partitioner/ShufflePartitioner.scala b/core/src/main/scala/org/apache/gearpump/partitioner/ShufflePartitioner.scala
new file mode 100644
index 0000000..5c66d66
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/partitioner/ShufflePartitioner.scala
@@ -0,0 +1,44 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.partitioner
+
+import java.util.Random
+
+import org.apache.gearpump.Message
+
+/**
+ * Round Robin partition the data to downstream processor tasks.
+ */
+class ShufflePartitioner extends UnicastPartitioner {
+ private var seed = 0
+ private var count = 0
+
+ override def getPartition(msg: Message, partitionNum: Int, currentPartitionId: Int): Int = {
+
+ if (seed == 0) {
+ seed = newSeed()
+ }
+
+ val result = ((count + seed) & Integer.MAX_VALUE) % partitionNum
+ count = count + 1
+ result
+ }
+
+ private def newSeed(): Int = new Random().nextInt()
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/security/Authenticator.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/security/Authenticator.scala b/core/src/main/scala/org/apache/gearpump/security/Authenticator.scala
new file mode 100644
index 0000000..497506b
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/security/Authenticator.scala
@@ -0,0 +1,68 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.security
+import scala.concurrent.{ExecutionContext, Future}
+
+import org.apache.gearpump.security.Authenticator.AuthenticationResult
+
+/**
+ * Authenticator for UI dashboard.
+ *
+ * Sub Class must implement a constructor with signature like this:
+ * this(config: Config)
+ */
+trait Authenticator {
+
+ // TODO: Change the signature to return more attributes of user credentials...
+ def authenticate(
+ user: String, password: String, ec: ExecutionContext): Future[AuthenticationResult]
+}
+
+object Authenticator {
+
+ trait AuthenticationResult {
+
+ def authenticated: Boolean
+
+ def permissionLevel: Int
+ }
+
+ val UnAuthenticated = new AuthenticationResult {
+ override val authenticated = false
+ override val permissionLevel = -1
+ }
+
+ /** Guest can view but have no permission to submit app or write */
+ val Guest = new AuthenticationResult {
+ override val authenticated = true
+ override val permissionLevel = 1000
+ }
+
+ /** User can submit app, kill app, but have no permission to add or remote machines */
+ val User = new AuthenticationResult {
+ override val authenticated = true
+ override val permissionLevel = 1000 + Guest.permissionLevel
+ }
+
+ /** Super user */
+ val Admin = new AuthenticationResult {
+ override val authenticated = true
+ override val permissionLevel = 1000 + User.permissionLevel
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/security/ConfigFileBasedAuthenticator.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/security/ConfigFileBasedAuthenticator.scala b/core/src/main/scala/org/apache/gearpump/security/ConfigFileBasedAuthenticator.scala
new file mode 100644
index 0000000..110fd8c
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/security/ConfigFileBasedAuthenticator.scala
@@ -0,0 +1,120 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.security
+
+import scala.concurrent.{ExecutionContext, Future}
+
+import com.typesafe.config.Config
+
+import org.apache.gearpump.security.Authenticator.AuthenticationResult
+import org.apache.gearpump.security.ConfigFileBasedAuthenticator._
+
+object ConfigFileBasedAuthenticator {
+
+ private val ROOT = "gearpump.ui-security.config-file-based-authenticator"
+ private val ADMINS = ROOT + "." + "admins"
+ private val USERS = ROOT + "." + "users"
+ private val GUESTS = ROOT + "." + "guests"
+
+ private case class Credentials(
+ admins: Map[String, String], users: Map[String, String], guests: Map[String, String]) {
+
+ def verify(user: String, password: String): AuthenticationResult = {
+ if (admins.contains(user)) {
+ if (verify(user, password, admins)) {
+ Authenticator.Admin
+ } else {
+ Authenticator.UnAuthenticated
+ }
+ } else if (users.contains(user)) {
+ if (verify(user, password, users)) {
+ Authenticator.User
+ } else {
+ Authenticator.UnAuthenticated
+ }
+ } else if (guests.contains(user)) {
+ if (verify(user, password, guests)) {
+ Authenticator.Guest
+ } else {
+ Authenticator.UnAuthenticated
+ }
+ } else {
+ Authenticator.UnAuthenticated
+ }
+ }
+
+ private def verify(user: String, password: String, map: Map[String, String]): Boolean = {
+ val storedPass = map(user)
+ PasswordUtil.verify(password, storedPass)
+ }
+ }
+}
+
+/**
+ * UI dashboard authenticator based on configuration file.
+ *
+ * It has three categories of users: admins, users, and guests.
+ * admins have unlimited permission, like shutdown a cluster, add/remove machines.
+ * users have limited permission to submit an application and etc..
+ * guests can not submit/kill applications, but can view the application status.
+ *
+ * see conf/gear.conf section gearpump.ui-security.config-file-based-authenticator to find
+ * information about how to configure this authenticator.
+ *
+ * [Security consideration]
+ * It will keep one-way sha1 digest of password instead of password itself. The original password is
+ * NOT kept in any way, so generally it is safe.
+ *
+ *
+ * digesting flow (from original password to digest):
+ * {{{
+ * random salt byte array of length 8 -> byte array of (salt + sha1(salt, password)) ->
+ * base64Encode.
+ * }}}
+ *
+ * Verification user input password with stored digest:
+ * {{{
+ * base64Decode -> extract salt -> do sha1(salt, password) -> generate digest:
+ * salt + sha1 -> compare the generated digest with the stored digest.
+ * }}}
+ */
+class ConfigFileBasedAuthenticator(config: Config) extends Authenticator {
+
+ private val credentials = loadCredentials(config)
+
+ override def authenticate(user: String, password: String, ec: ExecutionContext)
+ : Future[AuthenticationResult] = {
+ implicit val ctx = ec
+ Future {
+ credentials.verify(user, password)
+ }
+ }
+
+ private def loadCredentials(config: Config): Credentials = {
+ val admins = configToMap(config, ADMINS)
+ val users = configToMap(config, USERS)
+ val guests = configToMap(config, GUESTS)
+ new Credentials(admins, users, guests)
+ }
+
+ private def configToMap(config: Config, path: String) = {
+ import scala.collection.JavaConverters._
+ config.getConfig(path).root.unwrapped.asScala.toMap map { case (k, v) => k -> v.toString }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/security/PasswordUtil.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/security/PasswordUtil.scala b/core/src/main/scala/org/apache/gearpump/security/PasswordUtil.scala
new file mode 100644
index 0000000..25b68c6
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/security/PasswordUtil.scala
@@ -0,0 +1,102 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.security
+
+import java.security.MessageDigest
+import scala.util.Try
+
+import sun.misc.{BASE64Decoder, BASE64Encoder}
+
+/**
+ * Util to verify whether user input password is valid or not.
+ * It use sha1 to do the digesting.
+ */
+object PasswordUtil {
+ private val SALT_LENGTH = 8
+
+ /**
+ * Verifies user input password with stored digest:
+ * {{{
+ * base64Decode -> extract salt -> do sha1(salt, password) ->
+ * generate digest: salt + sha1 -> compare the generated digest with the stored digest.
+ * }}}
+ */
+ def verify(password: String, stored: String): Boolean = {
+ Try {
+ val decoded = base64Decode(stored)
+ val salt = new Array[Byte](SALT_LENGTH)
+ Array.copy(decoded, 0, salt, 0, SALT_LENGTH)
+
+ hash(password, salt) == stored
+ }.getOrElse(false)
+ }
+ /**
+ * digesting flow (from original password to digest):
+ * {{{
+ * random salt byte array of length 8 ->
+ * byte array of (salt + sha1(salt, password)) -> base64Encode
+ * }}}
+ */
+ def hash(password: String): String = {
+ // Salt generation 64 bits long
+ val salt = new Array[Byte](SALT_LENGTH)
+ new java.util.Random().nextBytes(salt)
+ hash(password, salt)
+ }
+
+ private def hash(password: String, salt: Array[Byte]): String = {
+ val digest = MessageDigest.getInstance("SHA-1")
+ digest.reset()
+ digest.update(salt)
+ var input = digest.digest(password.getBytes("UTF-8"))
+ digest.reset()
+ input = digest.digest(input)
+ val withSalt = salt ++ input
+ base64Encode(withSalt)
+ }
+
+ private def base64Encode(data: Array[Byte]): String = {
+ val endecoder = new BASE64Encoder()
+ endecoder.encode(data)
+ }
+
+ private def base64Decode(data: String): Array[Byte] = {
+ val decoder = new BASE64Decoder()
+ decoder.decodeBuffer(data)
+ }
+
+ // scalastyle:off println
+ private def help() = {
+ Console.println("usage: gear org.apache.gearpump.security.PasswordUtil -password " +
+ "<your password>")
+ }
+
+ def main(args: Array[String]): Unit = {
+ if (args.length != 2 || args(0) != "-password") {
+ help()
+ } else {
+ val pass = args(1)
+ val result = hash(pass)
+ Console.println("Here is the hashed password")
+ Console.println("==============================")
+ Console.println(result)
+ }
+ }
+ // scalastyle:on println
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/serializer/FastKryoSerializationFramework.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/serializer/FastKryoSerializationFramework.scala b/core/src/main/scala/org/apache/gearpump/serializer/FastKryoSerializationFramework.scala
new file mode 100644
index 0000000..6295faf
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/serializer/FastKryoSerializationFramework.scala
@@ -0,0 +1,46 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.serializer
+
+import akka.actor.ExtendedActorSystem
+
+import org.apache.gearpump.cluster.UserConfig
+
+/**
+ * A build-in serializer framework using kryo
+ *
+ * NOTE: The Kryo here is a shaded version by Gearpump
+ */
+class FastKryoSerializationFramework extends SerializationFramework {
+ private var system: ExtendedActorSystem = null
+
+ private lazy val pool = new ThreadLocal[Serializer]() {
+ override def initialValue(): Serializer = {
+ new FastKryoSerializer(system)
+ }
+ }
+
+ override def init(system: ExtendedActorSystem, config: UserConfig): Unit = {
+ this.system = system
+ }
+
+ override def get(): Serializer = {
+ pool.get()
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/serializer/FastKryoSerializer.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/serializer/FastKryoSerializer.scala b/core/src/main/scala/org/apache/gearpump/serializer/FastKryoSerializer.scala
new file mode 100644
index 0000000..ed1e347
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/serializer/FastKryoSerializer.scala
@@ -0,0 +1,83 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.serializer
+
+import akka.actor.ExtendedActorSystem
+
+import io.gearpump.esotericsoftware.kryo.Kryo.DefaultInstantiatorStrategy
+import io.gearpump.objenesis.strategy.StdInstantiatorStrategy
+import io.gearpump.romix.serialization.kryo.KryoSerializerWrapper
+import org.apache.gearpump.serializer.FastKryoSerializer.KryoSerializationException
+import org.apache.gearpump.util.LogUtil
+
+class FastKryoSerializer(system: ExtendedActorSystem) extends Serializer {
+
+ private val LOG = LogUtil.getLogger(getClass)
+ private val config = system.settings.config
+
+ private val kryoSerializer = new KryoSerializerWrapper(system)
+ private val kryo = kryoSerializer.kryo
+ val strategy = new DefaultInstantiatorStrategy
+ strategy.setFallbackInstantiatorStrategy(new StdInstantiatorStrategy)
+ kryo.setInstantiatorStrategy(strategy)
+ private val kryoClazz = new GearpumpSerialization(config).customize(kryo)
+
+ override def serialize(message: Any): Array[Byte] = {
+ try {
+ kryoSerializer.toBinary(message)
+ } catch {
+ case ex: java.lang.IllegalArgumentException =>
+ val clazz = message.getClass
+ val error = s"""
+ | ${ex.getMessage}
+ |You can also register the class by providing a configuration with serializer
+ |defined,
+ |
+ |gearpump{
+ | serializers {
+ | ## Follow this format when adding new serializer for new message types
+ | # "yourpackage.YourClass" = "yourpackage.YourSerializerForThisClass"
+ |
+ | ## If you intend to use default serializer for this class, then you can write this
+ | # "yourpackage.YourClass" = ""
+ | }
+ |}
+ |
+ |If you want to register the serializer globally, you need to change
+ |gear.conf on every worker in the cluster; if you only want to register
+ |the serializer for a single streaming application, you need to create
+ |a file under conf/ named application.conf, and add the above configuration
+ |into application.conf. To verify whether the configuration is effective,
+ |you can browser your UI http://{UI Server Host}:8090/api/v1.0/app/{appId}/config,
+ |and check whether your custom serializer is added.
+ """.stripMargin
+
+ LOG.error(error, ex)
+ throw new KryoSerializationException(error, ex)
+ }
+ }
+
+ override def deserialize(msg: Array[Byte]): Any = {
+ kryoSerializer.fromBinary(msg)
+ }
+}
+
+object FastKryoSerializer {
+ class KryoSerializationException(msg: String, ex: Throwable = null) extends Exception(msg, ex)
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/serializer/GearpumpSerialization.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/serializer/GearpumpSerialization.scala b/core/src/main/scala/org/apache/gearpump/serializer/GearpumpSerialization.scala
new file mode 100644
index 0000000..f9c6299
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/serializer/GearpumpSerialization.scala
@@ -0,0 +1,60 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.serializer
+
+import com.typesafe.config.Config
+import org.slf4j.Logger
+
+import io.gearpump.esotericsoftware.kryo.{Kryo, Serializer => KryoSerializer}
+import org.apache.gearpump.util.{Constants, LogUtil}
+
+class GearpumpSerialization(config: Config) {
+
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+
+ def customize(kryo: Kryo): Unit = {
+
+ val serializationMap = configToMap(config, Constants.GEARPUMP_SERIALIZERS)
+
+ serializationMap.foreach { kv =>
+ val (key, value) = kv
+ val keyClass = Class.forName(key)
+
+ if (value == null || value.isEmpty) {
+
+ // Use default serializer for this class type
+ kryo.register(keyClass)
+ } else {
+ val valueClass = Class.forName(value)
+ val register = kryo.register(keyClass,
+ valueClass.newInstance().asInstanceOf[KryoSerializer[_]])
+ LOG.debug(s"Registering ${keyClass}, id: ${register.getId}")
+ }
+ }
+ kryo.setReferences(false)
+
+ // Requires the user to register the class first before using
+ kryo.setRegistrationRequired(true)
+ }
+
+ private final def configToMap(config: Config, path: String) = {
+ import scala.collection.JavaConverters._
+ config.getConfig(path).root.unwrapped.asScala.toMap map { case (k, v) => k -> v.toString }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/serializer/SerializationFramework.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/serializer/SerializationFramework.scala b/core/src/main/scala/org/apache/gearpump/serializer/SerializationFramework.scala
new file mode 100644
index 0000000..995ba1f
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/serializer/SerializationFramework.scala
@@ -0,0 +1,44 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.serializer
+
+import akka.actor.ExtendedActorSystem
+
+import org.apache.gearpump.cluster.UserConfig
+
+/**
+ * User are allowed to use a customized serialization framework by extending this
+ * interface.
+ */
+trait SerializationFramework {
+ def init(system: ExtendedActorSystem, config: UserConfig)
+
+ /**
+ * Need to be thread safe
+ *
+ * Get a serializer to use.
+ * Note: this method can be called in a multi-thread environment. It's the
+ * responsibility of SerializationFramework Developer to assure this method
+ * is thread safe.
+ *
+ * To be thread-safe, one recommendation would be using a thread local pool
+ * to maintain reference to Serializer of same thread.
+ */
+ def get(): Serializer
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/serializer/Serializer.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/serializer/Serializer.scala b/core/src/main/scala/org/apache/gearpump/serializer/Serializer.scala
new file mode 100644
index 0000000..7c0f4bf
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/serializer/Serializer.scala
@@ -0,0 +1,28 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.serializer
+
+/**
+ * User defined message serializer
+ */
+trait Serializer {
+ def serialize(message: Any): Array[Byte]
+
+ def deserialize(msg: Array[Byte]): Any
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/transport/Express.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/transport/Express.scala b/core/src/main/scala/org/apache/gearpump/transport/Express.scala
new file mode 100644
index 0000000..ef1e8d9
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/transport/Express.scala
@@ -0,0 +1,135 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.transport
+
+import scala.collection.immutable.LongMap
+import scala.concurrent._
+
+import akka.actor._
+import akka.agent.Agent
+import org.slf4j.Logger
+
+import org.apache.gearpump.transport.netty.Client.Close
+import org.apache.gearpump.transport.netty.{TaskMessage, Context}
+import org.apache.gearpump.util.LogUtil
+
+trait ActorLookupById {
+
+ /** Lookup actor ref for local task actor by providing a TaskId (TaskId.toLong) */
+ def lookupLocalActor(id: Long): Option[ActorRef]
+}
+
+/**
+ * Custom networking layer.
+ *
+ * It will translate long sender/receiver address to shorter ones to reduce
+ * the network overhead.
+ */
+class Express(val system: ExtendedActorSystem) extends Extension with ActorLookupById {
+
+ import system.dispatcher
+
+ import org.apache.gearpump.transport.Express._
+ val localActorMap = Agent(LongMap.empty[ActorRef])
+ val remoteAddressMap = Agent(Map.empty[Long, HostPort])
+
+ val remoteClientMap = Agent(Map.empty[HostPort, ActorRef])
+
+ val conf = system.settings.config
+
+ lazy val (context, serverPort, localHost) = init
+
+ lazy val init = {
+ LOG.info(s"Start Express init ...${system.name}")
+ val context = new Context(system, conf)
+ val serverPort = context.bind("netty-server", this)
+ val localHost = HostPort(system.provider.getDefaultAddress.host.get, serverPort)
+ LOG.info(s"binding to netty server $localHost")
+
+ system.registerOnTermination(new Runnable {
+ override def run(): Unit = context.close()
+ })
+ (context, serverPort, localHost)
+ }
+
+ def unregisterLocalActor(id: Long): Unit = {
+ localActorMap.sendOff(_ - id)
+ }
+
+ /** Start Netty client actors to connect to remote machines */
+ def startClients(hostPorts: Set[HostPort]): Future[Map[HostPort, ActorRef]] = {
+ val clientsToClose = remoteClientMap.get().filterKeys(!hostPorts.contains(_)).keySet
+ closeClients(clientsToClose)
+ hostPorts.toList.foldLeft(Future(Map.empty[HostPort, ActorRef])) { (future, hostPort) =>
+ remoteClientMap.alter { map =>
+ if (!map.contains(hostPort)) {
+ val actor = context.connect(hostPort)
+ map + (hostPort -> actor)
+ } else {
+ map
+ }
+ }
+ }
+ }
+
+ def closeClients(hostPorts: Set[HostPort]): Future[Map[HostPort, ActorRef]] = {
+ remoteClientMap.alter { map =>
+ map.filterKeys(hostPorts.contains).foreach { hostAndClient =>
+ val (_, client) = hostAndClient
+ client ! Close
+ }
+ map -- hostPorts
+ }
+ }
+
+ def registerLocalActor(id: Long, actor: ActorRef): Unit = {
+ LOG.info(s"RegisterLocalActor: $id, actor: ${actor.path.name}")
+ init
+ localActorMap.sendOff(_ + (id -> actor))
+ }
+
+ def lookupLocalActor(id: Long): Option[ActorRef] = localActorMap.get().get(id)
+
+ def lookupRemoteAddress(id: Long): Option[HostPort] = remoteAddressMap.get().get(id)
+
+ /** Send message to remote task */
+ def transport(taskMessage: TaskMessage, remote: HostPort): Unit = {
+
+ val remoteClient = remoteClientMap.get.get(remote)
+ if (remoteClient.isDefined) {
+ remoteClient.get.tell(taskMessage, Actor.noSender)
+ } else {
+ val errorMsg = s"Clients has not been launched properly before transporting messages, " +
+ s"the destination is $remote"
+ LOG.error(errorMsg)
+ throw new Exception(errorMsg)
+ }
+ }
+}
+
+/** A customized transport layer by using Akka extension */
+object Express extends ExtensionId[Express] with ExtensionIdProvider {
+ val LOG: Logger = LogUtil.getLogger(getClass)
+
+ override def get(system: ActorSystem): Express = super.get(system)
+
+ override def lookup: ExtensionId[Express] = Express
+
+ override def createExtension(system: ExtendedActorSystem): Express = new Express(system)
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/transport/HostPort.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/transport/HostPort.scala b/core/src/main/scala/org/apache/gearpump/transport/HostPort.scala
new file mode 100644
index 0000000..d6dcd08
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/transport/HostPort.scala
@@ -0,0 +1,32 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.transport
+
+case class HostPort(host: String, port: Int) {
+ def toTuple: (String, Int) = {
+ (host, port)
+ }
+}
+
+object HostPort {
+ def apply(address: String): HostPort = {
+ val hostAndPort = address.split(":")
+ new HostPort(hostAndPort(0), hostAndPort(1).toInt)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/transport/netty/Client.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/transport/netty/Client.scala b/core/src/main/scala/org/apache/gearpump/transport/netty/Client.scala
new file mode 100644
index 0000000..506e11c
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/transport/netty/Client.scala
@@ -0,0 +1,249 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.transport.netty
+
+import java.net.{ConnectException, InetSocketAddress}
+import java.nio.channels.ClosedChannelException
+import java.util
+import java.util.Random
+import java.util.concurrent.TimeUnit
+
+import scala.concurrent.duration.FiniteDuration
+import scala.language.implicitConversions
+
+import akka.actor.Actor
+import org.jboss.netty.bootstrap.ClientBootstrap
+import org.jboss.netty.channel._
+import org.slf4j.Logger
+
+import org.apache.gearpump.transport.HostPort
+import org.apache.gearpump.util.LogUtil
+
+/**
+ * Netty Client implemented as an actor, on the other side, there is a netty server Actor.
+ * All messages sent to this actor will be forwarded to remote machine.
+ */
+class Client(conf: NettyConfig, factory: ChannelFactory, hostPort: HostPort) extends Actor {
+ import org.apache.gearpump.transport.netty.Client._
+
+ val name = s"netty-client-$hostPort"
+
+ private final var bootstrap: ClientBootstrap = null
+ private final val random: Random = new Random
+ private val serializer = conf.newTransportSerializer
+ private var channel: Channel = null
+
+ var batch = new util.ArrayList[TaskMessage]
+
+ private val init = {
+ bootstrap = NettyUtil.createClientBootStrap(factory,
+ new ClientPipelineFactory(name, conf), conf.buffer_size)
+ self ! Connect(0)
+ }
+
+ def receive: Receive = messageHandler orElse connectionHandler
+
+ def messageHandler: Receive = {
+ case msg: TaskMessage =>
+ batch.add(msg)
+ case flush@Flush(flushChannel) =>
+ if (channel != flushChannel) {
+ Unit // Drop, as it belong to old channel flush message
+ } else if (batch.size > 0 && flushChannel.isWritable) {
+ send(flushChannel, batch.iterator)
+ batch.clear()
+ self ! flush
+ } else {
+ import context.dispatcher
+ context.system.scheduler.scheduleOnce(
+ new FiniteDuration(conf.flushCheckInterval, TimeUnit.MILLISECONDS), self, flush)
+ }
+ }
+
+ def connectionHandler: Receive = {
+ case ChannelReady(channel) =>
+ this.channel = channel
+ self ! Flush(channel)
+ case Connect(tries) =>
+ if (null == channel) {
+ connect(tries)
+ } else {
+ LOG.error("there already exist a channel, will not establish a new one...")
+ }
+ case CompareAndReconnectIfEqual(oldChannel) =>
+ if (oldChannel == channel) {
+ channel = null
+ self ! Connect(0)
+ }
+ case Close =>
+ close()
+ context.become(closed)
+ }
+
+ def closed: Receive = {
+ case msg: AnyRef =>
+ LOG.error(s"This client $name is closed, drop any message ${msg.getClass.getSimpleName}...")
+ }
+
+ private def connect(tries: Int): Unit = {
+ LOG.info(s"netty client try to connect to $name, tries: $tries")
+ if (tries <= conf.max_retries) {
+ val remote_addr = new InetSocketAddress(hostPort.host, hostPort.port)
+ val future = bootstrap.connect(remote_addr)
+ future success { current =>
+ LOG.info(s"netty client successfully connectted to $name, tries: $tries")
+ self ! ChannelReady(current)
+ } fail { (current, ex) =>
+ LOG.error(s"failed to connect to $name, reason: ${ex.getMessage}, class: ${ex.getClass}")
+ current.close()
+ import context.dispatcher
+ context.system.scheduler.scheduleOnce(
+ new FiniteDuration(
+ getSleepTimeMs(tries), TimeUnit.MILLISECONDS), self, Connect(tries + 1))
+ }
+ } else {
+ LOG.error(s"fail to connect to a remote host $name after retied $tries ...")
+ self ! Close
+ }
+ }
+
+ private def send(flushChannel: Channel, msgs: util.Iterator[TaskMessage]) {
+ var messageBatch: MessageBatch = null
+
+ while (msgs.hasNext) {
+ val message: TaskMessage = msgs.next()
+ if (null == messageBatch) {
+ messageBatch = new MessageBatch(conf.messageBatchSize, serializer)
+ }
+ messageBatch.add(message)
+ if (messageBatch.isFull) {
+ val toBeFlushed: MessageBatch = messageBatch
+ flushRequest(flushChannel, toBeFlushed)
+ messageBatch = null
+ }
+ }
+ if (null != messageBatch && !messageBatch.isEmpty) {
+ flushRequest(flushChannel, messageBatch)
+ }
+ }
+
+ private def close() {
+ LOG.info(s"closing netty client $name...")
+ if (null != channel) {
+ channel.close()
+ channel = null
+ }
+ batch = null
+ }
+
+ override def postStop(): Unit = {
+ close()
+ }
+
+ private def flushRequest(channel: Channel, requests: MessageBatch) {
+ val future: ChannelFuture = channel.write(requests)
+ future.fail { (channel, ex) =>
+ if (channel.isOpen) {
+ channel.close
+ }
+ LOG.error(s"failed to send requests " +
+ s"to ${channel.getRemoteAddress} ${ex.getClass.getSimpleName}")
+ if (!ex.isInstanceOf[ClosedChannelException]) {
+ LOG.error(ex.getMessage, ex)
+ }
+ self ! CompareAndReconnectIfEqual(channel)
+ }
+ }
+
+ private def getSleepTimeMs(retries: Int): Long = {
+ if (retries > 30) {
+ conf.max_sleep_ms
+ } else {
+ val backoff = 1 << retries
+ val sleepMs = conf.base_sleep_ms * Math.max(1, random.nextInt(backoff))
+ if (sleepMs < conf.max_sleep_ms) sleepMs else conf.max_sleep_ms
+ }
+ }
+
+ private def isChannelWritable = (null != channel) && channel.isWritable
+}
+
+object Client {
+ val LOG: Logger = LogUtil.getLogger(getClass)
+
+ // Reconnect if current channel equals channel
+ case class CompareAndReconnectIfEqual(channel: Channel)
+
+ case class Connect(tries: Int)
+ case class ChannelReady(chanel: Channel)
+ case object Close
+
+ case class Flush(channel: Channel)
+
+ class ClientErrorHandler(name: String) extends SimpleChannelUpstreamHandler {
+
+ override def exceptionCaught(ctx: ChannelHandlerContext, event: ExceptionEvent) {
+ event.getCause match {
+ case ex: ConnectException => Unit
+ case ex: ClosedChannelException =>
+ LOG.warn("exception found when trying to close netty connection", ex.getMessage)
+ case ex => LOG.error("Connection failed " + name, ex)
+ }
+ }
+ }
+
+ class ClientPipelineFactory(name: String, conf: NettyConfig) extends ChannelPipelineFactory {
+ def getPipeline: ChannelPipeline = {
+ val pipeline: ChannelPipeline = Channels.pipeline
+ pipeline.addLast("decoder", new MessageDecoder(conf.newTransportSerializer))
+ pipeline.addLast("encoder", new MessageEncoder)
+ pipeline.addLast("handler", new ClientErrorHandler(name))
+ pipeline
+ }
+ }
+
+ implicit def channelFutureToChannelFutureOps(channel: ChannelFuture): ChannelFutureOps = {
+ new ChannelFutureOps(channel)
+ }
+
+ class ChannelFutureOps(channelFuture: ChannelFuture) {
+
+ def success(handler: (Channel => Unit)): ChannelFuture = {
+ channelFuture.addListener(new ChannelFutureListener {
+ def operationComplete(future: ChannelFuture) {
+ if (future.isSuccess) {
+ handler(future.getChannel)
+ }
+ }
+ })
+ channelFuture
+ }
+
+ def fail(handler: ((Channel, Throwable) => Unit)): ChannelFuture = {
+ channelFuture.addListener(new ChannelFutureListener {
+ def operationComplete(future: ChannelFuture) {
+ if (!future.isSuccess) {
+ handler(future.getChannel, future.getCause)
+ }
+ }
+ })
+ channelFuture
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/transport/netty/Context.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/transport/netty/Context.scala b/core/src/main/scala/org/apache/gearpump/transport/netty/Context.scala
new file mode 100644
index 0000000..bc19960
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/transport/netty/Context.scala
@@ -0,0 +1,114 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.transport.netty
+
+import java.io.Closeable
+import java.util.concurrent._
+
+import scala.collection.JavaConverters._
+
+import akka.actor.{ActorRef, ActorSystem, Props}
+import com.typesafe.config.Config
+import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory
+import org.slf4j.Logger
+
+import org.apache.gearpump.transport.netty.Server.ServerPipelineFactory
+import org.apache.gearpump.transport.{ActorLookupById, HostPort}
+import org.apache.gearpump.util.{Constants, LogUtil}
+
+object Context {
+ private final val LOG: Logger = LogUtil.getLogger(getClass)
+}
+
+/** Netty Context */
+class Context(system: ActorSystem, conf: NettyConfig) extends IContext {
+ import org.apache.gearpump.transport.netty.Context._
+
+ def this(system: ActorSystem, conf: Config) {
+ this(system, new NettyConfig(conf))
+ }
+
+ private val closeHandler = new ConcurrentLinkedQueue[Closeable]()
+ private val nettyDispatcher = system.settings.config.getString(Constants.NETTY_DISPATCHER)
+ val maxWorkers: Int = 1
+
+ private lazy val clientChannelFactory: NioClientSocketChannelFactory = {
+ val bossFactory: ThreadFactory = new NettyRenameThreadFactory("client" + "-boss")
+ val workerFactory: ThreadFactory = new NettyRenameThreadFactory("client" + "-worker")
+ val channelFactory =
+ new NioClientSocketChannelFactory(
+ Executors.newCachedThreadPool(bossFactory),
+ Executors.newCachedThreadPool(workerFactory), maxWorkers)
+
+ closeHandler.add(new Closeable {
+ override def close(): Unit = {
+ LOG.info("Closing all client resources....")
+ channelFactory.releaseExternalResources
+ }
+ })
+ channelFactory
+ }
+
+ def bind(
+ name: String, lookupActor : ActorLookupById, deserializeFlag : Boolean = true,
+ inputPort: Int = 0): Int = {
+ // TODO: whether we should expose it as application config?
+ val server = system.actorOf(Props(classOf[Server], name, conf, lookupActor,
+ deserializeFlag).withDispatcher(nettyDispatcher), name)
+ val (port, channel) = NettyUtil.newNettyServer(name,
+ new ServerPipelineFactory(server, conf), 5242880, inputPort)
+ val factory = channel.getFactory
+ closeHandler.add(new Closeable {
+ override def close(): Unit = {
+ system.stop(server)
+ channel.close()
+ LOG.info("Closing all server resources....")
+ factory.releaseExternalResources
+ }
+ })
+ port
+ }
+
+ def connect(hostPort: HostPort): ActorRef = {
+ val client = system.actorOf(Props(classOf[Client], conf, clientChannelFactory, hostPort)
+ .withDispatcher(nettyDispatcher))
+ closeHandler.add(new Closeable {
+ override def close(): Unit = {
+ LOG.info("closing Client actor....")
+ system.stop(client)
+ }
+ })
+
+ client
+ }
+
+ /**
+ * terminate this context
+ */
+ def close(): Unit = {
+
+ LOG.info(s"Context.term, cleanup resources...., " +
+ s"we have ${closeHandler.size()} items to close...")
+
+ // Cleans up resource in reverse order so that client actor can be cleaned
+ // before clientChannelFactory
+ closeHandler.iterator().asScala.toList.reverse.foreach(_.close())
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/transport/netty/IContext.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/transport/netty/IContext.scala b/core/src/main/scala/org/apache/gearpump/transport/netty/IContext.scala
new file mode 100644
index 0000000..dae7b3a
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/transport/netty/IContext.scala
@@ -0,0 +1,41 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.transport.netty
+
+import akka.actor.ActorRef
+
+import org.apache.gearpump.transport.{ActorLookupById, HostPort}
+
+trait IContext {
+
+ /**
+ * Create a Netty server connection.
+ */
+ def bind(name: String, lookupActor: ActorLookupById, deserializeFlag: Boolean, port: Int): Int
+
+ /**
+ * Create a Netty client actor
+ */
+ def connect(hostPort: HostPort): ActorRef
+
+ /**
+ * Close resource for this context
+ */
+ def close()
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/transport/netty/NettyConfig.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/transport/netty/NettyConfig.scala b/core/src/main/scala/org/apache/gearpump/transport/netty/NettyConfig.scala
new file mode 100644
index 0000000..03f759e
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/transport/netty/NettyConfig.scala
@@ -0,0 +1,39 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.transport.netty
+
+import com.typesafe.config.Config
+
+import org.apache.gearpump.util.Constants
+
+class NettyConfig(conf: Config) {
+
+ val buffer_size = conf.getInt(Constants.NETTY_BUFFER_SIZE)
+ val max_retries = conf.getInt(Constants.NETTY_MAX_RETRIES)
+ val base_sleep_ms = conf.getInt(Constants.NETTY_BASE_SLEEP_MS)
+ val max_sleep_ms = conf.getInt(Constants.NETTY_MAX_SLEEP_MS)
+ val messageBatchSize = conf.getInt(Constants.NETTY_MESSAGE_BATCH_SIZE)
+ val flushCheckInterval = conf.getInt(Constants.NETTY_FLUSH_CHECK_INTERVAL)
+
+ def newTransportSerializer: ITransportMessageSerializer = {
+ Class.forName(
+ conf.getString(Constants.GEARPUMP_TRANSPORT_SERIALIZER))
+ .newInstance().asInstanceOf[ITransportMessageSerializer]
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/transport/netty/NettyUtil.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/transport/netty/NettyUtil.scala b/core/src/main/scala/org/apache/gearpump/transport/netty/NettyUtil.scala
new file mode 100644
index 0000000..ddb0afe
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/transport/netty/NettyUtil.scala
@@ -0,0 +1,67 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.transport.netty
+
+import java.net.InetSocketAddress
+import java.util.concurrent.{Executors, ThreadFactory}
+
+import org.jboss.netty.bootstrap.{ClientBootstrap, ServerBootstrap}
+import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory
+import org.jboss.netty.channel.{Channel, ChannelFactory, ChannelPipelineFactory}
+
+object NettyUtil {
+
+ def newNettyServer(
+ name: String,
+ pipelineFactory: ChannelPipelineFactory,
+ buffer_size: Int,
+ inputPort: Int = 0): (Int, Channel) = {
+ val bossFactory: ThreadFactory = new NettyRenameThreadFactory(name + "-boss")
+ val workerFactory: ThreadFactory = new NettyRenameThreadFactory(name + "-worker")
+ val factory = new NioServerSocketChannelFactory(Executors.newCachedThreadPool(bossFactory),
+ Executors.newCachedThreadPool(workerFactory), 1)
+
+ val bootstrap = createServerBootStrap(factory, pipelineFactory, buffer_size)
+ val channel: Channel = bootstrap.bind(new InetSocketAddress(inputPort))
+ val port = channel.getLocalAddress().asInstanceOf[InetSocketAddress].getPort()
+ (port, channel)
+ }
+
+ def createServerBootStrap(
+ factory: ChannelFactory, pipelineFactory: ChannelPipelineFactory, buffer_size: Int)
+ : ServerBootstrap = {
+ val bootstrap = new ServerBootstrap(factory)
+ bootstrap.setOption("child.tcpNoDelay", true)
+ bootstrap.setOption("child.receiveBufferSize", buffer_size)
+ bootstrap.setOption("child.keepAlive", true)
+ bootstrap.setPipelineFactory(pipelineFactory)
+ bootstrap
+ }
+
+ def createClientBootStrap(
+ factory: ChannelFactory, pipelineFactory: ChannelPipelineFactory, buffer_size: Int)
+ : ClientBootstrap = {
+ val bootstrap = new ClientBootstrap(factory)
+ bootstrap.setOption("tcpNoDelay", true)
+ bootstrap.setOption("sendBufferSize", buffer_size)
+ bootstrap.setOption("keepAlive", true)
+ bootstrap.setPipelineFactory(pipelineFactory)
+ bootstrap
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/transport/netty/Server.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/transport/netty/Server.scala b/core/src/main/scala/org/apache/gearpump/transport/netty/Server.scala
new file mode 100644
index 0000000..8d39795
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/transport/netty/Server.scala
@@ -0,0 +1,135 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.transport.netty
+
+import java.util
+
+import scala.collection.JavaConverters._
+import scala.collection.immutable.IntMap
+import scala.concurrent.Future
+
+import akka.actor.{Actor, ActorContext, ActorRef, ExtendedActorSystem}
+import org.jboss.netty.channel._
+import org.jboss.netty.channel.group.{ChannelGroup, DefaultChannelGroup}
+import org.slf4j.Logger
+
+import org.apache.gearpump.transport.ActorLookupById
+import org.apache.gearpump.util.{AkkaHelper, LogUtil}
+
+/** Netty server actor, message received will be forward to the target on the address line. */
+class Server(
+ name: String, conf: NettyConfig, lookupActor: ActorLookupById, deserializeFlag: Boolean)
+ extends Actor {
+
+ private[netty] final val LOG: Logger = LogUtil.getLogger(getClass, context = name)
+ import org.apache.gearpump.transport.netty.Server._
+
+ val allChannels: ChannelGroup = new DefaultChannelGroup("gearpump-server")
+
+ val system = context.system.asInstanceOf[ExtendedActorSystem]
+
+ def receive: Receive = msgHandler orElse channelManager
+ // As we will only transfer TaskId on the wire,
+ // this object will translate taskId to or from ActorRef
+ private val taskIdActorRefTranslation = new TaskIdActorRefTranslation(context)
+
+ def channelManager: Receive = {
+ case AddChannel(channel) => allChannels.add(channel)
+ case CloseChannel(channel) =>
+ import context.dispatcher
+ Future {
+ channel.close.awaitUninterruptibly
+ allChannels.remove(channel)
+ }
+ }
+
+ def msgHandler: Receive = {
+ case MsgBatch(msgs) =>
+ msgs.asScala.groupBy(_.targetTask()).foreach { taskBatch =>
+ val (taskId, taskMessages) = taskBatch
+ val actor = lookupActor.lookupLocalActor(taskId)
+
+ if (actor.isEmpty) {
+ LOG.error(s"Cannot find actor for id: $taskId...")
+ } else taskMessages.foreach { taskMessage =>
+ actor.get.tell(taskMessage.message(),
+ taskIdActorRefTranslation.translateToActorRef(taskMessage.sessionId()))
+ }
+ }
+ }
+
+ override def postStop(): Unit = {
+ allChannels.close.awaitUninterruptibly
+ }
+}
+
+object Server {
+
+ class ServerPipelineFactory(server: ActorRef, conf: NettyConfig) extends ChannelPipelineFactory {
+ def getPipeline: ChannelPipeline = {
+ val pipeline: ChannelPipeline = Channels.pipeline
+ pipeline.addLast("decoder", new MessageDecoder(conf.newTransportSerializer))
+ pipeline.addLast("encoder", new MessageEncoder)
+ pipeline.addLast("handler", new ServerHandler(server))
+ pipeline
+ }
+ }
+
+ class ServerHandler(server: ActorRef) extends SimpleChannelUpstreamHandler {
+ private[netty] final val LOG: Logger = LogUtil.getLogger(getClass, context = server.path.name)
+
+ override def channelConnected(ctx: ChannelHandlerContext, e: ChannelStateEvent) {
+ server ! AddChannel(e.getChannel)
+ }
+
+ override def messageReceived(ctx: ChannelHandlerContext, e: MessageEvent) {
+ val msgs: util.List[TaskMessage] = e.getMessage.asInstanceOf[util.List[TaskMessage]]
+ if (msgs != null) {
+ server ! MsgBatch(msgs)
+ }
+ }
+
+ override def exceptionCaught(ctx: ChannelHandlerContext, e: ExceptionEvent) {
+ LOG.error("server errors in handling the request", e.getCause)
+ server ! CloseChannel(e.getChannel)
+ }
+ }
+
+ class TaskIdActorRefTranslation(context: ActorContext) {
+ private var taskIdtoActorRef = IntMap.empty[ActorRef]
+
+ /** 1-1 mapping from session id to fake ActorRef */
+ def translateToActorRef(sessionId: Int): ActorRef = {
+ if (!taskIdtoActorRef.contains(sessionId)) {
+
+ // A fake ActorRef for performance optimization.
+ val actorRef = AkkaHelper.actorFor(context.system, s"/session#$sessionId")
+ taskIdtoActorRef += sessionId -> actorRef
+ }
+ taskIdtoActorRef.get(sessionId).get
+ }
+ }
+
+ case class AddChannel(channel: Channel)
+
+ case class CloseChannel(channel: Channel)
+
+ case class MsgBatch(messages: java.lang.Iterable[TaskMessage])
+
+}
\ No newline at end of file
[13/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/test/scala/io/gearpump/services/AppMasterServiceSpec.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/test/scala/io/gearpump/services/AppMasterServiceSpec.scala b/services/jvm/src/test/scala/io/gearpump/services/AppMasterServiceSpec.scala
deleted file mode 100644
index 59da80d..0000000
--- a/services/jvm/src/test/scala/io/gearpump/services/AppMasterServiceSpec.scala
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.services
-
-import scala.concurrent.duration._
-import scala.util.{Success, Try}
-
-import akka.actor.ActorRef
-import akka.http.scaladsl.model.headers.`Cache-Control`
-import akka.http.scaladsl.testkit.{RouteTestTimeout, ScalatestRouteTest}
-import akka.testkit.TestActor.{AutoPilot, KeepRunning}
-import akka.testkit.{TestKit, TestProbe}
-import com.typesafe.config.{Config, ConfigFactory}
-import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
-import org.slf4j.Logger
-import upickle.default.read
-
-import io.gearpump.cluster.AppMasterToMaster.GeneralAppMasterSummary
-import io.gearpump.cluster.ClientToMaster.{GetLastFailure, QueryAppMasterConfig, QueryHistoryMetrics, ResolveAppId}
-import io.gearpump.cluster.MasterToAppMaster.{AppMasterData, AppMasterDataDetailRequest, AppMasterDataRequest}
-import io.gearpump.cluster.MasterToClient._
-import io.gearpump.cluster.TestUtil
-import io.gearpump.jarstore.JarStoreService
-import io.gearpump.streaming.executor.Executor.{ExecutorConfig, ExecutorSummary, GetExecutorSummary, QueryExecutorConfig}
-import io.gearpump.util.LogUtil
-// NOTE: This cannot be removed!!!
-import io.gearpump.services.util.UpickleUtil._
-
-class AppMasterServiceSpec extends FlatSpec with ScalatestRouteTest
- with Matchers with BeforeAndAfterAll {
-
- override def testConfig: Config = TestUtil.UI_CONFIG
-
- private val LOG: Logger = LogUtil.getLogger(getClass)
- private def actorRefFactory = system
-
- val mockAppMaster = TestProbe()
- val failure = LastFailure(System.currentTimeMillis(), "Some error")
-
- lazy val jarStoreService = JarStoreService.get(system.settings.config)
-
- def jarStore: JarStoreService = jarStoreService
-
- private def master = mockMaster.ref
-
- private def appMasterRoute = new AppMasterService(master, jarStore, system).route
-
- mockAppMaster.setAutoPilot {
- new AutoPilot {
- def run(sender: ActorRef, msg: Any): AutoPilot = msg match {
- case AppMasterDataDetailRequest(appId) =>
- sender ! GeneralAppMasterSummary(appId)
- KeepRunning
- case QueryHistoryMetrics(path, _, _, _) =>
- sender ! HistoryMetrics(path, List.empty[HistoryMetricsItem])
- KeepRunning
- case GetLastFailure(appId) =>
- sender ! failure
- KeepRunning
- case GetExecutorSummary(0) =>
- sender ! ExecutorSummary.empty
- KeepRunning
- case QueryExecutorConfig(0) =>
- sender ! ExecutorConfig(system.settings.config)
- KeepRunning
- }
- }
- }
-
- val mockMaster = TestProbe()
- mockMaster.setAutoPilot {
- new AutoPilot {
- def run(sender: ActorRef, msg: Any): AutoPilot = msg match {
- case ResolveAppId(0) =>
- sender ! ResolveAppIdResult(Success(mockAppMaster.ref))
- KeepRunning
- case AppMasterDataRequest(appId, _) =>
- sender ! AppMasterData("active")
- KeepRunning
- case QueryAppMasterConfig(appId) =>
- sender ! AppMasterConfig(null)
- KeepRunning
- }
- }
- }
-
- "AppMasterService" should "return a JSON structure for GET request when detail = false" in {
- implicit val customTimeout = RouteTestTimeout(15.seconds)
- Get(s"/api/$REST_VERSION/appmaster/0?detail=false") ~> appMasterRoute ~> check {
- val responseBody = responseAs[String]
- read[AppMasterData](responseBody)
-
- // Checks the header, should contains no-cache header.
- // Cache-Control:no-cache, max-age=0
- val noCache = header[`Cache-Control`].get.value()
- assert(noCache == "no-cache, max-age=0")
- }
-
- Get(s"/api/$REST_VERSION/appmaster/0?detail=true") ~> appMasterRoute ~> check {
- val responseBody = responseAs[String]
- }
- }
-
- "MetricsQueryService" should "return history metrics" in {
- implicit val customTimeout = RouteTestTimeout(15.seconds)
- (Get(s"/api/$REST_VERSION/appmaster/0/metrics/processor") ~> appMasterRoute) ~> check {
- val responseBody = responseAs[String]
- val config = Try(ConfigFactory.parseString(responseBody))
- assert(config.isSuccess)
- }
- }
-
- "AppMaster" should "return lastest error" in {
- implicit val customTimeout = RouteTestTimeout(15.seconds)
- (Get(s"/api/$REST_VERSION/appmaster/0/errors") ~> appMasterRoute) ~> check {
- val responseBody = responseAs[String]
- assert(read[LastFailure](responseBody) == failure)
- }
- }
-
- "ConfigQueryService" should "return config for application" in {
- implicit val customTimeout = RouteTestTimeout(15.seconds)
- (Get(s"/api/$REST_VERSION/appmaster/0/config") ~> appMasterRoute) ~> check {
- val responseBody = responseAs[String]
- val config = Try(ConfigFactory.parseString(responseBody))
- assert(config.isSuccess)
- }
- }
-
- it should "return config for executor " in {
- implicit val customTimeout = RouteTestTimeout(15.seconds)
- (Get(s"/api/$REST_VERSION/appmaster/0/executor/0/config") ~> appMasterRoute) ~> check {
- val responseBody = responseAs[String]
- val config = Try(ConfigFactory.parseString(responseBody))
- assert(config.isSuccess)
- }
- }
-
- it should "return return executor summary" in {
- implicit val customTimeout = RouteTestTimeout(15.seconds)
- (Get(s"/api/$REST_VERSION/appmaster/0/executor/0") ~> appMasterRoute) ~> check {
- val responseBody = responseAs[String]
- val executorSummary = read[ExecutorSummary](responseBody)
- assert(executorSummary.id == 0)
- }
- }
-
- override def afterAll {
- TestKit.shutdownActorSystem(system)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/test/scala/io/gearpump/services/MasterServiceSpec.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/test/scala/io/gearpump/services/MasterServiceSpec.scala b/services/jvm/src/test/scala/io/gearpump/services/MasterServiceSpec.scala
deleted file mode 100644
index a24db18..0000000
--- a/services/jvm/src/test/scala/io/gearpump/services/MasterServiceSpec.scala
+++ /dev/null
@@ -1,217 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.services
-
-import java.io.File
-import scala.concurrent.duration._
-import scala.concurrent.{ExecutionContext, Future}
-import scala.util.{Success, Try}
-
-import akka.actor.ActorRef
-import akka.http.scaladsl.marshalling.Marshal
-import akka.http.scaladsl.model._
-import akka.http.scaladsl.model.headers.`Cache-Control`
-import akka.http.scaladsl.testkit.{RouteTestTimeout, ScalatestRouteTest}
-import akka.stream.scaladsl.{FileIO, Source}
-import akka.testkit.TestActor.{AutoPilot, KeepRunning}
-import akka.testkit.TestProbe
-import com.typesafe.config.{Config, ConfigFactory}
-import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
-
-import io.gearpump.cluster.AppMasterToMaster.{GetAllWorkers, GetMasterData, GetWorkerData, MasterData, WorkerData}
-import io.gearpump.cluster.ClientToMaster.{QueryHistoryMetrics, QueryMasterConfig, ResolveWorkerId, SubmitApplication}
-import io.gearpump.cluster.MasterToAppMaster.{AppMasterData, AppMastersData, AppMastersDataRequest, WorkerList}
-import io.gearpump.cluster.MasterToClient._
-import io.gearpump.cluster.TestUtil
-import io.gearpump.cluster.worker.{WorkerId, WorkerSummary}
-import io.gearpump.jarstore.JarStoreService
-import io.gearpump.services.MasterService.{BuiltinPartitioners, SubmitApplicationRequest}
-// NOTE: This cannot be removed!!!
-import io.gearpump.services.util.UpickleUtil._
-import io.gearpump.streaming.ProcessorDescription
-import io.gearpump.util.Graph
-
-class MasterServiceSpec extends FlatSpec with ScalatestRouteTest
- with Matchers with BeforeAndAfterAll {
- import upickle.default.{read, write}
-
- override def testConfig: Config = TestUtil.UI_CONFIG
-
- private def actorRefFactory = system
- val workerId = 0
- val mockWorker = TestProbe()
-
- lazy val jarStoreService = JarStoreService.get(system.settings.config)
-
- private def master = mockMaster.ref
-
- def jarStore: JarStoreService = jarStoreService
-
- private def masterRoute = new MasterService(master, jarStore, system).route
-
- mockWorker.setAutoPilot {
- new AutoPilot {
- def run(sender: ActorRef, msg: Any): AutoPilot = msg match {
- case GetWorkerData(workerId) =>
- sender ! WorkerData(WorkerSummary.empty.copy(state = "active", workerId = workerId))
- KeepRunning
- case QueryHistoryMetrics(path, _, _, _) =>
- sender ! HistoryMetrics(path, List.empty[HistoryMetricsItem])
- KeepRunning
- }
- }
- }
-
- val mockMaster = TestProbe()
- mockMaster.setAutoPilot {
- new AutoPilot {
- def run(sender: ActorRef, msg: Any): AutoPilot = msg match {
- case GetMasterData =>
- sender ! MasterData(null)
- KeepRunning
- case AppMastersDataRequest =>
- sender ! AppMastersData(List.empty[AppMasterData])
- KeepRunning
- case GetAllWorkers =>
- sender ! WorkerList(List(WorkerId(0, 0L)))
- KeepRunning
- case ResolveWorkerId(WorkerId(0, 0L)) =>
- sender ! ResolveWorkerIdResult(Success(mockWorker.ref))
- KeepRunning
- case QueryHistoryMetrics(path, _, _, _) =>
- sender ! HistoryMetrics(path, List.empty[HistoryMetricsItem])
- KeepRunning
- case QueryMasterConfig =>
- sender ! MasterConfig(null)
- KeepRunning
- case submit: SubmitApplication =>
- sender ! SubmitApplicationResult(Success(0))
- KeepRunning
- }
- }
- }
-
- it should "return master info when asked" in {
- implicit val customTimeout = RouteTestTimeout(15.seconds)
- (Get(s"/api/$REST_VERSION/master") ~> masterRoute) ~> check {
- // Checks the type
- val content = responseAs[String]
- read[MasterData](content)
-
- // Checks the header, should contains no-cache header.
- // Cache-Control:no-cache, max-age=0
- val noCache = header[`Cache-Control`].get.value()
- assert(noCache == "no-cache, max-age=0")
- }
-
- mockMaster.expectMsg(GetMasterData)
- }
-
- it should "return a json structure of appMastersData for GET request" in {
- implicit val customTimeout = RouteTestTimeout(15.seconds)
- (Get(s"/api/$REST_VERSION/master/applist") ~> masterRoute) ~> check {
- // Checks the type
- read[AppMastersData](responseAs[String])
- }
- mockMaster.expectMsg(AppMastersDataRequest)
- }
-
- it should "return a json structure of worker data for GET request" in {
- implicit val customTimeout = RouteTestTimeout(25.seconds)
- Get(s"/api/$REST_VERSION/master/workerlist") ~> masterRoute ~> check {
- // Checks the type
- val workerListJson = responseAs[String]
- val workers = read[List[WorkerSummary]](workerListJson)
- assert(workers.size > 0)
- workers.foreach { worker =>
- worker.state shouldBe "active"
- }
- }
- mockMaster.expectMsg(GetAllWorkers)
- mockMaster.expectMsgType[ResolveWorkerId]
- mockWorker.expectMsgType[GetWorkerData]
- }
-
- it should "return config for master" in {
- implicit val customTimeout = RouteTestTimeout(15.seconds)
- (Get(s"/api/$REST_VERSION/master/config") ~> masterRoute) ~> check {
- val responseBody = responseAs[String]
- val config = Try(ConfigFactory.parseString(responseBody))
- assert(config.isSuccess)
- }
- mockMaster.expectMsg(QueryMasterConfig)
- }
-
- "submit invalid application" should "return an error" in {
- implicit val routeTestTimeout = RouteTestTimeout(30.second)
- val tempfile = new File("foo")
- val request = entity(tempfile)
-
- Post(s"/api/$REST_VERSION/master/submitapp", request) ~> masterRoute ~> check {
- assert(response.status.intValue == 500)
- }
- }
-
- private def entity(file: File)(implicit ec: ExecutionContext): Future[RequestEntity] = {
- val entity = HttpEntity(MediaTypes.`application/octet-stream`, file.length(),
- FileIO.fromFile(file, chunkSize = 100000))
-
- val body = Source.single(
- Multipart.FormData.BodyPart(
- "file",
- entity,
- Map("filename" -> file.getName)))
- val form = Multipart.FormData(body)
-
- Marshal(form).to[RequestEntity]
- }
-
- "MetricsQueryService" should "return history metrics" in {
- implicit val customTimeout = RouteTestTimeout(15.seconds)
- (Get(s"/api/$REST_VERSION/master/metrics/master") ~> masterRoute) ~> check {
- val responseBody = responseAs[String]
- val config = Try(ConfigFactory.parseString(responseBody))
- assert(config.isSuccess)
- }
- }
-
- "submitDag" should "submit a SubmitApplicationRequest and get an appId > 0" in {
- import io.gearpump.util.Graph._
- val processors = Map(
- 0 -> ProcessorDescription(0, "A", parallelism = 1),
- 1 -> ProcessorDescription(1, "B", parallelism = 1)
- )
- val dag = Graph(0 ~ "partitioner" ~> 1)
- val jsonValue = write(SubmitApplicationRequest("complexdag", processors, dag, null))
- Post(s"/api/$REST_VERSION/master/submitdag",
- HttpEntity(ContentTypes.`application/json`, jsonValue)) ~> masterRoute ~> check {
- val responseBody = responseAs[String]
- val submitApplicationResultValue = read[SubmitApplicationResultValue](responseBody)
- assert(submitApplicationResultValue.appId >= 0, "invalid appid")
- }
- }
-
- "MasterService" should "return Gearpump built-in partitioner list" in {
- (Get(s"/api/$REST_VERSION/master/partitioners") ~> masterRoute) ~> check {
- val responseBody = responseAs[String]
- val partitioners = read[BuiltinPartitioners](responseBody)
- assert(partitioners.partitioners.length > 0, "invalid response")
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/test/scala/io/gearpump/services/SecurityServiceSpec.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/test/scala/io/gearpump/services/SecurityServiceSpec.scala b/services/jvm/src/test/scala/io/gearpump/services/SecurityServiceSpec.scala
deleted file mode 100644
index 3cf99e9..0000000
--- a/services/jvm/src/test/scala/io/gearpump/services/SecurityServiceSpec.scala
+++ /dev/null
@@ -1,162 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.services
-
-import scala.concurrent.duration._
-
-import akka.actor.ActorSystem
-import akka.http.scaladsl.model.FormData
-import akka.http.scaladsl.model.headers.{Cookie, `Set-Cookie`, _}
-import akka.http.scaladsl.server.Directives._
-import akka.http.scaladsl.server.{AuthorizationFailedRejection, _}
-import akka.http.scaladsl.testkit.{RouteTestTimeout, ScalatestRouteTest}
-import com.typesafe.config.Config
-import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
-
-import io.gearpump.cluster.TestUtil
-// NOTE: This cannot be removed!!!
-import io.gearpump.services.util.UpickleUtil._
-
-class SecurityServiceSpec
- extends FlatSpec with ScalatestRouteTest with Matchers with BeforeAndAfterAll {
-
- override def testConfig: Config = TestUtil.UI_CONFIG
-
- implicit def actorSystem: ActorSystem = system
-
- it should "return 401 if not authenticated" in {
- val security = new SecurityService(SecurityServiceSpec.resource, actorSystem)
-
- implicit val customTimeout = RouteTestTimeout(15.seconds)
-
- (Get(s"/resource") ~> security.route) ~> check {
- assert(rejection.isInstanceOf[AuthenticationFailedRejection])
- }
- }
-
- "guest" should "get protected resource after authentication" in {
- val security = new SecurityService(SecurityServiceSpec.resource, actorSystem)
-
- implicit val customTimeout = RouteTestTimeout(15.seconds)
-
- var cookie: HttpCookiePair = null
- (Post(s"/login", FormData("username" -> "guest", "password" -> "guest"))
- ~> security.route) ~> check {
- assert("{\"user\":\"guest\"}" == responseAs[String])
- assert(status.intValue() == 200)
- assert(header[`Set-Cookie`].isDefined)
- val httpCookie = header[`Set-Cookie`].get.cookie
- assert(httpCookie.name == "gearpump_token")
- cookie = HttpCookiePair.apply(httpCookie.name, httpCookie.value)
- }
-
- // After authentication, everything is fine.
- Get("/resource").addHeader(Cookie(cookie)) ~> security.route ~> check {
- responseAs[String] shouldEqual "OK"
- }
-
- // However, guest cannot access high-permission operations, like POST.
- Post("/resource").addHeader(Cookie(cookie)) ~> security.route ~> check {
- assert(rejection == AuthorizationFailedRejection)
- }
-
- // Logout, should clear the session
- Post(s"/logout").addHeader(Cookie(cookie)) ~> security.route ~> check {
- assert("{\"user\":\"guest\"}" == responseAs[String])
- assert(status.intValue() == 200)
- assert(header[`Set-Cookie`].isDefined)
- val httpCookie = header[`Set-Cookie`].get.cookie
- assert(httpCookie.name == "gearpump_token")
- assert(httpCookie.value == "deleted")
- }
-
- // Access again, rejected this time.
- Get("/resource") ~> security.route ~> check {
- assert(rejection.isInstanceOf[AuthenticationFailedRejection])
- }
-
- Post("/resource") ~> security.route ~> check {
- assert(rejection.isInstanceOf[AuthenticationFailedRejection])
- }
- }
-
- "admin" should "get protected resource after authentication" in {
- val security = new SecurityService(SecurityServiceSpec.resource, actorSystem)
-
- implicit val customTimeout = RouteTestTimeout(15.seconds)
-
- var cookie: HttpCookiePair = null
- (Post(s"/login", FormData("username" -> "admin", "password" -> "admin"))
- ~> security.route) ~> check {
- assert("{\"user\":\"admin\"}" == responseAs[String])
- assert(status.intValue() == 200)
- assert(header[`Set-Cookie`].isDefined)
- val httpCookie = header[`Set-Cookie`].get.cookie
- assert(httpCookie.name == "gearpump_token")
- cookie = HttpCookiePair(httpCookie.name, httpCookie.value)
- }
-
- // After authentication, everything is fine.
- Get("/resource").addHeader(Cookie(cookie)) ~> security.route ~> check {
- responseAs[String] shouldEqual "OK"
- }
-
- // Not like guest, admimn can also access POST
- Post("/resource").addHeader(Cookie(cookie)) ~> security.route ~> check {
- responseAs[String] shouldEqual "OK"
- }
-
- // Logout, should clear the session
- Post(s"/logout").addHeader(Cookie(cookie)) ~> security.route ~> check {
- assert("{\"user\":\"admin\"}" == responseAs[String])
- assert(status.intValue() == 200)
- assert(header[`Set-Cookie`].isDefined)
- val httpCookie = header[`Set-Cookie`].get.cookie
- assert(httpCookie.name == "gearpump_token")
- assert(httpCookie.value == "deleted")
- }
-
- // Access again, rejected this time.
- Get("/resource") ~> security.route ~> check {
- assert(rejection.isInstanceOf[AuthenticationFailedRejection])
- }
-
- Post("/resource") ~> security.route ~> check {
- assert(rejection.isInstanceOf[AuthenticationFailedRejection])
- }
- }
-}
-
-object SecurityServiceSpec {
-
- val resource = new RouteService {
- override def route: Route = {
- get {
- path("resource") {
- complete("OK")
- }
- } ~
- post {
- path("resource") {
- complete("OK")
- }
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/test/scala/io/gearpump/services/StaticServiceSpec.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/test/scala/io/gearpump/services/StaticServiceSpec.scala b/services/jvm/src/test/scala/io/gearpump/services/StaticServiceSpec.scala
deleted file mode 100644
index f61e2f5..0000000
--- a/services/jvm/src/test/scala/io/gearpump/services/StaticServiceSpec.scala
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.services
-
-import scala.concurrent.duration._
-import scala.util.Try
-
-import akka.http.scaladsl.model.headers.`Cache-Control`
-import akka.http.scaladsl.testkit.{RouteTestTimeout, ScalatestRouteTest}
-import com.typesafe.config.{Config, ConfigFactory}
-import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
-
-import io.gearpump.cluster.TestUtil
-import io.gearpump.util.Constants
-// NOTE: This cannot be removed!!!
-import io.gearpump.services.util.UpickleUtil._
-
-class StaticServiceSpec
- extends FlatSpec with ScalatestRouteTest with Matchers with BeforeAndAfterAll {
-
- override def testConfig: Config = TestUtil.UI_CONFIG
- private val supervisorPath = system.settings.config.getString(
- Constants.GEARPUMP_SERVICE_SUPERVISOR_PATH)
-
- protected def route = new StaticService(system, supervisorPath).route
-
- it should "return version" in {
- implicit val customTimeout = RouteTestTimeout(15.seconds)
- (Get(s"/version") ~> route) ~> check {
- val responseBody = responseAs[String]
- val config = Try(ConfigFactory.parseString(responseBody))
- assert(responseBody == "Unknown-Version")
-
- // By default, it will be cached.
- assert(header[`Cache-Control`].isEmpty)
- }
- }
-
- it should "get correct supervisor path" in {
- implicit val customTimeout = RouteTestTimeout(15.seconds)
- (Get(s"/supervisor-actor-path") ~> route) ~> check {
- val responseBody = responseAs[String]
- val defaultSupervisorPath = ""
- assert(responseBody == defaultSupervisorPath)
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/test/scala/io/gearpump/services/WorkerServiceSpec.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/test/scala/io/gearpump/services/WorkerServiceSpec.scala b/services/jvm/src/test/scala/io/gearpump/services/WorkerServiceSpec.scala
deleted file mode 100644
index 2676a16..0000000
--- a/services/jvm/src/test/scala/io/gearpump/services/WorkerServiceSpec.scala
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.services
-
-import scala.concurrent.duration._
-import scala.util.{Success, Try}
-
-import akka.actor.ActorRef
-import akka.http.scaladsl.model.headers.`Cache-Control`
-import akka.http.scaladsl.testkit.{RouteTestTimeout, ScalatestRouteTest}
-import akka.testkit.TestActor.{AutoPilot, KeepRunning}
-import akka.testkit.{TestKit, TestProbe}
-import com.typesafe.config.{Config, ConfigFactory}
-import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
-
-import io.gearpump.cluster.AppMasterToMaster.{GetWorkerData, WorkerData}
-import io.gearpump.cluster.ClientToMaster.{QueryHistoryMetrics, QueryWorkerConfig, ResolveWorkerId}
-import io.gearpump.cluster.MasterToClient.{HistoryMetrics, HistoryMetricsItem, ResolveWorkerIdResult, WorkerConfig}
-import io.gearpump.cluster.TestUtil
-import io.gearpump.cluster.worker.{WorkerId, WorkerSummary}
-import io.gearpump.jarstore.JarStoreService
-// NOTE: This cannot be removed!!!
-import io.gearpump.services.util.UpickleUtil._
-
-class WorkerServiceSpec
- extends FlatSpec with ScalatestRouteTest with Matchers with BeforeAndAfterAll {
-
- override def testConfig: Config = TestUtil.DEFAULT_CONFIG
-
- protected def actorRefFactory = system
-
- val mockWorker = TestProbe()
-
- protected def master = mockMaster.ref
-
- lazy val jarStoreService = JarStoreService.get(system.settings.config)
-
- protected def workerRoute = new WorkerService(master, system).route
-
- mockWorker.setAutoPilot {
- new AutoPilot {
- def run(sender: ActorRef, msg: Any): AutoPilot = msg match {
- case GetWorkerData(workerId) =>
- sender ! WorkerData(WorkerSummary.empty)
- KeepRunning
- case QueryWorkerConfig(workerId) =>
- sender ! WorkerConfig(null)
- KeepRunning
- case QueryHistoryMetrics(path, _, _, _) =>
- sender ! HistoryMetrics(path, List.empty[HistoryMetricsItem])
- KeepRunning
- }
- }
- }
-
- val mockMaster = TestProbe()
- mockMaster.setAutoPilot {
- new AutoPilot {
- def run(sender: ActorRef, msg: Any): AutoPilot = msg match {
- case ResolveWorkerId(workerId) =>
- sender ! ResolveWorkerIdResult(Success(mockWorker.ref))
- KeepRunning
- }
- }
- }
-
- "ConfigQueryService" should "return config for worker" in {
- implicit val customTimeout = RouteTestTimeout(15.seconds)
- (Get(s"/api/$REST_VERSION/worker/${WorkerId.render(WorkerId(0, 0L))}/config")
- ~> workerRoute) ~> check {
- val responseBody = responseAs[String]
- val config = Try(ConfigFactory.parseString(responseBody))
- assert(config.isSuccess)
- }
- }
-
- it should "return WorkerData" in {
- implicit val customTimeout = RouteTestTimeout(15.seconds)
- (Get(s"/api/$REST_VERSION/worker/${WorkerId.render(WorkerId(1, 0L))}")
- ~> workerRoute) ~> check {
- val responseBody = responseAs[String]
- val config = Try(ConfigFactory.parseString(responseBody))
- assert(config.isSuccess)
-
- // Check the header, should contains no-cache header.
- // Cache-Control:no-cache, max-age=0
- val noCache = header[`Cache-Control`].get.value()
- assert(noCache == "no-cache, max-age=0")
- }
- }
-
- "MetricsQueryService" should "return history metrics" in {
- implicit val customTimeout = RouteTestTimeout(15.seconds)
- (Get(s"/api/$REST_VERSION/worker/${WorkerId.render(WorkerId(0, 0L))}/metrics/worker")
- ~> workerRoute) ~> check {
- val responseBody = responseAs[String]
- val config = Try(ConfigFactory.parseString(responseBody))
- assert(config.isSuccess)
- }
- }
-
- override def afterAll {
- TestKit.shutdownActorSystem(system)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/test/scala/io/gearpump/services/security/oauth2/CloudFoundryUAAOAuth2AuthenticatorSpec.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/test/scala/io/gearpump/services/security/oauth2/CloudFoundryUAAOAuth2AuthenticatorSpec.scala b/services/jvm/src/test/scala/io/gearpump/services/security/oauth2/CloudFoundryUAAOAuth2AuthenticatorSpec.scala
deleted file mode 100644
index 136026a..0000000
--- a/services/jvm/src/test/scala/io/gearpump/services/security/oauth2/CloudFoundryUAAOAuth2AuthenticatorSpec.scala
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.services.security.oauth2
-
-import scala.collection.JavaConverters._
-import scala.concurrent.Await
-import scala.concurrent.duration._
-
-import akka.actor.ActorSystem
-import akka.http.scaladsl.model.HttpEntity.Strict
-import akka.http.scaladsl.model.MediaTypes._
-import akka.http.scaladsl.model.Uri.{Path, Query}
-import akka.http.scaladsl.model._
-import akka.http.scaladsl.testkit.ScalatestRouteTest
-import com.typesafe.config.ConfigFactory
-import org.scalatest.FlatSpec
-
-import io.gearpump.security.Authenticator
-// NOTE: This cannot be removed!!!
-import io.gearpump.services.util.UpickleUtil._
-import io.gearpump.services.security.oauth2.impl.CloudFoundryUAAOAuth2Authenticator
-
-class CloudFoundryUAAOAuth2AuthenticatorSpec extends FlatSpec with ScalatestRouteTest {
-
- implicit val actorSystem: ActorSystem = system
- private val server = new MockOAuth2Server(system, null)
- server.start()
- private val serverHost = s"http://127.0.0.1:${server.port}"
-
- val configMap = Map(
- "class" -> "io.gearpump.services.security.oauth2.impl.CloudFoundryUAAOAuth2Authenticator",
- "callback" -> s"$serverHost/login/oauth2/cloudfoundryuaa/callback",
- "clientid" -> "gearpump_test2",
- "clientsecret" -> "gearpump_test2",
- "default-userrole" -> "user",
- "icon" -> "/icons/uaa.png",
- "uaahost" -> serverHost,
- "additional-authenticator-enabled" -> "false")
-
- val configString = ConfigFactory.parseMap(configMap.asJava)
-
- lazy val uaa = {
- val uaa = new CloudFoundryUAAOAuth2Authenticator
- uaa.init(configString, system.dispatcher)
- uaa
- }
-
- it should "generate the correct authorization request" in {
- val parameters = Uri(uaa.getAuthorizationUrl()).query().toMap
- assert(parameters("response_type") == "code")
- assert(parameters("client_id") == configMap("clientid"))
- assert(parameters("redirect_uri") == configMap("callback"))
- assert(parameters("scope") == "openid,cloud_controller.read")
- }
-
- it should "authenticate the authorization code and return the correct profile" in {
- val code = Map("code" -> "QGGVeA")
- val accessToken = "e2922002-0218-4513-a62d-1da2ba64ee4c"
- val refreshToken = "eyJhbGciOiJSUzI1NiJ9.eyJqdGkiOiI2Nm"
- val mail = "test@gearpump.io"
-
- def accessTokenEndpoint(request: HttpRequest): HttpResponse = {
- assert(request.getHeader("Authorization").get.value() ==
- "Basic Z2VhcnB1bXBfdGVzdDI6Z2VhcnB1bXBfdGVzdDI=")
- assert(request.entity.contentType.mediaType.value == "application/x-www-form-urlencoded")
-
- val body = request.entity.asInstanceOf[Strict].data.decodeString("UTF-8")
- val form = Uri./.withQuery(Query(body)).query().toMap
-
- assert(form("grant_type") == "authorization_code")
- assert(form("code") == "QGGVeA")
- assert(form("response_type") == "token")
- assert(form("redirect_uri") == configMap("callback"))
-
- val response =
- s"""
- |{
- | "access_token": "$accessToken",
- | "token_type": "bearer",
- | "refresh_token": "$refreshToken",
- | "expires_in": 43199,
- | "scope": "openid",
- | "jti": "e8739474-b2fa-42eb-a9ad-e065bf79d7e9"
- |}
- """.stripMargin
- HttpResponse(entity = HttpEntity(ContentType(`application/json`), response))
- }
-
- def protectedResourceEndpoint(request: HttpRequest): HttpResponse = {
- assert(request.getUri().query().get("access_token").get == accessToken)
- val response =
- s"""
- |{
- | "user_id": "e2922002-0218-4513-a62d-1da2ba64ee4c",
- | "user_name": "user",
- | "email": "$mail"
- |}
- """.stripMargin
- HttpResponse(entity = HttpEntity(ContentType(`application/json`), response))
- }
-
- server.requestHandler = (request: HttpRequest) => {
- if (request.uri.path.startsWith(Path("/oauth/token"))) {
- accessTokenEndpoint(request)
- } else if (request.uri.path.startsWith(Path("/userinfo"))) {
- protectedResourceEndpoint(request)
- } else {
- fail("Unexpected access to " + request.uri.toString())
- }
- }
-
- val userFuture = uaa.authenticate(code)
- val user = Await.result(userFuture, 30.seconds)
- assert(user.user == mail)
- assert(user.permissionLevel == Authenticator.User.permissionLevel)
- }
-
- override def cleanUp(): Unit = {
- server.stop()
- uaa.close()
- super.cleanUp()
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/test/scala/io/gearpump/services/security/oauth2/GoogleOAuth2AuthenticatorSpec.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/test/scala/io/gearpump/services/security/oauth2/GoogleOAuth2AuthenticatorSpec.scala b/services/jvm/src/test/scala/io/gearpump/services/security/oauth2/GoogleOAuth2AuthenticatorSpec.scala
deleted file mode 100644
index 70d8bb0..0000000
--- a/services/jvm/src/test/scala/io/gearpump/services/security/oauth2/GoogleOAuth2AuthenticatorSpec.scala
+++ /dev/null
@@ -1,163 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.services.security.oauth2
-
-import scala.collection.JavaConverters._
-import scala.concurrent.Await
-import scala.concurrent.duration._
-
-import akka.actor.ActorSystem
-import akka.http.scaladsl.model.HttpEntity.Strict
-import akka.http.scaladsl.model.MediaTypes._
-import akka.http.scaladsl.model.Uri.{Path, Query}
-import akka.http.scaladsl.model._
-import akka.http.scaladsl.testkit.ScalatestRouteTest
-import com.typesafe.config.ConfigFactory
-import org.scalatest.FlatSpec
-
-import io.gearpump.security.Authenticator
-// NOTE: This cannot be removed!!!
-import io.gearpump.services.util.UpickleUtil._
-import io.gearpump.services.security.oauth2.GoogleOAuth2AuthenticatorSpec.MockGoogleAuthenticator
-import io.gearpump.services.security.oauth2.impl.GoogleOAuth2Authenticator
-
-class GoogleOAuth2AuthenticatorSpec extends FlatSpec with ScalatestRouteTest {
-
- implicit val actorSystem: ActorSystem = system
- private val server = new MockOAuth2Server(system, null)
- server.start()
- private val serverHost = s"http://127.0.0.1:${server.port}"
-
- val configMap = Map(
- "class" -> "io.gearpump.services.security.oauth2.impl.GoogleOAuth2Authenticator",
- "callback" -> s"$serverHost/login/oauth2/google/callback",
- "clientid" -> "170234147043-a1tag68jtq6ab4bi11jvsj7vbaqcmhkt.apps.googleusercontent.com",
- "clientsecret" -> "ioeWLLDipz2S7aTDXym2-obe",
- "default-userrole" -> "guest",
- "icon" -> "/icons/google.png")
-
- val configString = ConfigFactory.parseMap(configMap.asJava)
-
- private lazy val google = {
- val google = new MockGoogleAuthenticator(serverHost)
- google.init(configString, system.dispatcher)
- google
- }
-
- it should "generate the correct authorization request" in {
- val parameters = Uri(google.getAuthorizationUrl()).query().toMap
- assert(parameters("response_type") == "code")
- assert(parameters("client_id") == configMap("clientid"))
- assert(parameters("redirect_uri") == configMap("callback"))
- assert(parameters("scope") == GoogleOAuth2Authenticator.Scope)
- }
-
- it should "authenticate the authorization code and return the correct profile" in {
- val code = Map("code" -> "4/PME0pfxjiBA42SukR-OTGl7fpFzTWzvZPf1TbkpXL4M#")
- val accessToken = "e2922002-0218-4513-a62d-1da2ba64ee4c"
- val refreshToken = "eyJhbGciOiJSUzI1NiJ9.eyJqdGkiOiI2Nm"
- val mail = "test@gearpump.io"
-
- def accessTokenEndpoint(request: HttpRequest): HttpResponse = {
-
- assert(request.entity.contentType.mediaType.value == "application/x-www-form-urlencoded")
-
- val body = request.entity.asInstanceOf[Strict].data.decodeString("UTF-8")
- val form = Uri./.withQuery(Query(body)).query().toMap
-
- assert(form("client_id") == configMap("clientid"))
- assert(form("client_secret") == configMap("clientsecret"))
- assert(form("grant_type") == "authorization_code")
- assert(form("code") == code("code"))
- assert(form("redirect_uri") == configMap("callback"))
- assert(form("scope") == GoogleOAuth2Authenticator.Scope)
-
- // scalastyle:off line.size.limit
- val response =
- s"""
- |{
- | "access_token": "$accessToken",
- | "token_type": "Bearer",
- | "expires_in": 3591,
- | "id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6ImY1NjQyYzY2MzdhYWQyOTJiOThlOGIwN2MwMzIxN2QwMzBmOTdkODkifQ.eyJpc3"
- |}
- """.stripMargin
- // scalastyle:on line.size.limit
-
- HttpResponse(entity = HttpEntity(ContentType(`application/json`), response))
- }
-
- def protectedResourceEndpoint(request: HttpRequest): HttpResponse = {
- assert(request.getUri().query().get("access_token").get == accessToken)
- val response =
- s"""
- |{
- | "kind": "plus#person",
- | "etag": "4OZ_Kt6ujOh1jaML_U6RM6APqoE/mZ57HcMOYXaNXYXS5XEGJ9yVsI8",
- | "nickname": "gearpump",
- | "gender": "female",
- | "emails": [
- | {
- | "value": "$mail",
- | "type": "account"
- | }
- | ]
- | }
- """.stripMargin
- HttpResponse(entity = HttpEntity(ContentType(`application/json`), response))
- }
-
- server.requestHandler = (request: HttpRequest) => {
- if (request.uri.path.startsWith(Path("/oauth2/v4/token"))) {
- accessTokenEndpoint(request)
- } else if (request.uri.path.startsWith(Path("/plus/v1/people/me"))) {
- protectedResourceEndpoint(request)
- } else {
- fail("Unexpected access to " + request.uri.toString())
- }
- }
-
- val userFuture = google.authenticate(code)
- val user = Await.result(userFuture, 30.seconds)
- assert(user.user == mail)
- assert(user.permissionLevel == Authenticator.Guest.permissionLevel)
- }
-
- override def cleanUp(): Unit = {
- server.stop()
- google.close()
- super.cleanUp()
- }
-}
-
-object GoogleOAuth2AuthenticatorSpec {
- class MockGoogleAuthenticator(host: String) extends GoogleOAuth2Authenticator {
- protected override def authorizeUrl: String = {
- super.authorizeUrl.replace("https://accounts.google.com", host)
- }
-
- protected override def accessTokenEndpoint: String = {
- super.accessTokenEndpoint.replace("https://www.googleapis.com", host)
- }
-
- protected override def protectedResourceUrl: String = {
- super.protectedResourceUrl.replace("https://www.googleapis.com", host)
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/test/scala/io/gearpump/services/security/oauth2/MockOAuth2Server.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/test/scala/io/gearpump/services/security/oauth2/MockOAuth2Server.scala b/services/jvm/src/test/scala/io/gearpump/services/security/oauth2/MockOAuth2Server.scala
deleted file mode 100644
index c03532d..0000000
--- a/services/jvm/src/test/scala/io/gearpump/services/security/oauth2/MockOAuth2Server.scala
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.services.security.oauth2
-
-import scala.concurrent.{Await, Future}
-
-import akka.actor.ActorSystem
-import akka.http.scaladsl.Http
-import akka.http.scaladsl.Http.ServerBinding
-import akka.http.scaladsl.model.{HttpRequest, HttpResponse}
-import akka.stream.ActorMaterializer
-import akka.stream.scaladsl.Sink
-
-import io.gearpump.util.Util
-// NOTE: This cannot be removed!!
-import io.gearpump.services.util.UpickleUtil._
-
-/**
- * Serves as a fake OAuth2 server.
- */
-class MockOAuth2Server(
- actorSystem: ActorSystem,
- var requestHandler: HttpRequest => HttpResponse) {
-
- implicit val system: ActorSystem = actorSystem
- implicit val materializer = ActorMaterializer()
- implicit val ec = system.dispatcher
-
- private var _port: Int = 0
- private var bindingFuture: Future[ServerBinding] = null
-
- def port: Int = _port
-
- def start(): Unit = {
- _port = Util.findFreePort().get
-
- val serverSource = Http().bind(interface = "127.0.0.1", port = _port)
- bindingFuture = {
- serverSource.to(Sink.foreach { connection =>
- connection handleWithSyncHandler requestHandler
- }).run()
- }
- }
-
- def stop(): Unit = {
- import scala.concurrent.duration._
- Await.result(bindingFuture.map(_.unbind()), 120.seconds)
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/test/scala/io/gearpump/services/util/UpickleSpec.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/test/scala/io/gearpump/services/util/UpickleSpec.scala b/services/jvm/src/test/scala/io/gearpump/services/util/UpickleSpec.scala
deleted file mode 100644
index b074813..0000000
--- a/services/jvm/src/test/scala/io/gearpump/services/util/UpickleSpec.scala
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.services.util
-
-import org.scalatest.{BeforeAndAfterEach, FlatSpec, Matchers}
-import upickle.default.{read, write}
-
-import io.gearpump.cluster.UserConfig
-import io.gearpump.metrics.Metrics.{Counter, MetricType}
-import io.gearpump.services.util.UpickleUtil._
-import io.gearpump.streaming.ProcessorId
-import io.gearpump.streaming.appmaster.{ProcessorSummary, StreamAppMasterSummary}
-import io.gearpump.util.Graph
-
-class UpickleSpec extends FlatSpec with Matchers with BeforeAndAfterEach {
-
- "UserConfig" should "serialize and deserialize with upickle correctly" in {
- val conf = UserConfig.empty.withString("key", "value")
- val serialized = write(conf)
- val deserialized = read[UserConfig](serialized)
- assert(deserialized.getString("key") == Some("value"))
- }
-
- "Graph" should "be able to serialize/deserialize correctly" in {
- val graph = new Graph[Int, String](List(0, 1), List((0, "edge", 1)))
- val serialized = write(graph)
-
- val deserialized = read[Graph[Int, String]](serialized)
-
- graph.vertices.toSet shouldBe deserialized.vertices.toSet
- graph.edges.toSet shouldBe deserialized.edges.toSet
- }
-
- "MetricType" should "be able to serialize/deserialize correctly" in {
- val metric: MetricType = Counter("counter", 100L)
- val serialized = write(metric)
- val deserialized = read[MetricType](serialized)
- metric shouldBe deserialized
- }
-
- "StreamingAppMasterDataDetail" should "serialize and deserialize with upickle correctly" in {
- val app = new StreamAppMasterSummary(appId = 0,
- processors = Map.empty[ProcessorId, ProcessorSummary],
- processorLevels = Map.empty[ProcessorId, Int]
- )
-
- val serialized = write(app)
- val deserialized = read[StreamAppMasterSummary](serialized)
- assert(deserialized == app)
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/test/scala/org/apache/gearpump/services/AdminServiceSpec.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/test/scala/org/apache/gearpump/services/AdminServiceSpec.scala b/services/jvm/src/test/scala/org/apache/gearpump/services/AdminServiceSpec.scala
new file mode 100644
index 0000000..b7f294c
--- /dev/null
+++ b/services/jvm/src/test/scala/org/apache/gearpump/services/AdminServiceSpec.scala
@@ -0,0 +1,53 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.services
+
+import scala.concurrent.Await
+import scala.concurrent.duration._
+
+import akka.actor.ActorSystem
+import akka.http.scaladsl.testkit.{RouteTestTimeout, ScalatestRouteTest}
+import com.typesafe.config.Config
+import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
+
+import org.apache.gearpump.cluster.TestUtil
+
+// NOTE: This cannot be removed!!!
+import org.apache.gearpump.services.util.UpickleUtil._
+
+class AdminServiceSpec
+ extends FlatSpec with ScalatestRouteTest with Matchers with BeforeAndAfterAll {
+
+ override def testConfig: Config = TestUtil.DEFAULT_CONFIG
+
+ implicit def actorSystem: ActorSystem = system
+
+ it should "shutdown the ActorSystem when receiving terminate" in {
+ val route = new AdminService(actorSystem).route
+ implicit val customTimeout = RouteTestTimeout(15.seconds)
+ (Post(s"/terminate") ~> route) ~> check {
+ assert(status.intValue() == 404)
+ }
+
+ Await.result(actorSystem.whenTerminated, 20.seconds)
+
+ // terminate should terminate current actor system
+ assert(actorSystem.whenTerminated.isCompleted)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/test/scala/org/apache/gearpump/services/AppMasterServiceSpec.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/test/scala/org/apache/gearpump/services/AppMasterServiceSpec.scala b/services/jvm/src/test/scala/org/apache/gearpump/services/AppMasterServiceSpec.scala
new file mode 100644
index 0000000..2ece554
--- /dev/null
+++ b/services/jvm/src/test/scala/org/apache/gearpump/services/AppMasterServiceSpec.scala
@@ -0,0 +1,167 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.services
+
+import scala.concurrent.duration._
+import scala.util.{Success, Try}
+
+import akka.actor.ActorRef
+import akka.http.scaladsl.model.headers.`Cache-Control`
+import akka.http.scaladsl.testkit.{RouteTestTimeout, ScalatestRouteTest}
+import akka.testkit.TestActor.{AutoPilot, KeepRunning}
+import akka.testkit.{TestKit, TestProbe}
+import com.typesafe.config.{Config, ConfigFactory}
+import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
+import org.slf4j.Logger
+import upickle.default.read
+
+import org.apache.gearpump.cluster.AppMasterToMaster.GeneralAppMasterSummary
+import org.apache.gearpump.cluster.ClientToMaster.{GetLastFailure, QueryAppMasterConfig, QueryHistoryMetrics, ResolveAppId}
+import org.apache.gearpump.cluster.MasterToAppMaster.{AppMasterData, AppMasterDataDetailRequest, AppMasterDataRequest}
+import org.apache.gearpump.cluster.MasterToClient._
+import org.apache.gearpump.cluster.TestUtil
+import org.apache.gearpump.jarstore.JarStoreService
+import org.apache.gearpump.streaming.executor.Executor.{ExecutorConfig, ExecutorSummary, GetExecutorSummary, QueryExecutorConfig}
+import org.apache.gearpump.util.LogUtil
+// NOTE: This cannot be removed!!!
+import org.apache.gearpump.services.util.UpickleUtil._
+
+class AppMasterServiceSpec extends FlatSpec with ScalatestRouteTest
+ with Matchers with BeforeAndAfterAll {
+
+ override def testConfig: Config = TestUtil.UI_CONFIG
+
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+ private def actorRefFactory = system
+
+ val mockAppMaster = TestProbe()
+ val failure = LastFailure(System.currentTimeMillis(), "Some error")
+
+ lazy val jarStoreService = JarStoreService.get(system.settings.config)
+
+ def jarStore: JarStoreService = jarStoreService
+
+ private def master = mockMaster.ref
+
+ private def appMasterRoute = new AppMasterService(master, jarStore, system).route
+
+ mockAppMaster.setAutoPilot {
+ new AutoPilot {
+ def run(sender: ActorRef, msg: Any): AutoPilot = msg match {
+ case AppMasterDataDetailRequest(appId) =>
+ sender ! GeneralAppMasterSummary(appId)
+ KeepRunning
+ case QueryHistoryMetrics(path, _, _, _) =>
+ sender ! HistoryMetrics(path, List.empty[HistoryMetricsItem])
+ KeepRunning
+ case GetLastFailure(appId) =>
+ sender ! failure
+ KeepRunning
+ case GetExecutorSummary(0) =>
+ sender ! ExecutorSummary.empty
+ KeepRunning
+ case QueryExecutorConfig(0) =>
+ sender ! ExecutorConfig(system.settings.config)
+ KeepRunning
+ }
+ }
+ }
+
+ val mockMaster = TestProbe()
+ mockMaster.setAutoPilot {
+ new AutoPilot {
+ def run(sender: ActorRef, msg: Any): AutoPilot = msg match {
+ case ResolveAppId(0) =>
+ sender ! ResolveAppIdResult(Success(mockAppMaster.ref))
+ KeepRunning
+ case AppMasterDataRequest(appId, _) =>
+ sender ! AppMasterData("active")
+ KeepRunning
+ case QueryAppMasterConfig(appId) =>
+ sender ! AppMasterConfig(null)
+ KeepRunning
+ }
+ }
+ }
+
+ "AppMasterService" should "return a JSON structure for GET request when detail = false" in {
+ implicit val customTimeout = RouteTestTimeout(15.seconds)
+ Get(s"/api/$REST_VERSION/appmaster/0?detail=false") ~> appMasterRoute ~> check {
+ val responseBody = responseAs[String]
+ read[AppMasterData](responseBody)
+
+ // Checks the header, should contains no-cache header.
+ // Cache-Control:no-cache, max-age=0
+ val noCache = header[`Cache-Control`].get.value()
+ assert(noCache == "no-cache, max-age=0")
+ }
+
+ Get(s"/api/$REST_VERSION/appmaster/0?detail=true") ~> appMasterRoute ~> check {
+ val responseBody = responseAs[String]
+ }
+ }
+
+ "MetricsQueryService" should "return history metrics" in {
+ implicit val customTimeout = RouteTestTimeout(15.seconds)
+ (Get(s"/api/$REST_VERSION/appmaster/0/metrics/processor") ~> appMasterRoute) ~> check {
+ val responseBody = responseAs[String]
+ val config = Try(ConfigFactory.parseString(responseBody))
+ assert(config.isSuccess)
+ }
+ }
+
+ "AppMaster" should "return lastest error" in {
+ implicit val customTimeout = RouteTestTimeout(15.seconds)
+ (Get(s"/api/$REST_VERSION/appmaster/0/errors") ~> appMasterRoute) ~> check {
+ val responseBody = responseAs[String]
+ assert(read[LastFailure](responseBody) == failure)
+ }
+ }
+
+ "ConfigQueryService" should "return config for application" in {
+ implicit val customTimeout = RouteTestTimeout(15.seconds)
+ (Get(s"/api/$REST_VERSION/appmaster/0/config") ~> appMasterRoute) ~> check {
+ val responseBody = responseAs[String]
+ val config = Try(ConfigFactory.parseString(responseBody))
+ assert(config.isSuccess)
+ }
+ }
+
+ it should "return config for executor " in {
+ implicit val customTimeout = RouteTestTimeout(15.seconds)
+ (Get(s"/api/$REST_VERSION/appmaster/0/executor/0/config") ~> appMasterRoute) ~> check {
+ val responseBody = responseAs[String]
+ val config = Try(ConfigFactory.parseString(responseBody))
+ assert(config.isSuccess)
+ }
+ }
+
+ it should "return return executor summary" in {
+ implicit val customTimeout = RouteTestTimeout(15.seconds)
+ (Get(s"/api/$REST_VERSION/appmaster/0/executor/0") ~> appMasterRoute) ~> check {
+ val responseBody = responseAs[String]
+ val executorSummary = read[ExecutorSummary](responseBody)
+ assert(executorSummary.id == 0)
+ }
+ }
+
+ override def afterAll {
+ TestKit.shutdownActorSystem(system)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/test/scala/org/apache/gearpump/services/MasterServiceSpec.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/test/scala/org/apache/gearpump/services/MasterServiceSpec.scala b/services/jvm/src/test/scala/org/apache/gearpump/services/MasterServiceSpec.scala
new file mode 100644
index 0000000..e365e9f
--- /dev/null
+++ b/services/jvm/src/test/scala/org/apache/gearpump/services/MasterServiceSpec.scala
@@ -0,0 +1,217 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.services
+
+import java.io.File
+import scala.concurrent.duration._
+import scala.concurrent.{ExecutionContext, Future}
+import scala.util.{Success, Try}
+
+import akka.actor.ActorRef
+import akka.http.scaladsl.marshalling.Marshal
+import akka.http.scaladsl.model._
+import akka.http.scaladsl.model.headers.`Cache-Control`
+import akka.http.scaladsl.testkit.{RouteTestTimeout, ScalatestRouteTest}
+import akka.stream.scaladsl.{FileIO, Source}
+import akka.testkit.TestActor.{AutoPilot, KeepRunning}
+import akka.testkit.TestProbe
+import com.typesafe.config.{Config, ConfigFactory}
+import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
+
+import org.apache.gearpump.cluster.AppMasterToMaster.{GetAllWorkers, GetMasterData, GetWorkerData, MasterData, WorkerData}
+import org.apache.gearpump.cluster.ClientToMaster.{QueryHistoryMetrics, QueryMasterConfig, ResolveWorkerId, SubmitApplication}
+import org.apache.gearpump.cluster.MasterToAppMaster.{AppMasterData, AppMastersData, AppMastersDataRequest, WorkerList}
+import org.apache.gearpump.cluster.MasterToClient._
+import org.apache.gearpump.cluster.TestUtil
+import org.apache.gearpump.cluster.worker.{WorkerId, WorkerSummary}
+import org.apache.gearpump.jarstore.JarStoreService
+import org.apache.gearpump.services.MasterService.{BuiltinPartitioners, SubmitApplicationRequest}
+// NOTE: This cannot be removed!!!
+import org.apache.gearpump.services.util.UpickleUtil._
+import org.apache.gearpump.streaming.ProcessorDescription
+import org.apache.gearpump.util.Graph
+
+class MasterServiceSpec extends FlatSpec with ScalatestRouteTest
+ with Matchers with BeforeAndAfterAll {
+ import upickle.default.{read, write}
+
+ override def testConfig: Config = TestUtil.UI_CONFIG
+
+ private def actorRefFactory = system
+ val workerId = 0
+ val mockWorker = TestProbe()
+
+ lazy val jarStoreService = JarStoreService.get(system.settings.config)
+
+ private def master = mockMaster.ref
+
+ def jarStore: JarStoreService = jarStoreService
+
+ private def masterRoute = new MasterService(master, jarStore, system).route
+
+ mockWorker.setAutoPilot {
+ new AutoPilot {
+ def run(sender: ActorRef, msg: Any): AutoPilot = msg match {
+ case GetWorkerData(workerId) =>
+ sender ! WorkerData(WorkerSummary.empty.copy(state = "active", workerId = workerId))
+ KeepRunning
+ case QueryHistoryMetrics(path, _, _, _) =>
+ sender ! HistoryMetrics(path, List.empty[HistoryMetricsItem])
+ KeepRunning
+ }
+ }
+ }
+
+ val mockMaster = TestProbe()
+ mockMaster.setAutoPilot {
+ new AutoPilot {
+ def run(sender: ActorRef, msg: Any): AutoPilot = msg match {
+ case GetMasterData =>
+ sender ! MasterData(null)
+ KeepRunning
+ case AppMastersDataRequest =>
+ sender ! AppMastersData(List.empty[AppMasterData])
+ KeepRunning
+ case GetAllWorkers =>
+ sender ! WorkerList(List(WorkerId(0, 0L)))
+ KeepRunning
+ case ResolveWorkerId(WorkerId(0, 0L)) =>
+ sender ! ResolveWorkerIdResult(Success(mockWorker.ref))
+ KeepRunning
+ case QueryHistoryMetrics(path, _, _, _) =>
+ sender ! HistoryMetrics(path, List.empty[HistoryMetricsItem])
+ KeepRunning
+ case QueryMasterConfig =>
+ sender ! MasterConfig(null)
+ KeepRunning
+ case submit: SubmitApplication =>
+ sender ! SubmitApplicationResult(Success(0))
+ KeepRunning
+ }
+ }
+ }
+
+ it should "return master info when asked" in {
+ implicit val customTimeout = RouteTestTimeout(15.seconds)
+ (Get(s"/api/$REST_VERSION/master") ~> masterRoute) ~> check {
+ // Checks the type
+ val content = responseAs[String]
+ read[MasterData](content)
+
+ // Checks the header, should contains no-cache header.
+ // Cache-Control:no-cache, max-age=0
+ val noCache = header[`Cache-Control`].get.value()
+ assert(noCache == "no-cache, max-age=0")
+ }
+
+ mockMaster.expectMsg(GetMasterData)
+ }
+
+ it should "return a json structure of appMastersData for GET request" in {
+ implicit val customTimeout = RouteTestTimeout(15.seconds)
+ (Get(s"/api/$REST_VERSION/master/applist") ~> masterRoute) ~> check {
+ // Checks the type
+ read[AppMastersData](responseAs[String])
+ }
+ mockMaster.expectMsg(AppMastersDataRequest)
+ }
+
+ it should "return a json structure of worker data for GET request" in {
+ implicit val customTimeout = RouteTestTimeout(25.seconds)
+ Get(s"/api/$REST_VERSION/master/workerlist") ~> masterRoute ~> check {
+ // Checks the type
+ val workerListJson = responseAs[String]
+ val workers = read[List[WorkerSummary]](workerListJson)
+ assert(workers.size > 0)
+ workers.foreach { worker =>
+ worker.state shouldBe "active"
+ }
+ }
+ mockMaster.expectMsg(GetAllWorkers)
+ mockMaster.expectMsgType[ResolveWorkerId]
+ mockWorker.expectMsgType[GetWorkerData]
+ }
+
+ it should "return config for master" in {
+ implicit val customTimeout = RouteTestTimeout(15.seconds)
+ (Get(s"/api/$REST_VERSION/master/config") ~> masterRoute) ~> check {
+ val responseBody = responseAs[String]
+ val config = Try(ConfigFactory.parseString(responseBody))
+ assert(config.isSuccess)
+ }
+ mockMaster.expectMsg(QueryMasterConfig)
+ }
+
+ "submit invalid application" should "return an error" in {
+ implicit val routeTestTimeout = RouteTestTimeout(30.second)
+ val tempfile = new File("foo")
+ val request = entity(tempfile)
+
+ Post(s"/api/$REST_VERSION/master/submitapp", request) ~> masterRoute ~> check {
+ assert(response.status.intValue == 500)
+ }
+ }
+
+ private def entity(file: File)(implicit ec: ExecutionContext): Future[RequestEntity] = {
+ val entity = HttpEntity(MediaTypes.`application/octet-stream`, file.length(),
+ FileIO.fromFile(file, chunkSize = 100000))
+
+ val body = Source.single(
+ Multipart.FormData.BodyPart(
+ "file",
+ entity,
+ Map("filename" -> file.getName)))
+ val form = Multipart.FormData(body)
+
+ Marshal(form).to[RequestEntity]
+ }
+
+ "MetricsQueryService" should "return history metrics" in {
+ implicit val customTimeout = RouteTestTimeout(15.seconds)
+ (Get(s"/api/$REST_VERSION/master/metrics/master") ~> masterRoute) ~> check {
+ val responseBody = responseAs[String]
+ val config = Try(ConfigFactory.parseString(responseBody))
+ assert(config.isSuccess)
+ }
+ }
+
+ "submitDag" should "submit a SubmitApplicationRequest and get an appId > 0" in {
+ import org.apache.gearpump.util.Graph._
+ val processors = Map(
+ 0 -> ProcessorDescription(0, "A", parallelism = 1),
+ 1 -> ProcessorDescription(1, "B", parallelism = 1)
+ )
+ val dag = Graph(0 ~ "partitioner" ~> 1)
+ val jsonValue = write(SubmitApplicationRequest("complexdag", processors, dag, null))
+ Post(s"/api/$REST_VERSION/master/submitdag",
+ HttpEntity(ContentTypes.`application/json`, jsonValue)) ~> masterRoute ~> check {
+ val responseBody = responseAs[String]
+ val submitApplicationResultValue = read[SubmitApplicationResultValue](responseBody)
+ assert(submitApplicationResultValue.appId >= 0, "invalid appid")
+ }
+ }
+
+ "MasterService" should "return Gearpump built-in partitioner list" in {
+ (Get(s"/api/$REST_VERSION/master/partitioners") ~> masterRoute) ~> check {
+ val responseBody = responseAs[String]
+ val partitioners = read[BuiltinPartitioners](responseBody)
+ assert(partitioners.partitioners.length > 0, "invalid response")
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/test/scala/org/apache/gearpump/services/SecurityServiceSpec.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/test/scala/org/apache/gearpump/services/SecurityServiceSpec.scala b/services/jvm/src/test/scala/org/apache/gearpump/services/SecurityServiceSpec.scala
new file mode 100644
index 0000000..c8bfb29
--- /dev/null
+++ b/services/jvm/src/test/scala/org/apache/gearpump/services/SecurityServiceSpec.scala
@@ -0,0 +1,162 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.services
+
+import scala.concurrent.duration._
+
+import akka.actor.ActorSystem
+import akka.http.scaladsl.model.FormData
+import akka.http.scaladsl.model.headers.{Cookie, `Set-Cookie`, _}
+import akka.http.scaladsl.server.Directives._
+import akka.http.scaladsl.server.{AuthorizationFailedRejection, _}
+import akka.http.scaladsl.testkit.{RouteTestTimeout, ScalatestRouteTest}
+import com.typesafe.config.Config
+import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
+
+import org.apache.gearpump.cluster.TestUtil
+// NOTE: This cannot be removed!!!
+import org.apache.gearpump.services.util.UpickleUtil._
+
+class SecurityServiceSpec
+ extends FlatSpec with ScalatestRouteTest with Matchers with BeforeAndAfterAll {
+
+ override def testConfig: Config = TestUtil.UI_CONFIG
+
+ implicit def actorSystem: ActorSystem = system
+
+ it should "return 401 if not authenticated" in {
+ val security = new SecurityService(SecurityServiceSpec.resource, actorSystem)
+
+ implicit val customTimeout = RouteTestTimeout(15.seconds)
+
+ (Get(s"/resource") ~> security.route) ~> check {
+ assert(rejection.isInstanceOf[AuthenticationFailedRejection])
+ }
+ }
+
+ "guest" should "get protected resource after authentication" in {
+ val security = new SecurityService(SecurityServiceSpec.resource, actorSystem)
+
+ implicit val customTimeout = RouteTestTimeout(15.seconds)
+
+ var cookie: HttpCookiePair = null
+ (Post(s"/login", FormData("username" -> "guest", "password" -> "guest"))
+ ~> security.route) ~> check {
+ assert("{\"user\":\"guest\"}" == responseAs[String])
+ assert(status.intValue() == 200)
+ assert(header[`Set-Cookie`].isDefined)
+ val httpCookie = header[`Set-Cookie`].get.cookie
+ assert(httpCookie.name == "gearpump_token")
+ cookie = HttpCookiePair.apply(httpCookie.name, httpCookie.value)
+ }
+
+ // After authentication, everything is fine.
+ Get("/resource").addHeader(Cookie(cookie)) ~> security.route ~> check {
+ responseAs[String] shouldEqual "OK"
+ }
+
+ // However, guest cannot access high-permission operations, like POST.
+ Post("/resource").addHeader(Cookie(cookie)) ~> security.route ~> check {
+ assert(rejection == AuthorizationFailedRejection)
+ }
+
+ // Logout, should clear the session
+ Post(s"/logout").addHeader(Cookie(cookie)) ~> security.route ~> check {
+ assert("{\"user\":\"guest\"}" == responseAs[String])
+ assert(status.intValue() == 200)
+ assert(header[`Set-Cookie`].isDefined)
+ val httpCookie = header[`Set-Cookie`].get.cookie
+ assert(httpCookie.name == "gearpump_token")
+ assert(httpCookie.value == "deleted")
+ }
+
+ // Access again, rejected this time.
+ Get("/resource") ~> security.route ~> check {
+ assert(rejection.isInstanceOf[AuthenticationFailedRejection])
+ }
+
+ Post("/resource") ~> security.route ~> check {
+ assert(rejection.isInstanceOf[AuthenticationFailedRejection])
+ }
+ }
+
+ "admin" should "get protected resource after authentication" in {
+ val security = new SecurityService(SecurityServiceSpec.resource, actorSystem)
+
+ implicit val customTimeout = RouteTestTimeout(15.seconds)
+
+ var cookie: HttpCookiePair = null
+ (Post(s"/login", FormData("username" -> "admin", "password" -> "admin"))
+ ~> security.route) ~> check {
+ assert("{\"user\":\"admin\"}" == responseAs[String])
+ assert(status.intValue() == 200)
+ assert(header[`Set-Cookie`].isDefined)
+ val httpCookie = header[`Set-Cookie`].get.cookie
+ assert(httpCookie.name == "gearpump_token")
+ cookie = HttpCookiePair(httpCookie.name, httpCookie.value)
+ }
+
+ // After authentication, everything is fine.
+ Get("/resource").addHeader(Cookie(cookie)) ~> security.route ~> check {
+ responseAs[String] shouldEqual "OK"
+ }
+
+ // Not like guest, admimn can also access POST
+ Post("/resource").addHeader(Cookie(cookie)) ~> security.route ~> check {
+ responseAs[String] shouldEqual "OK"
+ }
+
+ // Logout, should clear the session
+ Post(s"/logout").addHeader(Cookie(cookie)) ~> security.route ~> check {
+ assert("{\"user\":\"admin\"}" == responseAs[String])
+ assert(status.intValue() == 200)
+ assert(header[`Set-Cookie`].isDefined)
+ val httpCookie = header[`Set-Cookie`].get.cookie
+ assert(httpCookie.name == "gearpump_token")
+ assert(httpCookie.value == "deleted")
+ }
+
+ // Access again, rejected this time.
+ Get("/resource") ~> security.route ~> check {
+ assert(rejection.isInstanceOf[AuthenticationFailedRejection])
+ }
+
+ Post("/resource") ~> security.route ~> check {
+ assert(rejection.isInstanceOf[AuthenticationFailedRejection])
+ }
+ }
+}
+
+object SecurityServiceSpec {
+
+ val resource = new RouteService {
+ override def route: Route = {
+ get {
+ path("resource") {
+ complete("OK")
+ }
+ } ~
+ post {
+ path("resource") {
+ complete("OK")
+ }
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/test/scala/org/apache/gearpump/services/StaticServiceSpec.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/test/scala/org/apache/gearpump/services/StaticServiceSpec.scala b/services/jvm/src/test/scala/org/apache/gearpump/services/StaticServiceSpec.scala
new file mode 100644
index 0000000..33f0866
--- /dev/null
+++ b/services/jvm/src/test/scala/org/apache/gearpump/services/StaticServiceSpec.scala
@@ -0,0 +1,63 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.services
+
+import scala.concurrent.duration._
+import scala.util.Try
+
+import akka.http.scaladsl.model.headers.`Cache-Control`
+import akka.http.scaladsl.testkit.{RouteTestTimeout, ScalatestRouteTest}
+import com.typesafe.config.{Config, ConfigFactory}
+import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
+
+import org.apache.gearpump.cluster.TestUtil
+import org.apache.gearpump.util.Constants
+// NOTE: This cannot be removed!!!
+import org.apache.gearpump.services.util.UpickleUtil._
+
+class StaticServiceSpec
+ extends FlatSpec with ScalatestRouteTest with Matchers with BeforeAndAfterAll {
+
+ override def testConfig: Config = TestUtil.UI_CONFIG
+ private val supervisorPath = system.settings.config.getString(
+ Constants.GEARPUMP_SERVICE_SUPERVISOR_PATH)
+
+ protected def route = new StaticService(system, supervisorPath).route
+
+ it should "return version" in {
+ implicit val customTimeout = RouteTestTimeout(15.seconds)
+ (Get(s"/version") ~> route) ~> check {
+ val responseBody = responseAs[String]
+ val config = Try(ConfigFactory.parseString(responseBody))
+ assert(responseBody == "Unknown-Version")
+
+ // By default, it will be cached.
+ assert(header[`Cache-Control`].isEmpty)
+ }
+ }
+
+ it should "get correct supervisor path" in {
+ implicit val customTimeout = RouteTestTimeout(15.seconds)
+ (Get(s"/supervisor-actor-path") ~> route) ~> check {
+ val responseBody = responseAs[String]
+ val defaultSupervisorPath = ""
+ assert(responseBody == defaultSupervisorPath)
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/test/scala/org/apache/gearpump/services/WorkerServiceSpec.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/test/scala/org/apache/gearpump/services/WorkerServiceSpec.scala b/services/jvm/src/test/scala/org/apache/gearpump/services/WorkerServiceSpec.scala
new file mode 100644
index 0000000..4658c98
--- /dev/null
+++ b/services/jvm/src/test/scala/org/apache/gearpump/services/WorkerServiceSpec.scala
@@ -0,0 +1,121 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.services
+
+import scala.concurrent.duration._
+import scala.util.{Success, Try}
+
+import akka.actor.ActorRef
+import akka.http.scaladsl.model.headers.`Cache-Control`
+import akka.http.scaladsl.testkit.{RouteTestTimeout, ScalatestRouteTest}
+import akka.testkit.TestActor.{AutoPilot, KeepRunning}
+import akka.testkit.{TestKit, TestProbe}
+import com.typesafe.config.{Config, ConfigFactory}
+import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
+
+import org.apache.gearpump.cluster.AppMasterToMaster.{GetWorkerData, WorkerData}
+import org.apache.gearpump.cluster.ClientToMaster.{QueryHistoryMetrics, QueryWorkerConfig, ResolveWorkerId}
+import org.apache.gearpump.cluster.MasterToClient.{HistoryMetrics, HistoryMetricsItem, ResolveWorkerIdResult, WorkerConfig}
+import org.apache.gearpump.cluster.TestUtil
+import org.apache.gearpump.cluster.worker.{WorkerId, WorkerSummary}
+import org.apache.gearpump.jarstore.JarStoreService
+// NOTE: This cannot be removed!!!
+import org.apache.gearpump.services.util.UpickleUtil._
+
+class WorkerServiceSpec
+ extends FlatSpec with ScalatestRouteTest with Matchers with BeforeAndAfterAll {
+
+ override def testConfig: Config = TestUtil.DEFAULT_CONFIG
+
+ protected def actorRefFactory = system
+
+ val mockWorker = TestProbe()
+
+ protected def master = mockMaster.ref
+
+ lazy val jarStoreService = JarStoreService.get(system.settings.config)
+
+ protected def workerRoute = new WorkerService(master, system).route
+
+ mockWorker.setAutoPilot {
+ new AutoPilot {
+ def run(sender: ActorRef, msg: Any): AutoPilot = msg match {
+ case GetWorkerData(workerId) =>
+ sender ! WorkerData(WorkerSummary.empty)
+ KeepRunning
+ case QueryWorkerConfig(workerId) =>
+ sender ! WorkerConfig(null)
+ KeepRunning
+ case QueryHistoryMetrics(path, _, _, _) =>
+ sender ! HistoryMetrics(path, List.empty[HistoryMetricsItem])
+ KeepRunning
+ }
+ }
+ }
+
+ val mockMaster = TestProbe()
+ mockMaster.setAutoPilot {
+ new AutoPilot {
+ def run(sender: ActorRef, msg: Any): AutoPilot = msg match {
+ case ResolveWorkerId(workerId) =>
+ sender ! ResolveWorkerIdResult(Success(mockWorker.ref))
+ KeepRunning
+ }
+ }
+ }
+
+ "ConfigQueryService" should "return config for worker" in {
+ implicit val customTimeout = RouteTestTimeout(15.seconds)
+ (Get(s"/api/$REST_VERSION/worker/${WorkerId.render(WorkerId(0, 0L))}/config")
+ ~> workerRoute) ~> check {
+ val responseBody = responseAs[String]
+ val config = Try(ConfigFactory.parseString(responseBody))
+ assert(config.isSuccess)
+ }
+ }
+
+ it should "return WorkerData" in {
+ implicit val customTimeout = RouteTestTimeout(15.seconds)
+ (Get(s"/api/$REST_VERSION/worker/${WorkerId.render(WorkerId(1, 0L))}")
+ ~> workerRoute) ~> check {
+ val responseBody = responseAs[String]
+ val config = Try(ConfigFactory.parseString(responseBody))
+ assert(config.isSuccess)
+
+ // Check the header, should contains no-cache header.
+ // Cache-Control:no-cache, max-age=0
+ val noCache = header[`Cache-Control`].get.value()
+ assert(noCache == "no-cache, max-age=0")
+ }
+ }
+
+ "MetricsQueryService" should "return history metrics" in {
+ implicit val customTimeout = RouteTestTimeout(15.seconds)
+ (Get(s"/api/$REST_VERSION/worker/${WorkerId.render(WorkerId(0, 0L))}/metrics/worker")
+ ~> workerRoute) ~> check {
+ val responseBody = responseAs[String]
+ val config = Try(ConfigFactory.parseString(responseBody))
+ assert(config.isSuccess)
+ }
+ }
+
+ override def afterAll {
+ TestKit.shutdownActorSystem(system)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/test/scala/org/apache/gearpump/services/security/oauth2/CloudFoundryUAAOAuth2AuthenticatorSpec.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/test/scala/org/apache/gearpump/services/security/oauth2/CloudFoundryUAAOAuth2AuthenticatorSpec.scala b/services/jvm/src/test/scala/org/apache/gearpump/services/security/oauth2/CloudFoundryUAAOAuth2AuthenticatorSpec.scala
new file mode 100644
index 0000000..fef581e
--- /dev/null
+++ b/services/jvm/src/test/scala/org/apache/gearpump/services/security/oauth2/CloudFoundryUAAOAuth2AuthenticatorSpec.scala
@@ -0,0 +1,140 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.services.security.oauth2
+
+import scala.collection.JavaConverters._
+import scala.concurrent.Await
+import scala.concurrent.duration._
+
+import akka.actor.ActorSystem
+import akka.http.scaladsl.model.HttpEntity.Strict
+import akka.http.scaladsl.model.MediaTypes._
+import akka.http.scaladsl.model.Uri.{Path, Query}
+import akka.http.scaladsl.model._
+import akka.http.scaladsl.testkit.ScalatestRouteTest
+import com.typesafe.config.ConfigFactory
+import org.scalatest.FlatSpec
+
+import org.apache.gearpump.security.Authenticator
+// NOTE: This cannot be removed!!!
+import org.apache.gearpump.services.util.UpickleUtil._
+import org.apache.gearpump.services.security.oauth2.impl.CloudFoundryUAAOAuth2Authenticator
+
+class CloudFoundryUAAOAuth2AuthenticatorSpec extends FlatSpec with ScalatestRouteTest {
+
+ implicit val actorSystem: ActorSystem = system
+ private val server = new MockOAuth2Server(system, null)
+ server.start()
+ private val serverHost = s"http://127.0.0.1:${server.port}"
+
+ val configMap = Map(
+ "class" ->
+ "org.apache.gearpump.services.security.oauth2.impl.CloudFoundryUAAOAuth2Authenticator",
+ "callback" -> s"$serverHost/login/oauth2/cloudfoundryuaa/callback",
+ "clientid" -> "gearpump_test2",
+ "clientsecret" -> "gearpump_test2",
+ "default-userrole" -> "user",
+ "icon" -> "/icons/uaa.png",
+ "uaahost" -> serverHost,
+ "additional-authenticator-enabled" -> "false")
+
+ val configString = ConfigFactory.parseMap(configMap.asJava)
+
+ lazy val uaa = {
+ val uaa = new CloudFoundryUAAOAuth2Authenticator
+ uaa.init(configString, system.dispatcher)
+ uaa
+ }
+
+ it should "generate the correct authorization request" in {
+ val parameters = Uri(uaa.getAuthorizationUrl()).query().toMap
+ assert(parameters("response_type") == "code")
+ assert(parameters("client_id") == configMap("clientid"))
+ assert(parameters("redirect_uri") == configMap("callback"))
+ assert(parameters("scope") == "openid,cloud_controller.read")
+ }
+
+ it should "authenticate the authorization code and return the correct profile" in {
+ val code = Map("code" -> "QGGVeA")
+ val accessToken = "e2922002-0218-4513-a62d-1da2ba64ee4c"
+ val refreshToken = "eyJhbGciOiJSUzI1NiJ9.eyJqdGkiOiI2Nm"
+ val mail = "test@gearpump.io"
+
+ def accessTokenEndpoint(request: HttpRequest): HttpResponse = {
+ assert(request.getHeader("Authorization").get.value() ==
+ "Basic Z2VhcnB1bXBfdGVzdDI6Z2VhcnB1bXBfdGVzdDI=")
+ assert(request.entity.contentType.mediaType.value == "application/x-www-form-urlencoded")
+
+ val body = request.entity.asInstanceOf[Strict].data.decodeString("UTF-8")
+ val form = Uri./.withQuery(Query(body)).query().toMap
+
+ assert(form("grant_type") == "authorization_code")
+ assert(form("code") == "QGGVeA")
+ assert(form("response_type") == "token")
+ assert(form("redirect_uri") == configMap("callback"))
+
+ val response =
+ s"""
+ |{
+ | "access_token": "$accessToken",
+ | "token_type": "bearer",
+ | "refresh_token": "$refreshToken",
+ | "expires_in": 43199,
+ | "scope": "openid",
+ | "jti": "e8739474-b2fa-42eb-a9ad-e065bf79d7e9"
+ |}
+ """.stripMargin
+ HttpResponse(entity = HttpEntity(ContentType(`application/json`), response))
+ }
+
+ def protectedResourceEndpoint(request: HttpRequest): HttpResponse = {
+ assert(request.getUri().query().get("access_token").get == accessToken)
+ val response =
+ s"""
+ |{
+ | "user_id": "e2922002-0218-4513-a62d-1da2ba64ee4c",
+ | "user_name": "user",
+ | "email": "$mail"
+ |}
+ """.stripMargin
+ HttpResponse(entity = HttpEntity(ContentType(`application/json`), response))
+ }
+
+ server.requestHandler = (request: HttpRequest) => {
+ if (request.uri.path.startsWith(Path("/oauth/token"))) {
+ accessTokenEndpoint(request)
+ } else if (request.uri.path.startsWith(Path("/userinfo"))) {
+ protectedResourceEndpoint(request)
+ } else {
+ fail("Unexpected access to " + request.uri.toString())
+ }
+ }
+
+ val userFuture = uaa.authenticate(code)
+ val user = Await.result(userFuture, 30.seconds)
+ assert(user.user == mail)
+ assert(user.permissionLevel == Authenticator.User.permissionLevel)
+ }
+
+ override def cleanUp(): Unit = {
+ server.stop()
+ uaa.close()
+ super.cleanUp()
+ }
+}
[19/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/hbase/src/main/scala/io/gearpump/external/hbase/HBaseSink.scala
----------------------------------------------------------------------
diff --git a/external/hbase/src/main/scala/io/gearpump/external/hbase/HBaseSink.scala b/external/hbase/src/main/scala/io/gearpump/external/hbase/HBaseSink.scala
deleted file mode 100644
index a477ba6..0000000
--- a/external/hbase/src/main/scala/io/gearpump/external/hbase/HBaseSink.scala
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.external.hbase
-
-import java.io.{File, ObjectInputStream, ObjectOutputStream}
-
-import org.apache.hadoop.conf.Configuration
-import org.apache.hadoop.hbase.client.{Connection, ConnectionFactory, Put}
-import org.apache.hadoop.hbase.util.Bytes
-import org.apache.hadoop.hbase.{HBaseConfiguration, TableName}
-import org.apache.hadoop.security.UserGroupInformation
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.sink.DataSink
-import io.gearpump.streaming.task.TaskContext
-import io.gearpump.util.{Constants, FileUtils}
-
-class HBaseSink(
- userconfig: UserConfig, tableName: String, @transient var configuration: Configuration)
- extends DataSink{
- lazy val connection = HBaseSink.getConnection(userconfig, configuration)
- lazy val table = connection.getTable(TableName.valueOf(tableName))
-
- override def open(context: TaskContext): Unit = {}
-
- def this(userconfig: UserConfig, tableName: String) = {
- this(userconfig, tableName, HBaseConfiguration.create())
- }
-
- def insert(rowKey: String, columnGroup: String, columnName: String, value: String): Unit = {
- insert(Bytes.toBytes(rowKey), Bytes.toBytes(columnGroup),
- Bytes.toBytes(columnName), Bytes.toBytes(value))
- }
-
- def insert(
- rowKey: Array[Byte], columnGroup: Array[Byte], columnName: Array[Byte], value: Array[Byte])
- : Unit = {
- val put = new Put(rowKey)
- put.addColumn(columnGroup, columnName, value)
- table.put(put)
- }
-
- def put(msg: Any): Unit = {
- msg match {
- case seq: Seq[Any] =>
- seq.foreach(put)
- case tuple: (_, _, _, _) => {
- tuple._1 match {
- case str: String => {
- insert(tuple._1.asInstanceOf[String], tuple._2.asInstanceOf[String],
- tuple._3.asInstanceOf[String], tuple._4.asInstanceOf[String])
- }
- case byteArray: Array[Byte@unchecked] => {
- insert(tuple._1.asInstanceOf[Array[Byte]], tuple._2.asInstanceOf[Array[Byte]],
- tuple._3.asInstanceOf[Array[Byte]], tuple._4.asInstanceOf[Array[Byte]])
- }
- case _ =>
- // Skip
- }
- }
- }
- }
-
- override def write(message: Message): Unit = {
- put(message.msg)
- }
-
- def close(): Unit = {
- connection.close()
- table.close()
- }
-
- private def writeObject(out: ObjectOutputStream): Unit = {
- out.defaultWriteObject()
- configuration.write(out)
- }
-
- private def readObject(in: ObjectInputStream): Unit = {
- in.defaultReadObject()
- val clientConf = new Configuration(false)
- clientConf.readFields(in)
- configuration = HBaseConfiguration.create(clientConf)
- }
-}
-
-object HBaseSink {
- val HBASESINK = "hbasesink"
- val TABLE_NAME = "hbase.table.name"
- val COLUMN_FAMILY = "hbase.table.column.family"
- val COLUMN_NAME = "hbase.table.column.name"
-
- def apply[T](userconfig: UserConfig, tableName: String): HBaseSink = {
- new HBaseSink(userconfig, tableName)
- }
-
- def apply[T](userconfig: UserConfig, tableName: String, configuration: Configuration)
- : HBaseSink = {
- new HBaseSink(userconfig, tableName, configuration)
- }
-
- private def getConnection(userConfig: UserConfig, configuration: Configuration): Connection = {
- if (UserGroupInformation.isSecurityEnabled) {
- val principal = userConfig.getString(Constants.GEARPUMP_KERBEROS_PRINCIPAL)
- val keytabContent = userConfig.getBytes(Constants.GEARPUMP_KEYTAB_FILE)
- if (principal.isEmpty || keytabContent.isEmpty) {
- val errorMsg = s"HBase is security enabled, user should provide kerberos principal in " +
- s"${Constants.GEARPUMP_KERBEROS_PRINCIPAL} and keytab file " +
- s"in ${Constants.GEARPUMP_KEYTAB_FILE}"
- throw new Exception(errorMsg)
- }
- val keytabFile = File.createTempFile("login", ".keytab")
- FileUtils.writeByteArrayToFile(keytabFile, keytabContent.get)
- keytabFile.setExecutable(false)
- keytabFile.setWritable(false)
- keytabFile.setReadable(true, true)
-
- UserGroupInformation.setConfiguration(configuration)
- UserGroupInformation.loginUserFromKeytab(principal.get, keytabFile.getAbsolutePath)
- keytabFile.delete()
- }
- ConnectionFactory.createConnection(configuration)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/hbase/src/main/scala/io/gearpump/external/hbase/dsl/HBaseDSLSink.scala
----------------------------------------------------------------------
diff --git a/external/hbase/src/main/scala/io/gearpump/external/hbase/dsl/HBaseDSLSink.scala b/external/hbase/src/main/scala/io/gearpump/external/hbase/dsl/HBaseDSLSink.scala
deleted file mode 100644
index 11a20dc..0000000
--- a/external/hbase/src/main/scala/io/gearpump/external/hbase/dsl/HBaseDSLSink.scala
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.external.hbase.dsl
-
-import scala.language.implicitConversions
-
-import org.apache.hadoop.conf.Configuration
-
-import io.gearpump.cluster.UserConfig
-import io.gearpump.external.hbase.HBaseSink
-import io.gearpump.streaming.dsl.Stream
-import io.gearpump.streaming.dsl.Stream.Sink
-
-/** Create a HBase DSL Sink */
-class HBaseDSLSink[T](stream: Stream[T]) {
-
- def writeToHbase(userConfig: UserConfig, table: String, parallism: Int, description: String)
- : Stream[T] = {
- stream.sink(HBaseSink[T](userConfig, table), parallism, userConfig, description)
- }
-
- def writeToHbase(userConfig: UserConfig, configuration: Configuration, table: String,
- parallism: Int, description: String): Stream[T] = {
- stream.sink(HBaseSink[T](userConfig, table, configuration), parallism, userConfig, description)
- }
-}
-
-object HBaseDSLSink {
- implicit def streamToHBaseDSLSink[T](stream: Stream[T]): HBaseDSLSink[T] = {
- new HBaseDSLSink[T](stream)
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/hbase/src/main/scala/org/apache/gearpump/external/hbase/HBaseSink.scala
----------------------------------------------------------------------
diff --git a/external/hbase/src/main/scala/org/apache/gearpump/external/hbase/HBaseSink.scala b/external/hbase/src/main/scala/org/apache/gearpump/external/hbase/HBaseSink.scala
new file mode 100644
index 0000000..57751a4
--- /dev/null
+++ b/external/hbase/src/main/scala/org/apache/gearpump/external/hbase/HBaseSink.scala
@@ -0,0 +1,139 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.external.hbase
+
+import java.io.{File, ObjectInputStream, ObjectOutputStream}
+
+import org.apache.hadoop.conf.Configuration
+import org.apache.hadoop.hbase.client.{Connection, ConnectionFactory, Put}
+import org.apache.hadoop.hbase.util.Bytes
+import org.apache.hadoop.hbase.{HBaseConfiguration, TableName}
+import org.apache.hadoop.security.UserGroupInformation
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.sink.DataSink
+import org.apache.gearpump.streaming.task.TaskContext
+import org.apache.gearpump.util.{Constants, FileUtils}
+
+class HBaseSink(
+ userconfig: UserConfig, tableName: String, @transient var configuration: Configuration)
+ extends DataSink{
+ lazy val connection = HBaseSink.getConnection(userconfig, configuration)
+ lazy val table = connection.getTable(TableName.valueOf(tableName))
+
+ override def open(context: TaskContext): Unit = {}
+
+ def this(userconfig: UserConfig, tableName: String) = {
+ this(userconfig, tableName, HBaseConfiguration.create())
+ }
+
+ def insert(rowKey: String, columnGroup: String, columnName: String, value: String): Unit = {
+ insert(Bytes.toBytes(rowKey), Bytes.toBytes(columnGroup),
+ Bytes.toBytes(columnName), Bytes.toBytes(value))
+ }
+
+ def insert(
+ rowKey: Array[Byte], columnGroup: Array[Byte], columnName: Array[Byte], value: Array[Byte])
+ : Unit = {
+ val put = new Put(rowKey)
+ put.addColumn(columnGroup, columnName, value)
+ table.put(put)
+ }
+
+ def put(msg: Any): Unit = {
+ msg match {
+ case seq: Seq[Any] =>
+ seq.foreach(put)
+ case tuple: (_, _, _, _) => {
+ tuple._1 match {
+ case str: String => {
+ insert(tuple._1.asInstanceOf[String], tuple._2.asInstanceOf[String],
+ tuple._3.asInstanceOf[String], tuple._4.asInstanceOf[String])
+ }
+ case byteArray: Array[Byte@unchecked] => {
+ insert(tuple._1.asInstanceOf[Array[Byte]], tuple._2.asInstanceOf[Array[Byte]],
+ tuple._3.asInstanceOf[Array[Byte]], tuple._4.asInstanceOf[Array[Byte]])
+ }
+ case _ =>
+ // Skip
+ }
+ }
+ }
+ }
+
+ override def write(message: Message): Unit = {
+ put(message.msg)
+ }
+
+ def close(): Unit = {
+ connection.close()
+ table.close()
+ }
+
+ private def writeObject(out: ObjectOutputStream): Unit = {
+ out.defaultWriteObject()
+ configuration.write(out)
+ }
+
+ private def readObject(in: ObjectInputStream): Unit = {
+ in.defaultReadObject()
+ val clientConf = new Configuration(false)
+ clientConf.readFields(in)
+ configuration = HBaseConfiguration.create(clientConf)
+ }
+}
+
+object HBaseSink {
+ val HBASESINK = "hbasesink"
+ val TABLE_NAME = "hbase.table.name"
+ val COLUMN_FAMILY = "hbase.table.column.family"
+ val COLUMN_NAME = "hbase.table.column.name"
+
+ def apply[T](userconfig: UserConfig, tableName: String): HBaseSink = {
+ new HBaseSink(userconfig, tableName)
+ }
+
+ def apply[T](userconfig: UserConfig, tableName: String, configuration: Configuration)
+ : HBaseSink = {
+ new HBaseSink(userconfig, tableName, configuration)
+ }
+
+ private def getConnection(userConfig: UserConfig, configuration: Configuration): Connection = {
+ if (UserGroupInformation.isSecurityEnabled) {
+ val principal = userConfig.getString(Constants.GEARPUMP_KERBEROS_PRINCIPAL)
+ val keytabContent = userConfig.getBytes(Constants.GEARPUMP_KEYTAB_FILE)
+ if (principal.isEmpty || keytabContent.isEmpty) {
+ val errorMsg = s"HBase is security enabled, user should provide kerberos principal in " +
+ s"${Constants.GEARPUMP_KERBEROS_PRINCIPAL} and keytab file " +
+ s"in ${Constants.GEARPUMP_KEYTAB_FILE}"
+ throw new Exception(errorMsg)
+ }
+ val keytabFile = File.createTempFile("login", ".keytab")
+ FileUtils.writeByteArrayToFile(keytabFile, keytabContent.get)
+ keytabFile.setExecutable(false)
+ keytabFile.setWritable(false)
+ keytabFile.setReadable(true, true)
+
+ UserGroupInformation.setConfiguration(configuration)
+ UserGroupInformation.loginUserFromKeytab(principal.get, keytabFile.getAbsolutePath)
+ keytabFile.delete()
+ }
+ ConnectionFactory.createConnection(configuration)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/hbase/src/main/scala/org/apache/gearpump/external/hbase/dsl/HBaseDSLSink.scala
----------------------------------------------------------------------
diff --git a/external/hbase/src/main/scala/org/apache/gearpump/external/hbase/dsl/HBaseDSLSink.scala b/external/hbase/src/main/scala/org/apache/gearpump/external/hbase/dsl/HBaseDSLSink.scala
new file mode 100644
index 0000000..2417763
--- /dev/null
+++ b/external/hbase/src/main/scala/org/apache/gearpump/external/hbase/dsl/HBaseDSLSink.scala
@@ -0,0 +1,47 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.external.hbase.dsl
+
+import scala.language.implicitConversions
+
+import org.apache.hadoop.conf.Configuration
+
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.external.hbase.HBaseSink
+import org.apache.gearpump.streaming.dsl.Stream
+import org.apache.gearpump.streaming.dsl.Stream.Sink
+
+/** Create a HBase DSL Sink */
+class HBaseDSLSink[T](stream: Stream[T]) {
+
+ def writeToHbase(userConfig: UserConfig, table: String, parallism: Int, description: String)
+ : Stream[T] = {
+ stream.sink(HBaseSink[T](userConfig, table), parallism, userConfig, description)
+ }
+
+ def writeToHbase(userConfig: UserConfig, configuration: Configuration, table: String,
+ parallism: Int, description: String): Stream[T] = {
+ stream.sink(HBaseSink[T](userConfig, table, configuration), parallism, userConfig, description)
+ }
+}
+
+object HBaseDSLSink {
+ implicit def streamToHBaseDSLSink[T](stream: Stream[T]): HBaseDSLSink[T] = {
+ new HBaseDSLSink[T](stream)
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/hbase/src/test/scala/io/gearpump/external/hbase/HBaseSinkSpec.scala
----------------------------------------------------------------------
diff --git a/external/hbase/src/test/scala/io/gearpump/external/hbase/HBaseSinkSpec.scala b/external/hbase/src/test/scala/io/gearpump/external/hbase/HBaseSinkSpec.scala
deleted file mode 100644
index cad6581..0000000
--- a/external/hbase/src/test/scala/io/gearpump/external/hbase/HBaseSinkSpec.scala
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.external.hbase
-
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{Matchers, PropSpec}
-
-class HBaseSinkSpec extends PropSpec with PropertyChecks with Matchers {
-
- property("HBaseSink should insert a row successfully") {
-
- // import Mockito._
- // val htable = Mockito.mock(classOf[HTable])
- // val row = "row"
- // val group = "group"
- // val name = "name"
- // val value = "1.2"
- // val put = new Put(Bytes.toBytes(row))
- // put.add(Bytes.toBytes(group), Bytes.toBytes(name), Bytes.toBytes(value))
- // val hbaseSink = HBaseSink(htable)
- // hbaseSink.insert(put)
- // verify(htable).put(put)
-
- }
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/hbase/src/test/scala/org/apache/gearpump/external/hbase/HBaseSinkSpec.scala
----------------------------------------------------------------------
diff --git a/external/hbase/src/test/scala/org/apache/gearpump/external/hbase/HBaseSinkSpec.scala b/external/hbase/src/test/scala/org/apache/gearpump/external/hbase/HBaseSinkSpec.scala
new file mode 100644
index 0000000..24b9646
--- /dev/null
+++ b/external/hbase/src/test/scala/org/apache/gearpump/external/hbase/HBaseSinkSpec.scala
@@ -0,0 +1,41 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.external.hbase
+
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{Matchers, PropSpec}
+
+class HBaseSinkSpec extends PropSpec with PropertyChecks with Matchers {
+
+ property("HBaseSink should insert a row successfully") {
+
+ // import Mockito._
+ // val htable = Mockito.mock(classOf[HTable])
+ // val row = "row"
+ // val group = "group"
+ // val name = "name"
+ // val value = "1.2"
+ // val put = new Put(Bytes.toBytes(row))
+ // put.add(Bytes.toBytes(group), Bytes.toBytes(name), Bytes.toBytes(value))
+ // val hbaseSink = HBaseSink(htable)
+ // hbaseSink.insert(put)
+ // verify(htable).put(put)
+
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/main/scala/io/gearpump/streaming/kafka/KafkaSink.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/main/scala/io/gearpump/streaming/kafka/KafkaSink.scala b/external/kafka/src/main/scala/io/gearpump/streaming/kafka/KafkaSink.scala
deleted file mode 100644
index b482c7c..0000000
--- a/external/kafka/src/main/scala/io/gearpump/streaming/kafka/KafkaSink.scala
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.kafka
-
-import java.util.Properties
-
-import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord}
-import org.apache.kafka.common.serialization.ByteArraySerializer
-
-import io.gearpump.Message
-import io.gearpump.streaming.kafka.lib.KafkaUtil
-import io.gearpump.streaming.sink.DataSink
-import io.gearpump.streaming.task.TaskContext
-
-/**
- * kafka sink connectors that invokes org.apache.kafka.clients.producer.KafkaProducer to send
- * messages to kafka queue
- * @param getProducer is a function to construct a KafkaProducer
- * @param topic is the kafka topic to write to
- */
-class KafkaSink private[kafka](
- getProducer: () => KafkaProducer[Array[Byte], Array[Byte]], topic: String) extends DataSink {
-
- /**
- * @param topic producer topic
- * @param properties producer config
- */
- def this(topic: String, properties: Properties) = {
- this(() => KafkaUtil.createKafkaProducer(properties,
- new ByteArraySerializer, new ByteArraySerializer), topic)
- }
-
- /**
- *
- * creates an empty properties with `bootstrap.servers` set to `bootstrapServers`
- * and invokes `KafkaSink(topic, properties)`
- * @param topic producer topic
- * @param bootstrapServers kafka producer config `bootstrap.servers`
- */
- def this(topic: String, bootstrapServers: String) = {
- this(topic, KafkaUtil.buildProducerConfig(bootstrapServers))
- }
-
- // Lazily construct producer since KafkaProducer is not serializable
- private lazy val producer = getProducer()
-
- override def open(context: TaskContext): Unit = {}
-
- override def write(message: Message): Unit = {
- val record = message.msg match {
- case (k, v) =>
- new ProducerRecord[Array[Byte], Array[Byte]](topic, k.asInstanceOf[Array[Byte]],
- v.asInstanceOf[Array[Byte]])
- case v =>
- new ProducerRecord[Array[Byte], Array[Byte]](topic, v.asInstanceOf[Array[Byte]])
- }
- producer.send(record)
- }
-
- override def close(): Unit = {
- producer.close()
- }
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/main/scala/io/gearpump/streaming/kafka/KafkaSource.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/main/scala/io/gearpump/streaming/kafka/KafkaSource.scala b/external/kafka/src/main/scala/io/gearpump/streaming/kafka/KafkaSource.scala
deleted file mode 100644
index 1544445..0000000
--- a/external/kafka/src/main/scala/io/gearpump/streaming/kafka/KafkaSource.scala
+++ /dev/null
@@ -1,195 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.kafka
-
-import java.util.Properties
-import scala.collection.mutable.ArrayBuffer
-import scala.util.{Failure, Success}
-
-import kafka.common.TopicAndPartition
-import org.slf4j.Logger
-
-import io.gearpump.streaming.kafka.lib.consumer.{FetchThread, KafkaMessage}
-import io.gearpump.streaming.kafka.lib.{DefaultMessageDecoder, KafkaOffsetManager, KafkaSourceConfig, KafkaUtil}
-import io.gearpump.streaming.source.DefaultTimeStampFilter
-import io.gearpump.streaming.task.TaskContext
-import io.gearpump.streaming.transaction.api.OffsetStorage.StorageEmpty
-import io.gearpump.streaming.transaction.api._
-import io.gearpump.util.LogUtil
-import io.gearpump.{Message, TimeStamp}
-
-object KafkaSource {
- private val LOG: Logger = LogUtil.getLogger(classOf[KafkaSource])
-}
-
-/**
- * Kafka source connectors that pulls a batch of messages (`kafka.consumer.emit.batch.size`)
- * from multiple Kafka TopicAndPartition in a round-robin way.
- *
- * This is a TimeReplayableSource which is able to replay messages given a start time.
- * Each kafka message is tagged with a timestamp by
- * [[io.gearpump.streaming.transaction.api.MessageDecoder]] and the (offset, timestamp) mapping
- * is stored to a [[io.gearpump.streaming.transaction.api.OffsetStorage]]. On recovery,
- * we could retrieve the previously stored offset from the
- * [[io.gearpump.streaming.transaction.api.OffsetStorage]] by timestamp and start to read from
- * there.
- *
- * kafka message is wrapped into gearpump [[io.gearpump.Message]] and further filtered by a
- * [[io.gearpump.streaming.transaction.api.TimeStampFilter]]
- * such that obsolete messages are dropped.
- *
- * @param config kafka source config
- * @param offsetStorageFactory factory to build [[OffsetStorage]]
- * @param messageDecoder decodes [[io.gearpump.Message]] from raw bytes
- * @param timestampFilter filters out message based on timestamp
- * @param fetchThread fetches messages and puts on a in-memory queue
- * @param offsetManagers manages offset-to-timestamp storage for each kafka.common.TopicAndPartition
- */
-class KafkaSource(
- config: KafkaSourceConfig,
- offsetStorageFactory: OffsetStorageFactory,
- messageDecoder: MessageDecoder = new DefaultMessageDecoder,
- timestampFilter: TimeStampFilter = new DefaultTimeStampFilter,
- private var fetchThread: Option[FetchThread] = None,
- private var offsetManagers: Map[TopicAndPartition, KafkaOffsetManager] = {
- Map.empty[TopicAndPartition, KafkaOffsetManager]
- }) extends TimeReplayableSource {
- import io.gearpump.streaming.kafka.KafkaSource._
-
- private var startTime: Option[TimeStamp] = None
-
- /**
- * Constructs a Kafka Source by...
- *
- * @param topics comma-separated string of topics
- * @param properties kafka consumer config
- * @param offsetStorageFactory [[io.gearpump.streaming.transaction.api.OffsetStorageFactory]]
- * that creates [[io.gearpump.streaming.transaction.api.OffsetStorage]]
- *
- */
- def this(topics: String, properties: Properties, offsetStorageFactory: OffsetStorageFactory) = {
- this(KafkaSourceConfig(properties).withConsumerTopics(topics), offsetStorageFactory)
- }
- /**
- * Constructs a Kafka Source by...
- *
- * @param topics comma-separated string of topics
- * @param properties kafka consumer config
- * @param offsetStorageFactory [[io.gearpump.streaming.transaction.api.OffsetStorageFactory]]
- * that creates [[io.gearpump.streaming.transaction.api.OffsetStorage]]
- * @param messageDecoder decodes [[io.gearpump.Message]] from raw bytes
- * @param timestampFilter filters out message based on timestamp
- */
- def this(topics: String, properties: Properties, offsetStorageFactory: OffsetStorageFactory,
- messageDecoder: MessageDecoder, timestampFilter: TimeStampFilter) = {
- this(KafkaSourceConfig(properties)
- .withConsumerTopics(topics), offsetStorageFactory,
- messageDecoder, timestampFilter)
- }
-
- /**
- * Constructs a Kafka Source by...
- *
- * @param topics comma-separated string of topics
- * @param zkConnect kafka consumer config `zookeeper.connect`
- * @param offsetStorageFactory [[io.gearpump.streaming.transaction.api.OffsetStorageFactory]]
- * that creates [[io.gearpump.streaming.transaction.api.OffsetStorage]]
- */
- def this(topics: String, zkConnect: String, offsetStorageFactory: OffsetStorageFactory) =
- this(topics, KafkaUtil.buildConsumerConfig(zkConnect), offsetStorageFactory)
-
- /**
- * Constructs a Kafka Source by...
- *
- * @param topics comma-separated string of topics
- * @param zkConnect kafka consumer config `zookeeper.connect`
- * @param offsetStorageFactory [[io.gearpump.streaming.transaction.api.OffsetStorageFactory]]
- * that creates [[io.gearpump.streaming.transaction.api.OffsetStorage]]
- * @param messageDecoder decodes [[io.gearpump.Message]] from raw bytes
- * @param timestampFilter filters out message based on timestamp
- */
- def this(topics: String, zkConnect: String, offsetStorageFactory: OffsetStorageFactory,
- messageDecoder: MessageDecoder,
- timestampFilter: TimeStampFilter) = {
- this(topics, KafkaUtil.buildConsumerConfig(zkConnect), offsetStorageFactory,
- messageDecoder, timestampFilter)
- }
-
- LOG.debug(s"assigned ${offsetManagers.keySet}")
-
- private[kafka] def setStartTime(startTime: Option[TimeStamp]): Unit = {
- this.startTime = startTime
- fetchThread.foreach { fetch =>
- this.startTime.foreach { time =>
- offsetManagers.foreach { case (tp, offsetManager) =>
- offsetManager.resolveOffset(time) match {
- case Success(offset) =>
- LOG.debug(s"set start offset to $offset for $tp")
- fetch.setStartOffset(tp, offset)
- case Failure(StorageEmpty) =>
- LOG.debug(s"no previous TimeStamp stored")
- case Failure(e) => throw e
- }
- }
- }
- fetch.setDaemon(true)
- fetch.start()
- }
- }
-
- override def open(context: TaskContext, startTime: TimeStamp): Unit = {
- import context.{appId, appName, parallelism, taskId}
-
- val topics = config.getConsumerTopics
- val grouper = config.getGrouper
- val consumerConfig = config.consumerConfig
- val topicAndPartitions = grouper.group(parallelism, taskId.index,
- KafkaUtil.getTopicAndPartitions(KafkaUtil.connectZookeeper(consumerConfig)(), topics))
- this.fetchThread = Some(FetchThread(topicAndPartitions, config.getFetchThreshold,
- config.getFetchSleepMS, config.getConsumerStartOffset, consumerConfig))
- this.offsetManagers = topicAndPartitions.map { tp =>
- val storageTopic = s"app${appId}_${appName}_${tp.topic}_${tp.partition}"
- val storage = offsetStorageFactory.getOffsetStorage(storageTopic)
- tp -> new KafkaOffsetManager(storage)
- }.toMap
-
- setStartTime(Option(startTime))
- }
-
- override def read(): Message = {
- fetchThread.flatMap(_.poll.flatMap(filterMessage)).orNull
- }
-
- private def filterMessage(kafkaMsg: KafkaMessage): Option[Message] = {
- val msgOpt = offsetManagers(kafkaMsg.topicAndPartition)
- .filter(messageDecoder.fromBytes(kafkaMsg.msg) -> kafkaMsg.offset)
- msgOpt.flatMap { msg =>
- startTime match {
- case None =>
- Some(msg)
- case Some(time) =>
- timestampFilter.filter(msg, time)
- }
- }
- }
-
- override def close(): Unit = {
- offsetManagers.foreach(_._2.close())
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/main/scala/io/gearpump/streaming/kafka/KafkaStorage.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/main/scala/io/gearpump/streaming/kafka/KafkaStorage.scala b/external/kafka/src/main/scala/io/gearpump/streaming/kafka/KafkaStorage.scala
deleted file mode 100644
index e50bf84..0000000
--- a/external/kafka/src/main/scala/io/gearpump/streaming/kafka/KafkaStorage.scala
+++ /dev/null
@@ -1,148 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.kafka
-
-import java.util.Properties
-import scala.collection.mutable
-import scala.util.{Failure, Success, Try}
-
-import com.twitter.bijection.Injection
-import kafka.api.OffsetRequest
-import kafka.consumer.ConsumerConfig
-import org.I0Itec.zkclient.ZkClient
-import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord}
-import org.apache.kafka.common.serialization.ByteArraySerializer
-import org.slf4j.Logger
-
-import io.gearpump.TimeStamp
-import io.gearpump.streaming.kafka.lib.KafkaUtil
-import io.gearpump.streaming.kafka.lib.consumer.KafkaConsumer
-import io.gearpump.streaming.transaction.api.OffsetStorage.{Overflow, StorageEmpty, Underflow}
-import io.gearpump.streaming.transaction.api.{OffsetStorage, OffsetStorageFactory}
-import io.gearpump.util.LogUtil
-
-/**
- * Factory that builds [[KafkaStorage]]
- *
- * @param consumerProps kafka consumer config
- * @param producerProps kafka producer config
- */
-class KafkaStorageFactory(consumerProps: Properties, producerProps: Properties)
- extends OffsetStorageFactory {
-
- /**
- * Creates consumer config properties with `zookeeper.connect` set to zkConnect
- * and producer config properties with `bootstrap.servers` set to bootstrapServers
- *
- * @param zkConnect kafka consumer config `zookeeper.connect`
- * @param bootstrapServers kafka producer config `bootstrap.servers`
- */
- def this(zkConnect: String, bootstrapServers: String) =
- this(KafkaUtil.buildConsumerConfig(zkConnect), KafkaUtil.buildProducerConfig(bootstrapServers))
-
- override def getOffsetStorage(dir: String): OffsetStorage = {
- val topic = dir
- val consumerConfig = new ConsumerConfig(consumerProps)
- val getConsumer = () => KafkaConsumer(topic, 0, OffsetRequest.EarliestTime, consumerConfig)
- new KafkaStorage(topic, KafkaUtil.createKafkaProducer[Array[Byte], Array[Byte]](
- producerProps, new ByteArraySerializer, new ByteArraySerializer),
- getConsumer(), KafkaUtil.connectZookeeper(consumerConfig)())
- }
-}
-
-object KafkaStorage {
- private val LOG: Logger = LogUtil.getLogger(classOf[KafkaStorage])
-}
-
-/**
- * Stores offset-timestamp mapping to kafka
- *
- * @param topic kafka store topic
- * @param producer kafka producer
- * @param getConsumer function to get kafka consumer
- * @param connectZk function to connect zookeeper
- */
-class KafkaStorage private[kafka](
- topic: String,
- producer: KafkaProducer[Array[Byte], Array[Byte]],
- getConsumer: => KafkaConsumer,
- connectZk: => ZkClient)
- extends OffsetStorage {
-
- private lazy val consumer = getConsumer
-
- private val dataByTime: List[(TimeStamp, Array[Byte])] = {
- if (KafkaUtil.topicExists(connectZk, topic)) {
- load(consumer)
- } else {
- List.empty[(TimeStamp, Array[Byte])]
- }
- }
-
- /**
- * Offsets with timestamp less than `time` have already been processed by the system
- * so we look up the storage for the first offset with timestamp large equal than `time`
- * on replay.
- *
- * @param time the timestamp to look up for the earliest unprocessed offset
- * @return the earliest unprocessed offset if `time` is in the range, otherwise failure
- */
- override def lookUp(time: TimeStamp): Try[Array[Byte]] = {
- if (dataByTime.isEmpty) {
- Failure(StorageEmpty)
- } else {
- val min = dataByTime.head
- val max = dataByTime.last
- if (time < min._1) {
- Failure(Underflow(min._2))
- } else if (time > max._1) {
- Failure(Overflow(max._2))
- } else {
- Success(dataByTime.find(_._1 >= time).get._2)
- }
- }
- }
-
- override def append(time: TimeStamp, offset: Array[Byte]): Unit = {
- val message = new ProducerRecord[Array[Byte], Array[Byte]](
- topic, 0, Injection[Long, Array[Byte]](time), offset)
- producer.send(message)
- }
-
- override def close(): Unit = {
- producer.close()
- KafkaUtil.deleteTopic(connectZk, topic)
- }
-
- private[kafka] def load(consumer: KafkaConsumer): List[(TimeStamp, Array[Byte])] = {
- var messagesBuilder = new mutable.ArrayBuilder.ofRef[(TimeStamp, Array[Byte])]
- while (consumer.hasNext) {
- val kafkaMsg = consumer.next
- kafkaMsg.key.map { k =>
- Injection.invert[TimeStamp, Array[Byte]](k) match {
- case Success(time) =>
- messagesBuilder += (time -> kafkaMsg.msg)
- case Failure(e) => throw e
- }
- } orElse (throw new RuntimeException("offset key should not be null"))
- }
- consumer.close()
- messagesBuilder.result().toList
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/main/scala/io/gearpump/streaming/kafka/dsl/KafkaDSLSink.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/main/scala/io/gearpump/streaming/kafka/dsl/KafkaDSLSink.scala b/external/kafka/src/main/scala/io/gearpump/streaming/kafka/dsl/KafkaDSLSink.scala
deleted file mode 100644
index 2a852e2..0000000
--- a/external/kafka/src/main/scala/io/gearpump/streaming/kafka/dsl/KafkaDSLSink.scala
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.kafka.dsl
-
-import java.util.Properties
-
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.dsl
-import io.gearpump.streaming.kafka.KafkaSink
-
-class KafkaDSLSink[T](stream: dsl.Stream[T]) {
-
- /** Create a Kafka DSL Sink */
- def writeToKafka(
- topic: String,
- bootstrapServers: String,
- parallism: Int,
- description: String): dsl.Stream[T] = {
- stream.sink(new KafkaSink(topic, bootstrapServers), parallism, UserConfig.empty, description)
- }
-
- def writeToKafka(
- topic: String,
- properties: Properties,
- parallism: Int,
- description: String): dsl.Stream[T] = {
- stream.sink(new KafkaSink(topic, properties), parallism, UserConfig.empty, description)
- }
-}
-
-object KafkaDSLSink {
-
- import scala.language.implicitConversions
-
- implicit def streamToKafkaDSLSink[T](stream: dsl.Stream[T]): KafkaDSLSink[T] = {
- new KafkaDSLSink[T](stream)
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/main/scala/io/gearpump/streaming/kafka/dsl/KafkaDSLUtil.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/main/scala/io/gearpump/streaming/kafka/dsl/KafkaDSLUtil.scala b/external/kafka/src/main/scala/io/gearpump/streaming/kafka/dsl/KafkaDSLUtil.scala
deleted file mode 100644
index 325b40f..0000000
--- a/external/kafka/src/main/scala/io/gearpump/streaming/kafka/dsl/KafkaDSLUtil.scala
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.kafka.dsl
-
-import java.util.Properties
-
-import io.gearpump.streaming.dsl
-import io.gearpump.streaming.dsl.StreamApp
-import io.gearpump.streaming.kafka.KafkaSource
-import io.gearpump.streaming.kafka.lib.{DefaultMessageDecoder, KafkaSourceConfig}
-import io.gearpump.streaming.transaction.api.{MessageDecoder, OffsetStorageFactory, TimeStampFilter}
-
-object KafkaDSLUtil {
- def createStream[T](
- app: StreamApp,
- parallelism: Int,
- description: String,
- kafkaConfig: KafkaSourceConfig,
- offsetStorageFactory: OffsetStorageFactory,
- messageDecoder: MessageDecoder = new DefaultMessageDecoder): dsl.Stream[T] = {
- app.source[T](new KafkaSource(kafkaConfig, offsetStorageFactory, messageDecoder),
- parallelism, description)
- }
-
- def createStream[T](
- app: StreamApp,
- parallelism: Int,
- description: String,
- topics: String,
- zkConnect: String,
- offsetStorageFactory: OffsetStorageFactory): dsl.Stream[T] = {
- app.source[T](new KafkaSource(topics, zkConnect, offsetStorageFactory),
- parallelism, description)
- }
-
- def createStream[T](
- app: StreamApp,
- parallelism: Int,
- description: String,
- topics: String,
- zkConnect: String,
- offsetStorageFactory: OffsetStorageFactory,
- messageDecoder: MessageDecoder,
- timestampFilter: TimeStampFilter): dsl.Stream[T] = {
- app.source[T](new KafkaSource(topics, zkConnect, offsetStorageFactory,
- messageDecoder, timestampFilter), parallelism, description)
- }
-
- def createStream[T](
- app: StreamApp,
- parallelism: Int,
- description: String,
- topics: String,
- properties: Properties,
- offsetStorageFactory: OffsetStorageFactory): dsl.Stream[T] = {
- app.source[T](new KafkaSource(topics, properties, offsetStorageFactory),
- parallelism, description)
- }
-
- def createStream[T](
- app: StreamApp,
- topics: String,
- parallelism: Int,
- description: String,
- properties: Properties,
- offsetStorageFactory: OffsetStorageFactory,
- messageDecoder: MessageDecoder,
- timestampFilter: TimeStampFilter): dsl.Stream[T] = {
- app.source[T](new KafkaSource(topics, properties, offsetStorageFactory,
- messageDecoder, timestampFilter), parallelism, description)
- }
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/DefaultMessageDecoder.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/DefaultMessageDecoder.scala b/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/DefaultMessageDecoder.scala
deleted file mode 100644
index f846efe..0000000
--- a/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/DefaultMessageDecoder.scala
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.kafka.lib
-
-import scala.util.{Failure, Success}
-
-import com.twitter.bijection.Injection
-
-import io.gearpump.Message
-import io.gearpump.streaming.transaction.api.MessageDecoder
-
-class DefaultMessageDecoder extends MessageDecoder {
- override def fromBytes(bytes: Array[Byte]): Message = {
- Message(bytes, System.currentTimeMillis())
- }
-}
-
-class StringMessageDecoder extends MessageDecoder {
- override def fromBytes(bytes: Array[Byte]): Message = {
- Injection.invert[String, Array[Byte]](bytes) match {
- case Success(s) => Message(s, System.currentTimeMillis())
- case Failure(e) => throw e
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/KafkaOffsetManager.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/KafkaOffsetManager.scala b/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/KafkaOffsetManager.scala
deleted file mode 100644
index e9c95e3..0000000
--- a/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/KafkaOffsetManager.scala
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.kafka.lib
-
-import scala.util.{Failure, Success, Try}
-
-import com.twitter.bijection.Injection
-import org.slf4j.Logger
-
-import io.gearpump._
-import io.gearpump.streaming.transaction.api.OffsetStorage.{Overflow, StorageEmpty, Underflow}
-import io.gearpump.streaming.transaction.api.{OffsetManager, OffsetStorage}
-import io.gearpump.util.LogUtil
-
-object KafkaOffsetManager {
- private val LOG: Logger = LogUtil.getLogger(classOf[KafkaOffsetManager])
-}
-
-private[kafka] class KafkaOffsetManager(storage: OffsetStorage) extends OffsetManager {
- import io.gearpump.streaming.kafka.lib.KafkaOffsetManager._
-
- var maxTime: TimeStamp = 0L
-
- override def filter(messageAndOffset: (Message, Long)): Option[Message] = {
- val (message, offset) = messageAndOffset
- if (message.timestamp > maxTime) {
- maxTime = message.timestamp
- storage.append(maxTime, Injection[Long, Array[Byte]](offset))
- }
- Some(message)
- }
-
- override def resolveOffset(time: TimeStamp): Try[Long] = {
- storage.lookUp(time) match {
- case Success(offset) => Injection.invert[Long, Array[Byte]](offset)
- case Failure(Overflow(max)) =>
- LOG.warn(s"start time larger than the max stored TimeStamp; set to max offset")
- Injection.invert[Long, Array[Byte]](max)
- case Failure(Underflow(min)) =>
- LOG.warn(s"start time less than the min stored TimeStamp; set to min offset")
- Injection.invert[Long, Array[Byte]](min)
- case Failure(StorageEmpty) => Failure(StorageEmpty)
- case Failure(e) => throw e
- }
- }
-
- override def close(): Unit = {
- storage.close()
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/KafkaSourceConfig.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/KafkaSourceConfig.scala b/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/KafkaSourceConfig.scala
deleted file mode 100644
index 123f3ac..0000000
--- a/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/KafkaSourceConfig.scala
+++ /dev/null
@@ -1,175 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.kafka.lib
-
-import java.util.Properties
-
-import kafka.api.OffsetRequest
-import kafka.consumer.ConsumerConfig
-import org.slf4j.Logger
-
-import io.gearpump.streaming.kafka.lib.grouper.{KafkaDefaultGrouper, KafkaGrouper}
-import io.gearpump.util.LogUtil
-
-object KafkaSourceConfig {
-
- val NAME = "kafka_config"
-
- val ZOOKEEPER_CONNECT = "zookeeper.connect"
- val GROUP_ID = "group.id"
- val CONSUMER_START_OFFSET = "kafka.consumer.start.offset"
- val CONSUMER_TOPICS = "kafka.consumer.topics"
- val FETCH_THRESHOLD = "kafka.consumer.fetch.threshold"
- val FETCH_SLEEP_MS = "kafka.consumer.fetch.sleep.ms"
- val GROUPER_CLASS = "kafka.grouper.class"
-
- private val LOG: Logger = LogUtil.getLogger(getClass)
-
- def apply(consumerProps: Properties): KafkaSourceConfig = new KafkaSourceConfig(consumerProps)
-}
-
-/**
- * Extends kafka.consumer.ConsumerConfig with specific config needed by
- * [[io.gearpump.streaming.kafka.KafkaSource]]
- *
- * @param consumerProps kafka consumer config
- */
-class KafkaSourceConfig(val consumerProps: Properties = new Properties)
- extends java.io.Serializable {
- import io.gearpump.streaming.kafka.lib.KafkaSourceConfig._
-
- if (!consumerProps.containsKey(ZOOKEEPER_CONNECT)) {
- consumerProps.setProperty(ZOOKEEPER_CONNECT, "localhost:2181")
- }
-
- if (!consumerProps.containsKey(GROUP_ID)) {
- consumerProps.setProperty(GROUP_ID, "gearpump")
- }
-
- def consumerConfig: ConsumerConfig = new ConsumerConfig(consumerProps)
-
- /**
- * Set kafka consumer topics, seperated by comma.
- *
- * @param topics comma-separated string
- * @return new KafkaConfig based on this but with
- * [[io.gearpump.streaming.kafka.lib.KafkaSourceConfig#CONSUMER_TOPICS]]
- * set to given value
- */
- def withConsumerTopics(topics: String): KafkaSourceConfig = {
- consumerProps.setProperty(CONSUMER_TOPICS, topics)
- KafkaSourceConfig(consumerProps)
- }
-
- /**
- * Returns a list of kafka consumer topics
- */
- def getConsumerTopics: List[String] = {
- Option(consumerProps.getProperty(CONSUMER_TOPICS)).getOrElse("topic1").split(",").toList
- }
-
- /**
- * Sets the sleep interval if there are no more message or message buffer is full.
- *
- * Consumer.FetchThread will sleep for a while if no more messages or
- * the incoming queue size is above the
- * [[io.gearpump.streaming.kafka.lib.KafkaSourceConfig#FETCH_THRESHOLD]]
- *
- * @param sleepMS sleep interval in milliseconds
- * @return new KafkaConfig based on this but with
- * [[io.gearpump.streaming.kafka.lib.KafkaSourceConfig#FETCH_SLEEP_MS]] set to given value
- */
- def withFetchSleepMS(sleepMS: Int): KafkaSourceConfig = {
- consumerProps.setProperty(FETCH_SLEEP_MS, s"$sleepMS")
- KafkaSourceConfig(consumerProps)
- }
-
- /**
- * Gets the sleep interval
- *
- * Consumer.FetchThread sleeps for a while if no more messages or
- * the incoming queue is full (size is bigger than the
- * [[io.gearpump.streaming.kafka.lib.KafkaSourceConfig#FETCH_THRESHOLD]])
- *
- * @return sleep interval in milliseconds
- */
- def getFetchSleepMS: Int = {
- Option(consumerProps.getProperty(FETCH_SLEEP_MS)).getOrElse("100").toInt
- }
-
- /**
- * Sets the batch size we use for one fetch.
- *
- * Consumer.FetchThread stops fetching new messages if its incoming queue
- * size is above the threshold and starts again when the queue size is below it
- *
- * @param threshold queue size
- * @return new KafkaConfig based on this but with
- * [[io.gearpump.streaming.kafka.lib.KafkaSourceConfig#FETCH_THRESHOLD]] set to give value
- */
- def withFetchThreshold(threshold: Int): KafkaSourceConfig = {
- consumerProps.setProperty(FETCH_THRESHOLD, s"$threshold")
- KafkaSourceConfig(consumerProps)
- }
-
- /**
- * Returns fetch batch size.
- *
- * Consumer.FetchThread stops fetching new messages if
- * its incoming queue size is above the threshold and starts again when the queue size is below it
- *
- * @return fetch threshold
- */
- def getFetchThreshold: Int = {
- Option(consumerProps.getProperty(FETCH_THRESHOLD)).getOrElse("10000").toInt
- }
-
- /**
- * Sets [[io.gearpump.streaming.kafka.lib.grouper.KafkaGrouper]], which
- * defines how kafka.common.TopicAndPartitions are mapped to source tasks.
- *
- * @param className name of the factory class
- * @return new KafkaConfig based on this but with
- * [[io.gearpump.streaming.kafka.lib.KafkaSourceConfig#GROUPER_CLASS]] set to given value
- */
- def withGrouper(className: String): KafkaSourceConfig = {
- consumerProps.setProperty(GROUPER_CLASS, className)
- KafkaSourceConfig(consumerProps)
- }
-
- /**
- * Returns [[io.gearpump.streaming.kafka.lib.grouper.KafkaGrouper]] instance, which
- * defines how kafka.common.TopicAndPartitions are mapped to source tasks
- */
- def getGrouper: KafkaGrouper = {
- Class.forName(Option(consumerProps.getProperty(GROUPER_CLASS))
- .getOrElse(classOf[KafkaDefaultGrouper].getName)).newInstance().asInstanceOf[KafkaGrouper]
- }
-
- def withConsumerStartOffset(earliestOrLatest: Long): KafkaSourceConfig = {
- consumerProps.setProperty(CONSUMER_START_OFFSET, s"$earliestOrLatest")
- KafkaSourceConfig(consumerProps)
- }
-
- def getConsumerStartOffset: Long = {
- Option(consumerProps.getProperty(CONSUMER_START_OFFSET))
- .getOrElse(s"${OffsetRequest.EarliestTime}").toLong
- }
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/KafkaUtil.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/KafkaUtil.scala b/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/KafkaUtil.scala
deleted file mode 100644
index 2f7fcf7..0000000
--- a/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/KafkaUtil.scala
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.kafka.lib
-
-import java.io.InputStream
-import java.util.Properties
-
-import kafka.admin.AdminUtils
-import kafka.cluster.Broker
-import kafka.common.TopicAndPartition
-import kafka.consumer.ConsumerConfig
-import kafka.utils.{ZKStringSerializer, ZkUtils}
-import org.I0Itec.zkclient.ZkClient
-import org.apache.kafka.clients.producer.{KafkaProducer, ProducerConfig}
-import org.apache.kafka.common.serialization.Serializer
-import org.slf4j.Logger
-
-import io.gearpump.util.LogUtil
-
-object KafkaUtil {
- private val LOG: Logger = LogUtil.getLogger(getClass)
-
- def getBroker(connectZk: => ZkClient, topic: String, partition: Int): Broker = {
- val zkClient = connectZk
- try {
- val leader = ZkUtils.getLeaderForPartition(zkClient, topic, partition)
- .getOrElse(throw new RuntimeException(
- s"leader not available for TopicAndPartition($topic, $partition)"))
- ZkUtils.getBrokerInfo(zkClient, leader)
- .getOrElse(throw new RuntimeException(s"broker info not found for leader $leader"))
- } catch {
- case e: Exception =>
- LOG.error(e.getMessage)
- throw e
- } finally {
- zkClient.close()
- }
- }
-
- def getTopicAndPartitions(connectZk: => ZkClient, consumerTopics: List[String])
- : Array[TopicAndPartition] = {
- val zkClient = connectZk
- try {
- ZkUtils.getPartitionsForTopics(zkClient, consumerTopics).flatMap {
- case (topic, partitions) => partitions.map(TopicAndPartition(topic, _))
- }.toArray
- } catch {
- case e: Exception =>
- LOG.error(e.getMessage)
- throw e
- } finally {
- zkClient.close()
- }
- }
-
- def topicExists(connectZk: => ZkClient, topic: String): Boolean = {
- val zkClient = connectZk
- try {
- AdminUtils.topicExists(zkClient, topic)
- } catch {
- case e: Exception =>
- LOG.error(e.getMessage)
- throw e
- } finally {
- zkClient.close()
- }
- }
-
- /**
- * create a new kafka topic
- * return true if topic already exists, and false otherwise
- */
- def createTopic(connectZk: => ZkClient, topic: String, partitions: Int, replicas: Int)
- : Boolean = {
- val zkClient = connectZk
- try {
- if (AdminUtils.topicExists(zkClient, topic)) {
- LOG.info(s"topic $topic exists")
- true
- } else {
- AdminUtils.createTopic(zkClient, topic, partitions, replicas)
- LOG.info(s"created topic $topic")
- false
- }
- } catch {
- case e: Exception =>
- LOG.error(e.getMessage)
- throw e
- } finally {
- zkClient.close()
- }
- }
-
- def deleteTopic(connectZk: => ZkClient, topic: String): Unit = {
- val zkClient = connectZk
- try {
- AdminUtils.deleteTopic(zkClient, topic)
- } catch {
- case e: Exception =>
- LOG.error(e.getMessage)
- } finally {
- zkClient.close()
- }
- }
-
- def connectZookeeper(config: ConsumerConfig): () => ZkClient = {
- val zookeeperConnect = config.zkConnect
- val sessionTimeout = config.zkSessionTimeoutMs
- val connectionTimeout = config.zkConnectionTimeoutMs
- () => new ZkClient(zookeeperConnect, sessionTimeout, connectionTimeout, ZKStringSerializer)
- }
-
- def loadProperties(filename: String): Properties = {
- val props = new Properties()
- var propStream: InputStream = null
- try {
- propStream = getClass.getClassLoader.getResourceAsStream(filename)
- props.load(propStream)
- } catch {
- case e: Exception =>
- LOG.error(s"$filename not found")
- } finally {
- if (propStream != null) {
- propStream.close()
- }
- }
- props
- }
-
- def createKafkaProducer[K, V](properties: Properties,
- keySerializer: Serializer[K],
- valueSerializer: Serializer[V]): KafkaProducer[K, V] = {
- if (properties.getProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG) == null) {
- properties.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092")
- }
- new KafkaProducer[K, V](properties, keySerializer, valueSerializer)
- }
-
- def buildProducerConfig(bootstrapServers: String): Properties = {
- val properties = new Properties()
- properties.setProperty("bootstrap.servers", bootstrapServers)
- properties
- }
-
- def buildConsumerConfig(zkConnect: String): Properties = {
- val properties = new Properties()
- properties.setProperty("zookeeper.connect", zkConnect)
- properties.setProperty("group.id", "gearpump")
- properties
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/consumer/ExponentialBackoffSleeper.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/consumer/ExponentialBackoffSleeper.scala b/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/consumer/ExponentialBackoffSleeper.scala
deleted file mode 100644
index 141ae98..0000000
--- a/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/consumer/ExponentialBackoffSleeper.scala
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.kafka.lib.consumer
-
-/**
- * someone sleeps for exponentially increasing duration each time
- * until the cap
- *
- * @param backOffMultiplier The factor by which the duration increases.
- * @param initialDurationMs Time in milliseconds for initial sleep.
- * @param maximumDurationMs Cap up to which we will increase the duration.
- */
-private[consumer] class ExponentialBackoffSleeper(
- backOffMultiplier: Double = 2.0,
- initialDurationMs: Long = 100,
- maximumDurationMs: Long = 10000) {
-
- require(backOffMultiplier > 1.0, "backOffMultiplier must be greater than 1")
- require(initialDurationMs > 0, "initialDurationMs must be positive")
- require(maximumDurationMs >= initialDurationMs, "maximumDurationMs must be >= initialDurationMs")
-
- private var sleepDuration = initialDurationMs
-
- def reset(): Unit = {
- sleepDuration = initialDurationMs
- }
-
- def sleep(): Unit = {
- Thread.sleep(sleepDuration)
- setNextSleepDuration()
- }
-
- def getSleepDuration: Long = sleepDuration
-
- def setNextSleepDuration(): Unit = {
- val next = (sleepDuration * backOffMultiplier).asInstanceOf[Long]
- sleepDuration = math.min(math.max(initialDurationMs, next), maximumDurationMs)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/consumer/FetchThread.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/consumer/FetchThread.scala b/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/consumer/FetchThread.scala
deleted file mode 100644
index 8dbe145..0000000
--- a/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/consumer/FetchThread.scala
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.kafka.lib.consumer
-
-import java.nio.channels.ClosedByInterruptException
-import java.util.concurrent.LinkedBlockingQueue
-
-import kafka.common.TopicAndPartition
-import kafka.consumer.ConsumerConfig
-import org.slf4j.Logger
-
-import io.gearpump.util.LogUtil
-
-object FetchThread {
- private val LOG: Logger = LogUtil.getLogger(classOf[FetchThread])
-
- def apply(topicAndPartitions: Array[TopicAndPartition],
- fetchThreshold: Int,
- fetchSleepMS: Long,
- startOffsetTime: Long,
- consumerConfig: ConsumerConfig): FetchThread = {
- val createConsumer = (tp: TopicAndPartition) =>
- KafkaConsumer(tp.topic, tp.partition, startOffsetTime, consumerConfig)
-
- val incomingQueue = new LinkedBlockingQueue[KafkaMessage]()
- new FetchThread(topicAndPartitions, createConsumer, incomingQueue, fetchThreshold, fetchSleepMS)
- }
-}
-
-/**
- * A thread to fetch messages from multiple kafka org.apache.kafka.TopicAndPartition and puts them
- * onto a queue, which is asynchronously polled by a consumer
- *
- * @param createConsumer given a org.apache.kafka.TopicAndPartition, create a
- * [[io.gearpump.streaming.kafka.lib.consumer.KafkaConsumer]] to
- * connect to it
- * @param incomingQueue a queue to buffer incoming messages
- * @param fetchThreshold above which thread should stop fetching messages
- * @param fetchSleepMS interval to sleep when no more messages or hitting fetchThreshold
- */
-private[kafka] class FetchThread(topicAndPartitions: Array[TopicAndPartition],
- createConsumer: TopicAndPartition => KafkaConsumer,
- incomingQueue: LinkedBlockingQueue[KafkaMessage],
- fetchThreshold: Int,
- fetchSleepMS: Long) extends Thread {
- import io.gearpump.streaming.kafka.lib.consumer.FetchThread._
-
- private var consumers: Map[TopicAndPartition, KafkaConsumer] = createAllConsumers
-
- def setStartOffset(tp: TopicAndPartition, startOffset: Long): Unit = {
- consumers(tp).setStartOffset(startOffset)
- }
-
- def poll: Option[KafkaMessage] = {
- Option(incomingQueue.poll())
- }
-
- override def run(): Unit = {
- try {
- var nextOffsets = Map.empty[TopicAndPartition, Long]
- var reset = false
- val sleeper = new ExponentialBackoffSleeper(
- backOffMultiplier = 2.0,
- initialDurationMs = 100L,
- maximumDurationMs = 10000L)
- while (!Thread.currentThread().isInterrupted) {
- try {
- if (reset) {
- nextOffsets = consumers.mapValues(_.getNextOffset)
- resetConsumers(nextOffsets)
- reset = false
- }
- val hasMoreMessages = fetchMessage
- sleeper.reset()
- if (!hasMoreMessages) {
- Thread.sleep(fetchSleepMS)
- }
- } catch {
- case exception: Exception =>
- LOG.warn(s"resetting consumers due to $exception")
- reset = true
- sleeper.sleep()
- }
- }
- } catch {
- case e: InterruptedException => LOG.info("fetch thread got interrupted exception")
- case e: ClosedByInterruptException => LOG.info("fetch thread closed by interrupt exception")
- } finally {
- consumers.values.foreach(_.close())
- }
- }
-
- /**
- * fetch message from each TopicAndPartition in a round-robin way
- */
- def fetchMessage: Boolean = {
- consumers.foldLeft(false) { (hasNext, tpAndConsumer) =>
- val (_, consumer) = tpAndConsumer
- if (incomingQueue.size < fetchThreshold) {
- if (consumer.hasNext) {
- incomingQueue.put(consumer.next())
- true
- } else {
- hasNext
- }
- } else {
- true
- }
- }
- }
-
- private def createAllConsumers: Map[TopicAndPartition, KafkaConsumer] = {
- topicAndPartitions.map(tp => tp -> createConsumer(tp)).toMap
- }
-
- private def resetConsumers(nextOffsets: Map[TopicAndPartition, Long]): Unit = {
- consumers.values.foreach(_.close())
- consumers = createAllConsumers
- consumers.foreach { case (tp, consumer) =>
- consumer.setStartOffset(nextOffsets(tp))
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/consumer/KafkaConsumer.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/consumer/KafkaConsumer.scala b/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/consumer/KafkaConsumer.scala
deleted file mode 100644
index 77321b9..0000000
--- a/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/consumer/KafkaConsumer.scala
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.kafka.lib.consumer
-
-import kafka.api.{FetchRequestBuilder, OffsetRequest}
-import kafka.common.ErrorMapping._
-import kafka.common.TopicAndPartition
-import kafka.consumer.{ConsumerConfig, SimpleConsumer}
-import kafka.message.MessageAndOffset
-import kafka.utils.Utils
-
-import io.gearpump.streaming.kafka.lib.KafkaUtil
-
-object KafkaConsumer {
- def apply(topic: String, partition: Int, startOffsetTime: Long, config: ConsumerConfig)
- : KafkaConsumer = {
- val connectZk = KafkaUtil.connectZookeeper(config)
- val broker = KafkaUtil.getBroker(connectZk(), topic, partition)
- val soTimeout = config.socketTimeoutMs
- val soBufferSize = config.socketReceiveBufferBytes
- val fetchSize = config.fetchMessageMaxBytes
- val clientId = config.clientId
- val consumer = new SimpleConsumer(broker.host, broker.port, soTimeout, soBufferSize, clientId)
- val getIterator = (offset: Long) => {
- val request = new FetchRequestBuilder()
- .addFetch(topic, partition, offset, fetchSize)
- .build()
-
- val response = consumer.fetch(request)
- response.errorCode(topic, partition) match {
- case NoError => response.messageSet(topic, partition).iterator
- case error => throw exceptionFor(error)
- }
- }
- new KafkaConsumer(consumer, topic, partition, getIterator, startOffsetTime)
- }
-}
-
-/**
- * uses kafka kafka.consumer.SimpleConsumer to consume and iterate over
- * messages from a kafka kafka.common.TopicAndPartition.
- */
-class KafkaConsumer(consumer: SimpleConsumer,
- topic: String,
- partition: Int,
- getIterator: (Long) => Iterator[MessageAndOffset],
- startOffsetTime: Long = OffsetRequest.EarliestTime) {
- private val earliestOffset = consumer
- .earliestOrLatestOffset(TopicAndPartition(topic, partition), startOffsetTime, -1)
- private var nextOffset: Long = earliestOffset
- private var iterator: Iterator[MessageAndOffset] = getIterator(nextOffset)
-
- def setStartOffset(startOffset: Long): Unit = {
- nextOffset = startOffset
- iterator = getIterator(nextOffset)
- }
-
- def next(): KafkaMessage = {
- val mo = iterator.next()
- val message = mo.message
-
- nextOffset = mo.nextOffset
-
- val offset = mo.offset
- val payload = Utils.readBytes(message.payload)
- new KafkaMessage(topic, partition, offset, Option(message.key).map(Utils.readBytes), payload)
- }
-
- def hasNext: Boolean = {
- @annotation.tailrec
- def hasNextHelper(iter: Iterator[MessageAndOffset], newIterator: Boolean): Boolean = {
- if (iter.hasNext) true
- else if (newIterator) false
- else {
- iterator = getIterator(nextOffset)
- hasNextHelper(iterator, newIterator = true)
- }
- }
- hasNextHelper(iterator, newIterator = false)
- }
-
- def getNextOffset: Long = nextOffset
-
- def close(): Unit = {
- consumer.close()
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/consumer/KafkaMessage.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/consumer/KafkaMessage.scala b/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/consumer/KafkaMessage.scala
deleted file mode 100644
index 16330ed..0000000
--- a/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/consumer/KafkaMessage.scala
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.kafka.lib.consumer
-
-import kafka.common.TopicAndPartition
-
-/**
- * wrapper over messages from kafka
- * @param topicAndPartition where message comes from
- * @param offset message offset on kafka queue
- * @param key message key, could be None
- * @param msg message payload
- */
-case class KafkaMessage(topicAndPartition: TopicAndPartition, offset: Long,
- key: Option[Array[Byte]], msg: Array[Byte]) {
-
- def this(topic: String, partition: Int, offset: Long,
- key: Option[Array[Byte]], msg: Array[Byte]) = {
- this(TopicAndPartition(topic, partition), offset, key, msg)
- }
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/grouper/KafkaDefaultGrouper.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/grouper/KafkaDefaultGrouper.scala b/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/grouper/KafkaDefaultGrouper.scala
deleted file mode 100644
index 0f968e2..0000000
--- a/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/grouper/KafkaDefaultGrouper.scala
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.kafka.lib.grouper
-
-import kafka.common.TopicAndPartition
-
-/**
- * default grouper groups TopicAndPartitions among StreamProducers by partitions
- *
- * e.g. given 2 topics (topicA with 2 partitions and topicB with 3 partitions) and
- * 2 streamProducers (streamProducer0 and streamProducer1)
- *
- * streamProducer0 gets (topicA, partition1), (topicB, partition1) and (topicA, partition3)
- * streamProducer1 gets (topicA, partition2), (topicB, partition2)
- */
-class KafkaDefaultGrouper extends KafkaGrouper {
- def group(taskNum: Int, taskIndex: Int, topicAndPartitions: Array[TopicAndPartition])
- : Array[TopicAndPartition] = {
- topicAndPartitions.indices.filter(_ % taskNum == taskIndex)
- .map(i => topicAndPartitions(i)).toArray
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/grouper/KafkaGrouper.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/grouper/KafkaGrouper.scala b/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/grouper/KafkaGrouper.scala
deleted file mode 100644
index 6660a04..0000000
--- a/external/kafka/src/main/scala/io/gearpump/streaming/kafka/lib/grouper/KafkaGrouper.scala
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.kafka.lib.grouper
-
-import kafka.common.TopicAndPartition
-
-/**
- * this class dispatches kafka kafka.common.TopicAndPartition to gearpump tasks
- */
-trait KafkaGrouper {
- def group(taskNum: Int, taskIndex: Int, topicAndPartitions: Array[TopicAndPartition])
- : Array[TopicAndPartition]
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/KafkaSink.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/KafkaSink.scala b/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/KafkaSink.scala
new file mode 100644
index 0000000..cb90f93
--- /dev/null
+++ b/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/KafkaSink.scala
@@ -0,0 +1,80 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.kafka
+
+import java.util.Properties
+
+import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord}
+import org.apache.kafka.common.serialization.ByteArraySerializer
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.streaming.kafka.lib.KafkaUtil
+import org.apache.gearpump.streaming.sink.DataSink
+import org.apache.gearpump.streaming.task.TaskContext
+
+/**
+ * kafka sink connectors that invokes org.apache.kafka.clients.producer.KafkaProducer to send
+ * messages to kafka queue
+ * @param getProducer is a function to construct a KafkaProducer
+ * @param topic is the kafka topic to write to
+ */
+class KafkaSink private[kafka](
+ getProducer: () => KafkaProducer[Array[Byte], Array[Byte]], topic: String) extends DataSink {
+
+ /**
+ * @param topic producer topic
+ * @param properties producer config
+ */
+ def this(topic: String, properties: Properties) = {
+ this(() => KafkaUtil.createKafkaProducer(properties,
+ new ByteArraySerializer, new ByteArraySerializer), topic)
+ }
+
+ /**
+ *
+ * creates an empty properties with `bootstrap.servers` set to `bootstrapServers`
+ * and invokes `KafkaSink(topic, properties)`
+ * @param topic producer topic
+ * @param bootstrapServers kafka producer config `bootstrap.servers`
+ */
+ def this(topic: String, bootstrapServers: String) = {
+ this(topic, KafkaUtil.buildProducerConfig(bootstrapServers))
+ }
+
+ // Lazily construct producer since KafkaProducer is not serializable
+ private lazy val producer = getProducer()
+
+ override def open(context: TaskContext): Unit = {}
+
+ override def write(message: Message): Unit = {
+ val record = message.msg match {
+ case (k, v) =>
+ new ProducerRecord[Array[Byte], Array[Byte]](topic, k.asInstanceOf[Array[Byte]],
+ v.asInstanceOf[Array[Byte]])
+ case v =>
+ new ProducerRecord[Array[Byte], Array[Byte]](topic, v.asInstanceOf[Array[Byte]])
+ }
+ producer.send(record)
+ }
+
+ override def close(): Unit = {
+ producer.close()
+ }
+}
+
[07/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/ExecutorManager.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/ExecutorManager.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/ExecutorManager.scala
new file mode 100644
index 0000000..79a65c4
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/ExecutorManager.scala
@@ -0,0 +1,209 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.appmaster
+
+import scala.concurrent.duration._
+import scala.util.{Failure, Try}
+
+import akka.actor.SupervisorStrategy.Stop
+import akka.actor._
+import akka.remote.RemoteScope
+import com.typesafe.config.Config
+import org.apache.commons.lang.exception.ExceptionUtils
+
+import org.apache.gearpump.cluster.AppMasterToWorker.ChangeExecutorResource
+import org.apache.gearpump.cluster.appmaster.ExecutorSystemScheduler.{ExecutorSystemJvmConfig, ExecutorSystemStarted, StartExecutorSystemTimeout, StartExecutorSystems}
+import org.apache.gearpump.cluster.appmaster.WorkerInfo
+import org.apache.gearpump.cluster.scheduler.{Resource, ResourceRequest}
+import org.apache.gearpump.cluster.worker.WorkerId
+import org.apache.gearpump.cluster.{AppJar, AppMasterContext, ExecutorContext, UserConfig}
+import org.apache.gearpump.streaming.ExecutorId
+import org.apache.gearpump.streaming.ExecutorToAppMaster.RegisterExecutor
+import org.apache.gearpump.streaming.appmaster.ExecutorManager._
+import org.apache.gearpump.streaming.executor.Executor
+import org.apache.gearpump.util.{LogUtil, Util}
+
+/**
+ * ExecutorManager manage the start and stop of all executors.
+ *
+ * ExecutorManager will launch Executor when asked. It hide the details like starting
+ * a new ExecutorSystem from user. Please use ExecutorManager.props() to construct this actor
+ */
+private[appmaster] class ExecutorManager(
+ userConfig: UserConfig,
+ appContext: AppMasterContext,
+ executorFactory: (ExecutorContext, UserConfig, Address, ExecutorId) => Props,
+ clusterConfig: Config,
+ appName: String)
+ extends Actor {
+
+ private val LOG = LogUtil.getLogger(getClass)
+
+ import appContext.{appId, masterProxy, username}
+
+ private var taskManager: ActorRef = null
+
+ private implicit val actorSystem = context.system
+ private val systemConfig = context.system.settings.config
+
+ private var executors = Map.empty[Int, ExecutorInfo]
+
+ def receive: Receive = waitForTaskManager
+
+ def waitForTaskManager: Receive = {
+ case SetTaskManager(taskManager) =>
+ this.taskManager = taskManager
+ context.become(service orElse terminationWatch)
+ }
+
+ // If something wrong on executor, ExecutorManager will stop the current executor,
+ // and wait for AppMaster to start a new executor.
+ override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 10,
+ withinTimeRange = 1.minute) {
+ case ex: Throwable =>
+ val executorId = Try(sender.path.name.toInt)
+ executorId match {
+ case scala.util.Success(id) => {
+ executors -= id
+ LOG.error(s"Executor $id throws exception, stop it...\n" +
+ ExceptionUtils.getStackTrace(ex))
+ }
+ case Failure(ex) => {
+ LOG.error(s"Sender ${sender.path} is dead, but seems it is not an executor...")
+ }
+ }
+ Stop
+ }
+
+ // Responds to outside queries
+ def service: Receive = {
+ case StartExecutors(resources, jar) =>
+ masterProxy ! StartExecutorSystems(resources, getExecutorJvmConfig(Some(jar)))
+ case ExecutorSystemStarted(executorSystem, boundedJar) =>
+ import executorSystem.{address, executorSystemId, resource => executorResource, worker}
+
+ val executorId = executorSystemId
+ val executorContext = ExecutorContext(executorId, worker, appId, appName,
+ appMaster = context.parent, executorResource)
+ executors += executorId -> ExecutorInfo(executorId, null, worker, boundedJar)
+
+ // Starts executor
+ val executor = context.actorOf(executorFactory(executorContext, userConfig,
+ address, executorId), executorId.toString)
+ executorSystem.bindLifeCycleWith(executor)
+ case StartExecutorSystemTimeout =>
+ taskManager ! StartExecutorsTimeOut
+
+ case RegisterExecutor(executor, executorId, resource, worker) =>
+ LOG.info(s"executor $executorId has been launched")
+ // Watches for executor termination
+ context.watch(executor)
+ val executorInfo = executors.get(executorId).get
+ executors += executorId -> executorInfo.copy(executor = executor)
+ taskManager ! ExecutorStarted(executorId, resource, worker.workerId, executorInfo.boundedJar)
+
+ // Broadcasts message to all executors
+ case BroadCast(msg) =>
+ LOG.info(s"Broadcast ${msg.getClass.getSimpleName} to all executors")
+ context.children.foreach(_ forward msg)
+
+ // Unicasts message to single executor
+ case UniCast(executorId, msg) =>
+ LOG.info(s"Unicast ${msg.getClass.getSimpleName} to executor $executorId")
+ val executor = executors.get(executorId)
+ executor.foreach(_.executor forward msg)
+
+ case GetExecutorInfo =>
+ sender ! executors
+
+ // Tells Executor manager resources that are occupied. The Executor Manager can use this
+ // information to tell worker to reclaim un-used resources
+ case ExecutorResourceUsageSummary(resources) =>
+ executors.foreach { pair =>
+ val (executorId, executor) = pair
+ val resource = resources.get(executorId)
+ val worker = executor.worker.ref
+ // Notifies the worker the actual resource used by this application.
+ resource match {
+ case Some(resource) =>
+ worker ! ChangeExecutorResource(appId, executorId, resource)
+ case None =>
+ worker ! ChangeExecutorResource(appId, executorId, Resource(0))
+ }
+ }
+ }
+
+ def terminationWatch: Receive = {
+ case Terminated(actor) =>
+ val executorId = Try(actor.path.name.toInt)
+ executorId match {
+ case scala.util.Success(id) => {
+ executors -= id
+ LOG.error(s"Executor $id is down")
+ taskManager ! ExecutorStopped(id)
+ }
+ case scala.util.Failure(ex) =>
+ LOG.error(s"failed to get the executor Id from path string ${actor.path}", ex)
+ }
+ }
+
+ private def getExecutorJvmConfig(jar: Option[AppJar]): ExecutorSystemJvmConfig = {
+ val executorAkkaConfig = clusterConfig
+ val jvmSetting = Util.resolveJvmSetting(executorAkkaConfig.withFallback(systemConfig)).executor
+
+ ExecutorSystemJvmConfig(jvmSetting.classPath, jvmSetting.vmargs, jar,
+ username, executorAkkaConfig)
+ }
+}
+
+private[appmaster] object ExecutorManager {
+ case class StartExecutors(resources: Array[ResourceRequest], jar: AppJar)
+ case class BroadCast(msg: Any)
+
+ case class UniCast(executorId: Int, msg: Any)
+
+ case object GetExecutorInfo
+
+ case class ExecutorStarted(
+ executorId: Int, resource: Resource, workerId: WorkerId, boundedJar: Option[AppJar])
+ case class ExecutorStopped(executorId: Int)
+
+ case class SetTaskManager(taskManager: ActorRef)
+
+ case object StartExecutorsTimeOut
+
+ def props(
+ userConfig: UserConfig, appContext: AppMasterContext, clusterConfig: Config, appName: String)
+ : Props = {
+ val executorFactory =
+ (executorContext: ExecutorContext,
+ userConfig: UserConfig,
+ address: Address,
+ executorId: ExecutorId) =>
+ Props(classOf[Executor], executorContext, userConfig)
+ .withDeploy(Deploy(scope = RemoteScope(address)))
+
+ Props(new ExecutorManager(userConfig, appContext, executorFactory, clusterConfig, appName))
+ }
+
+ case class ExecutorResourceUsageSummary(resources: Map[ExecutorId, Resource])
+
+ case class ExecutorInfo(
+ executorId: ExecutorId, executor: ActorRef, worker: WorkerInfo, boundedJar: Option[AppJar])
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/JarScheduler.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/JarScheduler.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/JarScheduler.scala
new file mode 100644
index 0000000..6de5306
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/JarScheduler.scala
@@ -0,0 +1,175 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.appmaster
+
+import akka.actor._
+import akka.pattern.ask
+import com.typesafe.config.Config
+import org.apache.gearpump.TimeStamp
+import org.apache.gearpump.cluster.AppJar
+import org.apache.gearpump.cluster.scheduler.{Resource, ResourceRequest}
+import org.apache.gearpump.cluster.worker.WorkerId
+import org.apache.gearpump.partitioner.PartitionerDescription
+import org.apache.gearpump.streaming.appmaster.JarScheduler._
+import org.apache.gearpump.streaming.task.TaskId
+import org.apache.gearpump.streaming.{DAG, ProcessorDescription}
+import org.apache.gearpump.util.{Constants, Graph, LogUtil}
+
+import scala.concurrent.Future
+
+/**
+ * Different processors of the stream application can use different jars. JarScheduler is the
+ * scheduler for different jars.
+ *
+ * For a DAG of multiple processors, each processor can have its own jar. Tasks of same jar
+ * is scheduled by TaskScheduler, and TaskSchedulers are scheduled by JarScheduler.
+ *
+ * In runtime, the implementation is delegated to actor JarSchedulerImpl
+ */
+class JarScheduler(appId: Int, appName: String, config: Config, factory: ActorRefFactory) {
+ private val actor: ActorRef = factory.actorOf(Props(new JarSchedulerImpl(appId, appName, config)))
+ private implicit val dispatcher = factory.dispatcher
+ private implicit val timeout = Constants.FUTURE_TIMEOUT
+
+ /** Set the current DAG version active */
+ def setDag(dag: DAG, startClock: Future[TimeStamp]): Unit = {
+ actor ! TransitToNewDag
+ startClock.map { start =>
+ actor ! NewDag(dag, start)
+ }
+ }
+
+ /** AppMaster ask JarScheduler about how many resource it wants */
+ def getResourceRequestDetails(): Future[Array[ResourceRequestDetail]] = {
+ (actor ? GetResourceRequestDetails).asInstanceOf[Future[Array[ResourceRequestDetail]]]
+ }
+
+ /**
+ * AppMaster has resource allocated, and ask the jar scheduler to schedule tasks
+ * for this executor.
+ */
+ def scheduleTask(appJar: AppJar, workerId: WorkerId, executorId: Int, resource: Resource)
+ : Future[List[TaskId]] = {
+ (actor ? ScheduleTask(appJar, workerId, executorId, resource))
+ .asInstanceOf[Future[List[TaskId]]]
+ }
+
+ /**
+ * Some executor JVM process is dead. AppMaster asks jar scheduler to re-schedule the impacted
+ * tasks.
+ */
+ def executorFailed(executorId: Int): Future[Option[ResourceRequestDetail]] = {
+ (actor ? ExecutorFailed(executorId)).asInstanceOf[Future[Option[ResourceRequestDetail]]]
+ }
+}
+
+object JarScheduler {
+
+ case class ResourceRequestDetail(jar: AppJar, requests: Array[ResourceRequest])
+
+ case class NewDag(dag: DAG, startTime: TimeStamp)
+
+ case object TransitToNewDag
+
+ case object GetResourceRequestDetails
+
+ /**
+ * Schedule tasks for one appJar.
+ *
+ * @param appJar Application jar.
+ * @param workerId Worker machine Id.
+ * @param executorId Executor Id.
+ * @param resource Slots that are available.
+ */
+ case class ScheduleTask(appJar: AppJar, workerId: WorkerId, executorId: Int, resource: Resource)
+
+ /** Some executor JVM is dead, try to recover tasks that are located on failed executor */
+ case class ExecutorFailed(executorId: Int)
+
+ class JarSchedulerImpl(appId: Int, appName: String, config: Config) extends Actor with Stash {
+
+ // Each TaskScheduler maps to a jar.
+ private var taskSchedulers = Map.empty[AppJar, TaskScheduler]
+
+ private val LOG = LogUtil.getLogger(getClass)
+
+ def receive: Receive = waitForNewDag
+
+ def waitForNewDag: Receive = {
+ case TransitToNewDag => // Continue current state
+ case NewDag(dag, startTime) =>
+
+ LOG.info(s"Init JarScheduler, dag version: ${dag.version}, startTime: $startTime")
+
+ val processors = dag.processors.values.groupBy(_.jar)
+
+ taskSchedulers = processors.map { jarAndProcessors =>
+ val (jar, processors) = jarAndProcessors
+ // Construct the sub DAG, each sub DAG maps to a separate jar.
+ val subGraph = Graph.empty[ProcessorDescription, PartitionerDescription]
+ processors.foreach { processor =>
+ if (startTime < processor.life.death) {
+ subGraph.addVertex(processor)
+ }
+ }
+ val subDagForSingleJar = DAG(subGraph)
+
+ val taskScheduler = taskSchedulers
+ .getOrElse(jar, new TaskSchedulerImpl(appId, appName, config))
+
+ LOG.info(s"Set DAG for TaskScheduler, count: " + subDagForSingleJar.processors.size)
+ taskScheduler.setDAG(subDagForSingleJar)
+ jar -> taskScheduler
+ }
+ unstashAll()
+ context.become(ready)
+ case other =>
+ stash()
+ }
+
+ def ready: Receive = {
+ // Notifies there is a new DAG coming.
+ case TransitToNewDag =>
+ context.become(waitForNewDag)
+
+ case GetResourceRequestDetails =>
+
+ // Asks each TaskScheduler (Each for one jar) the resource requests.
+ val result: Array[ResourceRequestDetail] = taskSchedulers.map { jarAndScheduler =>
+ val (jar, scheduler) = jarAndScheduler
+ ResourceRequestDetail(jar, scheduler.getResourceRequests())
+ }.toArray
+ LOG.info(s"GetRequestDetails " + result.mkString(";"))
+ sender ! result
+
+ case ScheduleTask(appJar, workerId, executorId, resource) =>
+ val result: List[TaskId] = taskSchedulers.get(appJar).map { scheduler =>
+ scheduler.schedule(workerId, executorId, resource)
+ }.getOrElse(List.empty)
+ LOG.info(s"ScheduleTask " + result.mkString(";"))
+ sender ! result
+ case ExecutorFailed(executorId) =>
+ val result: Option[ResourceRequestDetail] = taskSchedulers.
+ find(_._2.scheduledTasks(executorId).nonEmpty).map { jarAndScheduler =>
+ ResourceRequestDetail(jarAndScheduler._1, jarAndScheduler._2.executorFailed(executorId))
+ }
+ LOG.info(s"ExecutorFailed " + result.mkString(";"))
+ sender ! result
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/StreamAppMasterSummary.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/StreamAppMasterSummary.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/StreamAppMasterSummary.scala
new file mode 100644
index 0000000..3d43ee7
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/StreamAppMasterSummary.scala
@@ -0,0 +1,61 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.appmaster
+
+import org.apache.gearpump._
+import org.apache.gearpump.cluster.AppMasterToMaster.AppMasterSummary
+import org.apache.gearpump.cluster.MasterToAppMaster.AppMasterStatus
+import org.apache.gearpump.cluster.{MasterToAppMaster, UserConfig}
+import org.apache.gearpump.streaming.appmaster.AppMaster.ExecutorBrief
+import org.apache.gearpump.streaming.{ExecutorId, LifeTime, ProcessorId}
+import org.apache.gearpump.util.Graph
+import org.apache.gearpump.util.HistoryMetricsService.HistoryMetricsConfig
+
+/** Stream application summary, used for REST API */
+case class StreamAppMasterSummary(
+ appType: String = "streaming",
+ appId: Int,
+ appName: String = null,
+ actorPath: String = null,
+ clock: TimeStamp = 0L,
+ status: AppMasterStatus = MasterToAppMaster.AppMasterActive,
+ startTime: TimeStamp = 0L,
+ uptime: TimeStamp = 0L,
+ user: String = null,
+ homeDirectory: String = "",
+ logFile: String = "",
+ dag: Graph[ProcessorId, String] = null,
+ executors: List[ExecutorBrief] = null,
+ processors: Map[ProcessorId, ProcessorSummary] = Map.empty[ProcessorId, ProcessorSummary],
+ // Hiearachy level for each processor
+ processorLevels: Map[ProcessorId, Int] = Map.empty[ProcessorId, Int],
+ historyMetricsConfig: HistoryMetricsConfig = null)
+ extends AppMasterSummary
+
+case class TaskCount(count: Int)
+
+case class ProcessorSummary(
+ id: ProcessorId,
+ taskClass: String,
+ parallelism: Int,
+ description: String,
+ taskConf: UserConfig,
+ life: LifeTime,
+ executors: List[ExecutorId],
+ taskCount: Map[ExecutorId, TaskCount])
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/TaskLocator.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/TaskLocator.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/TaskLocator.scala
new file mode 100644
index 0000000..87630b7
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/TaskLocator.scala
@@ -0,0 +1,97 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.appmaster
+
+import com.typesafe.config.{Config, ConfigFactory, ConfigRenderOptions, ConfigValueFactory}
+import org.apache.gearpump.cluster.worker.WorkerId
+import org.apache.gearpump.streaming.appmaster.TaskLocator.{Localities, Locality, NonLocality, WorkerLocality}
+import org.apache.gearpump.streaming.task.TaskId
+
+import scala.collection.JavaConverters._
+import scala.util.Try
+
+/**
+ * TaskLocator is used to decide which machine one task should run on.
+ *
+ * User can config [[org.apache.gearpump.streaming.Constants#GEARPUMP_STREAMING_LOCALITIES]] to
+ * decide to control which machine the task is running on.
+ */
+class TaskLocator(appName: String, config: Config) {
+ private val taskLocalities: Map[TaskId, Locality] = loadTaskLocalities(config)
+
+ /** Finds where a task should belongs to */
+ def locateTask(taskId: TaskId): Locality = {
+ taskLocalities.getOrElse(taskId, NonLocality)
+ }
+
+ private def loadTaskLocalities(config: Config): Map[TaskId, Locality] = {
+ import org.apache.gearpump.streaming.Constants.GEARPUMP_STREAMING_LOCALITIES
+ Try(config.getConfig(s"$GEARPUMP_STREAMING_LOCALITIES.$appName")).map { appConfig =>
+ val json = appConfig.root().render(ConfigRenderOptions.concise)
+ Localities.fromJson(json)
+ }.map { localityConfig =>
+ import localityConfig.localities
+ localities.keySet.flatMap { workerId =>
+ val tasks = localities(workerId)
+ tasks.map((_, WorkerLocality(workerId)))
+ }.toArray.toMap
+ }.getOrElse(Map.empty[TaskId, Locality])
+ }
+}
+
+object TaskLocator {
+
+ trait Locality
+
+ /** Means we require the resource from the specific worker */
+ case class WorkerLocality(workerId: WorkerId) extends Locality
+
+ /** Means no preference on worker */
+ object NonLocality extends Locality
+
+ /** Localities settings. Mapping from workerId to list of taskId */
+ case class Localities(localities: Map[WorkerId, Array[TaskId]])
+
+ object Localities {
+ val pattern = "task_([0-9]+)_([0-9]+)".r
+
+ // To avoid polluting the classpath, we do the JSON translation ourself instead of
+ // introducing JSON library dependencies directly.
+ def fromJson(json: String): Localities = {
+ val localities = ConfigFactory.parseString(json).getAnyRef("localities")
+ .asInstanceOf[java.util.Map[String, String]].asScala.map { pair =>
+ val workerId: WorkerId = WorkerId.parse(pair._1)
+ val tasks = pair._2.split(",").map { task =>
+ val pattern(processorId, taskIndex) = task
+ TaskId(processorId.toInt, taskIndex.toInt)
+ }
+ (workerId, tasks)
+ }.toMap
+ new Localities(localities)
+ }
+
+ def toJson(localities: Localities): String = {
+ val map = localities.localities.toList.map { pair =>
+ (WorkerId.render(pair._1), pair._2.map(task =>
+ s"task_${task.processorId}_${task.index}").mkString(","))
+ }.toMap.asJava
+ ConfigFactory.empty().withValue("localities", ConfigValueFactory.fromAnyRef(map)).
+ root.render(ConfigRenderOptions.concise())
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/TaskManager.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/TaskManager.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/TaskManager.scala
new file mode 100644
index 0000000..662418c
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/TaskManager.scala
@@ -0,0 +1,496 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.appmaster
+
+import akka.actor._
+import akka.pattern.ask
+import org.apache.gearpump.TimeStamp
+import org.apache.gearpump.cluster.MasterToAppMaster.ReplayFromTimestampWindowTrailingEdge
+import org.apache.gearpump.streaming.AppMasterToExecutor._
+import org.apache.gearpump.streaming.ExecutorToAppMaster.{MessageLoss, RegisterTask, UnRegisterTask}
+import org.apache.gearpump.streaming._
+import org.apache.gearpump.streaming.appmaster.AppMaster.{AllocateResourceTimeOut, LookupTaskActorRef, TaskActorRef}
+import org.apache.gearpump.streaming.appmaster.ClockService.{ChangeToNewDAG, ChangeToNewDAGSuccess}
+import org.apache.gearpump.streaming.appmaster.DagManager.{GetLatestDAG, GetTaskLaunchData, LatestDAG, NewDAGDeployed, TaskLaunchData, WatchChange}
+import org.apache.gearpump.streaming.appmaster.ExecutorManager.{ExecutorStarted, StartExecutorsTimeOut, _}
+import org.apache.gearpump.streaming.appmaster.TaskManager._
+import org.apache.gearpump.streaming.appmaster.TaskRegistry.{Accept, TaskLocation}
+import org.apache.gearpump.streaming.executor.Executor.RestartTasks
+import org.apache.gearpump.streaming.executor.ExecutorRestartPolicy
+import org.apache.gearpump.streaming.task._
+import org.apache.gearpump.streaming.util.ActorPathUtil
+import org.apache.gearpump.util.{Constants, LogUtil}
+import org.slf4j.Logger
+
+import scala.concurrent.Future
+import scala.concurrent.duration._
+
+/**
+ *
+ * TaskManager track all tasks's status.
+ *
+ * It is state machine with three states:
+ * 1. applicationReady
+ * 2. recovery
+ * 3. dynamicDag
+ *
+ * When in state applicationReady:
+ * 1. When there is message-loss or JVM crash, transit to state recovery.
+ * 2. When user modify the DAG, transit to dynamicDag.
+ *
+ * When in state recovery:
+ * 1. When all tasks has been recovered, transit to applicationReady.
+ *
+ * When in state dynamicDag:
+ * 1. When dynamic dag transition is complete, transit to applicationReady.
+ * 2. When there is message loss or JVM crash, transit to state recovery.
+ */
+private[appmaster] class TaskManager(
+ appId: Int,
+ dagManager: ActorRef,
+ jarScheduler: JarScheduler,
+ executorManager: ActorRef,
+ clockService: ActorRef,
+ appMaster: ActorRef,
+ appName: String)
+ extends Actor {
+
+ private val LOG: Logger = LogUtil.getLogger(getClass, app = appId)
+ private val systemConfig = context.system.settings.config
+
+ private val ids = new SessionIdFactory()
+
+ private val executorRestartPolicy = new ExecutorRestartPolicy(maxNrOfRetries = 5,
+ withinTimeRange = 20.seconds)
+
+ private implicit val timeout = Constants.FUTURE_TIMEOUT
+ private implicit val actorSystem = context.system
+
+ import context.dispatcher
+
+ dagManager ! WatchChange(watcher = self)
+ executorManager ! SetTaskManager(self)
+
+ private def getStartClock: Future[TimeStamp] = {
+ (clockService ? GetStartClock).asInstanceOf[Future[StartClock]].map(_.clock)
+ }
+
+ private var startClock: Future[TimeStamp] = getStartClock
+
+ def receive: Receive = applicationReady(DagReadyState.empty)
+
+ private def onClientQuery(taskRegistry: TaskRegistry): Receive = {
+ case clock: ClockEvent =>
+ clockService forward clock
+ case GetTaskList =>
+ sender ! TaskList(taskRegistry.getTaskExecutorMap)
+ case LookupTaskActorRef(taskId) =>
+ val executorId = taskRegistry.getExecutorId(taskId)
+ val requestor = sender
+ executorId.map { executorId =>
+ val taskPath = ActorPathUtil.taskActorPath(appMaster, executorId, taskId)
+ context.actorSelection(taskPath).resolveOne(3.seconds).map { taskActorRef =>
+ requestor ! TaskActorRef(taskActorRef)
+ }
+ }
+ }
+
+ /**
+ * State applicationReady
+ */
+ def applicationReady(state: DagReadyState): Receive = {
+ executorManager ! state.taskRegistry.usedResource
+ dagManager ! NewDAGDeployed(state.dag.version)
+ dagManager ! GetLatestDAG
+ LOG.info(s"goto state ApplicationReady(dag = ${state.dag.version})...")
+
+ val recoverRegistry = new TaskRegistry(expectedTasks = state.dag.tasks,
+ deadTasks = state.taskRegistry.deadTasks)
+
+ val recoverState = new StartDagState(state.dag, recoverRegistry)
+
+ val onError: Receive = {
+ case executorStopped@ExecutorStopped(executorId) =>
+ if (state.taskRegistry.isTaskRegisteredForExecutor(executorId)) {
+ self ! executorStopped
+ context.become(recovery(recoverState))
+ }
+ case MessageLoss(executorId, taskId, cause) =>
+ if (state.taskRegistry.isTaskRegisteredForExecutor(executorId) &&
+ executorRestartPolicy.allowRestartExecutor(executorId)) {
+ context.become(recovery(recoverState))
+ } else {
+ val errorMsg = s"Task $taskId fails too many times to recover"
+ appMaster ! FailedToRecover(errorMsg)
+ }
+ case replay: ReplayFromTimestampWindowTrailingEdge =>
+ LOG.error(s"Received $replay")
+ context.become(recovery(recoverState))
+ }
+
+ val onNewDag: Receive = {
+ case LatestDAG(newDag) =>
+
+ if (newDag.version > state.dag.version) {
+
+ executorManager ! BroadCast(StartDynamicDag(newDag.version))
+ LOG.info("Broadcasting StartDynamicDag")
+
+ val dagDiff = migrate(state.dag, newDag)
+ jarScheduler.setDag(newDag, startClock)
+ val resourceRequestsDetails = jarScheduler.getResourceRequestDetails()
+ resourceRequestsDetails.map { details =>
+ details.foreach { detail =>
+ if (detail.requests.length > 0 && detail.requests.exists(!_.resource.isEmpty)) {
+ executorManager ! StartExecutors(detail.requests, detail.jar)
+ }
+ }
+ }
+
+ var modifiedTasks = List.empty[TaskId]
+ for (processorId <- dagDiff.modifiedProcessors ++ dagDiff.impactedUpstream) {
+ val executors = state.taskRegistry.processorExecutors(processorId)
+ executors.foreach { pair =>
+ val (executorId, tasks) = pair
+ modifiedTasks ++= tasks
+ dagManager ! GetTaskLaunchData(newDag.version, processorId,
+ ChangeTasksOnExecutor(executorId, tasks))
+ }
+ }
+
+ val taskChangeRegistry = new TaskChangeRegistry(modifiedTasks)
+
+ val deadTasks = state.taskRegistry.deadTasks
+ val registeredTasks = state.taskRegistry.registeredTasks
+ val dynamicTaskRegistry = new TaskRegistry(newDag.tasks, registeredTasks, deadTasks)
+
+ val nextState = new StartDagState(newDag, dynamicTaskRegistry, taskChangeRegistry)
+ context.become(dynamicDag(nextState, recoverState))
+ }
+ }
+
+ val onUnRegisterTask: Receive = {
+ case unRegister: UnRegisterTask =>
+
+ LOG.info(s"Received $unRegister, stop task ${unRegister.taskId}")
+ sender ! StopTask(unRegister.taskId)
+
+ val taskId = unRegister.taskId
+ val registry = state.taskRegistry
+ val deadTasks = registry.deadTasks
+
+ val newRegistry = registry.copy(registeredTasks = registry.registeredTasks - taskId,
+ deadTasks = deadTasks + taskId)
+
+ val newState = new DagReadyState(state.dag, newRegistry)
+ context.become(applicationReady(newState))
+ }
+
+ // Recovers to same version
+ onClientQuery(state.taskRegistry) orElse onError orElse onNewDag orElse
+ onUnRegisterTask orElse unHandled("applicationReady")
+ }
+
+ /**
+ * State dynamicDag
+ */
+ def dynamicDag(state: StartDagState, recoverState: StartDagState): Receive = {
+ LOG.info(s"DynamicDag transit to dag version: ${state.dag.version}...")
+
+ val onMessageLoss: Receive = {
+ case executorStopped@ExecutorStopped(executorId) =>
+ context.become(recovery(recoverState))
+ case MessageLoss(executorId, taskId, cause) =>
+ if (state.taskRegistry.isTaskRegisteredForExecutor(executorId) &&
+ executorRestartPolicy.allowRestartExecutor(executorId)) {
+ context.become(recovery(recoverState))
+ } else {
+ val errorMsg = s"Task $taskId fails too many times to recover"
+ appMaster ! FailedToRecover(errorMsg)
+ }
+ }
+
+ onMessageLoss orElse onClientQuery(state.taskRegistry) orElse
+ startDag(state, recoverState) orElse unHandled("dynamicDag")
+ }
+
+ private def startDag(state: StartDagState, recoverState: StartDagState): Receive = {
+ case executor: ExecutorStarted =>
+ import executor.{boundedJar, executorId, resource, workerId}
+ val taskIdsFuture = jarScheduler.scheduleTask(boundedJar.get, workerId, executorId, resource)
+ taskIdsFuture.foreach { taskIds =>
+ LOG.info(s"Executor $executor has been started, " +
+ s"start to schedule tasks: ${taskIds.mkString(",")}")
+ taskIds.groupBy(_.processorId).foreach { pair =>
+ val (processorId, tasks) = pair
+ dagManager ! GetTaskLaunchData(state.dag.version, processorId,
+ StartTasksOnExecutor(executor.executorId, tasks))
+ }
+ }
+
+ case StartExecutorsTimeOut =>
+ appMaster ! AllocateResourceTimeOut
+ case TaskLaunchData(processorDescription, subscribers, command) =>
+ command match {
+ case StartTasksOnExecutor(executorId, tasks) =>
+ LOG.info(s"Start tasks on Executor($executorId), tasks: " + tasks)
+ val launchTasks = LaunchTasks(tasks, state.dag.version, processorDescription, subscribers)
+ executorManager ! UniCast(executorId, launchTasks)
+ tasks.foreach(executorRestartPolicy.addTaskToExecutor(executorId, _))
+ case ChangeTasksOnExecutor(executorId, tasks) =>
+ LOG.info("change Task on executor: " + executorId + ", tasks: " + tasks)
+ val changeTasks = ChangeTasks(tasks, state.dag.version, processorDescription.life,
+ subscribers)
+ executorManager ! UniCast(executorId, changeTasks)
+ case other =>
+ LOG.error(s"severe error! we expect ExecutorStarted but get ${other.getClass.toString}")
+ }
+ case TasksLaunched =>
+ // We will track all launched task by message RegisterTask
+ case TasksChanged(tasks) =>
+ tasks.foreach(task => state.taskChangeRegistry.taskChanged(task))
+
+ if (allTasksReady(state)) {
+ broadcastLocations(state)
+ }
+
+ case RegisterTask(taskId, executorId, host) =>
+ val client = sender
+ val register = state.taskRegistry
+ val status = register.registerTask(taskId, TaskLocation(executorId, host))
+ if (status == Accept) {
+ LOG.info(s"RegisterTask($taskId) TaskLocation: $host, Executor: $executorId")
+ val sessionId = ids.newSessionId
+
+ startClock.foreach(clock => client ! TaskRegistered(taskId, sessionId, clock))
+ if (allTasksReady(state)) {
+ broadcastLocations(state)
+ }
+ } else {
+ sender ! TaskRejected(taskId)
+ }
+
+ case TaskChanged(taskId, dagVersion) =>
+ state.taskChangeRegistry.taskChanged(taskId)
+ if (allTasksReady(state)) {
+ broadcastLocations(state)
+ }
+ case locationReceived: TaskLocationsReceived =>
+ state.executorReadyRegistry.registerExecutor(locationReceived.executorId)
+ if (allTasksReady(state) &&
+ state.executorReadyRegistry.allRegistered(state.taskRegistry.executors)) {
+ LOG.info("All executors are ready to start...")
+ clockService ! ChangeToNewDAG(state.dag)
+ }
+ case locationRejected: TaskLocationsRejected =>
+ LOG.error(s"received $locationRejected, start to recover")
+ context.become(recovery(recoverState))
+
+ case ChangeToNewDAGSuccess(_) =>
+ if (allTasksReady(state) &&
+ state.executorReadyRegistry.allRegistered(state.taskRegistry.executors)) {
+ executorManager ! BroadCast(StartAllTasks(state.dag.version))
+ context.become(applicationReady(new DagReadyState(state.dag, state.taskRegistry)))
+ }
+ }
+
+ def onExecutorError: Receive = {
+ case ExecutorStopped(executorId) =>
+ if (executorRestartPolicy.allowRestartExecutor(executorId)) {
+ jarScheduler.executorFailed(executorId).foreach { resourceRequestDetail =>
+ if (resourceRequestDetail.isDefined) {
+ executorManager ! StartExecutors(resourceRequestDetail.get.requests,
+ resourceRequestDetail.get.jar)
+ }
+ }
+ } else {
+ val errorMsg = s"Executor restarted too many times to recover"
+ appMaster ! FailedToRecover(errorMsg)
+ }
+ }
+
+ private def allTasksReady(state: StartDagState): Boolean = {
+ import state.{taskChangeRegistry, taskRegistry}
+ taskRegistry.isAllTasksRegistered && taskChangeRegistry.allTaskChanged
+ }
+
+ private def broadcastLocations(state: StartDagState): Unit = {
+ LOG.info(s"All tasks have been launched; send Task locations to all executors")
+ val taskLocations = state.taskRegistry.getTaskLocations
+ executorManager ! BroadCast(TaskLocationsReady(taskLocations, state.dag.version))
+ }
+
+ /**
+ * State recovery
+ */
+ def recovery(state: StartDagState): Receive = {
+ val recoverDagVersion = state.dag.version
+ executorManager ! BroadCast(RestartTasks(recoverDagVersion))
+
+ // Use new Start Clock so that we recover at timepoint we fails.
+ startClock = getStartClock
+
+ jarScheduler.setDag(state.dag, startClock)
+
+ LOG.info(s"goto state Recovery(recoverDag = $recoverDagVersion)...")
+ val ignoreClock: Receive = {
+ case clock: ClockEvent =>
+ // Ignores clock events.
+ }
+
+ if (state.dag.isEmpty) {
+ applicationReady(new DagReadyState(state.dag, state.taskRegistry))
+ } else {
+ val registry = new TaskRegistry(expectedTasks = state.dag.tasks,
+ deadTasks = state.taskRegistry.deadTasks)
+
+ val recoverState = new StartDagState(state.dag, registry)
+ ignoreClock orElse startDag(state, recoverState) orElse onExecutorError orElse
+ unHandled("recovery")
+ }
+ }
+
+ private def unHandled(state: String): Receive = {
+ case other =>
+ LOG.info(s"Received unknown message $other in state $state")
+ }
+}
+
+private[appmaster] object TaskManager {
+
+ /**
+ * When application is ready, then transit to DagReadyState
+ */
+ class DagReadyState(val dag: DAG, val taskRegistry: TaskRegistry)
+
+ object DagReadyState {
+ def empty: DagReadyState = {
+ new DagReadyState(
+ DAG.empty.copy(version = -1),
+ new TaskRegistry(List.empty[TaskId]))
+ }
+ }
+
+ /**
+ * When application is booting up or doing recovery, it use StartDagState
+ */
+ class StartDagState(
+ val dag: DAG,
+ val taskRegistry: TaskRegistry,
+ val taskChangeRegistry: TaskChangeRegistry = new TaskChangeRegistry(List.empty[TaskId]),
+ val executorReadyRegistry: ExecutorRegistry = new ExecutorRegistry)
+
+ case object GetTaskList
+
+ case class TaskList(tasks: Map[TaskId, ExecutorId])
+
+ case class FailedToRecover(errorMsg: String)
+
+ /**
+ * Starts new Tasks on Executor executorId
+ */
+ case class StartTasksOnExecutor(executorId: Int, tasks: List[TaskId])
+
+ /**
+ * Changes existing tasks on executor executorId
+ */
+ case class ChangeTasksOnExecutor(executorId: Int, tasks: List[TaskId])
+
+ /**
+ * Tracks the registration of all new started executors.
+ */
+ class ExecutorRegistry {
+ private var registeredExecutors = Set.empty[ExecutorId]
+
+ def registerExecutor(executorId: ExecutorId): Unit = {
+ registeredExecutors += executorId
+ }
+
+ def allRegistered(all: List[ExecutorId]): Boolean = {
+ all.forall(executor => registeredExecutors.contains(executor))
+ }
+ }
+
+ /**
+ * Tracks the registration of all changed tasks.
+ */
+ class TaskChangeRegistry(targetTasks: List[TaskId]) {
+ private var registeredTasks = Set.empty[TaskId]
+ def taskChanged(taskId: TaskId): Unit = {
+ registeredTasks += taskId
+ }
+ def allTaskChanged: Boolean = {
+ targetTasks.forall(taskId => registeredTasks.contains(taskId))
+ }
+ }
+
+ object TaskChangeRegistry {
+ def empty: TaskChangeRegistry = new TaskChangeRegistry(List.empty[TaskId])
+ }
+
+ /**
+ * DAGDiff is used to track impacted processors when doing dynamic dag.
+ */
+ case class DAGDiff(
+ addedProcessors: List[ProcessorId],
+ modifiedProcessors: List[ProcessorId],
+ impactedUpstream: List[ProcessorId])
+
+ /**
+ * Migrates from old DAG to new DAG, return DAGDiff
+ */
+ def migrate(leftDAG: DAG, rightDAG: DAG): DAGDiff = {
+ val left = leftDAG.processors.keySet
+ val right = rightDAG.processors.keySet
+
+ val added = right -- left
+ val join = right -- added
+
+ val modified = join.filter { processorId =>
+ leftDAG.processors(processorId) != rightDAG.processors(processorId)
+ }
+
+ val upstream = (list: Set[ProcessorId]) => {
+ list.flatMap { processorId =>
+ rightDAG.graph.incomingEdgesOf(processorId).map(_._1).toSet
+ } -- list
+ }
+
+ val impactedUpstream = upstream(added ++ modified)
+
+ // All upstream tasks are affected, and should be handled properly.
+ DAGDiff(added.toList, modified.toList, impactedUpstream.toList)
+ }
+
+ /**
+ * Each new task will be assigned with a unique session Id.
+ */
+ class SessionIdFactory {
+ private var nextSessionId = 1
+
+ /**
+ * Returns a new session Id for new task
+ */
+ final def newSessionId: Int = {
+ val sessionId = nextSessionId
+ nextSessionId += 1
+ sessionId
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/TaskRegistry.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/TaskRegistry.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/TaskRegistry.scala
new file mode 100644
index 0000000..b910d57
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/TaskRegistry.scala
@@ -0,0 +1,142 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.appmaster
+
+import org.apache.gearpump.cluster.scheduler.Resource
+import org.apache.gearpump.streaming.appmaster.ExecutorManager.ExecutorResourceUsageSummary
+import org.apache.gearpump.streaming.appmaster.TaskRegistry._
+import org.apache.gearpump.streaming.task.TaskId
+import org.apache.gearpump.streaming.{ExecutorId, ProcessorId}
+import org.apache.gearpump.transport.HostPort
+import org.apache.gearpump.util.LogUtil
+import org.slf4j.Logger
+
+/**
+ * Tracks the registration of all tasks, when the application is booting up.
+ */
+class TaskRegistry(val expectedTasks: List[TaskId],
+ var registeredTasks: Map[TaskId, TaskLocation] = Map.empty[TaskId, TaskLocation],
+ var deadTasks: Set[TaskId] = Set.empty[TaskId]) {
+
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+
+ private val processors = expectedTasks.map(_.processorId).toSet
+
+ /**
+ * When a task is booted, it need to call registerTask to register itself.
+ * If this task is valid, then accept it, otherwise reject it.
+ *
+ * @param taskId Task that register itself to TaskRegistry.
+ * @param location The host and port where this task is running on. NOTE: The host and port
+ * is NOT the same host and port of Akka remoting. Instead, it is host and port
+ * of custom netty layer, see [[org.apache.gearpump.transport.netty.Context]].
+ */
+ def registerTask(taskId: TaskId, location: TaskLocation): RegisterTaskStatus = {
+ val processorId = taskId.processorId
+
+ if (processors.contains(processorId)) {
+ registeredTasks += taskId -> location
+ Accept
+ } else {
+ LOG.error(s" the task is not accepted for registration, taskId: ${taskId}")
+ Reject
+ }
+ }
+
+ def copy(expectedTasks: List[TaskId] = this.expectedTasks,
+ registeredTasks: Map[TaskId, TaskLocation] = this.registeredTasks,
+ deadTasks: Set[TaskId] = this.deadTasks): TaskRegistry = {
+ new TaskRegistry(expectedTasks, registeredTasks, deadTasks)
+ }
+
+ def getTaskLocations: TaskLocations = {
+ val taskLocations = registeredTasks.toList.groupBy(_._2.host).map { pair =>
+ val (k, v) = pair
+ val taskIds = v.map(_._1)
+ (k, taskIds.toSet)
+ }
+ TaskLocations(taskLocations)
+ }
+
+ def getTaskExecutorMap: Map[TaskId, ExecutorId] = {
+ getTaskLocations.locations.flatMap { pair =>
+ val (hostPort, taskSet) = pair
+ taskSet.map { taskId =>
+ (taskId, getExecutorId(taskId).getOrElse(-1))
+ }
+ }
+ }
+
+ /** Query the executor Id where the task is running on */
+ def getExecutorId(taskId: TaskId): Option[Int] = {
+ registeredTasks.get(taskId).map(_.executorId)
+ }
+
+ /** Gets list of allocated executor Ids */
+ def executors: List[ExecutorId] = {
+ registeredTasks.toList.map(_._2.executorId)
+ }
+
+ def isAllTasksRegistered: Boolean = {
+ val aliveTasks = (expectedTasks.toSet -- deadTasks)
+ aliveTasks.forall(task => registeredTasks.contains(task))
+ }
+
+ def isTaskRegisteredForExecutor(executorId: ExecutorId): Boolean = {
+ registeredTasks.exists(_._2.executorId == executorId)
+ }
+
+ private def filterTasks(processorId: ProcessorId): List[TaskId] = {
+ registeredTasks.keys.toList.filter(_.processorId == processorId)
+ }
+
+ /** List of executors that current processor taks are running on */
+ def processorExecutors(processorId: ProcessorId): Map[ExecutorId, List[TaskId]] = {
+ val taskToExecutor = filterTasks(processorId).flatMap { taskId =>
+ getExecutorId(taskId).map { executorId =>
+ (taskId, executorId)
+ }
+ }
+
+ val executorToTasks = taskToExecutor.groupBy(_._2).map { kv =>
+ val (k, v) = kv
+ (k, v.map(_._1))
+ }
+ executorToTasks
+ }
+
+ /** Summary about how many resources are used for all running tasks */
+ def usedResource: ExecutorResourceUsageSummary = {
+ val resourceMap = registeredTasks.foldLeft(Map.empty[ExecutorId, Resource]) { (map, task) =>
+ val resource = map.getOrElse(task._2.executorId, Resource(0)) + Resource(1)
+ map + (task._2.executorId -> resource)
+ }
+ ExecutorResourceUsageSummary(resourceMap)
+ }
+}
+
+object TaskRegistry {
+ sealed trait RegisterTaskStatus
+ case object Accept extends RegisterTaskStatus
+ case object Reject extends RegisterTaskStatus
+
+ case class TaskLocation(executorId: Int, host: HostPort)
+
+ case class TaskLocations(locations: Map[HostPort, Set[TaskId]])
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/TaskSchedulerImpl.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/TaskSchedulerImpl.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/TaskSchedulerImpl.scala
new file mode 100644
index 0000000..df4490c
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/TaskSchedulerImpl.scala
@@ -0,0 +1,177 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.appmaster
+
+import com.typesafe.config.Config
+import org.apache.gearpump.cluster.scheduler.{Resource, ResourceRequest}
+import org.apache.gearpump.cluster.worker.WorkerId
+import org.apache.gearpump.streaming.DAG
+import org.apache.gearpump.streaming.appmaster.TaskLocator.{Locality, WorkerLocality}
+import org.apache.gearpump.streaming.appmaster.TaskScheduler.{Location, TaskStatus}
+import org.apache.gearpump.streaming.task.TaskId
+import org.apache.gearpump.util.Constants
+
+/**
+ * Schedules tasks to run for new allocated resources. TaskScheduler only schedule tasks that
+ * share the same jar. For scheduling for multiple jars, see
+ * [[org.apache.gearpump.streaming.appmaster.JarScheduler]].
+ */
+trait TaskScheduler {
+
+ /**
+ * This notify the scheduler that the task DAG is created.
+ * @param dag task dag
+ */
+ def setDAG(dag: DAG): Unit
+
+ /**
+ * Get the resource requirements for all unscheduled tasks.
+ */
+ def getResourceRequests(): Array[ResourceRequest]
+
+ /**
+ * This notifies the scheduler that a resource slot on {workerId} and {executorId} is allocated
+ * , and expect a task to be scheduled in return.
+ * Task locality should be considered when deciding whether to offer a task on target {worker}
+ * and {executor}
+ *
+ * @param workerId which worker this resource is located.
+ * @param executorId which executorId this resource belongs to.
+ * @return a list of tasks
+ */
+ def schedule(workerId: WorkerId, executorId: Int, resource: Resource): List[TaskId]
+
+ /**
+ * This notifies the scheduler that {executorId} is failed, and expect a set of
+ * ResourceRequest for all failed tasks on that executor.
+ *
+ * @param executorId executor that failed
+ * @return resource requests of the failed executor
+ */
+ def executorFailed(executorId: Int): Array[ResourceRequest]
+
+ /**
+ * Queries the task list that already scheduled on the executor
+ *
+ * @param executorId executor to query
+ * @return a list of tasks
+ */
+ def scheduledTasks(executorId: Int): List[TaskId]
+}
+
+object TaskScheduler {
+ case class Location(workerId: WorkerId, executorId: Int)
+
+ class TaskStatus(val taskId: TaskId, val preferLocality: Locality, var allocation: Location)
+}
+
+class TaskSchedulerImpl(appId: Int, appName: String, config: Config) extends TaskScheduler {
+ private val executorNum = config.getInt(Constants.APPLICATION_EXECUTOR_NUMBER)
+
+ private var tasks = List.empty[TaskStatus]
+
+ // Finds the locality of the tasks
+ private val taskLocator = new TaskLocator(appName, config)
+
+ override def setDAG(dag: DAG): Unit = {
+ val taskMap = tasks.map(_.taskId).zip(tasks).toMap
+
+ tasks = dag.tasks.sortBy(_.index).map { taskId =>
+ val locality = taskLocator.locateTask(taskId)
+ taskMap.getOrElse(taskId, new TaskStatus(taskId, locality, allocation = null))
+ }
+ }
+
+ def getResourceRequests(): Array[ResourceRequest] = {
+ fetchResourceRequests(fromOneWorker = false)
+ }
+
+ import org.apache.gearpump.cluster.scheduler.Relaxation._
+ private def fetchResourceRequests(fromOneWorker: Boolean = false): Array[ResourceRequest] = {
+ var workersResourceRequest = Map.empty[WorkerId, Resource]
+
+ tasks.filter(_.allocation == null).foreach { task =>
+ task.preferLocality match {
+ case WorkerLocality(workerId) =>
+ val current = workersResourceRequest.getOrElse(workerId, Resource.empty)
+ workersResourceRequest += workerId -> (current + Resource(1))
+ case _ =>
+ val workerId = WorkerId.unspecified
+ val current = workersResourceRequest.getOrElse(workerId, Resource.empty)
+ workersResourceRequest += workerId -> (current + Resource(1))
+ }
+ }
+
+ workersResourceRequest.map { workerIdAndResource =>
+ val (workerId, resource) = workerIdAndResource
+ if (workerId == WorkerId.unspecified) {
+ ResourceRequest(resource, workerId = WorkerId.unspecified, executorNum = executorNum)
+ } else {
+ ResourceRequest(resource, workerId, relaxation = SPECIFICWORKER)
+ }
+ }.toArray
+ }
+
+ override def schedule(workerId: WorkerId, executorId: Int, resource: Resource): List[TaskId] = {
+ var scheduledTasks = List.empty[TaskId]
+ val location = Location(workerId, executorId)
+ // Schedules tasks for specific worker
+ scheduledTasks ++= scheduleTasksForLocality(resource, location,
+ (locality) => locality == WorkerLocality(workerId))
+
+ // Schedules tasks without specific location preference
+ scheduledTasks ++= scheduleTasksForLocality(resource - Resource(scheduledTasks.length),
+ location, (locality) => true)
+ scheduledTasks
+ }
+
+ private def scheduleTasksForLocality(
+ resource: Resource, resourceLocation: Location, matcher: (Locality) => Boolean)
+ : List[TaskId] = {
+ var scheduledTasks = List.empty[TaskId]
+ var index = 0
+ var remain = resource.slots
+ while (index < tasks.length && remain > 0) {
+ val taskStatus = tasks(index)
+ if (taskStatus.allocation == null && matcher(taskStatus.preferLocality)) {
+ taskStatus.allocation = resourceLocation
+ scheduledTasks +:= taskStatus.taskId
+ remain -= 1
+ }
+ index += 1
+ }
+ scheduledTasks
+ }
+
+ override def executorFailed(executorId: Int): Array[ResourceRequest] = {
+ val failedTasks = tasks.filter { status =>
+ status.allocation != null && status.allocation.executorId == executorId
+ }
+ // Cleans the location of failed tasks
+ failedTasks.foreach(_.allocation = null)
+
+ Array(ResourceRequest(Resource(failedTasks.length),
+ workerId = WorkerId.unspecified, relaxation = ONEWORKER))
+ }
+
+ override def scheduledTasks(executorId: Int): List[TaskId] = {
+ tasks.filter { status =>
+ status.allocation != null && status.allocation.executorId == executorId
+ }.map(_.taskId)
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/dsl/Stream.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/dsl/Stream.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/dsl/Stream.scala
new file mode 100644
index 0000000..5ca92dd
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/dsl/Stream.scala
@@ -0,0 +1,229 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.dsl
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.dsl.op._
+import org.apache.gearpump.streaming.sink.DataSink
+import org.apache.gearpump.streaming.task.{Task, TaskContext}
+import org.apache.gearpump.util.Graph
+import org.slf4j.{Logger, LoggerFactory}
+
+import scala.language.implicitConversions
+
+class Stream[T](
+ private val graph: Graph[Op, OpEdge], private val thisNode: Op,
+ private val edge: Option[OpEdge] = None) {
+
+ /**
+ * converts a value[T] to a list of value[R]
+ *
+ * @param fun FlatMap function
+ * @param description The description message for this operation
+ * @return A new stream with type [R]
+ */
+ def flatMap[R](fun: T => TraversableOnce[R], description: String = null): Stream[R] = {
+ val flatMapOp = FlatMapOp(fun, Option(description).getOrElse("flatmap"))
+ graph.addVertex(flatMapOp)
+ graph.addEdge(thisNode, edge.getOrElse(Direct), flatMapOp)
+ new Stream[R](graph, flatMapOp)
+ }
+
+ /**
+ * Maps message of type T message of type R
+ *
+ * @param fun Function
+ * @return A new stream with type [R]
+ */
+ def map[R](fun: T => R, description: String = null): Stream[R] = {
+ this.flatMap({ data =>
+ Option(fun(data))
+ }, Option(description).getOrElse("map"))
+ }
+
+ /**
+ * Keeps records when fun(T) == true
+ *
+ * @param fun the filter
+ * @return a new stream after filter
+ */
+ def filter(fun: T => Boolean, description: String = null): Stream[T] = {
+ this.flatMap({ data =>
+ if (fun(data)) Option(data) else None
+ }, Option(description).getOrElse("filter"))
+ }
+
+ /**
+ * Reduces operations.
+ *
+ * @param fun reduction function
+ * @param description description message for this operator
+ * @return a new stream after reduction
+ */
+ def reduce(fun: (T, T) => T, description: String = null): Stream[T] = {
+ val reduceOp = ReduceOp(fun, Option(description).getOrElse("reduce"))
+ graph.addVertex(reduceOp)
+ graph.addEdge(thisNode, edge.getOrElse(Direct), reduceOp)
+ new Stream(graph, reduceOp)
+ }
+
+ /**
+ * Log to task log file
+ */
+ def log(): Unit = {
+ this.map(msg => LoggerFactory.getLogger("dsl").info(msg.toString), "log")
+ }
+
+ /**
+ * Merges data from two stream into one
+ *
+ * @param other the other stream
+ * @return the merged stream
+ */
+ def merge(other: Stream[T], description: String = null): Stream[T] = {
+ val mergeOp = MergeOp(Option(description).getOrElse("merge"))
+ graph.addVertex(mergeOp)
+ graph.addEdge(thisNode, edge.getOrElse(Direct), mergeOp)
+ graph.addEdge(other.thisNode, other.edge.getOrElse(Shuffle), mergeOp)
+ new Stream[T](graph, mergeOp)
+ }
+
+ /**
+ * Group by function (T => Group)
+ *
+ * For example, we have T type, People(name: String, gender: String, age: Int)
+ * groupBy[People](_.gender) will group the people by gender.
+ *
+ * You can append other combinators after groupBy
+ *
+ * For example,
+ * {{{
+ * Stream[People].groupBy(_.gender).flatmap(..).filter.(..).reduce(..)
+ * }}}
+ *
+ * @param fun Group by function
+ * @param parallelism Parallelism level
+ * @param description The description
+ * @return the grouped stream
+ */
+ def groupBy[Group](fun: T => Group, parallelism: Int = 1, description: String = null)
+ : Stream[T] = {
+ val groupOp = GroupByOp(fun, parallelism, Option(description).getOrElse("groupBy"))
+ graph.addVertex(groupOp)
+ graph.addEdge(thisNode, edge.getOrElse(Shuffle), groupOp)
+ new Stream[T](graph, groupOp)
+ }
+
+ /**
+ * Connects with a low level Processor(TaskDescription)
+ *
+ * @param processor a user defined processor
+ * @param parallelism parallelism level
+ * @return new stream after processing with type [R]
+ */
+ def process[R](
+ processor: Class[_ <: Task], parallelism: Int, conf: UserConfig = UserConfig.empty,
+ description: String = null): Stream[R] = {
+ val processorOp = ProcessorOp(processor, parallelism, conf,
+ Option(description).getOrElse("process"))
+ graph.addVertex(processorOp)
+ graph.addEdge(thisNode, edge.getOrElse(Shuffle), processorOp)
+ new Stream[R](graph, processorOp, Some(Shuffle))
+ }
+}
+
+class KVStream[K, V](stream: Stream[Tuple2[K, V]]) {
+ /**
+ * GroupBy key
+ *
+ * Applies to Stream[Tuple2[K,V]]
+ *
+ * @param parallelism the parallelism for this operation
+ * @return the new KV stream
+ */
+ def groupByKey(parallelism: Int = 1): Stream[Tuple2[K, V]] = {
+ stream.groupBy(Stream.getTupleKey[K, V], parallelism, "groupByKey")
+ }
+
+ /**
+ * Sum the value of the tuples
+ *
+ * Apply to Stream[Tuple2[K,V]], V must be of type Number
+ *
+ * For input (key, value1), (key, value2), will generate (key, value1 + value2)
+ * @param numeric the numeric operations
+ * @return the sum stream
+ */
+ def sum(implicit numeric: Numeric[V]): Stream[(K, V)] = {
+ stream.reduce(Stream.sumByValue[K, V](numeric), "sum")
+ }
+}
+
+object Stream {
+
+ def apply[T](graph: Graph[Op, OpEdge], node: Op, edge: Option[OpEdge]): Stream[T] = {
+ new Stream[T](graph, node, edge)
+ }
+
+ def getTupleKey[K, V](tuple: Tuple2[K, V]): K = tuple._1
+
+ def sumByValue[K, V](numeric: Numeric[V]): (Tuple2[K, V], Tuple2[K, V]) => Tuple2[K, V]
+ = (tuple1, tuple2) => Tuple2(tuple1._1, numeric.plus(tuple1._2, tuple2._2))
+
+ implicit def streamToKVStream[K, V](stream: Stream[Tuple2[K, V]]): KVStream[K, V] = {
+ new KVStream(stream)
+ }
+
+ implicit class Sink[T](stream: Stream[T]) extends java.io.Serializable {
+ def sink[T](dataSink: DataSink, parallism: Int, conf: UserConfig, description: String)
+ : Stream[T] = {
+ implicit val sink = DataSinkOp[T](dataSink, parallism, conf,
+ Some(description).getOrElse("traversable"))
+ stream.graph.addVertex(sink)
+ stream.graph.addEdge(stream.thisNode, Shuffle, sink)
+ new Stream[T](stream.graph, sink)
+ }
+
+ def sink[T](
+ sink: Class[_ <: Task], parallism: Int, conf: UserConfig = UserConfig.empty,
+ description: String = null): Stream[T] = {
+ val sinkOp = ProcessorOp(sink, parallism, conf, Option(description).getOrElse("source"))
+ stream.graph.addVertex(sinkOp)
+ stream.graph.addEdge(stream.thisNode, Shuffle, sinkOp)
+ new Stream[T](stream.graph, sinkOp)
+ }
+ }
+}
+
+class LoggerSink[T] extends DataSink {
+ var logger: Logger = null
+
+ private var context: TaskContext = null
+
+ override def open(context: TaskContext): Unit = {
+ this.logger = context.logger
+ }
+
+ override def write(message: Message): Unit = {
+ logger.info("logging message " + message.msg)
+ }
+
+ override def close(): Unit = Unit
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/dsl/StreamApp.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/dsl/StreamApp.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/dsl/StreamApp.scala
new file mode 100644
index 0000000..5027500
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/dsl/StreamApp.scala
@@ -0,0 +1,123 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.dsl
+
+import akka.actor.ActorSystem
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.cluster.client.ClientContext
+import org.apache.gearpump.streaming.StreamApplication
+import org.apache.gearpump.streaming.dsl.op.{DataSourceOp, Op, OpEdge, ProcessorOp}
+import org.apache.gearpump.streaming.dsl.plan.Planner
+import org.apache.gearpump.streaming.source.DataSource
+import org.apache.gearpump.streaming.task.{Task, TaskContext}
+import org.apache.gearpump.util.Graph
+import org.apache.gearpump.{Message, TimeStamp}
+
+import scala.language.implicitConversions
+
+/**
+ * Example:
+ * {{{
+ * val data = "This is a good start, bingo!! bingo!!"
+ * app.fromCollection(data.lines.toList).
+ * // word => (word, count)
+ * flatMap(line => line.split("[\\s]+")).map((_, 1)).
+ * // (word, count1), (word, count2) => (word, count1 + count2)
+ * groupBy(kv => kv._1).reduce(sum(_, _))
+ *
+ * val appId = context.submit(app)
+ * context.close()
+ * }}}
+ *
+ * @param name name of app
+ */
+class StreamApp(
+ val name: String, system: ActorSystem, userConfig: UserConfig, val graph: Graph[Op, OpEdge]) {
+
+ def this(name: String, system: ActorSystem, userConfig: UserConfig) = {
+ this(name, system, userConfig, Graph.empty[Op, OpEdge])
+ }
+
+ def plan(): StreamApplication = {
+ implicit val actorSystem = system
+ val planner = new Planner
+ val dag = planner.plan(graph)
+ StreamApplication(name, dag, userConfig)
+ }
+}
+
+object StreamApp {
+ def apply(name: String, context: ClientContext, userConfig: UserConfig = UserConfig.empty)
+ : StreamApp = {
+ new StreamApp(name, context.system, userConfig)
+ }
+
+ implicit def streamAppToApplication(streamApp: StreamApp): StreamApplication = {
+ streamApp.plan
+ }
+
+ implicit class Source(app: StreamApp) extends java.io.Serializable {
+
+ def source[T](dataSource: DataSource, parallism: Int): Stream[T] = {
+ source(dataSource, parallism, UserConfig.empty)
+ }
+
+ def source[T](dataSource: DataSource, parallism: Int, description: String): Stream[T] = {
+ source(dataSource, parallism, UserConfig.empty, description)
+ }
+
+ def source[T](dataSource: DataSource, parallism: Int, conf: UserConfig): Stream[T] = {
+ source(dataSource, parallism, conf, description = null)
+ }
+
+ def source[T](dataSource: DataSource, parallism: Int, conf: UserConfig, description: String)
+ : Stream[T] = {
+ implicit val sourceOp = DataSourceOp(dataSource, parallism, conf, description)
+ app.graph.addVertex(sourceOp)
+ new Stream[T](app.graph, sourceOp)
+ }
+ def source[T](seq: Seq[T], parallism: Int, description: String): Stream[T] = {
+ this.source(new CollectionDataSource[T](seq), parallism, UserConfig.empty, description)
+ }
+
+ def source[T](source: Class[_ <: Task], parallism: Int, conf: UserConfig, description: String)
+ : Stream[T] = {
+ val sourceOp = ProcessorOp(source, parallism, conf, Option(description).getOrElse("source"))
+ app.graph.addVertex(sourceOp)
+ new Stream[T](app.graph, sourceOp)
+ }
+ }
+}
+
+/** A test message source which generated message sequence repeatedly. */
+class CollectionDataSource[T](seq: Seq[T]) extends DataSource {
+ private lazy val iterator: Iterator[T] = seq.iterator
+
+ override def read(): Message = {
+ if (iterator.hasNext) {
+ Message(iterator.next())
+ } else {
+ null
+ }
+ }
+
+ override def close(): Unit = {}
+
+ override def open(context: TaskContext, startTime: TimeStamp): Unit = {}
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/dsl/javaapi/JavaStream.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/dsl/javaapi/JavaStream.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/dsl/javaapi/JavaStream.scala
new file mode 100644
index 0000000..6eff20c
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/dsl/javaapi/JavaStream.scala
@@ -0,0 +1,77 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.dsl.javaapi
+
+import scala.collection.JavaConverters._
+
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.dsl.Stream
+import org.apache.gearpump.streaming.javaapi.dsl.functions._
+import org.apache.gearpump.streaming.task.Task
+
+/**
+ * Java DSL
+ */
+class JavaStream[T](val stream: Stream[T]) {
+
+ /** FlatMap on stream */
+ def flatMap[R](fn: FlatMapFunction[T, R], description: String): JavaStream[R] = {
+ new JavaStream[R](stream.flatMap({ t: T => fn(t).asScala }, description))
+ }
+
+ /** Map on stream */
+ def map[R](fn: MapFunction[T, R], description: String): JavaStream[R] = {
+ new JavaStream[R](stream.map({ t: T => fn(t) }, description))
+ }
+
+ /** Only keep the messages that FilterFunction returns true. */
+ def filter(fn: FilterFunction[T], description: String): JavaStream[T] = {
+ new JavaStream[T](stream.filter({ t: T => fn(t) }, description))
+ }
+
+ /** Does aggregation on the stream */
+ def reduce(fn: ReduceFunction[T], description: String): JavaStream[T] = {
+ new JavaStream[T](stream.reduce({ (t1: T, t2: T) => fn(t1, t2) }, description))
+ }
+
+ def log(): Unit = {
+ stream.log()
+ }
+
+ /** Merges streams of same type together */
+ def merge(other: JavaStream[T], description: String): JavaStream[T] = {
+ new JavaStream[T](stream.merge(other.stream, description))
+ }
+
+ /**
+ * Group by a stream and turns it to a list of sub-streams. Operations chained after
+ * groupBy applies to sub-streams.
+ */
+ def groupBy[Group](fn: GroupByFunction[T, Group], parallelism: Int, description: String)
+ : JavaStream[T] = {
+ new JavaStream[T](stream.groupBy({t: T => fn(t)}, parallelism, description))
+ }
+
+ /** Add a low level Processor to process messages */
+ def process[R](
+ processor: Class[_ <: Task], parallelism: Int, conf: UserConfig, description: String)
+ : JavaStream[R] = {
+ new JavaStream[R](stream.process(processor, parallelism, conf, description))
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/dsl/javaapi/JavaStreamApp.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/dsl/javaapi/JavaStreamApp.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/dsl/javaapi/JavaStreamApp.scala
new file mode 100644
index 0000000..0d841be
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/dsl/javaapi/JavaStreamApp.scala
@@ -0,0 +1,47 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.dsl.javaapi
+
+import java.util.Collection
+import scala.collection.JavaConverters._
+
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.cluster.client.ClientContext
+import org.apache.gearpump.streaming.dsl.{CollectionDataSource, StreamApp}
+import org.apache.gearpump.streaming.source.DataSource
+
+class JavaStreamApp(name: String, context: ClientContext, userConfig: UserConfig) {
+
+ private val streamApp = StreamApp(name, context, userConfig)
+
+ def source[T](collection: Collection[T], parallelism: Int,
+ conf: UserConfig, description: String): JavaStream[T] = {
+ val dataSource = new CollectionDataSource(collection.asScala.toSeq)
+ source(dataSource, parallelism, conf, description)
+ }
+
+ def source[T](dataSource: DataSource, parallelism: Int,
+ conf: UserConfig, description: String): JavaStream[T] = {
+ new JavaStream[T](streamApp.source(dataSource, parallelism, conf, description))
+ }
+
+ def run(): Unit = {
+ context.submit(streamApp)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/dsl/op/OP.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/dsl/op/OP.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/dsl/op/OP.scala
new file mode 100644
index 0000000..49d9dec
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/dsl/op/OP.scala
@@ -0,0 +1,109 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.dsl.op
+
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.sink.DataSink
+import org.apache.gearpump.streaming.source.DataSource
+import org.apache.gearpump.streaming.task.Task
+
+/**
+ * Operators for the DSL
+ */
+sealed trait Op {
+ def description: String
+ def conf: UserConfig
+}
+
+/**
+ * When translated to running DAG, SlaveOP can be attach to MasterOP or other SlaveOP
+ * "Attach" means running in same Actor.
+ */
+trait SlaveOp[T] extends Op
+
+case class FlatMapOp[T, R](
+ fun: (T) => TraversableOnce[R], description: String, conf: UserConfig = UserConfig.empty)
+ extends SlaveOp[T]
+
+case class ReduceOp[T](fun: (T, T) => T, description: String, conf: UserConfig = UserConfig.empty)
+ extends SlaveOp[T]
+
+trait MasterOp extends Op
+
+trait ParameterizedOp[T] extends MasterOp
+
+case class MergeOp(description: String, override val conf: UserConfig = UserConfig.empty)
+ extends MasterOp
+
+case class GroupByOp[T, R](
+ fun: T => R, parallelism: Int, description: String,
+ override val conf: UserConfig = UserConfig.empty)
+ extends ParameterizedOp[T]
+
+case class ProcessorOp[T <: Task](
+ processor: Class[T], parallelism: Int, conf: UserConfig, description: String)
+ extends ParameterizedOp[T]
+
+case class DataSourceOp[T](
+ dataSource: DataSource, parallelism: Int, conf: UserConfig, description: String)
+ extends ParameterizedOp[T]
+
+case class DataSinkOp[T](
+ dataSink: DataSink, parallelism: Int, conf: UserConfig, description: String)
+ extends ParameterizedOp[T]
+
+/**
+ * Contains operators which can be chained to single one.
+ *
+ * For example, flatmap().map().reduce() can be chained to single operator as
+ * no data shuffling is required.
+ * @param ops list of operations
+ */
+case class OpChain(ops: List[Op]) extends Op {
+ def head: Op = ops.head
+ def last: Op = ops.last
+
+ def description: String = null
+
+ override def conf: UserConfig = {
+ // The head's conf has priority
+ ops.reverse.foldLeft(UserConfig.empty) { (conf, op) =>
+ conf.withConfig(op.conf)
+ }
+ }
+}
+
+trait OpEdge
+
+/**
+ * The upstream OP and downstream OP doesn't require network data shuffle.
+ *
+ * For example, map, flatmap operation doesn't require network shuffle, we can use Direct
+ * to represent the relation with upstream operators.
+ */
+case object Direct extends OpEdge
+
+/**
+ * The upstream OP and downstream OP DOES require network data shuffle.
+ *
+ * For example, map, flatmap operation doesn't require network shuffle, we can use Direct
+ * to represent the relation with upstream operators.
+ */
+case object Shuffle extends OpEdge
+
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/dsl/partitioner/GroupbyPartitioner.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/dsl/partitioner/GroupbyPartitioner.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/dsl/partitioner/GroupbyPartitioner.scala
new file mode 100644
index 0000000..b2e2932
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/dsl/partitioner/GroupbyPartitioner.scala
@@ -0,0 +1,46 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.dsl.partitioner
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.partitioner.UnicastPartitioner
+
+/**
+ * Partition messages by applying group by function first.
+ *
+ * For example:
+ * {{{
+ * case class People(name: String, gender: String)
+ *
+ * object Test{
+ *
+ * val groupBy: (People => String) = people => people.gender
+ * val partitioner = GroupByPartitioner(groupBy)
+ * }
+ * }}}
+ *
+ * @param groupBy First apply message with groupBy function, then pick the hashCode of the output
+ * to do the partitioning. You must define hashCode() for output type of groupBy function.
+ */
+class GroupByPartitioner[T, GROUP](groupBy: T => GROUP = null) extends UnicastPartitioner {
+ override def getPartition(msg: Message, partitionNum: Int, currentPartitionId: Int): Int = {
+ val hashCode = groupBy(msg.msg.asInstanceOf[T]).hashCode()
+ (hashCode & Integer.MAX_VALUE) % partitionNum
+ }
+}
\ No newline at end of file
[33/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/pagerank/src/main/scala/io/gearpump/experiments/pagerank/PageRankWorker.scala
----------------------------------------------------------------------
diff --git a/examples/pagerank/src/main/scala/io/gearpump/experiments/pagerank/PageRankWorker.scala b/examples/pagerank/src/main/scala/io/gearpump/experiments/pagerank/PageRankWorker.scala
deleted file mode 100644
index 9f38cd7..0000000
--- a/examples/pagerank/src/main/scala/io/gearpump/experiments/pagerank/PageRankWorker.scala
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.experiments.pagerank
-
-import akka.actor.Actor.Receive
-
-import io.gearpump.cluster.UserConfig
-import io.gearpump.experiments.pagerank.PageRankApplication.NodeWithTaskId
-import io.gearpump.experiments.pagerank.PageRankController.Tick
-import io.gearpump.experiments.pagerank.PageRankWorker.{LatestWeight, UpdateWeight}
-import io.gearpump.streaming.task.{Task, TaskContext, TaskId, TaskWrapper}
-import io.gearpump.util.Graph
-
-class PageRankWorker(taskContext: TaskContext, conf: UserConfig) extends Task(taskContext, conf) {
- import taskContext.taskId
-
- private var weight: Double = 1.0
- private var upstreamWeights = Map.empty[TaskId, Double]
-
- val taskCount = conf.getInt(PageRankApplication.COUNT).get
- lazy val allTasks = (0 until taskCount).toList.map(TaskId(processorId = 1, _))
-
- private val graph = conf.getValue[Graph[NodeWithTaskId[_], AnyRef]](PageRankApplication.DAG).get
-
- private val node = graph.vertices.find { node =>
- node.taskId == taskContext.taskId.index
- }.get
-
- private val downstream = graph.outgoingEdgesOf(node).map(_._3)
- .map(id => taskId.copy(index = id.taskId)).toSeq
- private val upstreamCount = graph.incomingEdgesOf(node).map(_._1).length
-
- LOG.info(s"downstream nodes: $downstream")
-
- private var tick = 0
-
- private def output(msg: AnyRef, tasks: TaskId*): Unit = {
- taskContext.asInstanceOf[TaskWrapper].outputUnManaged(msg, tasks: _*)
- }
-
- override def receiveUnManagedMessage: Receive = {
- case Tick(tick) =>
- this.tick = tick
-
- if (downstream.length == 0) {
- // If there is no downstream, we will evenly distribute our page rank to
- // every node in the graph
- val update = UpdateWeight(taskId, weight / taskCount)
- output(update, allTasks: _*)
- } else {
- val update = UpdateWeight(taskId, weight / downstream.length)
- output(update, downstream: _*)
- }
- case update@UpdateWeight(upstreamTaskId, weight) =>
- upstreamWeights += upstreamTaskId -> weight
- if (upstreamWeights.size == upstreamCount) {
- val nextWeight = upstreamWeights.foldLeft(0.0) { (sum, item) => sum + item._2 }
- this.upstreamWeights = Map.empty[TaskId, Double]
- this.weight = nextWeight
- output(LatestWeight(taskId, weight, tick), TaskId(0, 0))
- }
- }
-}
-
-object PageRankWorker {
- case class UpdateWeight(taskId: TaskId, weight: Double)
- case class LatestWeight(taskId: TaskId, weight: Double, tick: Int)
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/pagerank/src/main/scala/io/gearpump/experiments/pagerank/example/PageRankExample.scala
----------------------------------------------------------------------
diff --git a/examples/pagerank/src/main/scala/io/gearpump/experiments/pagerank/example/PageRankExample.scala b/examples/pagerank/src/main/scala/io/gearpump/experiments/pagerank/example/PageRankExample.scala
deleted file mode 100644
index 3877974..0000000
--- a/examples/pagerank/src/main/scala/io/gearpump/experiments/pagerank/example/PageRankExample.scala
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.experiments.pagerank.example
-
-import io.gearpump.cluster.client.ClientContext
-import io.gearpump.experiments.pagerank.PageRankApplication
-import io.gearpump.util.Graph.Node
-import io.gearpump.util.{AkkaApp, Graph}
-
-/** A very simple PageRank example, Cyclic graph is not supported */
-object PageRankExample extends AkkaApp {
-
- val a = "a"
- val b = "b"
- val c = "c"
- val d = "d"
-
- def help(): Unit = Unit
-
- def main(akkaConf: Config, args: Array[String]): Unit = {
- val pageRankGraph = Graph(a ~> b, a ~> c, a ~> d, b ~> a, b ~> d, d ~> b, d ~> c, c ~> b)
- val app = new PageRankApplication("pagerank", iteration = 100, delta = 0.001, pageRankGraph)
- val context = ClientContext(akkaConf)
- val appId = context.submit(app)
- context.close()
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/pagerank/src/main/scala/org/apache/gearpump/experiments/pagerank/PageRankApplication.scala
----------------------------------------------------------------------
diff --git a/examples/pagerank/src/main/scala/org/apache/gearpump/experiments/pagerank/PageRankApplication.scala b/examples/pagerank/src/main/scala/org/apache/gearpump/experiments/pagerank/PageRankApplication.scala
new file mode 100644
index 0000000..023ee35
--- /dev/null
+++ b/examples/pagerank/src/main/scala/org/apache/gearpump/experiments/pagerank/PageRankApplication.scala
@@ -0,0 +1,77 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.experiments.pagerank
+
+import akka.actor.ActorSystem
+
+import org.apache.gearpump.cluster.{Application, ApplicationMaster, UserConfig}
+import org.apache.gearpump.experiments.pagerank.PageRankApplication.NodeWithTaskId
+import org.apache.gearpump.partitioner.HashPartitioner
+import org.apache.gearpump.streaming.appmaster.AppMaster
+import org.apache.gearpump.streaming.{Processor, StreamApplication}
+import org.apache.gearpump.util.Graph
+import org.apache.gearpump.util.Graph.Node
+
+/**
+ *
+ * A simple and naive pagerank implementation.
+ *
+ * @param name name of the application
+ * @param iteration max iteration count
+ * @param delta decide the accuracy when the page rank example stops.
+ * @param dag the page rank graph
+ */
+class PageRankApplication[T](
+ override val name: String, iteration: Int, delta: Double, dag: Graph[T, _])
+ extends Application {
+
+ override def appMaster: Class[_ <: ApplicationMaster] = classOf[AppMaster]
+ override def userConfig(implicit system: ActorSystem): UserConfig = {
+
+ // Map node with taskId
+ var taskId = 0
+ val pageRankDag = dag.mapVertex { node =>
+ val updatedNode = NodeWithTaskId(taskId, node)
+ taskId += 1
+ updatedNode
+ }
+
+ val taskCount = taskId
+
+ val userConfig = UserConfig.empty.withValue(PageRankApplication.DAG, pageRankDag).
+ withInt(PageRankApplication.ITERATION, iteration).
+ withInt(PageRankApplication.COUNT, taskCount).
+ withDouble(PageRankApplication.DELTA, delta)
+
+ val controller = Processor[PageRankController](1)
+ val pageRankWorker = Processor[PageRankWorker](taskCount)
+ val partitioner = new HashPartitioner
+
+ val app = StreamApplication(name, Graph(controller ~ partitioner ~> pageRankWorker), userConfig)
+ app.userConfig
+ }
+}
+
+object PageRankApplication {
+ val DAG = "PageRank.DAG"
+ val ITERATION = "PageRank.Iteration"
+ val COUNT = "PageRank.COUNT"
+ val DELTA = "PageRank.DELTA"
+ val REPORTER = "PageRank.Reporter"
+ case class NodeWithTaskId[T](taskId: Int, node: T)
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/pagerank/src/main/scala/org/apache/gearpump/experiments/pagerank/PageRankController.scala
----------------------------------------------------------------------
diff --git a/examples/pagerank/src/main/scala/org/apache/gearpump/experiments/pagerank/PageRankController.scala b/examples/pagerank/src/main/scala/org/apache/gearpump/experiments/pagerank/PageRankController.scala
new file mode 100644
index 0000000..d461876
--- /dev/null
+++ b/examples/pagerank/src/main/scala/org/apache/gearpump/experiments/pagerank/PageRankController.scala
@@ -0,0 +1,79 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.experiments.pagerank
+
+import akka.actor.Actor.Receive
+
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.experiments.pagerank.PageRankController.Tick
+import org.apache.gearpump.experiments.pagerank.PageRankWorker.LatestWeight
+import org.apache.gearpump.streaming.task._
+
+class PageRankController(taskContext: TaskContext, conf: UserConfig)
+ extends Task(taskContext, conf) {
+
+ val taskCount = conf.getInt(PageRankApplication.COUNT).get
+ val iterationMax = conf.getInt(PageRankApplication.ITERATION).get
+ val delta = conf.getDouble(PageRankApplication.DELTA).get
+
+ val tasks = (0 until taskCount).toList.map(TaskId(1, _))
+
+ var tick: Int = 0
+ var receivedWeightForCurrentTick = 0
+
+ var weights = Map.empty[TaskId, Double]
+ var deltas = Map.empty[TaskId, Double]
+
+ override def onStart(startTime: StartTime): Unit = {
+ output(Tick(tick), tasks: _*)
+ }
+
+ private def output(msg: AnyRef, tasks: TaskId*): Unit = {
+ taskContext.asInstanceOf[TaskWrapper].outputUnManaged(msg, tasks: _*)
+ }
+
+ override def receiveUnManagedMessage: Receive = {
+ case LatestWeight(taskId, weight, replyTick) =>
+ if (this.tick == replyTick) {
+
+ deltas += taskId -> Math.abs(weight - weights.getOrElse(taskId, 0.0))
+ weights += taskId -> weight
+ receivedWeightForCurrentTick += 1
+ if (receivedWeightForCurrentTick == taskCount) {
+ this.tick += 1
+ receivedWeightForCurrentTick = 0
+ if (continueIteration) {
+ LOG.debug(s"next iteration: $tick, weight: $weights, delta: $deltas")
+ output(Tick(tick), tasks: _*)
+ } else {
+ LOG.info(s"iterations: $tick, weight: $weights, delta: $deltas")
+ }
+ }
+ }
+ }
+
+ private def continueIteration: Boolean = {
+ (tick < iterationMax) && deltas.values.foldLeft(false) { (deltaExceed, value) =>
+ deltaExceed || value > delta
+ }
+ }
+}
+
+object PageRankController {
+ case class Tick(iteration: Int)
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/pagerank/src/main/scala/org/apache/gearpump/experiments/pagerank/PageRankWorker.scala
----------------------------------------------------------------------
diff --git a/examples/pagerank/src/main/scala/org/apache/gearpump/experiments/pagerank/PageRankWorker.scala b/examples/pagerank/src/main/scala/org/apache/gearpump/experiments/pagerank/PageRankWorker.scala
new file mode 100644
index 0000000..e033bf1
--- /dev/null
+++ b/examples/pagerank/src/main/scala/org/apache/gearpump/experiments/pagerank/PageRankWorker.scala
@@ -0,0 +1,83 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.experiments.pagerank
+
+import akka.actor.Actor.Receive
+
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.experiments.pagerank.PageRankApplication.NodeWithTaskId
+import org.apache.gearpump.experiments.pagerank.PageRankController.Tick
+import org.apache.gearpump.experiments.pagerank.PageRankWorker.{LatestWeight, UpdateWeight}
+import org.apache.gearpump.streaming.task.{Task, TaskContext, TaskId, TaskWrapper}
+import org.apache.gearpump.util.Graph
+
+class PageRankWorker(taskContext: TaskContext, conf: UserConfig) extends Task(taskContext, conf) {
+ import taskContext.taskId
+
+ private var weight: Double = 1.0
+ private var upstreamWeights = Map.empty[TaskId, Double]
+
+ val taskCount = conf.getInt(PageRankApplication.COUNT).get
+ lazy val allTasks = (0 until taskCount).toList.map(TaskId(processorId = 1, _))
+
+ private val graph = conf.getValue[Graph[NodeWithTaskId[_], AnyRef]](PageRankApplication.DAG).get
+
+ private val node = graph.vertices.find { node =>
+ node.taskId == taskContext.taskId.index
+ }.get
+
+ private val downstream = graph.outgoingEdgesOf(node).map(_._3)
+ .map(id => taskId.copy(index = id.taskId)).toSeq
+ private val upstreamCount = graph.incomingEdgesOf(node).map(_._1).length
+
+ LOG.info(s"downstream nodes: $downstream")
+
+ private var tick = 0
+
+ private def output(msg: AnyRef, tasks: TaskId*): Unit = {
+ taskContext.asInstanceOf[TaskWrapper].outputUnManaged(msg, tasks: _*)
+ }
+
+ override def receiveUnManagedMessage: Receive = {
+ case Tick(tick) =>
+ this.tick = tick
+
+ if (downstream.length == 0) {
+ // If there is no downstream, we will evenly distribute our page rank to
+ // every node in the graph
+ val update = UpdateWeight(taskId, weight / taskCount)
+ output(update, allTasks: _*)
+ } else {
+ val update = UpdateWeight(taskId, weight / downstream.length)
+ output(update, downstream: _*)
+ }
+ case update@UpdateWeight(upstreamTaskId, weight) =>
+ upstreamWeights += upstreamTaskId -> weight
+ if (upstreamWeights.size == upstreamCount) {
+ val nextWeight = upstreamWeights.foldLeft(0.0) { (sum, item) => sum + item._2 }
+ this.upstreamWeights = Map.empty[TaskId, Double]
+ this.weight = nextWeight
+ output(LatestWeight(taskId, weight, tick), TaskId(0, 0))
+ }
+ }
+}
+
+object PageRankWorker {
+ case class UpdateWeight(taskId: TaskId, weight: Double)
+ case class LatestWeight(taskId: TaskId, weight: Double, tick: Int)
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/pagerank/src/main/scala/org/apache/gearpump/experiments/pagerank/example/PageRankExample.scala
----------------------------------------------------------------------
diff --git a/examples/pagerank/src/main/scala/org/apache/gearpump/experiments/pagerank/example/PageRankExample.scala b/examples/pagerank/src/main/scala/org/apache/gearpump/experiments/pagerank/example/PageRankExample.scala
new file mode 100644
index 0000000..9dc311f
--- /dev/null
+++ b/examples/pagerank/src/main/scala/org/apache/gearpump/experiments/pagerank/example/PageRankExample.scala
@@ -0,0 +1,42 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.experiments.pagerank.example
+
+import org.apache.gearpump.cluster.client.ClientContext
+import org.apache.gearpump.experiments.pagerank.PageRankApplication
+import org.apache.gearpump.util.Graph.Node
+import org.apache.gearpump.util.{AkkaApp, Graph}
+
+/** A very simple PageRank example, Cyclic graph is not supported */
+object PageRankExample extends AkkaApp {
+
+ val a = "a"
+ val b = "b"
+ val c = "c"
+ val d = "d"
+
+ def help(): Unit = Unit
+
+ def main(akkaConf: Config, args: Array[String]): Unit = {
+ val pageRankGraph = Graph(a ~> b, a ~> c, a ~> d, b ~> a, b ~> d, d ~> b, d ~> c, c ~> b)
+ val app = new PageRankApplication("pagerank", iteration = 100, delta = 0.001, pageRankGraph)
+ val context = ClientContext(akkaConf)
+ val appId = context.submit(app)
+ context.close()
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/complexdag/src/main/scala/io/gearpump/streaming/examples/complexdag/Dag.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/complexdag/src/main/scala/io/gearpump/streaming/examples/complexdag/Dag.scala b/examples/streaming/complexdag/src/main/scala/io/gearpump/streaming/examples/complexdag/Dag.scala
deleted file mode 100644
index b517126..0000000
--- a/examples/streaming/complexdag/src/main/scala/io/gearpump/streaming/examples/complexdag/Dag.scala
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.complexdag
-
-import org.slf4j.Logger
-
-import io.gearpump.cluster.UserConfig
-import io.gearpump.cluster.client.ClientContext
-import io.gearpump.cluster.main.{ArgumentsParser, CLIOption, ParseResult}
-import io.gearpump.partitioner.HashPartitioner
-import io.gearpump.streaming.task.TaskContext
-import io.gearpump.streaming.{Processor, StreamApplication}
-import io.gearpump.util.Graph.{Node => GraphNode}
-import io.gearpump.util.{AkkaApp, Graph, LogUtil}
-
-case class Source_0(_context: TaskContext, _conf: UserConfig) extends Source(_context, _conf)
-case class Source_1(_context: TaskContext, _conf: UserConfig) extends Source(_context, _conf)
-case class Node_0(_context: TaskContext, _conf: UserConfig) extends Node(_context, _conf)
-case class Node_1(_context: TaskContext, _conf: UserConfig) extends Node(_context, _conf)
-case class Node_2(_context: TaskContext, _conf: UserConfig) extends Node(_context, _conf)
-case class Node_3(_context: TaskContext, _conf: UserConfig) extends Node(_context, _conf)
-case class Node_4(_context: TaskContext, _conf: UserConfig) extends Node(_context, _conf)
-case class Sink_0(_context: TaskContext, _conf: UserConfig) extends Sink(_context, _conf)
-case class Sink_1(_context: TaskContext, _conf: UserConfig) extends Sink(_context, _conf)
-case class Sink_2(_context: TaskContext, _conf: UserConfig) extends Sink(_context, _conf)
-case class Sink_3(_context: TaskContext, _conf: UserConfig) extends Sink(_context, _conf)
-case class Sink_4(_context: TaskContext, _conf: UserConfig) extends Sink(_context, _conf)
-
-/**
- * digraph flow {
- * Source_0 -> Sink_0;
- * Source_0 -> Sink_1;
- * Source_0 -> Sink_2;
- * Source_0 -> Node_1;
- * Source_1 -> Node_0;
- * Node_0 -> Sink_3;
- * Node_1 -> Sink_3;
- * Node_1 -> Sink_4;
- * Node_1 -> Node_4;
- * Node_2 -> Node_3;
- * Node_1 -> Node_3;
- * Source_0 -> Node_2;
- * Source_0 -> Node_3;
- * Node_3 -> Sink_3;
- * Node_4 -> Sink_3;
- * Source_1 -> Sink_4;
- * }
- */
-object Dag extends AkkaApp with ArgumentsParser {
- private val LOG: Logger = LogUtil.getLogger(getClass)
- val RUN_FOR_EVER = -1
-
- override val options: Array[(String, CLIOption[Any])] = Array.empty
-
- def application(config: ParseResult): StreamApplication = {
-
- val source_0 = Processor[Source_0](1)
- val source_1 = Processor[Source_1](1)
- val node_0 = Processor[Node_0](1)
- val node_1 = Processor[Node_1](1)
- val node_2 = Processor[Node_2](1)
- val node_3 = Processor[Node_3](1)
- val node_4 = Processor[Node_4](1)
- val sink_0 = Processor[Sink_0](1)
- val sink_1 = Processor[Sink_1](1)
- val sink_2 = Processor[Sink_2](1)
- val sink_3 = Processor[Sink_3](1)
- val sink_4 = Processor[Sink_4](1)
- val partitioner = new HashPartitioner
- val app = StreamApplication("dag", Graph(
- source_0 ~ partitioner ~> sink_1,
- source_0 ~ partitioner ~> sink_2,
- source_0 ~ partitioner ~> node_2,
- source_0 ~ partitioner ~> node_3,
- source_0 ~ partitioner ~> node_1,
- source_0 ~ partitioner ~> sink_0,
- node_2 ~ partitioner ~> node_3,
- node_1 ~ partitioner ~> node_3,
- node_1 ~ partitioner ~> sink_3,
- node_1 ~ partitioner ~> node_4,
- source_1 ~ partitioner ~> sink_4,
- source_1 ~ partitioner ~> node_0,
- node_3 ~ partitioner ~> sink_3,
- node_4 ~ partitioner ~> sink_3,
- node_0 ~ partitioner ~> sink_3
- ), UserConfig.empty)
- app
- }
-
- override def main(akkaConf: Config, args: Array[String]): Unit = {
- val userConf = parse(args)
- val context = ClientContext(akkaConf)
- val appId = context.submit(application(userConf))
- context.close()
- }
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/complexdag/src/main/scala/io/gearpump/streaming/examples/complexdag/Node.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/complexdag/src/main/scala/io/gearpump/streaming/examples/complexdag/Node.scala b/examples/streaming/complexdag/src/main/scala/io/gearpump/streaming/examples/complexdag/Node.scala
deleted file mode 100644
index dfad6c8..0000000
--- a/examples/streaming/complexdag/src/main/scala/io/gearpump/streaming/examples/complexdag/Node.scala
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.complexdag
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.task.{StartTime, Task, TaskContext}
-
-class Node(taskContext: TaskContext, conf: UserConfig) extends Task(taskContext, conf) {
- import taskContext.output
-
- override def onStart(startTime: StartTime): Unit = {}
-
- override def onNext(msg: Message): Unit = {
- val list = msg.msg.asInstanceOf[Vector[String]]
- output(new Message(list :+ getClass.getCanonicalName, System.currentTimeMillis()))
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/complexdag/src/main/scala/io/gearpump/streaming/examples/complexdag/Sink.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/complexdag/src/main/scala/io/gearpump/streaming/examples/complexdag/Sink.scala b/examples/streaming/complexdag/src/main/scala/io/gearpump/streaming/examples/complexdag/Sink.scala
deleted file mode 100644
index b091a17..0000000
--- a/examples/streaming/complexdag/src/main/scala/io/gearpump/streaming/examples/complexdag/Sink.scala
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.complexdag
-
-import scala.collection.mutable
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.task.{StartTime, Task, TaskContext}
-
-class Sink(taskContext: TaskContext, conf: UserConfig) extends Task(taskContext, conf) {
-
- var list = mutable.MutableList[String]()
-
- override def onStart(startTime: StartTime): Unit = {
- list += getClass.getCanonicalName
- }
-
- override def onNext(msg: Message): Unit = {
- val l = msg.msg.asInstanceOf[Vector[String]]
- list.size match {
- case 1 =>
- l.foreach(f => {
- list += f
- })
- case _ =>
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/complexdag/src/main/scala/io/gearpump/streaming/examples/complexdag/Source.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/complexdag/src/main/scala/io/gearpump/streaming/examples/complexdag/Source.scala b/examples/streaming/complexdag/src/main/scala/io/gearpump/streaming/examples/complexdag/Source.scala
deleted file mode 100644
index df656ac..0000000
--- a/examples/streaming/complexdag/src/main/scala/io/gearpump/streaming/examples/complexdag/Source.scala
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.complexdag
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.task.{StartTime, Task, TaskContext}
-
-class Source(taskContext: TaskContext, conf: UserConfig) extends Task(taskContext, conf) {
- import taskContext.output
-
- override def onStart(startTime: StartTime): Unit = {
- self ! Message("start")
- }
-
- override def onNext(msg: Message): Unit = {
- val list = Vector(getClass.getCanonicalName)
- output(new Message(list, System.currentTimeMillis))
- self ! Message("continue", System.currentTimeMillis())
- }
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/complexdag/src/main/scala/org/apache/gearpump/streaming/examples/complexdag/Dag.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/complexdag/src/main/scala/org/apache/gearpump/streaming/examples/complexdag/Dag.scala b/examples/streaming/complexdag/src/main/scala/org/apache/gearpump/streaming/examples/complexdag/Dag.scala
new file mode 100644
index 0000000..3b6ceb8
--- /dev/null
+++ b/examples/streaming/complexdag/src/main/scala/org/apache/gearpump/streaming/examples/complexdag/Dag.scala
@@ -0,0 +1,113 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.complexdag
+
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.cluster.client.ClientContext
+import org.apache.gearpump.cluster.main.{ArgumentsParser, CLIOption, ParseResult}
+import org.apache.gearpump.partitioner.HashPartitioner
+import org.apache.gearpump.streaming.task.TaskContext
+import org.apache.gearpump.streaming.{Processor, StreamApplication}
+import org.apache.gearpump.util.Graph.{Node => GraphNode}
+import org.apache.gearpump.util.{AkkaApp, Graph, LogUtil}
+
+case class Source_0(_context: TaskContext, _conf: UserConfig) extends Source(_context, _conf)
+case class Source_1(_context: TaskContext, _conf: UserConfig) extends Source(_context, _conf)
+case class Node_0(_context: TaskContext, _conf: UserConfig) extends Node(_context, _conf)
+case class Node_1(_context: TaskContext, _conf: UserConfig) extends Node(_context, _conf)
+case class Node_2(_context: TaskContext, _conf: UserConfig) extends Node(_context, _conf)
+case class Node_3(_context: TaskContext, _conf: UserConfig) extends Node(_context, _conf)
+case class Node_4(_context: TaskContext, _conf: UserConfig) extends Node(_context, _conf)
+case class Sink_0(_context: TaskContext, _conf: UserConfig) extends Sink(_context, _conf)
+case class Sink_1(_context: TaskContext, _conf: UserConfig) extends Sink(_context, _conf)
+case class Sink_2(_context: TaskContext, _conf: UserConfig) extends Sink(_context, _conf)
+case class Sink_3(_context: TaskContext, _conf: UserConfig) extends Sink(_context, _conf)
+case class Sink_4(_context: TaskContext, _conf: UserConfig) extends Sink(_context, _conf)
+
+/**
+ * digraph flow {
+ * Source_0 -> Sink_0;
+ * Source_0 -> Sink_1;
+ * Source_0 -> Sink_2;
+ * Source_0 -> Node_1;
+ * Source_1 -> Node_0;
+ * Node_0 -> Sink_3;
+ * Node_1 -> Sink_3;
+ * Node_1 -> Sink_4;
+ * Node_1 -> Node_4;
+ * Node_2 -> Node_3;
+ * Node_1 -> Node_3;
+ * Source_0 -> Node_2;
+ * Source_0 -> Node_3;
+ * Node_3 -> Sink_3;
+ * Node_4 -> Sink_3;
+ * Source_1 -> Sink_4;
+ * }
+ */
+object Dag extends AkkaApp with ArgumentsParser {
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+ val RUN_FOR_EVER = -1
+
+ override val options: Array[(String, CLIOption[Any])] = Array.empty
+
+ def application(config: ParseResult): StreamApplication = {
+
+ val source_0 = Processor[Source_0](1)
+ val source_1 = Processor[Source_1](1)
+ val node_0 = Processor[Node_0](1)
+ val node_1 = Processor[Node_1](1)
+ val node_2 = Processor[Node_2](1)
+ val node_3 = Processor[Node_3](1)
+ val node_4 = Processor[Node_4](1)
+ val sink_0 = Processor[Sink_0](1)
+ val sink_1 = Processor[Sink_1](1)
+ val sink_2 = Processor[Sink_2](1)
+ val sink_3 = Processor[Sink_3](1)
+ val sink_4 = Processor[Sink_4](1)
+ val partitioner = new HashPartitioner
+ val app = StreamApplication("dag", Graph(
+ source_0 ~ partitioner ~> sink_1,
+ source_0 ~ partitioner ~> sink_2,
+ source_0 ~ partitioner ~> node_2,
+ source_0 ~ partitioner ~> node_3,
+ source_0 ~ partitioner ~> node_1,
+ source_0 ~ partitioner ~> sink_0,
+ node_2 ~ partitioner ~> node_3,
+ node_1 ~ partitioner ~> node_3,
+ node_1 ~ partitioner ~> sink_3,
+ node_1 ~ partitioner ~> node_4,
+ source_1 ~ partitioner ~> sink_4,
+ source_1 ~ partitioner ~> node_0,
+ node_3 ~ partitioner ~> sink_3,
+ node_4 ~ partitioner ~> sink_3,
+ node_0 ~ partitioner ~> sink_3
+ ), UserConfig.empty)
+ app
+ }
+
+ override def main(akkaConf: Config, args: Array[String]): Unit = {
+ val userConf = parse(args)
+ val context = ClientContext(akkaConf)
+ val appId = context.submit(application(userConf))
+ context.close()
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/complexdag/src/main/scala/org/apache/gearpump/streaming/examples/complexdag/Node.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/complexdag/src/main/scala/org/apache/gearpump/streaming/examples/complexdag/Node.scala b/examples/streaming/complexdag/src/main/scala/org/apache/gearpump/streaming/examples/complexdag/Node.scala
new file mode 100644
index 0000000..8d163f9
--- /dev/null
+++ b/examples/streaming/complexdag/src/main/scala/org/apache/gearpump/streaming/examples/complexdag/Node.scala
@@ -0,0 +1,34 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.complexdag
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.task.{StartTime, Task, TaskContext}
+
+class Node(taskContext: TaskContext, conf: UserConfig) extends Task(taskContext, conf) {
+ import taskContext.output
+
+ override def onStart(startTime: StartTime): Unit = {}
+
+ override def onNext(msg: Message): Unit = {
+ val list = msg.msg.asInstanceOf[Vector[String]]
+ output(new Message(list :+ getClass.getCanonicalName, System.currentTimeMillis()))
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/complexdag/src/main/scala/org/apache/gearpump/streaming/examples/complexdag/Sink.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/complexdag/src/main/scala/org/apache/gearpump/streaming/examples/complexdag/Sink.scala b/examples/streaming/complexdag/src/main/scala/org/apache/gearpump/streaming/examples/complexdag/Sink.scala
new file mode 100644
index 0000000..8dfa565
--- /dev/null
+++ b/examples/streaming/complexdag/src/main/scala/org/apache/gearpump/streaming/examples/complexdag/Sink.scala
@@ -0,0 +1,45 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.complexdag
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.task.{StartTime, Task, TaskContext}
+
+import scala.collection.mutable
+
+class Sink(taskContext: TaskContext, conf: UserConfig) extends Task(taskContext, conf) {
+
+ var list = mutable.MutableList[String]()
+
+ override def onStart(startTime: StartTime): Unit = {
+ list += getClass.getCanonicalName
+ }
+
+ override def onNext(msg: Message): Unit = {
+ val l = msg.msg.asInstanceOf[Vector[String]]
+ list.size match {
+ case 1 =>
+ l.foreach(f => {
+ list += f
+ })
+ case _ =>
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/complexdag/src/main/scala/org/apache/gearpump/streaming/examples/complexdag/Source.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/complexdag/src/main/scala/org/apache/gearpump/streaming/examples/complexdag/Source.scala b/examples/streaming/complexdag/src/main/scala/org/apache/gearpump/streaming/examples/complexdag/Source.scala
new file mode 100644
index 0000000..0359519
--- /dev/null
+++ b/examples/streaming/complexdag/src/main/scala/org/apache/gearpump/streaming/examples/complexdag/Source.scala
@@ -0,0 +1,38 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.complexdag
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.task.{StartTime, Task, TaskContext}
+
+class Source(taskContext: TaskContext, conf: UserConfig) extends Task(taskContext, conf) {
+ import taskContext.output
+
+ override def onStart(startTime: StartTime): Unit = {
+ self ! Message("start")
+ }
+
+ override def onNext(msg: Message): Unit = {
+ val list = Vector(getClass.getCanonicalName)
+ output(new Message(list, System.currentTimeMillis))
+ self ! Message("continue", System.currentTimeMillis())
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/complexdag/src/test/scala/io/gearpump/streaming/examples/complexdag/DagSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/complexdag/src/test/scala/io/gearpump/streaming/examples/complexdag/DagSpec.scala b/examples/streaming/complexdag/src/test/scala/io/gearpump/streaming/examples/complexdag/DagSpec.scala
deleted file mode 100644
index b142d8d..0000000
--- a/examples/streaming/complexdag/src/test/scala/io/gearpump/streaming/examples/complexdag/DagSpec.scala
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.complexdag
-
-import scala.concurrent.Future
-import scala.util.Success
-
-import org.scalatest._
-import org.scalatest.prop.PropertyChecks
-
-import io.gearpump.cluster.ClientToMaster.SubmitApplication
-import io.gearpump.cluster.MasterToClient.SubmitApplicationResult
-import io.gearpump.cluster.{MasterHarness, TestUtil}
-
-class DagSpec extends PropSpec with PropertyChecks
- with Matchers with BeforeAndAfterAll with MasterHarness {
-
- override def beforeAll {
- startActorSystem()
- }
-
- override def afterAll {
- shutdownActorSystem()
- }
-
- protected override def config = TestUtil.DEFAULT_CONFIG
-
- property("Dag should succeed to submit application with required arguments") {
- val requiredArgs = Array.empty[String]
-
- val masterReceiver = createMockMaster()
- val args = requiredArgs
-
- Future {
- Dag.main(masterConfig, args)
- }
- masterReceiver.expectMsgType[SubmitApplication](PROCESS_BOOT_TIME)
- masterReceiver.reply(SubmitApplicationResult(Success(0)))
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/complexdag/src/test/scala/io/gearpump/streaming/examples/complexdag/NodeSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/complexdag/src/test/scala/io/gearpump/streaming/examples/complexdag/NodeSpec.scala b/examples/streaming/complexdag/src/test/scala/io/gearpump/streaming/examples/complexdag/NodeSpec.scala
deleted file mode 100644
index 35c5824..0000000
--- a/examples/streaming/complexdag/src/test/scala/io/gearpump/streaming/examples/complexdag/NodeSpec.scala
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.examples.complexdag
-
-import org.mockito.Mockito._
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{BeforeAndAfter, Matchers, PropSpec}
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.MockUtil
-import io.gearpump.streaming.MockUtil._
-
-class NodeSpec extends PropSpec with PropertyChecks with Matchers with BeforeAndAfter {
-
- val context = MockUtil.mockTaskContext
-
- val node = new Node(context, UserConfig.empty)
-
- property("Node should send a Vector[String](classOf[Node].getCanonicalName, " +
- "classOf[Node].getCanonicalName") {
- val list = Vector(classOf[Node].getCanonicalName)
- val expected = Vector(classOf[Node].getCanonicalName, classOf[Node].getCanonicalName)
- node.onNext(Message(list))
- verify(context).output(argMatch[Message](_.msg == expected))
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/complexdag/src/test/scala/io/gearpump/streaming/examples/complexdag/SinkSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/complexdag/src/test/scala/io/gearpump/streaming/examples/complexdag/SinkSpec.scala b/examples/streaming/complexdag/src/test/scala/io/gearpump/streaming/examples/complexdag/SinkSpec.scala
deleted file mode 100644
index 341f6c6..0000000
--- a/examples/streaming/complexdag/src/test/scala/io/gearpump/streaming/examples/complexdag/SinkSpec.scala
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.examples.complexdag
-
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{BeforeAndAfter, Matchers, PropSpec}
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.MockUtil
-
-class SinkSpec extends PropSpec with PropertyChecks with Matchers with BeforeAndAfter {
-
- val context = MockUtil.mockTaskContext
-
- val sink = new Sink(context, UserConfig.empty)
-
- property("Sink should send a Vector[String](classOf[Sink].getCanonicalName, " +
- "classOf[Sink].getCanonicalName") {
- val list = Vector(classOf[Sink].getCanonicalName)
- val expected = Vector(classOf[Sink].getCanonicalName, classOf[Sink].getCanonicalName)
- sink.onNext(Message(list))
-
- (0 until sink.list.size).map(i => {
- assert(sink.list(i).equals(expected(i)))
- })
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/complexdag/src/test/scala/io/gearpump/streaming/examples/complexdag/SourceSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/complexdag/src/test/scala/io/gearpump/streaming/examples/complexdag/SourceSpec.scala b/examples/streaming/complexdag/src/test/scala/io/gearpump/streaming/examples/complexdag/SourceSpec.scala
deleted file mode 100644
index faa7aa7..0000000
--- a/examples/streaming/complexdag/src/test/scala/io/gearpump/streaming/examples/complexdag/SourceSpec.scala
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.examples.complexdag
-
-import akka.actor.ActorSystem
-import org.mockito.Mockito._
-import org.scalatest.{Matchers, WordSpec}
-
-import io.gearpump.Message
-import io.gearpump.cluster.{TestUtil, UserConfig}
-import io.gearpump.streaming.MockUtil
-import io.gearpump.streaming.MockUtil._
-
-class SourceSpec extends WordSpec with Matchers {
-
- "Source" should {
- "Source should send a msg of Vector[String](classOf[Source].getCanonicalName)" in {
- val system1 = ActorSystem("Source", TestUtil.DEFAULT_CONFIG)
-
- val system2 = ActorSystem("Reporter", TestUtil.DEFAULT_CONFIG)
-
- val context = MockUtil.mockTaskContext
-
- val source = new Source(context, UserConfig.empty)
- source.onNext(Message("start"))
-
- verify(context).output(argMatch[Message](Vector(classOf[Source].getCanonicalName) == _.msg))
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/complexdag/src/test/scala/org/apache/gearpump/streaming/examples/complexdag/DagSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/complexdag/src/test/scala/org/apache/gearpump/streaming/examples/complexdag/DagSpec.scala b/examples/streaming/complexdag/src/test/scala/org/apache/gearpump/streaming/examples/complexdag/DagSpec.scala
new file mode 100644
index 0000000..cf8ae63
--- /dev/null
+++ b/examples/streaming/complexdag/src/test/scala/org/apache/gearpump/streaming/examples/complexdag/DagSpec.scala
@@ -0,0 +1,55 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.complexdag
+
+import org.apache.gearpump.cluster.ClientToMaster.SubmitApplication
+import org.apache.gearpump.cluster.MasterToClient.SubmitApplicationResult
+import org.apache.gearpump.cluster.{MasterHarness, TestUtil}
+import org.scalatest._
+import org.scalatest.prop.PropertyChecks
+
+import scala.concurrent.Future
+import scala.util.Success
+
+class DagSpec extends PropSpec with PropertyChecks
+ with Matchers with BeforeAndAfterAll with MasterHarness {
+
+ override def beforeAll {
+ startActorSystem()
+ }
+
+ override def afterAll {
+ shutdownActorSystem()
+ }
+
+ protected override def config = TestUtil.DEFAULT_CONFIG
+
+ property("Dag should succeed to submit application with required arguments") {
+ val requiredArgs = Array.empty[String]
+
+ val masterReceiver = createMockMaster()
+ val args = requiredArgs
+
+ Future {
+ Dag.main(masterConfig, args)
+ }
+ masterReceiver.expectMsgType[SubmitApplication](PROCESS_BOOT_TIME)
+ masterReceiver.reply(SubmitApplicationResult(Success(0)))
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/complexdag/src/test/scala/org/apache/gearpump/streaming/examples/complexdag/NodeSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/complexdag/src/test/scala/org/apache/gearpump/streaming/examples/complexdag/NodeSpec.scala b/examples/streaming/complexdag/src/test/scala/org/apache/gearpump/streaming/examples/complexdag/NodeSpec.scala
new file mode 100644
index 0000000..241e0f6
--- /dev/null
+++ b/examples/streaming/complexdag/src/test/scala/org/apache/gearpump/streaming/examples/complexdag/NodeSpec.scala
@@ -0,0 +1,41 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.examples.complexdag
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.MockUtil
+import org.apache.gearpump.streaming.MockUtil._
+import org.mockito.Mockito._
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{BeforeAndAfter, Matchers, PropSpec}
+
+class NodeSpec extends PropSpec with PropertyChecks with Matchers with BeforeAndAfter {
+
+ val context = MockUtil.mockTaskContext
+
+ val node = new Node(context, UserConfig.empty)
+
+ property("Node should send a Vector[String](classOf[Node].getCanonicalName, " +
+ "classOf[Node].getCanonicalName") {
+ val list = Vector(classOf[Node].getCanonicalName)
+ val expected = Vector(classOf[Node].getCanonicalName, classOf[Node].getCanonicalName)
+ node.onNext(Message(list))
+ verify(context).output(argMatch[Message](_.msg == expected))
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/complexdag/src/test/scala/org/apache/gearpump/streaming/examples/complexdag/SinkSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/complexdag/src/test/scala/org/apache/gearpump/streaming/examples/complexdag/SinkSpec.scala b/examples/streaming/complexdag/src/test/scala/org/apache/gearpump/streaming/examples/complexdag/SinkSpec.scala
new file mode 100644
index 0000000..e7bed30
--- /dev/null
+++ b/examples/streaming/complexdag/src/test/scala/org/apache/gearpump/streaming/examples/complexdag/SinkSpec.scala
@@ -0,0 +1,43 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.examples.complexdag
+
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{BeforeAndAfter, Matchers, PropSpec}
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.MockUtil
+
+class SinkSpec extends PropSpec with PropertyChecks with Matchers with BeforeAndAfter {
+
+ val context = MockUtil.mockTaskContext
+
+ val sink = new Sink(context, UserConfig.empty)
+
+ property("Sink should send a Vector[String](classOf[Sink].getCanonicalName, " +
+ "classOf[Sink].getCanonicalName") {
+ val list = Vector(classOf[Sink].getCanonicalName)
+ val expected = Vector(classOf[Sink].getCanonicalName, classOf[Sink].getCanonicalName)
+ sink.onNext(Message(list))
+
+ (0 until sink.list.size).map(i => {
+ assert(sink.list(i).equals(expected(i)))
+ })
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/complexdag/src/test/scala/org/apache/gearpump/streaming/examples/complexdag/SourceSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/complexdag/src/test/scala/org/apache/gearpump/streaming/examples/complexdag/SourceSpec.scala b/examples/streaming/complexdag/src/test/scala/org/apache/gearpump/streaming/examples/complexdag/SourceSpec.scala
new file mode 100644
index 0000000..20cad1c
--- /dev/null
+++ b/examples/streaming/complexdag/src/test/scala/org/apache/gearpump/streaming/examples/complexdag/SourceSpec.scala
@@ -0,0 +1,44 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.examples.complexdag
+
+import akka.actor.ActorSystem
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.{TestUtil, UserConfig}
+import org.apache.gearpump.streaming.MockUtil
+import org.apache.gearpump.streaming.MockUtil._
+import org.mockito.Mockito._
+import org.scalatest.{Matchers, WordSpec}
+
+class SourceSpec extends WordSpec with Matchers {
+
+ "Source" should {
+ "Source should send a msg of Vector[String](classOf[Source].getCanonicalName)" in {
+ val system1 = ActorSystem("Source", TestUtil.DEFAULT_CONFIG)
+
+ val system2 = ActorSystem("Reporter", TestUtil.DEFAULT_CONFIG)
+
+ val context = MockUtil.mockTaskContext
+
+ val source = new Source(context, UserConfig.empty)
+ source.onNext(Message("start"))
+
+ verify(context).output(argMatch[Message](Vector(classOf[Source].getCanonicalName) == _.msg))
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/fsio/README.md
----------------------------------------------------------------------
diff --git a/examples/streaming/fsio/README.md b/examples/streaming/fsio/README.md
index 06fefb6..200cdb1 100644
--- a/examples/streaming/fsio/README.md
+++ b/examples/streaming/fsio/README.md
@@ -16,7 +16,7 @@ In order to run the example:
3. Submit the application:<br>
```bash
- ./target/pack/bin/gear app -jar ./examples/target/$SCALA_VERSION_MAJOR/gearpump-examples-assembly-$VERSION.jar io.gearpump.streaming.examples.sol.SOL -input $INPUT_FILE_PATH -output $OUTPUT_DIRECTORY
+ ./target/pack/bin/gear app -jar ./examples/target/$SCALA_VERSION_MAJOR/gearpump-examples-assembly-$VERSION.jar org.apache.gearpump.streaming.examples.sol.SOL -input $INPUT_FILE_PATH -output $OUTPUT_DIRECTORY
```
4. Stop the application:<br>
```bash
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/fsio/src/main/scala/io/gearpump/streaming/examples/fsio/HadoopConfig.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/fsio/src/main/scala/io/gearpump/streaming/examples/fsio/HadoopConfig.scala b/examples/streaming/fsio/src/main/scala/io/gearpump/streaming/examples/fsio/HadoopConfig.scala
deleted file mode 100644
index 3b53c9c..0000000
--- a/examples/streaming/fsio/src/main/scala/io/gearpump/streaming/examples/fsio/HadoopConfig.scala
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.examples.fsio
-
-import java.io.{ByteArrayInputStream, ByteArrayOutputStream, DataInputStream, DataOutputStream}
-import scala.language.implicitConversions
-
-import org.apache.hadoop.conf.Configuration
-
-import io.gearpump.cluster.UserConfig
-import io.gearpump.util.Constants._
-
-class HadoopConfig(config: UserConfig) {
-
- def withHadoopConf(conf: Configuration): UserConfig = {
- config.withBytes(HADOOP_CONF, serializeHadoopConf(conf))
- }
-
- def hadoopConf: Configuration = deserializeHadoopConf(config.getBytes(HADOOP_CONF).get)
-
- private def serializeHadoopConf(conf: Configuration): Array[Byte] = {
- val out = new ByteArrayOutputStream()
- val dataOut = new DataOutputStream(out)
- conf.write(dataOut)
- dataOut.close()
- out.toByteArray
- }
-
- private def deserializeHadoopConf(bytes: Array[Byte]): Configuration = {
- val in = new ByteArrayInputStream(bytes)
- val dataIn = new DataInputStream(in)
- val result = new Configuration()
- result.readFields(dataIn)
- dataIn.close()
- result
- }
-}
-
-object HadoopConfig {
- def empty: HadoopConfig = new HadoopConfig(UserConfig.empty)
- def apply(config: UserConfig): HadoopConfig = new HadoopConfig(config)
-
- implicit def userConfigToHadoopConfig(userConf: UserConfig): HadoopConfig = {
- HadoopConfig(userConf)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/fsio/src/main/scala/io/gearpump/streaming/examples/fsio/SeqFileStreamProcessor.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/fsio/src/main/scala/io/gearpump/streaming/examples/fsio/SeqFileStreamProcessor.scala b/examples/streaming/fsio/src/main/scala/io/gearpump/streaming/examples/fsio/SeqFileStreamProcessor.scala
deleted file mode 100644
index 13fc3f9..0000000
--- a/examples/streaming/fsio/src/main/scala/io/gearpump/streaming/examples/fsio/SeqFileStreamProcessor.scala
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.examples.fsio
-
-import java.io.File
-import java.util.concurrent.TimeUnit
-import scala.concurrent.duration.FiniteDuration
-
-import akka.actor.Cancellable
-import org.apache.hadoop.fs.{FileSystem, Path}
-import org.apache.hadoop.io.SequenceFile._
-import org.apache.hadoop.io.{SequenceFile, Text}
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.examples.fsio.HadoopConfig._
-import io.gearpump.streaming.examples.fsio.SeqFileStreamProcessor._
-import io.gearpump.streaming.task.{StartTime, Task, TaskContext}
-
-class SeqFileStreamProcessor(taskContext: TaskContext, config: UserConfig)
- extends Task(taskContext, config) {
-
- import taskContext.taskId
-
- val outputPath = new Path(config.getString(OUTPUT_PATH).get + File.separator + taskId)
- var writer: SequenceFile.Writer = null
- val textClass = new Text().getClass
- val key = new Text()
- val value = new Text()
- val hadoopConf = config.hadoopConf
-
- private var msgCount: Long = 0
- private var snapShotKVCount: Long = 0
- private var snapShotTime: Long = 0
- private var scheduler: Cancellable = null
-
- override def onStart(startTime: StartTime): Unit = {
-
- val fs = FileSystem.get(hadoopConf)
- fs.deleteOnExit(outputPath)
- writer = SequenceFile.createWriter(hadoopConf, Writer.file(outputPath),
- Writer.keyClass(textClass), Writer.valueClass(textClass))
-
- scheduler = taskContext.schedule(new FiniteDuration(5, TimeUnit.SECONDS),
- new FiniteDuration(5, TimeUnit.SECONDS))(reportStatus())
- snapShotTime = System.currentTimeMillis()
- LOG.info("sequence file bolt initiated")
- }
-
- override def onNext(msg: Message): Unit = {
- val kv = msg.msg.asInstanceOf[String].split("\\+\\+")
- if (kv.length >= 2) {
- key.set(kv(0))
- value.set(kv(1))
- writer.append(key, value)
- }
- msgCount += 1
- }
-
- override def onStop(): Unit = {
- if (scheduler != null) {
- scheduler.cancel()
- }
- writer.close()
- LOG.info("sequence file bolt stopped")
- }
-
- private def reportStatus() = {
- val current: Long = System.currentTimeMillis()
- LOG.info(s"Task $taskId Throughput: ${
- (msgCount - snapShotKVCount,
- (current - snapShotTime) / 1000)
- } (KVPairs, second)")
- snapShotKVCount = msgCount
- snapShotTime = current
- }
-}
-
-object SeqFileStreamProcessor {
- val OUTPUT_PATH = "outputpath"
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/fsio/src/main/scala/io/gearpump/streaming/examples/fsio/SeqFileStreamProducer.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/fsio/src/main/scala/io/gearpump/streaming/examples/fsio/SeqFileStreamProducer.scala b/examples/streaming/fsio/src/main/scala/io/gearpump/streaming/examples/fsio/SeqFileStreamProducer.scala
deleted file mode 100644
index f9b0d22..0000000
--- a/examples/streaming/fsio/src/main/scala/io/gearpump/streaming/examples/fsio/SeqFileStreamProducer.scala
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.examples.fsio
-
-import org.apache.hadoop.fs.{FileSystem, Path}
-import org.apache.hadoop.io.SequenceFile._
-import org.apache.hadoop.io.{SequenceFile, Text}
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.examples.fsio.HadoopConfig._
-import io.gearpump.streaming.examples.fsio.SeqFileStreamProducer._
-import io.gearpump.streaming.task.{StartTime, Task, TaskContext}
-
-class SeqFileStreamProducer(taskContext: TaskContext, config: UserConfig)
- extends Task(taskContext, config) {
-
- import taskContext.output
-
- val value = new Text()
- val key = new Text()
- var reader: SequenceFile.Reader = null
- val hadoopConf = config.hadoopConf
- val fs = FileSystem.get(hadoopConf)
- val inputPath = new Path(config.getString(INPUT_PATH).get)
-
- override def onStart(startTime: StartTime): Unit = {
- reader = new SequenceFile.Reader(hadoopConf, Reader.file(inputPath))
- self ! Start
- LOG.info("sequence file spout initiated")
- }
-
- override def onNext(msg: Message): Unit = {
- if (reader.next(key, value)) {
- output(Message(key + "++" + value))
- } else {
- reader.close()
- reader = new SequenceFile.Reader(hadoopConf, Reader.file(inputPath))
- }
- self ! Continue
- }
-
- override def onStop(): Unit = {
- reader.close()
- }
-}
-
-object SeqFileStreamProducer {
- def INPUT_PATH: String = "inputpath"
-
- val Start = Message("start")
- val Continue = Message("continue")
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/fsio/src/main/scala/io/gearpump/streaming/examples/fsio/SequenceFileIO.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/fsio/src/main/scala/io/gearpump/streaming/examples/fsio/SequenceFileIO.scala b/examples/streaming/fsio/src/main/scala/io/gearpump/streaming/examples/fsio/SequenceFileIO.scala
deleted file mode 100644
index 7272f2b..0000000
--- a/examples/streaming/fsio/src/main/scala/io/gearpump/streaming/examples/fsio/SequenceFileIO.scala
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.examples.fsio
-
-import org.apache.hadoop.conf.Configuration
-import org.slf4j.Logger
-
-import io.gearpump.cluster.UserConfig
-import io.gearpump.cluster.client.ClientContext
-import io.gearpump.cluster.main.{ArgumentsParser, CLIOption, ParseResult}
-import io.gearpump.partitioner.ShufflePartitioner
-import io.gearpump.streaming.examples.fsio.HadoopConfig._
-import io.gearpump.streaming.{Processor, StreamApplication}
-import io.gearpump.util.Graph._
-import io.gearpump.util.{AkkaApp, Graph, LogUtil}
-
-object SequenceFileIO extends AkkaApp with ArgumentsParser {
- private val LOG: Logger = LogUtil.getLogger(getClass)
-
- override val options: Array[(String, CLIOption[Any])] = Array(
- "source" -> CLIOption[Int]("<sequence file reader number>", required = false,
- defaultValue = Some(1)),
- "sink" -> CLIOption[Int]("<sequence file writer number>", required = false,
- defaultValue = Some(1)),
- "input" -> CLIOption[String]("<input file path>", required = true),
- "output" -> CLIOption[String]("<output file directory>", required = true)
- )
-
- def application(config: ParseResult): StreamApplication = {
- val spoutNum = config.getInt("source")
- val boltNum = config.getInt("sink")
- val input = config.getString("input")
- val output = config.getString("output")
- val appConfig = UserConfig.empty.withString(SeqFileStreamProducer.INPUT_PATH, input)
- .withString(SeqFileStreamProcessor.OUTPUT_PATH, output)
- val hadoopConfig = appConfig.withHadoopConf(new Configuration())
- val partitioner = new ShufflePartitioner()
- val streamProducer = Processor[SeqFileStreamProducer](spoutNum)
- val streamProcessor = Processor[SeqFileStreamProcessor](boltNum)
-
- val app = StreamApplication("SequenceFileIO",
- Graph(streamProducer ~ partitioner ~> streamProcessor), hadoopConfig)
- app
- }
-
- override def main(akkaConf: Config, args: Array[String]): Unit = {
- val config = parse(args)
- val context = ClientContext(akkaConf)
- val appId = context.submit(application(config))
- context.close()
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/fsio/src/main/scala/org/apache/gearpump/streaming/examples/fsio/HadoopConfig.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/fsio/src/main/scala/org/apache/gearpump/streaming/examples/fsio/HadoopConfig.scala b/examples/streaming/fsio/src/main/scala/org/apache/gearpump/streaming/examples/fsio/HadoopConfig.scala
new file mode 100644
index 0000000..144dd78
--- /dev/null
+++ b/examples/streaming/fsio/src/main/scala/org/apache/gearpump/streaming/examples/fsio/HadoopConfig.scala
@@ -0,0 +1,61 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.examples.fsio
+
+import java.io.{ByteArrayInputStream, ByteArrayOutputStream, DataInputStream, DataOutputStream}
+import scala.language.implicitConversions
+
+import org.apache.hadoop.conf.Configuration
+
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.util.Constants._
+
+class HadoopConfig(config: UserConfig) {
+
+ def withHadoopConf(conf: Configuration): UserConfig = {
+ config.withBytes(HADOOP_CONF, serializeHadoopConf(conf))
+ }
+
+ def hadoopConf: Configuration = deserializeHadoopConf(config.getBytes(HADOOP_CONF).get)
+
+ private def serializeHadoopConf(conf: Configuration): Array[Byte] = {
+ val out = new ByteArrayOutputStream()
+ val dataOut = new DataOutputStream(out)
+ conf.write(dataOut)
+ dataOut.close()
+ out.toByteArray
+ }
+
+ private def deserializeHadoopConf(bytes: Array[Byte]): Configuration = {
+ val in = new ByteArrayInputStream(bytes)
+ val dataIn = new DataInputStream(in)
+ val result = new Configuration()
+ result.readFields(dataIn)
+ dataIn.close()
+ result
+ }
+}
+
+object HadoopConfig {
+ def empty: HadoopConfig = new HadoopConfig(UserConfig.empty)
+ def apply(config: UserConfig): HadoopConfig = new HadoopConfig(config)
+
+ implicit def userConfigToHadoopConfig(userConf: UserConfig): HadoopConfig = {
+ HadoopConfig(userConf)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/fsio/src/main/scala/org/apache/gearpump/streaming/examples/fsio/SeqFileStreamProcessor.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/fsio/src/main/scala/org/apache/gearpump/streaming/examples/fsio/SeqFileStreamProcessor.scala b/examples/streaming/fsio/src/main/scala/org/apache/gearpump/streaming/examples/fsio/SeqFileStreamProcessor.scala
new file mode 100644
index 0000000..2e4a556
--- /dev/null
+++ b/examples/streaming/fsio/src/main/scala/org/apache/gearpump/streaming/examples/fsio/SeqFileStreamProcessor.scala
@@ -0,0 +1,96 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.examples.fsio
+
+import java.io.File
+import java.util.concurrent.TimeUnit
+import scala.concurrent.duration.FiniteDuration
+
+import akka.actor.Cancellable
+import org.apache.hadoop.fs.{FileSystem, Path}
+import org.apache.hadoop.io.SequenceFile._
+import org.apache.hadoop.io.{SequenceFile, Text}
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.examples.fsio.HadoopConfig._
+import org.apache.gearpump.streaming.examples.fsio.SeqFileStreamProcessor._
+import org.apache.gearpump.streaming.task.{StartTime, Task, TaskContext}
+
+class SeqFileStreamProcessor(taskContext: TaskContext, config: UserConfig)
+ extends Task(taskContext, config) {
+
+ import taskContext.taskId
+
+ val outputPath = new Path(config.getString(OUTPUT_PATH).get + File.separator + taskId)
+ var writer: SequenceFile.Writer = null
+ val textClass = new Text().getClass
+ val key = new Text()
+ val value = new Text()
+ val hadoopConf = config.hadoopConf
+
+ private var msgCount: Long = 0
+ private var snapShotKVCount: Long = 0
+ private var snapShotTime: Long = 0
+ private var scheduler: Cancellable = null
+
+ override def onStart(startTime: StartTime): Unit = {
+
+ val fs = FileSystem.get(hadoopConf)
+ fs.deleteOnExit(outputPath)
+ writer = SequenceFile.createWriter(hadoopConf, Writer.file(outputPath),
+ Writer.keyClass(textClass), Writer.valueClass(textClass))
+
+ scheduler = taskContext.schedule(new FiniteDuration(5, TimeUnit.SECONDS),
+ new FiniteDuration(5, TimeUnit.SECONDS))(reportStatus())
+ snapShotTime = System.currentTimeMillis()
+ LOG.info("sequence file bolt initiated")
+ }
+
+ override def onNext(msg: Message): Unit = {
+ val kv = msg.msg.asInstanceOf[String].split("\\+\\+")
+ if (kv.length >= 2) {
+ key.set(kv(0))
+ value.set(kv(1))
+ writer.append(key, value)
+ }
+ msgCount += 1
+ }
+
+ override def onStop(): Unit = {
+ if (scheduler != null) {
+ scheduler.cancel()
+ }
+ writer.close()
+ LOG.info("sequence file bolt stopped")
+ }
+
+ private def reportStatus() = {
+ val current: Long = System.currentTimeMillis()
+ LOG.info(s"Task $taskId Throughput: ${
+ (msgCount - snapShotKVCount,
+ (current - snapShotTime) / 1000)
+ } (KVPairs, second)")
+ snapShotKVCount = msgCount
+ snapShotTime = current
+ }
+}
+
+object SeqFileStreamProcessor {
+ val OUTPUT_PATH = "outputpath"
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/fsio/src/main/scala/org/apache/gearpump/streaming/examples/fsio/SeqFileStreamProducer.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/fsio/src/main/scala/org/apache/gearpump/streaming/examples/fsio/SeqFileStreamProducer.scala b/examples/streaming/fsio/src/main/scala/org/apache/gearpump/streaming/examples/fsio/SeqFileStreamProducer.scala
new file mode 100644
index 0000000..02d2434
--- /dev/null
+++ b/examples/streaming/fsio/src/main/scala/org/apache/gearpump/streaming/examples/fsio/SeqFileStreamProducer.scala
@@ -0,0 +1,68 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.examples.fsio
+
+import org.apache.hadoop.fs.{FileSystem, Path}
+import org.apache.hadoop.io.SequenceFile._
+import org.apache.hadoop.io.{SequenceFile, Text}
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.examples.fsio.HadoopConfig._
+import org.apache.gearpump.streaming.examples.fsio.SeqFileStreamProducer._
+import org.apache.gearpump.streaming.task.{StartTime, Task, TaskContext}
+
+class SeqFileStreamProducer(taskContext: TaskContext, config: UserConfig)
+ extends Task(taskContext, config) {
+
+ import taskContext.output
+
+ val value = new Text()
+ val key = new Text()
+ var reader: SequenceFile.Reader = null
+ val hadoopConf = config.hadoopConf
+ val fs = FileSystem.get(hadoopConf)
+ val inputPath = new Path(config.getString(INPUT_PATH).get)
+
+ override def onStart(startTime: StartTime): Unit = {
+ reader = new SequenceFile.Reader(hadoopConf, Reader.file(inputPath))
+ self ! Start
+ LOG.info("sequence file spout initiated")
+ }
+
+ override def onNext(msg: Message): Unit = {
+ if (reader.next(key, value)) {
+ output(Message(key + "++" + value))
+ } else {
+ reader.close()
+ reader = new SequenceFile.Reader(hadoopConf, Reader.file(inputPath))
+ }
+ self ! Continue
+ }
+
+ override def onStop(): Unit = {
+ reader.close()
+ }
+}
+
+object SeqFileStreamProducer {
+ def INPUT_PATH: String = "inputpath"
+
+ val Start = Message("start")
+ val Continue = Message("continue")
+}
[45/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/util/Constants.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/util/Constants.scala b/core/src/main/scala/io/gearpump/util/Constants.scala
deleted file mode 100644
index 342cd87..0000000
--- a/core/src/main/scala/io/gearpump/util/Constants.scala
+++ /dev/null
@@ -1,177 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.util
-
-import java.util.concurrent.TimeUnit
-
-import io.gearpump.partitioner._
-
-object Constants {
- val MASTER_WATCHER = "masterwatcher"
- val SINGLETON_MANAGER = "singleton"
-
- val MASTER_CONFIG = "gearpump-master"
- val WORKER_CONFIG = "gearpump-worker"
- val UI_CONFIG = "gearpump-ui"
- val LINUX_CONFIG = "gearpump-linux" // linux or Mac
-
- val MASTER = "master"
- val WORKER = "worker"
-
- val GEARPUMP_WORKER_SLOTS = "gearpump.worker.slots"
- val GEARPUMP_EXECUTOR_PROCESS_LAUNCHER = "gearpump.worker.executor-process-launcher"
- val GEARPUMP_SCHEDULING_SCHEDULER = "gearpump.scheduling.scheduler-class"
- val GEARPUMP_SCHEDULING_REQUEST = "gearpump.scheduling.requests"
- val GEARPUMP_TRANSPORT_SERIALIZER = "gearpump.transport.serializer"
- val GEARPUMP_SERIALIZER_POOL = "gearpump.serialization-framework"
- val GEARPUMP_SERIALIZERS = "gearpump.serializers"
- val GEARPUMP_TASK_DISPATCHER = "gearpump.task-dispatcher"
- val GEARPUMP_CLUSTER_MASTERS = "gearpump.cluster.masters"
- val GEARPUMP_MASTERCLIENT_TIMEOUT = "gearpump.masterclient.timeout"
- val GEARPUMP_CLUSTER_EXECUTOR_WORKER_SHARE_SAME_PROCESS =
- "gearpump.worker.executor-share-same-jvm-as-worker"
-
- val GEARPUMP_HOME = "gearpump.home"
- val GEARPUMP_FULL_SCALA_VERSION = "gearpump.binary-version-with-scala-version"
- val GEARPUMP_HOSTNAME = "gearpump.hostname"
- val GEARPUMP_APPMASTER_ARGS = "gearpump.appmaster.vmargs"
- val GEARPUMP_APPMASTER_EXTRA_CLASSPATH = "gearpump.appmaster.extraClasspath"
- val GEARPUMP_EXECUTOR_ARGS = "gearpump.executor.vmargs"
- val GEARPUMP_EXECUTOR_EXTRA_CLASSPATH = "gearpump.executor.extraClasspath"
- val GEARPUMP_LOG_DAEMON_DIR = "gearpump.log.daemon.dir"
- val GEARPUMP_LOG_APPLICATION_DIR = "gearpump.log.application.dir"
- val HADOOP_CONF = "hadoopConf"
-
- // Id used to identity Master JVM process in low level resource manager like YARN.
- // In YARN, it means the container Id.
- val GEARPUMP_MASTER_RESOURCE_MANAGER_CONTAINER_ID =
- "gearpump.master-resource-manager-container-id"
-
- // Id used to identity Worker JVM process in low level resource manager like YARN.
- // In YARN, it means the container Id.
- val GEARPUMP_WORKER_RESOURCE_MANAGER_CONTAINER_ID =
- "gearpump.worker-resource-manager-container-id"
-
- // true or false
- val GEARPUMP_REMOTE_DEBUG_EXECUTOR_JVM = "gearpump.remote-debug-executor-jvm"
- val GEARPUMP_REMOTE_DEBUG_PORT = "gearpump.remote-debug-port"
-
- // Whether to turn on GC log, true or false
- val GEARPUMP_VERBOSE_GC = "gearpump.verbose-gc"
-
- // The time out for Future, like ask.
- // !Important! This global timeout setting will also impact the UI
- // responsive time if set to too big. Please make sure you have
- // enough justification to change this global setting, otherwise
- // please use your local timeout setting instead.
- val FUTURE_TIMEOUT = akka.util.Timeout(15, TimeUnit.SECONDS)
-
- val GEARPUMP_START_EXECUTOR_SYSTEM_TIMEOUT_MS = "gearpump.start-executor-system-timeout-ms"
-
- val APPMASTER_DEFAULT_EXECUTOR_ID = -1
-
- val NETTY_BUFFER_SIZE = "gearpump.netty.buffer-size"
- val NETTY_MAX_RETRIES = "gearpump.netty.max-retries"
- val NETTY_BASE_SLEEP_MS = "gearpump.netty.base-sleep-ms"
- val NETTY_MAX_SLEEP_MS = "gearpump.netty.max-sleep-ms"
- val NETTY_MESSAGE_BATCH_SIZE = "gearpump.netty.message-batch-size"
- val NETTY_FLUSH_CHECK_INTERVAL = "gearpump.netty.flush-check-interval"
- val NETTY_TCP_HOSTNAME = "akka.remote.netty.tcp.hostname"
- val NETTY_DISPATCHER = "gearpump.netty.dispatcher"
-
- val GEARPUMP_USERNAME = "gearpump.username"
- val GEARPUMP_APPLICATION_ID = "gearpump.applicationId"
- val GEARPUMP_MASTER_STARTTIME = "gearpump.master.starttime"
- val GEARPUMP_EXECUTOR_ID = "gearpump.executorId"
- // Application jar property
- val GEARPUMP_APP_JAR = "gearpump.app.jar"
- val GEARPUMP_APP_NAME_PREFIX = "gearpump.app.name.prefix"
-
- // Where the jar is stored at. It can be a HDFS, or a local disk.
- val GEARPUMP_APP_JAR_STORE_ROOT_PATH = "gearpump.jarstore.rootpath"
-
- // Uses java property -Dgearpump.config.file=xxx.conf to set customized configuration
- // Otherwise application.conf in classpath will be loaded
- val GEARPUMP_CUSTOM_CONFIG_FILE = "gearpump.config.file"
-
- // Metrics related
- val GEARPUMP_METRIC_ENABLED = "gearpump.metrics.enabled"
- val GEARPUMP_METRIC_SAMPLE_RATE = "gearpump.metrics.sample-rate"
- val GEARPUMP_METRIC_REPORT_INTERVAL = "gearpump.metrics.report-interval-ms"
- val GEARPUMP_METRIC_GRAPHITE_HOST = "gearpump.metrics.graphite.host"
- val GEARPUMP_METRIC_GRAPHITE_PORT = "gearpump.metrics.graphite.port"
- val GEARPUMP_METRIC_REPORTER = "gearpump.metrics.reporter"
-
- // Retains at max @RETAIN_HISTORY_HOURS history data
- val GEARPUMP_METRIC_RETAIN_HISTORY_DATA_HOURS = "gearpump.metrics.retainHistoryData.hours"
-
- // Time interval between two history data points.
- val GEARPUMP_RETAIN_HISTORY_DATA_INTERVAL_MS = "gearpump.metrics.retainHistoryData.intervalMs"
-
- // Retains at max @RETAIN_LATEST_SECONDS recent data points
- val GEARPUMP_RETAIN_RECENT_DATA_SECONDS = "gearpump.metrics.retainRecentData.seconds"
-
- // time interval between two recent data points.
- val GEARPUMP_RETAIN_RECENT_DATA_INTERVAL_MS = "gearpump.metrics.retainRecentData.intervalMs"
-
- // AppMaster will max wait this time until it declare the resource cannot be allocated,
- // and shutdown itself
- val GEARPUMP_RESOURCE_ALLOCATION_TIMEOUT = "gearpump.resource-allocation-timeout-seconds"
-
- // Service related
- val GEARPUMP_SERVICE_HTTP = "gearpump.services.http"
- val GEARPUMP_SERVICE_HOST = "gearpump.services.host"
- val GEARPUMP_SERVICE_SUPERVISOR_PATH = "gearpump.services.supervisor-actor-path"
- val GEARPUMP_SERVICE_RENDER_CONFIG_CONCISE = "gearpump.services.config-render-option-concise"
-
- // The partitioners provided by Gearpump
- val BUILTIN_PARTITIONERS = Array(
- classOf[BroadcastPartitioner],
- classOf[CoLocationPartitioner],
- classOf[HashPartitioner],
- classOf[ShuffleGroupingPartitioner],
- classOf[ShufflePartitioner])
-
- // Security related
- val GEARPUMP_KEYTAB_FILE = "gearpump.keytab.file"
- val GEARPUMP_KERBEROS_PRINCIPAL = "gearpump.kerberos.principal"
-
- val GEARPUMP_METRICS_MAX_LIMIT = "gearpump.metrics.akka.max-limit-on-query"
- val GEARPUMP_METRICS_AGGREGATORS = "gearpump.metrics.akka.metrics-aggregator-class"
-
- val GEARPUMP_UI_SECURITY = "gearpump.ui-security"
- val GEARPUMP_UI_SECURITY_AUTHENTICATION_ENABLED = "gearpump.ui-security.authentication-enabled"
- val GEARPUMP_UI_AUTHENTICATOR_CLASS = "gearpump.ui-security.authenticator"
- // OAuth Authentication Factory for UI server.
- val GEARPUMP_UI_OAUTH2_AUTHENTICATOR_ENABLED = "gearpump.ui-security.oauth2-authenticator-enabled"
- val GEARPUMP_UI_OAUTH2_AUTHENTICATORS = "gearpump.ui-security.oauth2-authenticators"
- val GEARPUMP_UI_OAUTH2_AUTHENTICATOR_CLASS = "class"
- val GEARPUMP_UI_OAUTH2_AUTHENTICATOR_CALLBACK = "callback"
- val GEARPUMP_UI_OAUTH2_AUTHENTICATOR_CLIENT_ID = "clientid"
- val GEARPUMP_UI_OAUTH2_AUTHENTICATOR_CLIENT_SECRET = "clientsecret"
- val GEARPUMP_UI_OAUTH2_AUTHENTICATOR_DEFAULT_USER_ROLE = "default-userrole"
- val GEARPUMP_UI_OAUTH2_AUTHENTICATOR_AUTHORIZATION_CODE = "code"
- val GEARPUMP_UI_OAUTH2_AUTHENTICATOR_ACCESS_TOKEN = "accesstoken"
-
- val PREFER_IPV4 = "java.net.preferIPv4Stack"
-
- val APPLICATION_EXECUTOR_NUMBER = "gearpump.application.executor-num"
-
- val AKKA_SCHEDULER_TICK_DURATION = "akka.scheduler.tick-duration"
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/util/FileUtils.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/util/FileUtils.scala b/core/src/main/scala/io/gearpump/util/FileUtils.scala
deleted file mode 100644
index 1561587..0000000
--- a/core/src/main/scala/io/gearpump/util/FileUtils.scala
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.util
-
-import java.io.{File, IOException}
-import java.nio.charset.Charset
-
-import io.gearpump.google.common.io.Files
-
-object FileUtils {
- private val UTF8 = Charset.forName("UTF-8")
-
- def write(file: File, str: String): Unit = {
- Files.write(str, file, UTF8)
- }
-
- def read(file: File): String = {
- Files.asCharSource(file, UTF8).read()
- }
-
- def writeByteArrayToFile(file: File, bytes: Array[Byte]): Unit = {
- Files.write(bytes, file)
- }
-
- def readFileToByteArray(file: File): Array[Byte] = {
- Files.toByteArray(file)
- }
-
- /** recursively making all parent directories including itself */
- def forceMkdir(directory: File): Unit = {
- if (directory.exists() && directory.isFile) {
- throw new IOException(s"Failed to create directory ${directory.toString}, it already exist")
- }
- Files.createParentDirs(directory)
- val result = directory.mkdir()
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/util/Graph.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/util/Graph.scala b/core/src/main/scala/io/gearpump/util/Graph.scala
deleted file mode 100644
index 8c34329..0000000
--- a/core/src/main/scala/io/gearpump/util/Graph.scala
+++ /dev/null
@@ -1,497 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.util
-import scala.annotation.tailrec
-import scala.collection.mutable
-import scala.language.implicitConversions
-
-/**
- * Generic mutable Graph libraries.
- */
-class Graph[N, E](vertexList: List[N], edgeList: List[(N, E, N)]) extends Serializable {
-
- private val _vertices = mutable.Set.empty[N]
- private val _edges = mutable.Set.empty[(N, E, N)]
-
- // This is used to ensure the output of this Graph is always stable
- // Like method vertices(), or edges()
- private var _indexs = Map.empty[Any, Int]
- private var _nextIndex = 0
- private def nextId: Int = {
- val result = _nextIndex
- _nextIndex += 1
- result
- }
-
- private def init(): Unit = {
- Option(vertexList).getOrElse(List.empty[N]).foreach(addVertex(_))
- Option(edgeList).getOrElse(List.empty[(N, E, N)]).foreach(addEdge(_))
- }
-
- init()
-
- /**
- * Add a vertex
- * Current Graph is changed.
- */
- def addVertex(vertex: N): Unit = {
- val result = _vertices.add(vertex)
- if (result) {
- _indexs += vertex -> nextId
- }
- }
-
- /**
- * Add a edge
- * Current Graph is changed.
- */
- def addEdge(edge: (N, E, N)): Unit = {
- val result = _edges.add(edge)
- if (result) {
- _indexs += edge -> nextId
- }
- }
-
- /**
- * return all vertices.
- * The result is stable
- */
- def vertices: List[N] = {
- // Sorts the vertex so that we can keep the order for mapVertex
- _vertices.toList.sortBy(_indexs(_))
- }
-
- /**
- * out degree
- */
- def outDegreeOf(node: N): Int = {
- edges.count(_._1 == node)
- }
-
- /**
- * in degree
- */
- def inDegreeOf(node: N): Int = {
- edges.count(_._3 == node)
- }
-
- /**
- * out going edges.
- */
- def outgoingEdgesOf(node: N): List[(N, E, N)] = {
- edges.filter(_._1 == node)
- }
-
- /**
- * incoming edges.
- */
- def incomingEdgesOf(node: N): List[(N, E, N)] = {
- edges.filter(_._3 == node)
- }
-
- /**
- * Remove vertex
- * Current Graph is changed.
- */
- def removeVertex(node: N): Unit = {
- _vertices.remove(node)
- _indexs -= node
- val toBeRemoved = incomingEdgesOf(node) ++ outgoingEdgesOf(node)
- toBeRemoved.foreach(removeEdge(_))
- }
-
- /**
- * Remove edge
- * Current Graph is changed.
- */
- private def removeEdge(edge: (N, E, N)): Unit = {
- _indexs -= edge
- _edges.remove(edge)
- }
-
- /**
- * add edge
- * Current Graph is changed.
- */
- def addEdge(node1: N, edge: E, node2: N): Unit = {
- addVertex(node1)
- addVertex(node2)
- addEdge((node1, edge, node2))
- }
-
- /**
- * Map a graph to a new graph, with vertex converted to a new type
- * Current Graph is not changed.
- */
- def mapVertex[NewNode](fun: N => NewNode): Graph[NewNode, E] = {
- val vertexes = vertices.map(node => (node, fun(node)))
-
- val vertexMap: Map[N, NewNode] = vertexes.toMap
-
- val newEdges = edges.map { edge =>
- (vertexMap(edge._1), edge._2, vertexMap(edge._3))
- }
- new Graph(vertexes.map(_._2), newEdges)
- }
-
- /**
- * Map a graph to a new graph, with edge converted to new type
- * Current graph is not changed.
- */
- def mapEdge[NewEdge](fun: (N, E, N) => NewEdge): Graph[N, NewEdge] = {
- val newEdges = edges.map { edge =>
- (edge._1, fun(edge._1, edge._2, edge._3), edge._3)
- }
- new Graph(vertices, newEdges)
- }
-
- /**
- * edges connected to node
- */
- def edgesOf(node: N): List[(N, E, N)] = {
- (incomingEdgesOf(node) ++ outgoingEdgesOf(node)).toSet[(N, E, N)].toList.sortBy(_indexs(_))
- }
-
- /**
- * all edges
- */
- def edges: List[(N, E, N)] = {
- _edges.toList.sortBy(_indexs(_))
- }
-
- /**
- * Add another graph
- * Current graph is changed.
- */
- def addGraph(other: Graph[N, E]): Graph[N, E] = {
- (vertices ++ other.vertices).foreach(addVertex(_))
- (edges ++ other.edges).foreach(edge => addEdge(edge._1, edge._2, edge._3))
- this
- }
-
- /**
- * clone the graph
- */
- def copy: Graph[N, E] = {
- new Graph(vertices, edges)
- }
-
- /**
- * check empty
- */
- def isEmpty: Boolean = {
- val vertexCount = vertices.size
- val edgeCount = edges.length
- if (vertexCount + edgeCount == 0) {
- true
- } else {
- false
- }
- }
-
- /**
- * sub-graph which contains current node and all neighbour
- * nodes and edges.
- *
- */
- def subGraph(node: N): Graph[N, E] = {
- val newGraph = Graph.empty[N, E]
- for (edge <- edgesOf(node)) {
- newGraph.addEdge(edge._1, edge._2, edge._3)
- }
- newGraph
- }
-
- /**
- * replace vertex, the current Graph is mutated.
- */
- def replaceVertex(node: N, newNode: N): Graph[N, E] = {
- for (edge <- incomingEdgesOf(node)) {
- addEdge(edge._1, edge._2, newNode)
- }
-
- for (edge <- outgoingEdgesOf(node)) {
- addEdge(newNode, edge._2, edge._3)
- }
- removeVertex(node)
- this
- }
-
- private def removeZeroInDegree: List[N] = {
- val toBeRemoved = vertices.filter(inDegreeOf(_) == 0).sortBy(_indexs(_))
- toBeRemoved.foreach(removeVertex(_))
- toBeRemoved
- }
-
- /**
- * Return an iterator of vertex in topological order
- * The node returned by Iterator is stable sorted.
- */
- def topologicalOrderIterator: Iterator[N] = {
- val newGraph = copy
- var output = List.empty[N]
-
- while (!newGraph.isEmpty) {
- output ++= newGraph.removeZeroInDegree
- }
- output.iterator
- }
-
- /**
- * Return all circles in graph.
- *
- * The reference of this algorithm is:
- * https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
- */
- private def findCircles: mutable.MutableList[mutable.MutableList[N]] = {
- val inStack = mutable.Map.empty[N, Boolean]
- val stack = mutable.Stack[N]()
- val indexMap = mutable.Map.empty[N, Int]
- val lowLink = mutable.Map.empty[N, Int]
- var index = 0
-
- val circles = mutable.MutableList.empty[mutable.MutableList[N]]
-
- def tarjan(node: N): Unit = {
- indexMap(node) = index
- lowLink(node) = index
- index += 1
- inStack(node) = true
- stack.push(node)
-
- outgoingEdgesOf(node).foreach {
- edge => {
- if (!indexMap.contains(edge._3)) {
- tarjan(edge._3)
- if (lowLink.get(edge._3).get < lowLink.get(node).get) {
- lowLink(node) = lowLink(edge._3)
- }
- } else {
- if (inStack.get(edge._3).get && (indexMap.get(edge._3).get < lowLink.get(node).get)) {
- lowLink(node) = indexMap(edge._3)
- }
- }
- }
- }
-
- if (indexMap.get(node).get == lowLink.get(node).get) {
- val circle = mutable.MutableList.empty[N]
- var n = node
- do {
- n = stack.pop()
- inStack(n) = false
- circle += n
- } while (n != node)
- circles += circle
- }
- }
-
- vertices.foreach {
- node => {
- if (!indexMap.contains(node)) tarjan(node)
- }
- }
-
- circles
- }
-
- /**
- * Return an iterator of vertex in topological order of graph with circles
- * The node returned by Iterator is stable sorted.
- *
- * The reference of this algorithm is:
- * http://www.drdobbs.com/database/topological-sorting/184410262
- */
- def topologicalOrderWithCirclesIterator: Iterator[N] = {
- val circles = findCircles
- val newGraph = Graph.empty[mutable.MutableList[N], E]
- circles.foreach {
- circle => {
- newGraph.addVertex(circle)
- }
- }
-
- for (circle1 <- circles; circle2 <- circles; if circle1 != circle2) yield {
- for (node1 <- circle1; node2 <- circle2) yield {
- var edges = outgoingEdgesOf(node1)
- for (edge <- edges; if edge._3 == node2) yield {
- newGraph.addEdge(circle1, edge._2, circle2)
- }
-
- edges = outgoingEdgesOf(node2)
- for (edge <- edges; if edge._3 == node1) yield {
- newGraph.addEdge(circle2, edge._2, circle1)
- }
- }
- }
-
- val topo = newGraph.topologicalOrderIterator
- topo.flatMap(_.sortBy(_indexs(_)).iterator)
- }
-
- /**
- * check whether there is a loop
- */
- def hasCycle(): Boolean = {
- @tailrec
- def detectCycle(graph: Graph[N, E]): Boolean = {
- if (graph.edges.isEmpty) {
- false
- } else if (graph.vertices.nonEmpty && !graph.vertices.exists(graph.inDegreeOf(_) == 0)) {
- true
- } else {
- graph.removeZeroInDegree
- detectCycle(graph)
- }
- }
-
- detectCycle(copy)
- }
-
- /**
- * Check whether there are two edges connecting two nodes.
- */
- def hasDuplicatedEdge(): Boolean = {
- edges.groupBy(edge => (edge._1, edge._3)).values.exists(_.size > 1)
- }
-
- /**
- * Generate a level map for each vertex withholding:
- * {{{
- * if vertex A -> B, then level(A) -> level(B)
- * }}}
- */
- def vertexHierarchyLevelMap(): Map[N, Int] = {
- val newGraph = copy
- var output = Map.empty[N, Int]
- var level = 0
- while (!newGraph.isEmpty) {
- output ++= newGraph.removeZeroInDegree.map((_, level)).toMap
- level += 1
- }
- output
- }
-
- override def toString: String = {
- Map("vertices" -> vertices.mkString(","),
- "edges" -> edges.mkString(",")).toString()
- }
-}
-
-object Graph {
-
- /**
- * Example:
- *
- * {{{
- * Graph(1 ~ 2 ~> 4 ~ 5 ~> 7, 8~9~>55, 11)
- * Will create a graph with:
- * nodes:
- * 1, 4, 7, 8, 55, 11
- * edge:
- * 2: (1->4)
- * 5: (4->7)
- * 9: (8->55)
- * }}}
- */
- def apply[N, E](elems: Path[_ <: N, _ <: E]*): Graph[N, E] = {
- val graph = empty[N, E]
- elems.foreach { path =>
- path.updategraph(graph)
- }
- graph
- }
-
- def apply[N, E](vertices: List[N], edges: List[(N, E, N)]): Graph[N, E] = {
- new Graph(vertices, edges)
- }
-
- def unapply[N, E](graph: Graph[N, E]): Option[(List[N], List[(N, E, N)])] = {
- Some((graph.vertices, graph.edges))
- }
-
- def empty[N, E]: Graph[N, E] = {
- new Graph(List.empty[N], List.empty[(N, E, N)])
- }
-
- class Path[N, + E](path: List[Either[N, E]]) {
-
- def ~[Edge >: E](edge: Edge): Path[N, Edge] = {
- new Path(path :+ Right(edge))
- }
-
- def ~>[Node >: N](node: Node): Path[Node, E] = {
- new Path(path :+ Left(node))
- }
-
- def to[Node >: N, Edge >: E](node: Node, edge: Edge): Path[Node, Edge] = {
- this ~ edge ~> node
- }
-
- private[Graph] def updategraph[Node >: N, Edge >: E](graph: Graph[Node, Edge]): Unit = {
- val nodeEdgePair: Tuple2[Option[N], Option[E]] = (None, None)
- path.foldLeft(nodeEdgePair) { (pair, either) =>
- val (lastNode, lastEdge) = pair
- either match {
- case Left(node) =>
- graph.addVertex(node)
- if (lastNode.isDefined) {
- graph.addEdge(lastNode.get, lastEdge.getOrElse(null.asInstanceOf[Edge]), node)
- }
- (Some(node), None)
- case Right(edge) =>
- (lastNode, Some(edge))
- }
- }
- }
- }
-
- object Path {
- implicit def anyToPath[N, E](any: N): Path[N, E] = Node(any)
- }
-
- implicit class Node[N, E](self: N) extends Path[N, E](List(Left(self))) {
-
- override def ~[Edge](edge: Edge): Path[N, Edge] = {
- new Path(List(Left(self), Right(edge)))
- }
-
- override def ~>[Node >: N](node: Node): Path[Node, E] = {
- new NodeList(List(self, node))
- }
-
- override def to[Node >: N, Edge >: E](node: Node, edge: Edge): Path[Node, Edge] = {
- this ~ edge ~> node
- }
- }
-
- class NodeList[N, E](nodes: List[N]) extends Path[N, E](nodes.map(Left(_))) {
- override def ~[Edge](edge: Edge): Path[N, Edge] = {
- new Path(nodes.map(Left(_)) :+ Right(edge))
- }
-
- override def ~>[Node >: N](node: Node): Path[Node, E] = {
- new NodeList(nodes :+ node)
- }
-
- override def to[Node >: N, Edge >: E](node: Node, edge: Edge): Path[Node, Edge] = {
- this ~ edge ~> node
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/util/HistoryMetricsService.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/util/HistoryMetricsService.scala b/core/src/main/scala/io/gearpump/util/HistoryMetricsService.scala
deleted file mode 100644
index 7552444..0000000
--- a/core/src/main/scala/io/gearpump/util/HistoryMetricsService.scala
+++ /dev/null
@@ -1,404 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.util
-
-import java.util
-import scala.collection.mutable.ListBuffer
-
-import akka.actor.Actor
-import com.typesafe.config.Config
-import org.slf4j.Logger
-
-import io.gearpump.TimeStamp
-import io.gearpump.cluster.ClientToMaster.{QueryHistoryMetrics, ReadOption}
-import io.gearpump.cluster.MasterToClient.{HistoryMetrics, HistoryMetricsItem}
-import io.gearpump.metrics.Metrics._
-import io.gearpump.metrics.MetricsAggregator
-import io.gearpump.util.Constants._
-import io.gearpump.util.HistoryMetricsService.{DummyMetricsAggregator, HistoryMetricsConfig, HistoryMetricsStore, SkipAllAggregator}
-
-/**
- *
- * Metrics service to serve history metrics data
- *
- * For simplicity, HistoryMetricsService will maintain 72 hours coarse-grained data
- * for last 72 hours, and fine-grained data for past 5 min.
- *
- * For the coarse-grained data of past 72 hours, one or two sample point will be stored
- * for each hour.
- *
- * For fine-grained data in last 5 min, there will be 1 sample point per 15 seconds.
- */
-class HistoryMetricsService(name: String, config: HistoryMetricsConfig) extends Actor {
- private val LOG: Logger = LogUtil.getLogger(getClass, name = name)
- private var metricsStore = Map.empty[String, HistoryMetricsStore]
- private val systemConfig = context.system.settings.config
-
- def receive: Receive = metricHandler orElse commandHandler
- def metricHandler: Receive = {
- case ReportMetrics =>
- sender ! DemandMoreMetrics(self)
- case metrics: MetricType =>
- val name = metrics.name
- if (metricsStore.contains(name)) {
- metricsStore(name).add(metrics)
- } else {
- val store = HistoryMetricsStore(name, metrics, config)
- metricsStore += name -> store
- store.add(metrics)
- }
- }
-
- private def toRegularExpression(input: String): String = {
- "^" + input.flatMap {
- case '*' => ".*"
- case '?' => "."
- case char if "()[]$^.{}|\\".contains(char) => "\\" + char
- case other => s"$other"
- } + ".*$"
- }
-
- private def fetchMetricsHistory(pathPattern: String, readOption: ReadOption.ReadOption)
- : List[HistoryMetricsItem] = {
-
- val result = new ListBuffer[HistoryMetricsItem]
-
- val regex = toRegularExpression(pathPattern).r.pattern
-
- val iter = metricsStore.iterator
- while (iter.hasNext) {
- val (name, store) = iter.next()
-
- val matcher = regex.matcher(name)
- if (matcher.matches()) {
- readOption match {
- case ReadOption.ReadLatest =>
- result.append(store.readLatest: _*)
- case ReadOption.ReadRecent =>
- result.append(store.readRecent: _*)
- case ReadOption.ReadHistory =>
- result.append(store.readHistory: _*)
- case _ =>
- // Skip all other options.
- }
- }
- }
- result.toList
- }
-
- val dummyAggregator = new DummyMetricsAggregator
- private var aggregators: Map[String, MetricsAggregator] = Map.empty[String, MetricsAggregator]
-
- import scala.collection.JavaConverters._
- private val validAggregators: Set[String] = {
- val rootConfig = systemConfig.getConfig(Constants.GEARPUMP_METRICS_AGGREGATORS).root.unwrapped
- rootConfig.keySet().asScala.toSet
- }
-
- def commandHandler: Receive = {
- // Path accept syntax ? *, ? will match one char, * will match at least one char
- case QueryHistoryMetrics(inputPath, readOption, aggregatorClazz, options) =>
-
- val aggregator = {
- if (aggregatorClazz == null || aggregatorClazz.isEmpty) {
- dummyAggregator
- } else if (aggregators.contains(aggregatorClazz)) {
- aggregators(aggregatorClazz)
- } else if (validAggregators.contains(aggregatorClazz)) {
- val clazz = Class.forName(aggregatorClazz)
- val constructor = clazz.getConstructor(classOf[Config])
- val aggregator = constructor.newInstance(systemConfig).asInstanceOf[MetricsAggregator]
- aggregators += aggregatorClazz -> aggregator
- aggregator
- } else {
- LOG.error(s"Aggregator $aggregatorClazz is not in the white list ${validAggregators}, " +
- s"we will drop all messages. Please see config at ${GEARPUMP_METRICS_AGGREGATORS}")
- val skipAll = new SkipAllAggregator
- aggregators += aggregatorClazz -> new SkipAllAggregator
- skipAll
- }
- }
-
- val metrics = fetchMetricsHistory(inputPath, readOption).iterator
- sender ! HistoryMetrics(inputPath, aggregator.aggregate(options, metrics))
- }
-}
-
-object HistoryMetricsService {
-
- trait MetricsStore {
- def add(inputMetrics: MetricType): Unit
-
- def read: List[HistoryMetricsItem]
-
- /**
- * read latest inserted records
- * @return
- */
- def readLatest: List[HistoryMetricsItem]
- }
-
- trait HistoryMetricsStore {
- def add(inputMetrics: MetricType): Unit
-
- /**
- * read latest inserted records
- * @return
- */
- def readLatest: List[HistoryMetricsItem]
-
- def readRecent: List[HistoryMetricsItem]
-
- def readHistory: List[HistoryMetricsItem]
- }
-
- class DummyHistoryMetricsStore extends HistoryMetricsStore {
-
- val empty = List.empty[HistoryMetricsItem]
-
- override def add(inputMetrics: MetricType): Unit = Unit
-
- override def readRecent: List[HistoryMetricsItem] = empty
-
- /**
- * read latest inserted records
- * @return
- */
- override def readLatest: List[HistoryMetricsItem] = empty
-
- override def readHistory: List[HistoryMetricsItem] = empty
- }
-
- object HistoryMetricsStore {
- def apply(name: String, metric: MetricType, config: HistoryMetricsConfig)
- : HistoryMetricsStore = {
- metric match {
- case histogram: Histogram => new HistogramMetricsStore(config)
- case meter: Meter => new MeterMetricsStore(config)
- case counter: Counter => new CounterMetricsStore(config)
- case gauge: Gauge => new GaugeMetricsStore(config)
- case _ => new DummyHistoryMetricsStore // other metrics are not supported
- }
- }
- }
-
- /**
- * Metrics store to store history data points
- * For each time point, we will store single data point.
- *
- * @param retainCount how many data points to retain, old data will be removed
- * @param retainIntervalMs time interval between two data points.
- */
- class SingleValueMetricsStore(retainCount: Int, retainIntervalMs: Long) extends MetricsStore {
-
- private val queue = new util.ArrayDeque[HistoryMetricsItem]()
- private var latest = List.empty[HistoryMetricsItem]
-
- // End of the time window we are tracking
- private var endTime = 0L
-
- override def add(inputMetrics: MetricType): Unit = {
- add(inputMetrics, System.currentTimeMillis())
- }
-
- def add(inputMetrics: MetricType, now: TimeStamp): Unit = {
-
- val metrics = HistoryMetricsItem(now, inputMetrics)
- latest = List(metrics)
-
- if (now >= endTime) {
- queue.addFirst(metrics)
- endTime = (now / retainIntervalMs + 1) * retainIntervalMs
-
- // Removes old data
- if (queue.size() > retainCount) {
- queue.removeLast()
- }
- }
- }
-
- def read: List[HistoryMetricsItem] = {
- val result = new ListBuffer[HistoryMetricsItem]
- import scala.collection.JavaConverters._
- queue.iterator().asScala.foreach(result.prepend(_))
- result.toList
- }
-
- override def readLatest: List[HistoryMetricsItem] = {
- latest
- }
- }
-
- /**
- * Config for how long to keep history metrics data.
- *
- * @param retainHistoryDataHours Retain at max @RETAIN_HISTORY_HOURS history data(unit hour)
- * @param retainHistoryDataIntervalMs time interval between two history data points.(unit: ms)
- * @param retainRecentDataSeconds Retain at max @RETAIN_LATEST_SECONDS
- * recent data points(unit: seconds)
- * @param retainRecentDataIntervalMs Retain at max @RETAIN_LATEST_SECONDS recent
- * data points(unit: ms)
- */
- case class HistoryMetricsConfig(
- retainHistoryDataHours: Int,
- retainHistoryDataIntervalMs: Int,
- retainRecentDataSeconds: Int,
- retainRecentDataIntervalMs: Int)
-
- object HistoryMetricsConfig {
- def apply(config: Config): HistoryMetricsConfig = {
- val historyHour = config.getInt(GEARPUMP_METRIC_RETAIN_HISTORY_DATA_HOURS)
- val historyInterval = config.getInt(GEARPUMP_RETAIN_HISTORY_DATA_INTERVAL_MS)
-
- val recentSeconds = config.getInt(GEARPUMP_RETAIN_RECENT_DATA_SECONDS)
- val recentInterval = config.getInt(GEARPUMP_RETAIN_RECENT_DATA_INTERVAL_MS)
- HistoryMetricsConfig(historyHour, historyInterval, recentSeconds, recentInterval)
- }
- }
-
- class HistogramMetricsStore(config: HistoryMetricsConfig) extends HistoryMetricsStore {
-
- private val history = new SingleValueMetricsStore(
- config.retainHistoryDataHours * 3600 * 1000 / config.retainHistoryDataIntervalMs,
- config.retainHistoryDataIntervalMs)
-
- private val recent = new SingleValueMetricsStore(
- config.retainRecentDataSeconds * 1000 / config.retainRecentDataIntervalMs,
- config.retainRecentDataIntervalMs)
-
- override def add(inputMetrics: MetricType): Unit = {
- recent.add(inputMetrics)
- history.add(inputMetrics)
- }
-
- override def readRecent: List[HistoryMetricsItem] = {
- recent.read
- }
-
- override def readHistory: List[HistoryMetricsItem] = {
- history.read
- }
-
- override def readLatest: List[HistoryMetricsItem] = {
- recent.readLatest
- }
- }
-
- class MeterMetricsStore(config: HistoryMetricsConfig) extends HistoryMetricsStore {
-
- private val history = new SingleValueMetricsStore(
- config.retainHistoryDataHours * 3600 * 1000 / config.retainHistoryDataIntervalMs,
- config.retainHistoryDataIntervalMs)
-
- private val recent = new SingleValueMetricsStore(
- config.retainRecentDataSeconds * 1000 / config.retainRecentDataIntervalMs,
- config.retainRecentDataIntervalMs)
-
- override def add(inputMetrics: MetricType): Unit = {
- recent.add(inputMetrics)
- history.add(inputMetrics)
- }
-
- override def readRecent: List[HistoryMetricsItem] = {
- recent.read
- }
-
- override def readHistory: List[HistoryMetricsItem] = {
- history.read
- }
-
- override def readLatest: List[HistoryMetricsItem] = {
- recent.readLatest
- }
- }
-
- class CounterMetricsStore(config: HistoryMetricsConfig) extends HistoryMetricsStore {
-
- private val history = new SingleValueMetricsStore(
- config.retainHistoryDataHours * 3600 * 1000 / config.retainHistoryDataIntervalMs,
- config.retainHistoryDataIntervalMs)
-
- private val recent = new SingleValueMetricsStore(
- config.retainRecentDataSeconds * 1000 / config.retainRecentDataIntervalMs,
- config.retainRecentDataIntervalMs)
-
- override def add(inputMetrics: MetricType): Unit = {
- history.add(inputMetrics)
- recent.add(inputMetrics)
- }
-
- override def readRecent: List[HistoryMetricsItem] = {
- recent.read
- }
-
- override def readHistory: List[HistoryMetricsItem] = {
- history.read
- }
-
- override def readLatest: List[HistoryMetricsItem] = {
- recent.readLatest
- }
- }
-
- class GaugeMetricsStore(config: HistoryMetricsConfig) extends HistoryMetricsStore {
-
- private val compartor = (left: HistoryMetricsItem, right: HistoryMetricsItem) =>
- left.value.asInstanceOf[Gauge].value > right.value.asInstanceOf[Gauge].value
-
- private val history = new SingleValueMetricsStore(
- config.retainHistoryDataHours * 3600 * 1000 / config.retainHistoryDataIntervalMs,
- config.retainHistoryDataIntervalMs)
-
- private val recent = new SingleValueMetricsStore(
- config.retainRecentDataSeconds * 1000 / config.retainRecentDataIntervalMs,
- config.retainRecentDataIntervalMs)
-
- override def add(inputMetrics: MetricType): Unit = {
- recent.add(inputMetrics)
- history.add(inputMetrics)
- }
-
- override def readRecent: List[HistoryMetricsItem] = {
- recent.read
- }
-
- override def readHistory: List[HistoryMetricsItem] = {
- history.read
- }
-
- override def readLatest: List[HistoryMetricsItem] = {
- recent.readLatest
- }
- }
-
- class DummyMetricsAggregator extends MetricsAggregator {
- def aggregate(options: Map[String, String], inputs: Iterator[HistoryMetricsItem])
- : List[HistoryMetricsItem] = {
- inputs.toList
- }
- }
-
- class SkipAllAggregator extends MetricsAggregator {
- private val empty = List.empty[HistoryMetricsItem]
- def aggregate(options: Map[String, String], inputs: Iterator[HistoryMetricsItem])
- : List[HistoryMetricsItem] = {
- empty
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/util/LogUtil.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/util/LogUtil.scala b/core/src/main/scala/io/gearpump/util/LogUtil.scala
deleted file mode 100644
index 1669129..0000000
--- a/core/src/main/scala/io/gearpump/util/LogUtil.scala
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.util
-
-import java.io.File
-import java.net.InetAddress
-import java.util.Properties
-import scala.util.Try
-
-import com.typesafe.config.Config
-import org.apache.log4j.PropertyConfigurator
-import org.slf4j.{Logger, LoggerFactory}
-
-object LogUtil {
- object ProcessType extends Enumeration {
- type ProcessType = Value
- val MASTER, WORKER, LOCAL, APPLICATION, UI = Value
- }
-
- def getLogger[T](
- clazz: Class[T], context: String = null, master: Any = null, worker: Any = null,
- executor: Any = null, task: Any = null, app: Any = null, name: String = null): Logger = {
- var env = ""
-
- if (null != context) {
- env += context
- }
- if (null != master) {
- env += "master" + master
- }
- if (null != worker) {
- env += "worker" + worker
- }
-
- if (null != app) {
- env += "app" + app
- }
-
- if (null != executor) {
- env += "exec" + executor
- }
- if (null != task) {
- env += task
- }
- if (null != name) {
- env += name
- }
-
- if (!env.isEmpty) {
- LoggerFactory.getLogger(clazz.getSimpleName + "@" + env)
- } else {
- LoggerFactory.getLogger(clazz.getSimpleName)
- }
- }
-
- /** Custom the log file locations by reading config from system properties */
- def loadConfiguration(config: Config, processType: ProcessType.ProcessType): Unit = {
- // Set log file name
- val propName = s"gearpump.${processType.toString.toLowerCase}.log.file"
- val props = loadConfiguration
-
- props.setProperty("gearpump.log.file", "${" + propName + "}")
-
- props.setProperty("JVM_NAME", jvmName)
-
- processType match {
- case ProcessType.APPLICATION =>
- props.setProperty("log4j.rootAppender", "${gearpump.application.logger}")
- props.setProperty("gearpump.application.log.rootdir",
- applicationLogDir(config).getAbsolutePath)
- case _ =>
- props.setProperty("log4j.rootAppender", "${gearpump.root.logger}")
- props.setProperty("gearpump.log.dir", daemonLogDir(config).getAbsolutePath)
- }
-
- PropertyConfigurator.configure(props)
- }
-
- def daemonLogDir(config: Config): File = {
- val dir = config.getString(Constants.GEARPUMP_LOG_DAEMON_DIR)
- new File(dir)
- }
-
- def verboseLogToConsole(): Unit = {
- val props = loadConfiguration
- props.setProperty("log4j.rootLogger", "DEBUG,console")
- PropertyConfigurator.configure(props)
- }
-
- def loadConfiguration: Properties = {
- val props = new Properties()
- val log4jConfStream = getClass().getClassLoader.getResourceAsStream("log4j.properties")
- if (log4jConfStream != null) {
- props.load(log4jConfStream)
- }
- log4jConfStream.close()
- props
- }
-
- private def jvmName: String = {
- val hostname = Try(InetAddress.getLocalHost.getHostName).getOrElse("local")
- java.lang.management.ManagementFactory.getRuntimeMXBean().getName()
- }
-
- def applicationLogDir(config: Config): File = {
- val appLogDir = config.getString(Constants.GEARPUMP_LOG_APPLICATION_DIR)
- new File(appLogDir)
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/util/ProcessLogRedirector.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/util/ProcessLogRedirector.scala b/core/src/main/scala/io/gearpump/util/ProcessLogRedirector.scala
deleted file mode 100644
index 0b843f3..0000000
--- a/core/src/main/scala/io/gearpump/util/ProcessLogRedirector.scala
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.util
-
-import java.io.{Closeable, Flushable}
-import scala.sys.process.ProcessLogger
-
-import org.slf4j.LoggerFactory
-
-/** Redirect the console output to parent process */
-class ProcessLogRedirector extends ProcessLogger with Closeable with Flushable with ConsoleOutput {
- private val LOG = LoggerFactory.getLogger("redirect")
-
- // We only capture the first 1K chars
- private final val LENGTH = 1000
- private var _error: String = ""
- private var _output: String = ""
-
- def error: String = _error
- def output: String = _output
-
- def out(s: => String): Unit = {
- if (_output.length <= LENGTH) {
- _output += "\n" + s
- }
- LOG.info(s)
- }
- def err(s: => String): Unit = {
- if (_error.length <= LENGTH) {
- _error += "\n" + s
- }
- LOG.error(s)
- }
- def buffer[T](f: => T): T = f
- def close(): Unit = Unit
- def flush(): Unit = Unit
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/util/ReferenceEqual.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/util/ReferenceEqual.scala b/core/src/main/scala/io/gearpump/util/ReferenceEqual.scala
deleted file mode 100644
index f6c7a2b..0000000
--- a/core/src/main/scala/io/gearpump/util/ReferenceEqual.scala
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.util
-
-/**
- * Check equal using reference-equal.
- */
-trait ReferenceEqual extends AnyRef {
-
- override def equals(other: Any): Boolean = {
- this.eq(other.asInstanceOf[AnyRef])
- }
-
- override def hashCode(): Int = {
- super.hashCode()
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/util/RestartPolicy.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/util/RestartPolicy.scala b/core/src/main/scala/io/gearpump/util/RestartPolicy.scala
deleted file mode 100644
index 245cb1b..0000000
--- a/core/src/main/scala/io/gearpump/util/RestartPolicy.scala
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.util
-
-import scala.concurrent.duration.Duration
-
-import akka.actor.ChildRestartStats
-
-/**
- * When one executor or task fails, Gearpump will try to start. However, if it fails after
- * multiple retries, then we abort.
- *
- * @param maxNrOfRetries The number of times is allowed to be restarted, negative value means no
- * limit, if the limit is exceeded the policy will not allow to restart
- * @param withinTimeRange Duration of the time window for maxNrOfRetries.
- * Duration.Inf means no window
- */
-class RestartPolicy(maxNrOfRetries: Int, withinTimeRange: Duration) {
- private val status = new ChildRestartStats(null, 0, 0L)
- private val retriesWindow = (Some(maxNrOfRetries), Some(withinTimeRange.toMillis.toInt))
-
- def allowRestart: Boolean = {
- status.requestRestartPermission(retriesWindow)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/util/RichProcess.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/util/RichProcess.scala b/core/src/main/scala/io/gearpump/util/RichProcess.scala
deleted file mode 100644
index ab5611f..0000000
--- a/core/src/main/scala/io/gearpump/util/RichProcess.scala
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.util
-
-import scala.sys.process.Process
-
-trait ConsoleOutput {
- def output: String
- def error: String
-}
-
-/** Extends Process by providing a additional logger: ConsoleOutput interface. */
-class RichProcess(process: Process, _logger: ConsoleOutput) extends Process {
- def exitValue(): scala.Int = process.exitValue()
- def destroy(): scala.Unit = process.destroy()
- def logger: ConsoleOutput = _logger
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/util/TimeOutScheduler.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/util/TimeOutScheduler.scala b/core/src/main/scala/io/gearpump/util/TimeOutScheduler.scala
deleted file mode 100644
index 64b920c..0000000
--- a/core/src/main/scala/io/gearpump/util/TimeOutScheduler.scala
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.util
-
-import java.util.concurrent.TimeUnit
-import scala.concurrent.duration._
-
-import akka.actor.{Actor, ActorRef}
-import akka.pattern.ask
-
-/** A helper util to send a message to remote actor and notify callback when timeout */
-trait TimeOutScheduler {
- this: Actor =>
- import context.dispatcher
-
- def sendMsgWithTimeOutCallBack(
- target: ActorRef, msg: AnyRef, milliSeconds: Long, timeOutHandler: => Unit): Unit = {
- val result = target.ask(msg)(FiniteDuration(milliSeconds, TimeUnit.MILLISECONDS))
- result onSuccess {
- case msg =>
- self ! msg
- }
- result onFailure {
- case _ => timeOutHandler
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/util/Util.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/util/Util.scala b/core/src/main/scala/io/gearpump/util/Util.scala
deleted file mode 100644
index 8ed9bb3..0000000
--- a/core/src/main/scala/io/gearpump/util/Util.scala
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.util
-
-import java.io.{BufferedReader, File, FileInputStream, InputStreamReader}
-import java.net.{ServerSocket, URI}
-import scala.concurrent.forkjoin.ThreadLocalRandom
-import scala.sys.process.Process
-import scala.util.{Failure, Success, Try}
-
-import com.typesafe.config.{Config, ConfigFactory}
-
-import io.gearpump.cluster.AppJar
-import io.gearpump.jarstore.JarStoreService
-import io.gearpump.transport.HostPort
-
-object Util {
- val LOG = LogUtil.getLogger(getClass)
- private val defaultUri = new URI("file:///")
- private val appNamePattern = "^[a-zA-Z_][a-zA-Z0-9_]+$".r.pattern
-
- def validApplicationName(appName: String): Boolean = {
- appNamePattern.matcher(appName).matches()
- }
-
- def getCurrentClassPath: Array[String] = {
- val classpath = System.getProperty("java.class.path")
- val classpathList = classpath.split(File.pathSeparator)
- classpathList
- }
-
- def version: String = {
- val home = System.getProperty(Constants.GEARPUMP_HOME)
- val version = Try {
- val versionFile = new FileInputStream(new File(home, "VERSION"))
- val reader = new BufferedReader(new InputStreamReader(versionFile))
- val version = reader.readLine().replace("version:=", "")
- versionFile.close()
- version
- }
- version match {
- case Success(version) =>
- version
- case Failure(ex) =>
- LOG.error("failed to read VERSION file, " + ex.getMessage)
- "Unknown-Version"
- }
- }
-
- def startProcess(options: Array[String], classPath: Array[String], mainClass: String,
- arguments: Array[String]): RichProcess = {
- val java = System.getProperty("java.home") + "/bin/java"
- val command = List(java) ++ options ++
- List("-cp", classPath.mkString(File.pathSeparator), mainClass) ++ arguments
- LOG.info(s"Starting executor process java $mainClass ${arguments.mkString(" ")} " +
- s"\n ${options.mkString(" ")}")
- val logger = new ProcessLogRedirector()
- val process = Process(command).run(logger)
- new RichProcess(process, logger)
- }
-
- /**
- * hostList format: host1:port1,host2:port2,host3:port3...
- */
- def parseHostList(hostList: String): List[HostPort] = {
- val masters = hostList.trim.split(",").map { address =>
- val hostAndPort = address.split(":")
- HostPort(hostAndPort(0), hostAndPort(1).toInt)
- }
- masters.toList
- }
-
- def resolvePath(path: String): String = {
- val uri = new URI(path)
- if (uri.getScheme == null && uri.getFragment == null) {
- val absolutePath = new File(path).getCanonicalPath.replaceAll("\\\\", "/")
- "file://" + absolutePath
- } else {
- path
- }
- }
-
- def isLocalPath(path: String): Boolean = {
- val uri = new URI(path)
- val scheme = uri.getScheme
- val authority = uri.getAuthority
- if (scheme == null && authority == null) {
- true
- } else if (scheme == defaultUri.getScheme) {
- true
- } else {
- false
- }
- }
-
- def randInt(): Int = {
- Math.abs(ThreadLocalRandom.current.nextInt())
- }
-
- def findFreePort(): Try[Int] = {
- Try {
- val socket = new ServerSocket(0)
- socket.setReuseAddress(true)
- val port = socket.getLocalPort()
- socket.close
- port
- }
- }
-
- def uploadJar(jarFile: File, jarStoreService: JarStoreService): AppJar = {
- val remotePath = jarStoreService.copyFromLocal(jarFile)
- AppJar(jarFile.getName, remotePath)
- }
-
- /**
- * This util can be used to filter out configuration from specific origin
- *
- * For example, if you want to filter out configuration from reference.conf
- * Then you can use like this:
- *
- * filterOutOrigin(config, "reference.conf")
- */
- import scala.collection.JavaConverters._
- def filterOutOrigin(config: Config, originFile: String): Config = {
- config.entrySet().asScala.foldLeft(ConfigFactory.empty()) { (config, entry) =>
- val key = entry.getKey
- val value = entry.getValue
- val origin = value.origin()
- if (origin.resource() == originFile) {
- config
- } else {
- config.withValue(key, value)
- }
- }
- }
-
- case class JvmSetting(vmargs: Array[String], classPath: Array[String])
-
- case class AppJvmSettings(appMater: JvmSetting, executor: JvmSetting)
-
- /** Get an effective AppJvmSettings from Config */
- def resolveJvmSetting(conf: Config): AppJvmSettings = {
-
- import io.gearpump.util.Constants._
-
- val appMasterVMArgs = Try(conf.getString(GEARPUMP_APPMASTER_ARGS).split("\\s+")
- .filter(_.nonEmpty)).toOption
- val executorVMArgs = Try(conf.getString(GEARPUMP_EXECUTOR_ARGS).split("\\s+")
- .filter(_.nonEmpty)).toOption
-
- val appMasterClassPath = Try(
- conf.getString(GEARPUMP_APPMASTER_EXTRA_CLASSPATH)
- .split("[;:]").filter(_.nonEmpty)).toOption
-
- val executorClassPath = Try(
- conf.getString(GEARPUMP_EXECUTOR_EXTRA_CLASSPATH)
- .split(File.pathSeparator).filter(_.nonEmpty)).toOption
-
- AppJvmSettings(
- JvmSetting(appMasterVMArgs.getOrElse(Array.empty[String]),
- appMasterClassPath.getOrElse(Array.empty[String])),
- JvmSetting(executorVMArgs
- .getOrElse(Array.empty[String]), executorClassPath.getOrElse(Array.empty[String])))
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/Message.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/Message.scala b/core/src/main/scala/org/apache/gearpump/Message.scala
new file mode 100644
index 0000000..871ebe1
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/Message.scala
@@ -0,0 +1,32 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump
+
+/**
+ * Each message contains a immutable timestamp.
+ *
+ * For example, if you take a picture, the time you take the picture is the
+ * message's timestamp.
+ * @param msg Accept any type except Null, Nothing and Unit
+ */
+case class Message(msg: Any, timestamp: TimeStamp = Message.noTimeStamp)
+
+object Message {
+ val noTimeStamp: TimeStamp = 0L
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/cluster/AppDescription.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/cluster/AppDescription.scala b/core/src/main/scala/org/apache/gearpump/cluster/AppDescription.scala
new file mode 100644
index 0000000..91c2675
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/cluster/AppDescription.scala
@@ -0,0 +1,145 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster
+
+import scala.reflect.ClassTag
+
+import akka.actor.{Actor, ActorRef, ActorSystem}
+import com.typesafe.config.{Config, ConfigFactory}
+
+import org.apache.gearpump.cluster.appmaster.WorkerInfo
+import org.apache.gearpump.cluster.scheduler.Resource
+import org.apache.gearpump.jarstore.FilePath
+
+/**
+ * This contains all information to run an application
+ *
+ * @param name The name of this application
+ * @param appMaster The class name of AppMaster Actor
+ * @param userConfig user configuration.
+ * @param clusterConfig User provided cluster config, it overrides gear.conf when starting
+ * new applications. In most cases, you should not need to change it. If you do
+ * really need to change it, please use ClusterConfigSource(filePath) to
+ * construct the object, while filePath points to the .conf file.
+ */
+case class AppDescription(
+ name: String, appMaster: String, userConfig: UserConfig,
+ clusterConfig: Config = ConfigFactory.empty())
+
+/**
+ * Each job, streaming or not streaming, need to provide an Application class.
+ * The master uses this class to start AppMaster.
+ */
+trait Application {
+
+ /** Name of this application, must be unique in the system */
+ def name: String
+
+ /** Custom user configuration */
+ def userConfig(implicit system: ActorSystem): UserConfig
+
+ /**
+ * AppMaster class, must have a constructor like this:
+ * this(appContext: AppMasterContext, app: AppDescription)
+ */
+ def appMaster: Class[_ <: ApplicationMaster]
+}
+
+object Application {
+ def apply[T <: ApplicationMaster](
+ name: String, userConfig: UserConfig)(implicit tag: ClassTag[T]): Application = {
+ new DefaultApplication(name, userConfig,
+ tag.runtimeClass.asInstanceOf[Class[_ <: ApplicationMaster]])
+ }
+
+ class DefaultApplication(
+ override val name: String, inputUserConfig: UserConfig,
+ val appMaster: Class[_ <: ApplicationMaster]) extends Application {
+ override def userConfig(implicit system: ActorSystem): UserConfig = inputUserConfig
+ }
+
+ def ApplicationToAppDescription(app: Application)(implicit system: ActorSystem)
+ : AppDescription = {
+ val filterJvmReservedKeys = ClusterConfig.filterOutDefaultConfig(system.settings.config)
+ AppDescription(app.name, app.appMaster.getName, app.userConfig, filterJvmReservedKeys)
+ }
+}
+
+/**
+ * Used for verification. All AppMaster must extend this interface
+ */
+abstract class ApplicationMaster extends Actor
+
+/**
+ * This contains context information when starting an AppMaster
+ *
+ * @param appId application instance id assigned, it is unique in the cluster
+ * @param username The username who submitted this application
+ * @param resource Resouce allocated to start this AppMaster daemon. AppMaster are allowed to
+ * request more resource from Master.
+ * @param appJar application Jar. If the jar is already in classpath, then it can be None.
+ * @param masterProxy The proxy to master actor, it bridges the messages between appmaster
+ * and master
+ * @param registerData AppMaster are required to send this data to Master by when doing
+ * RegisterAppMaster.
+ */
+case class AppMasterContext(
+ appId: Int,
+ username: String,
+ resource: Resource,
+ workerInfo: WorkerInfo,
+ appJar: Option[AppJar],
+ masterProxy: ActorRef,
+ registerData: AppMasterRegisterData)
+
+/**
+ * Jar file container in the cluster
+ *
+ * @param name A meaningful name to represent this jar
+ * @param filePath Where the jar file is stored.
+ */
+case class AppJar(name: String, filePath: FilePath)
+
+/**
+ * Serves as the context to start an Executor JVM.
+ */
+// TODO: ExecutorContext doesn't belong to this package in logic.
+case class ExecutorContext(
+ executorId: Int, worker: WorkerInfo, appId: Int, appName: String,
+ appMaster: ActorRef, resource: Resource)
+
+/**
+ * JVM configurations to start an Executor JVM.
+ *
+ * @param classPath When executor is created by a worker JVM, executor automatically inherits
+ * parent worker's classpath. Sometimes, you still want to add some extra
+ * classpath, you can do this by specify classPath option.
+ * @param jvmArguments java arguments like -Dxx=yy
+ * @param mainClass Executor main class name like org.apache.gearpump.xx.AppMaster
+ * @param arguments Executor command line arguments
+ * @param jar application jar
+ * @param executorAkkaConfig Akka config used to initialize the actor system of this executor.
+ * It uses org.apache.gearpump.util.Constants.GEARPUMP_CUSTOM_CONFIG_FILE
+ * to pass the config to executor process
+ */
+// TODO: ExecutorContext doesn't belong to this package in logic.
+case class ExecutorJVMConfig(
+ classPath: Array[String], jvmArguments: Array[String], mainClass: String,
+ arguments: Array[String], jar: Option[AppJar], username: String,
+ executorAkkaConfig: Config = ConfigFactory.empty())
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/cluster/ClusterConfig.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/cluster/ClusterConfig.scala b/core/src/main/scala/org/apache/gearpump/cluster/ClusterConfig.scala
new file mode 100644
index 0000000..332e770
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/cluster/ClusterConfig.scala
@@ -0,0 +1,180 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster
+
+import java.io.File
+
+import com.typesafe.config._
+
+import org.apache.gearpump.util.Constants._
+import org.apache.gearpump.util.{Constants, FileUtils, LogUtil, Util}
+
+/**
+ *
+ * All Gearpump application should use this class to load configurations.
+ *
+ * Compared with Akka built-in com.typesafe.config.ConfigFactory, this class also
+ * resolve config from file gear.conf and geardefault.conf.
+ *
+ * Overriding order:
+ * {{{
+ * System Properties
+ * > Custom configuration file (by using system property -Dgearpump.config.file) >
+ * > gear.conf
+ * > geardefault.conf
+ * > reference.conf
+ * }}}
+ */
+
+object ClusterConfig {
+ /**
+ * alias for default
+ * default is a reserved word for java
+ */
+ def defaultConfig: Config = {
+ default(APPLICATION)
+ }
+
+ /**
+ * default application for user.
+ * Usually used when user want to start an client application.
+ */
+ def default(configFile: String = APPLICATION): Config = {
+ load(configFile).default
+ }
+
+ /**
+ * configuration for master node
+ */
+ def master(configFile: String = null): Config = {
+ load(configFile).master
+ }
+
+ /*
+ * configuration for worker node
+ */
+ def worker(configFile: String = null): Config = {
+ load(configFile).worker
+ }
+
+ /**
+ * configuration for UI server
+ */
+ def ui(configFile: String = null): Config = {
+ load(configFile).ui
+ }
+
+ /**
+ * try to load system property gearpump.config.file, or use configFile
+ */
+ private def load(configFile: String): Configs = {
+ val file = Option(System.getProperty(GEARPUMP_CUSTOM_CONFIG_FILE))
+ file match {
+ case Some(path) =>
+ LOG.info("loading config file " + path + "..........")
+ load(ClusterConfigSource(path))
+ case None =>
+ LOG.info("loading config file application.conf...")
+ load(ClusterConfigSource(configFile))
+ }
+ }
+
+ val APPLICATION = "application.conf"
+ val LOG = LogUtil.getLogger(getClass)
+
+ def saveConfig(conf: Config, file: File): Unit = {
+ val serialized = conf.root().render()
+ FileUtils.write(file, serialized)
+ }
+
+ def render(config: Config, concise: Boolean = false): String = {
+ if (concise) {
+ config.root().render(ConfigRenderOptions.concise().setFormatted(true))
+ } else {
+ config.root().render(ConfigRenderOptions.defaults())
+ }
+ }
+
+ /** filter JVM reserved keys and akka default reference.conf */
+ def filterOutDefaultConfig(input: Config): Config = {
+ val updated = filterOutJvmReservedKeys(input)
+ Util.filterOutOrigin(updated, "reference.conf")
+ }
+
+ private[gearpump] def load(source: ClusterConfigSource): Configs = {
+
+ val systemProperties = getSystemProperties
+
+ val user = source.getConfig
+
+ val gear = ConfigFactory.parseResourcesAnySyntax("gear.conf",
+ ConfigParseOptions.defaults.setAllowMissing(true))
+
+ val gearDefault = ConfigFactory.parseResourcesAnySyntax("geardefault.conf",
+ ConfigParseOptions.defaults.setAllowMissing(true))
+
+ val all = systemProperties.withFallback(user).withFallback(gear).withFallback(gearDefault)
+
+ val linux = all.getConfig(LINUX_CONFIG)
+
+ var basic = all.withoutPath(MASTER_CONFIG).withoutPath(WORKER_CONFIG).
+ withoutPath(UI_CONFIG).withoutPath(LINUX_CONFIG)
+
+ if (!akka.util.Helpers.isWindows) {
+
+ // Change the akka.scheduler.tick-duration to 1 ms for Linux or Mac
+ basic = linux.withFallback(basic)
+ }
+
+ val master = replaceHost(all.getConfig(MASTER_CONFIG).withFallback(basic))
+ val worker = replaceHost(all.getConfig(WORKER_CONFIG).withFallback(basic))
+ val ui = replaceHost(all.getConfig(UI_CONFIG).withFallback(basic))
+ val app = replaceHost(basic)
+
+ new Configs(master, worker, ui, app)
+ }
+
+ private def replaceHost(config: Config): Config = {
+ val hostName = config.getString(Constants.GEARPUMP_HOSTNAME)
+ config.withValue(NETTY_TCP_HOSTNAME, ConfigValueFactory.fromAnyRef(hostName))
+ }
+
+ val JVM_RESERVED_PROPERTIES = List(
+ "os", "java", "sun", "boot", "user", "prog", "path", "line", "awt", "file"
+ )
+
+ private def getSystemProperties: Config = {
+ // Excludes default java system properties
+ JVM_RESERVED_PROPERTIES.foldLeft(ConfigFactory.systemProperties()) { (config, property) =>
+ config.withoutPath(property)
+ }
+ }
+
+ class ConfigValidationException(msg: String) extends Exception(msg: String)
+
+ private def filterOutJvmReservedKeys(input: Config): Config = {
+ val filterJvmReservedKeys = JVM_RESERVED_PROPERTIES.foldLeft(input) { (config, key) =>
+ config.withoutPath(key)
+ }
+ filterJvmReservedKeys
+ }
+
+ protected class Configs(
+ val master: Config, val worker: Config, val ui: Config, val default: Config)
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/cluster/ClusterConfigSource.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/cluster/ClusterConfigSource.scala b/core/src/main/scala/org/apache/gearpump/cluster/ClusterConfigSource.scala
new file mode 100644
index 0000000..920ceae
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/cluster/ClusterConfigSource.scala
@@ -0,0 +1,63 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster
+
+import java.io.File
+import scala.language.implicitConversions
+
+import com.typesafe.config.{Config, ConfigFactory, ConfigParseOptions}
+
+/**
+ * Data Source of ClusterConfig
+ *
+ * Please use ClusterConfigSource.apply(filePath) to construct this object
+ */
+sealed trait ClusterConfigSource extends Serializable {
+ def getConfig: Config
+}
+
+object ClusterConfigSource {
+
+ /**
+ * Construct ClusterConfigSource from resource name or file path
+ */
+ def apply(filePath: String): ClusterConfigSource = {
+
+ if (null == filePath) {
+ new ClusterConfigSourceImpl(ConfigFactory.empty())
+ } else {
+ var config = ConfigFactory.parseFileAnySyntax(new File(filePath),
+ ConfigParseOptions.defaults.setAllowMissing(true))
+
+ if (null == config || config.isEmpty) {
+ config = ConfigFactory.parseResourcesAnySyntax(filePath,
+ ConfigParseOptions.defaults.setAllowMissing(true))
+ }
+ new ClusterConfigSourceImpl(config)
+ }
+ }
+
+ implicit def FilePathToClusterConfigSource(filePath: String): ClusterConfigSource = {
+ apply(filePath)
+ }
+
+ private class ClusterConfigSourceImpl(config: Config) extends ClusterConfigSource {
+ override def getConfig: Config = config
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/cluster/ClusterMessage.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/cluster/ClusterMessage.scala b/core/src/main/scala/org/apache/gearpump/cluster/ClusterMessage.scala
new file mode 100644
index 0000000..e6ab13b
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/cluster/ClusterMessage.scala
@@ -0,0 +1,288 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster
+
+import org.apache.gearpump.cluster.worker.{WorkerSummary, WorkerId}
+
+import scala.util.Try
+
+import akka.actor.ActorRef
+import com.typesafe.config.Config
+
+import org.apache.gearpump.TimeStamp
+import org.apache.gearpump.cluster.MasterToAppMaster.AppMasterStatus
+import org.apache.gearpump.cluster.master.{MasterNode, MasterSummary}
+import org.apache.gearpump.cluster.scheduler.{Resource, ResourceAllocation, ResourceRequest}
+import org.apache.gearpump.metrics.Metrics.MetricType
+
+object ClientToMaster {
+ case object AddMaster
+ case class AddWorker(count: Int)
+ case class RemoveMaster(masterContainerId: String)
+ case class RemoveWorker(workerContainerId: String)
+
+ /** Command result of AddMaster, RemoveMaster, and etc... */
+ case class CommandResult(success: Boolean, exception: String = null) {
+ override def toString: String = {
+ val tag = getClass.getSimpleName
+ if (success) {
+ s"$tag(success)"
+ } else {
+ s"$tag(failure, $exception)"
+ }
+ }
+ }
+
+ /** Submit an application to master */
+ case class SubmitApplication(
+ appDescription: AppDescription, appJar: Option[AppJar],
+ username: String = System.getProperty("user.name"))
+
+ case class RestartApplication(appId: Int)
+ case class ShutdownApplication(appId: Int)
+
+ /** Client send ResolveAppId to Master to resolves AppMaster actor path by providing appId */
+ case class ResolveAppId(appId: Int)
+
+ /** Client send ResolveWorkerId to master to get the Actor path of worker. */
+ case class ResolveWorkerId(workerId: WorkerId)
+
+ /** Get an active Jar store to upload job jars, like wordcount.jar */
+ case object GetJarStoreServer
+
+ /** Service address of JarStore */
+ case class JarStoreServerAddress(url: String)
+
+ /** Query AppMaster config by providing appId */
+ case class QueryAppMasterConfig(appId: Int)
+
+ /** Query worker config */
+ case class QueryWorkerConfig(workerId: WorkerId)
+
+ /** Query master config */
+ case object QueryMasterConfig
+
+ /** Options for read the metrics from the cluster */
+ object ReadOption {
+ type ReadOption = String
+
+ val Key: String = "readOption"
+
+ /** Read the latest record of the metrics, only return 1 record for one metric name (id) */
+ val ReadLatest: ReadOption = "readLatest"
+
+ /** Read recent metrics from cluster, typically it contains metrics in 5 minutes */
+ val ReadRecent = "readRecent"
+
+ /**
+ * Read the history metrics, typically it contains metrics for 48 hours
+ *
+ * NOTE: Each hour only contain one or two data points.
+ */
+ val ReadHistory = "readHistory"
+ }
+
+ /** Query history metrics from master or app master. */
+ case class QueryHistoryMetrics(
+ path: String, readOption: ReadOption.ReadOption = ReadOption.ReadLatest,
+ aggregatorClazz: String = "", options: Map[String, String] = Map.empty[String, String])
+
+ /**
+ * If there are message loss, the clock would pause for a while. This message is used to
+ * pin-point which task has stalling clock value, and usually it means something wrong on
+ * that machine.
+ */
+ case class GetStallingTasks(appId: Int)
+
+ /**
+ * Request app master for a short list of cluster app that administrators should be aware of.
+ */
+ case class GetLastFailure(appId: Int)
+}
+
+object MasterToClient {
+
+ /** Result of SubmitApplication */
+ // TODO: Merge with SubmitApplicationResultValue and change this to (appId: Option, ex: Exception)
+ case class SubmitApplicationResult(appId: Try[Int])
+
+ case class SubmitApplicationResultValue(appId: Int)
+
+ case class ShutdownApplicationResult(appId: Try[Int])
+ case class ReplayApplicationResult(appId: Try[Int])
+
+ /** Return Actor ref of app master */
+ case class ResolveAppIdResult(appMaster: Try[ActorRef])
+
+ /** Return Actor ref of worker */
+ case class ResolveWorkerIdResult(worker: Try[ActorRef])
+
+ case class AppMasterConfig(config: Config)
+
+ case class WorkerConfig(config: Config)
+
+ case class MasterConfig(config: Config)
+
+ case class HistoryMetricsItem(time: TimeStamp, value: MetricType)
+
+ /**
+ * History metrics returned from master, worker, or app master.
+ *
+ * All metric items are organized like a tree, path is used to navigate through the tree.
+ * For example, when querying with path == "executor0.task1.throughput*", the metrics
+ * provider picks metrics whose source matches the path.
+ *
+ * @param path The path client provided. The returned metrics are the result query of this path.
+ * @param metrics The detailed metrics.
+ */
+ case class HistoryMetrics(path: String, metrics: List[HistoryMetricsItem])
+
+ /** Return the last error of this streaming application job */
+ case class LastFailure(time: TimeStamp, error: String)
+}
+
+trait AppMasterRegisterData
+
+object AppMasterToMaster {
+
+ /**
+ * Register an AppMaster by providing a ActorRef, and registerData
+ * @param registerData The registerData is provided by Master when starting the app master.
+ * App master should return the registerData back to master.
+ * Typically registerData hold some context information for this app Master.
+ */
+
+ case class RegisterAppMaster(appMaster: ActorRef, registerData: AppMasterRegisterData)
+
+ case class InvalidAppMaster(appId: Int, appMaster: String, reason: Throwable)
+
+ case class RequestResource(appId: Int, request: ResourceRequest)
+
+ /**
+ * Each application job can save some data in the distributed cluster storage on master nodes.
+ *
+ * @param appId App Id of the client application who send the request.
+ * @param key Key name
+ * @param value Value to store on distributed cluster storage on master nodes
+ */
+ case class SaveAppData(appId: Int, key: String, value: Any)
+
+ /** The application specific data is successfully stored */
+ case object AppDataSaved
+
+ /** Fail to store the application data */
+ case object SaveAppDataFailed
+
+ /** Fetch the application specific data that stored previously */
+ case class GetAppData(appId: Int, key: String)
+
+ /** The KV data returned for query GetAppData */
+ case class GetAppDataResult(key: String, value: Any)
+
+ /**
+ * AppMasterSummary returned to REST API query. Streaming and Non-streaming
+ * have very different application info. AppMasterSummary is the common interface.
+ */
+ trait AppMasterSummary {
+ def appType: String
+ def appId: Int
+ def appName: String
+ def actorPath: String
+ def status: AppMasterStatus
+ def startTime: TimeStamp
+ def uptime: TimeStamp
+ def user: String
+ }
+
+ /** Represents a generic application that is not a streaming job */
+ case class GeneralAppMasterSummary(
+ appId: Int,
+ appType: String = "general",
+ appName: String = null,
+ actorPath: String = null,
+ status: AppMasterStatus = MasterToAppMaster.AppMasterActive,
+ startTime: TimeStamp = 0L,
+ uptime: TimeStamp = 0L,
+ user: String = null)
+ extends AppMasterSummary
+
+ /** Fetches the list of workers from Master */
+ case object GetAllWorkers
+
+ /** Get worker data of workerId */
+ case class GetWorkerData(workerId: WorkerId)
+
+ /** Response to GetWorkerData */
+ case class WorkerData(workerDescription: WorkerSummary)
+
+ /** Get Master data */
+ case object GetMasterData
+
+ /** Response to GetMasterData */
+ case class MasterData(masterDescription: MasterSummary)
+}
+
+object MasterToAppMaster {
+
+ /** Resource allocated for application xx */
+ case class ResourceAllocated(allocations: Array[ResourceAllocation])
+
+ /** Master confirm reception of RegisterAppMaster message */
+ case class AppMasterRegistered(appId: Int)
+
+ /** Shutdown the application job */
+ case object ShutdownAppMaster
+
+ type AppMasterStatus = String
+ val AppMasterActive: AppMasterStatus = "active"
+ val AppMasterInActive: AppMasterStatus = "inactive"
+ val AppMasterNonExist: AppMasterStatus = "nonexist"
+
+ sealed trait StreamingType
+ case class AppMasterData(
+ status: AppMasterStatus, appId: Int = 0, appName: String = null, appMasterPath: String = null,
+ workerPath: String = null, submissionTime: TimeStamp = 0, startTime: TimeStamp = 0,
+ finishTime: TimeStamp = 0, user: String = null)
+
+ case class AppMasterDataRequest(appId: Int, detail: Boolean = false)
+
+ case class AppMastersData(appMasters: List[AppMasterData])
+ case object AppMastersDataRequest
+ case class AppMasterDataDetailRequest(appId: Int)
+ case class AppMasterMetricsRequest(appId: Int) extends StreamingType
+
+ case class ReplayFromTimestampWindowTrailingEdge(appId: Int)
+
+ case class WorkerList(workers: List[WorkerId])
+}
+
+object AppMasterToWorker {
+ case class LaunchExecutor(
+ appId: Int, executorId: Int, resource: Resource, executorJvmConfig: ExecutorJVMConfig)
+
+ case class ShutdownExecutor(appId: Int, executorId: Int, reason: String)
+ case class ChangeExecutorResource(appId: Int, executorId: Int, resource: Resource)
+}
+
+object WorkerToAppMaster {
+ case class ExecutorLaunchRejected(reason: String = null, ex: Throwable = null)
+ case class ShutdownExecutorSucceed(appId: Int, executorId: Int)
+ case class ShutdownExecutorFailed(reason: String = null, ex: Throwable = null)
+}
+
[31/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/sol/src/main/scala/org/apache/gearpump/streaming/examples/sol/SOLStreamProcessor.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/sol/src/main/scala/org/apache/gearpump/streaming/examples/sol/SOLStreamProcessor.scala b/examples/streaming/sol/src/main/scala/org/apache/gearpump/streaming/examples/sol/SOLStreamProcessor.scala
new file mode 100644
index 0000000..796b0d2
--- /dev/null
+++ b/examples/streaming/sol/src/main/scala/org/apache/gearpump/streaming/examples/sol/SOLStreamProcessor.scala
@@ -0,0 +1,66 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.sol
+
+import java.util.concurrent.TimeUnit
+import scala.concurrent.duration.FiniteDuration
+
+import akka.actor.Cancellable
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.task.{StartTime, Task, TaskContext}
+
+class SOLStreamProcessor(taskContext: TaskContext, conf: UserConfig)
+ extends Task(taskContext, conf) {
+ import taskContext.output
+
+ val taskConf = taskContext
+
+ private var msgCount: Long = 0
+ private var scheduler: Cancellable = null
+ private var snapShotWordCount: Long = 0
+ private var snapShotTime: Long = 0
+
+ override def onStart(startTime: StartTime): Unit = {
+ scheduler = taskContext.schedule(new FiniteDuration(5, TimeUnit.SECONDS),
+ new FiniteDuration(5, TimeUnit.SECONDS))(reportWordCount())
+ snapShotTime = System.currentTimeMillis()
+ }
+
+ override def onNext(msg: Message): Unit = {
+ output(msg)
+ msgCount = msgCount + 1
+ }
+
+ override def onStop(): Unit = {
+ if (scheduler != null) {
+ scheduler.cancel()
+ }
+ }
+
+ def reportWordCount(): Unit = {
+ val current: Long = System.currentTimeMillis()
+ LOG.info(s"Task ${taskConf.taskId} " +
+ s"Throughput: ${(msgCount - snapShotWordCount, (current - snapShotTime) / 1000)} " +
+ s"(words, second)")
+ snapShotWordCount = msgCount
+ snapShotTime = current
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/sol/src/main/scala/org/apache/gearpump/streaming/examples/sol/SOLStreamProducer.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/sol/src/main/scala/org/apache/gearpump/streaming/examples/sol/SOLStreamProducer.scala b/examples/streaming/sol/src/main/scala/org/apache/gearpump/streaming/examples/sol/SOLStreamProducer.scala
new file mode 100644
index 0000000..84ed038
--- /dev/null
+++ b/examples/streaming/sol/src/main/scala/org/apache/gearpump/streaming/examples/sol/SOLStreamProducer.scala
@@ -0,0 +1,78 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.sol
+
+import java.util.Random
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.examples.sol.SOLStreamProducer._
+import org.apache.gearpump.streaming.task.{StartTime, Task, TaskContext}
+
+class SOLStreamProducer(taskContext: TaskContext, conf: UserConfig)
+ extends Task(taskContext, conf) {
+
+ import taskContext.output
+
+ private val sizeInBytes = conf.getInt(SOLStreamProducer.BYTES_PER_MESSAGE)
+ .getOrElse(DEFAULT_MESSAGE_SIZE)
+ private var messages: Array[String] = null
+ private var rand: Random = null
+ private var messageCount: Long = 0
+
+ override def onStart(startTime: StartTime): Unit = {
+ prepareRandomMessage
+ self ! Start
+ }
+
+ private def prepareRandomMessage = {
+ rand = new Random()
+ val differentMessages = 100
+ messages = new Array(differentMessages)
+
+ 0.until(differentMessages).map { index =>
+ val sb = new StringBuilder(sizeInBytes)
+ // Even though java encodes strings in UCS2, the serialized version sent by the tuples
+ // is UTF8, so it should be a single byte
+ 0.until(sizeInBytes).foldLeft(sb) { (sb, j) =>
+ sb.append(rand.nextInt(9))
+ }
+ messages(index) = sb.toString()
+ }
+ }
+
+ override def onNext(msg: Message): Unit = {
+ val message = messages(rand.nextInt(messages.length))
+ output(new Message(message, System.currentTimeMillis()))
+ messageCount = messageCount + 1L
+ self ! messageSourceMinClock
+ }
+
+ // messageSourceMinClock represent the min clock of the message source
+ private def messageSourceMinClock: Message = {
+ Message("tick", System.currentTimeMillis())
+ }
+}
+
+object SOLStreamProducer {
+ val DEFAULT_MESSAGE_SIZE = 100
+ // Bytes
+ val BYTES_PER_MESSAGE = "bytesPerMessage"
+ val Start = Message("start")
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/sol/src/test/scala/io/gearpump/streaming/examples/sol/SOLSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/sol/src/test/scala/io/gearpump/streaming/examples/sol/SOLSpec.scala b/examples/streaming/sol/src/test/scala/io/gearpump/streaming/examples/sol/SOLSpec.scala
deleted file mode 100644
index 6e266d0..0000000
--- a/examples/streaming/sol/src/test/scala/io/gearpump/streaming/examples/sol/SOLSpec.scala
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.sol
-
-import scala.concurrent.Future
-import scala.util.Success
-
-import com.typesafe.config.Config
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{BeforeAndAfterAll, Matchers, PropSpec}
-
-import io.gearpump.cluster.ClientToMaster.SubmitApplication
-import io.gearpump.cluster.MasterToClient.SubmitApplicationResult
-import io.gearpump.cluster.{MasterHarness, TestUtil}
-
-class SOLSpec
- extends PropSpec with PropertyChecks with Matchers with BeforeAndAfterAll with MasterHarness {
- override def beforeAll {
- startActorSystem()
- }
-
- override def afterAll {
- shutdownActorSystem()
- }
-
- override def config: Config = TestUtil.DEFAULT_CONFIG
-
- property("SOL should succeed to submit application with required arguments") {
- val requiredArgs = Array.empty[String]
- val optionalArgs = Array(
- "-streamProducer", "1",
- "-streamProcessor", "1",
- "-bytesPerMessage", "100",
- "-stages", "10")
-
- val args = {
- Table(
- ("requiredArgs", "optionalArgs"),
- (requiredArgs, optionalArgs)
- )
- }
- val masterReceiver = createMockMaster()
- forAll(args) { (requiredArgs: Array[String], optionalArgs: Array[String]) =>
- val args = requiredArgs ++ optionalArgs
-
- Future {
- SOL.main(masterConfig, args)
- }
-
- masterReceiver.expectMsgType[SubmitApplication](PROCESS_BOOT_TIME)
- masterReceiver.reply(SubmitApplicationResult(Success(0)))
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/sol/src/test/scala/io/gearpump/streaming/examples/sol/SOLStreamProcessorSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/sol/src/test/scala/io/gearpump/streaming/examples/sol/SOLStreamProcessorSpec.scala b/examples/streaming/sol/src/test/scala/io/gearpump/streaming/examples/sol/SOLStreamProcessorSpec.scala
deleted file mode 100644
index f5035b4..0000000
--- a/examples/streaming/sol/src/test/scala/io/gearpump/streaming/examples/sol/SOLStreamProcessorSpec.scala
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.examples.sol
-
-import org.mockito.Mockito._
-import org.scalacheck.Gen
-import org.scalatest.{FlatSpec, Matchers}
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.MockUtil
-import io.gearpump.streaming.task.StartTime
-
-class SOLStreamProcessorSpec extends FlatSpec with Matchers {
-
- it should "pass the message downstream" in {
- val stringGenerator = Gen.alphaStr
- val context = MockUtil.mockTaskContext
-
- val sol = new SOLStreamProcessor(context, UserConfig.empty)
- sol.onStart(StartTime(0))
- val msg = Message("msg")
- sol.onNext(msg)
- verify(context, times(1)).output(msg)
- sol.onStop()
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/sol/src/test/scala/io/gearpump/streaming/examples/sol/SOLStreamProducerSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/sol/src/test/scala/io/gearpump/streaming/examples/sol/SOLStreamProducerSpec.scala b/examples/streaming/sol/src/test/scala/io/gearpump/streaming/examples/sol/SOLStreamProducerSpec.scala
deleted file mode 100644
index 4bac30c..0000000
--- a/examples/streaming/sol/src/test/scala/io/gearpump/streaming/examples/sol/SOLStreamProducerSpec.scala
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.examples.sol
-
-import org.mockito.Matchers._
-import org.mockito.Mockito._
-import org.scalatest.{Matchers, WordSpec}
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.MockUtil
-import io.gearpump.streaming.task.StartTime
-
-class SOLStreamProducerSpec extends WordSpec with Matchers {
-
- "SOLStreamProducer" should {
- "producer message continuously" in {
-
- val conf = UserConfig.empty.withInt(SOLStreamProducer.BYTES_PER_MESSAGE, 100)
- val context = MockUtil.mockTaskContext
-
- val producer = new SOLStreamProducer(context, conf)
- producer.onStart(StartTime(0))
- producer.onNext(Message("msg"))
- verify(context).output(any[Message])
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/sol/src/test/scala/org/apache/gearpump/streaming/examples/sol/SOLSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/sol/src/test/scala/org/apache/gearpump/streaming/examples/sol/SOLSpec.scala b/examples/streaming/sol/src/test/scala/org/apache/gearpump/streaming/examples/sol/SOLSpec.scala
new file mode 100644
index 0000000..29e8284
--- /dev/null
+++ b/examples/streaming/sol/src/test/scala/org/apache/gearpump/streaming/examples/sol/SOLSpec.scala
@@ -0,0 +1,70 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.sol
+
+import scala.concurrent.Future
+import scala.util.Success
+
+import com.typesafe.config.Config
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{BeforeAndAfterAll, Matchers, PropSpec}
+
+import org.apache.gearpump.cluster.ClientToMaster.SubmitApplication
+import org.apache.gearpump.cluster.MasterToClient.SubmitApplicationResult
+import org.apache.gearpump.cluster.{MasterHarness, TestUtil}
+
+class SOLSpec
+ extends PropSpec with PropertyChecks with Matchers with BeforeAndAfterAll with MasterHarness {
+ override def beforeAll {
+ startActorSystem()
+ }
+
+ override def afterAll {
+ shutdownActorSystem()
+ }
+
+ override def config: Config = TestUtil.DEFAULT_CONFIG
+
+ property("SOL should succeed to submit application with required arguments") {
+ val requiredArgs = Array.empty[String]
+ val optionalArgs = Array(
+ "-streamProducer", "1",
+ "-streamProcessor", "1",
+ "-bytesPerMessage", "100",
+ "-stages", "10")
+
+ val args = {
+ Table(
+ ("requiredArgs", "optionalArgs"),
+ (requiredArgs, optionalArgs)
+ )
+ }
+ val masterReceiver = createMockMaster()
+ forAll(args) { (requiredArgs: Array[String], optionalArgs: Array[String]) =>
+ val args = requiredArgs ++ optionalArgs
+
+ Future {
+ SOL.main(masterConfig, args)
+ }
+
+ masterReceiver.expectMsgType[SubmitApplication](PROCESS_BOOT_TIME)
+ masterReceiver.reply(SubmitApplicationResult(Success(0)))
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/sol/src/test/scala/org/apache/gearpump/streaming/examples/sol/SOLStreamProcessorSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/sol/src/test/scala/org/apache/gearpump/streaming/examples/sol/SOLStreamProcessorSpec.scala b/examples/streaming/sol/src/test/scala/org/apache/gearpump/streaming/examples/sol/SOLStreamProcessorSpec.scala
new file mode 100644
index 0000000..a6cc966
--- /dev/null
+++ b/examples/streaming/sol/src/test/scala/org/apache/gearpump/streaming/examples/sol/SOLStreamProcessorSpec.scala
@@ -0,0 +1,42 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.examples.sol
+
+import org.mockito.Mockito._
+import org.scalacheck.Gen
+import org.scalatest.{FlatSpec, Matchers}
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.MockUtil
+import org.apache.gearpump.streaming.task.StartTime
+
+class SOLStreamProcessorSpec extends FlatSpec with Matchers {
+
+ it should "pass the message downstream" in {
+ val stringGenerator = Gen.alphaStr
+ val context = MockUtil.mockTaskContext
+
+ val sol = new SOLStreamProcessor(context, UserConfig.empty)
+ sol.onStart(StartTime(0))
+ val msg = Message("msg")
+ sol.onNext(msg)
+ verify(context, times(1)).output(msg)
+ sol.onStop()
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/sol/src/test/scala/org/apache/gearpump/streaming/examples/sol/SOLStreamProducerSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/sol/src/test/scala/org/apache/gearpump/streaming/examples/sol/SOLStreamProducerSpec.scala b/examples/streaming/sol/src/test/scala/org/apache/gearpump/streaming/examples/sol/SOLStreamProducerSpec.scala
new file mode 100644
index 0000000..2316de8
--- /dev/null
+++ b/examples/streaming/sol/src/test/scala/org/apache/gearpump/streaming/examples/sol/SOLStreamProducerSpec.scala
@@ -0,0 +1,43 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.examples.sol
+
+import org.mockito.Matchers._
+import org.mockito.Mockito._
+import org.scalatest.{Matchers, WordSpec}
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.MockUtil
+import org.apache.gearpump.streaming.task.StartTime
+
+class SOLStreamProducerSpec extends WordSpec with Matchers {
+
+ "SOLStreamProducer" should {
+ "producer message continuously" in {
+
+ val conf = UserConfig.empty.withInt(SOLStreamProducer.BYTES_PER_MESSAGE, 100)
+ val context = MockUtil.mockTaskContext
+
+ val producer = new SOLStreamProducer(context, conf)
+ producer.onStart(StartTime(0))
+ producer.onNext(Message("msg"))
+ verify(context).output(any[Message])
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/state/src/main/resources/state.conf
----------------------------------------------------------------------
diff --git a/examples/streaming/state/src/main/resources/state.conf b/examples/streaming/state/src/main/resources/state.conf
index 7e26d4b..a7eec2b 100644
--- a/examples/streaming/state/src/main/resources/state.conf
+++ b/examples/streaming/state/src/main/resources/state.conf
@@ -1,6 +1,6 @@
state {
checkpoint {
interval = 1000 # milliseconds
- store.factory = io.gearpump.streaming.kafka.KafkaCheckpointStoreFactory
+ store.factory = org.apache.gearpump.streaming.kafka.KafkaCheckpointStoreFactory
}
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/state/src/main/scala/io/gearpump/streaming/examples/state/MessageCountApp.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/state/src/main/scala/io/gearpump/streaming/examples/state/MessageCountApp.scala b/examples/streaming/state/src/main/scala/io/gearpump/streaming/examples/state/MessageCountApp.scala
deleted file mode 100644
index 3c6cde6..0000000
--- a/examples/streaming/state/src/main/scala/io/gearpump/streaming/examples/state/MessageCountApp.scala
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.state
-
-import akka.actor.ActorSystem
-import org.apache.hadoop.conf.Configuration
-
-import io.gearpump.cluster.UserConfig
-import io.gearpump.cluster.client.ClientContext
-import io.gearpump.cluster.main.{ArgumentsParser, CLIOption, ParseResult}
-import io.gearpump.partitioner.HashPartitioner
-import io.gearpump.streaming.examples.state.processor.CountProcessor
-import io.gearpump.streaming.hadoop.HadoopCheckpointStoreFactory
-import io.gearpump.streaming.hadoop.lib.rotation.FileSizeRotation
-import io.gearpump.streaming.kafka.{KafkaSink, KafkaSource, KafkaStorageFactory}
-import io.gearpump.streaming.sink.DataSinkProcessor
-import io.gearpump.streaming.source.DataSourceProcessor
-import io.gearpump.streaming.state.impl.PersistentStateConfig
-import io.gearpump.streaming.{Processor, StreamApplication}
-import io.gearpump.util.Graph.Node
-import io.gearpump.util.{AkkaApp, Graph}
-
-/** Does exactly-once message count */
-object MessageCountApp extends AkkaApp with ArgumentsParser {
- val SOURCE_TASK = "sourceTask"
- val COUNT_TASK = "countTask"
- val SINK_TASK = "sinkTask"
- val SOURCE_TOPIC = "sourceTopic"
- val SINK_TOPIC = "sinkTopic"
- val ZOOKEEPER_CONNECT = "zookeeperConnect"
- val BROKER_LIST = "brokerList"
- val DEFAULT_FS = "defaultFS"
-
- override val options: Array[(String, CLIOption[Any])] = Array(
- SOURCE_TASK -> CLIOption[Int]("<how many kafka source tasks>", required = false,
- defaultValue = Some(1)),
- COUNT_TASK -> CLIOption("<how many count tasks>", required = false, defaultValue = Some(1)),
- SINK_TASK -> CLIOption[Int]("<how many kafka sink tasks>", required = false,
- defaultValue = Some(1)),
- SOURCE_TOPIC -> CLIOption[String]("<kafka source topic>", required = true),
- SINK_TOPIC -> CLIOption[String]("<kafka sink topic>", required = true),
- ZOOKEEPER_CONNECT -> CLIOption[String]("<Zookeeper connect string, e.g. localhost:2181/kafka>",
- required = true),
- BROKER_LIST -> CLIOption[String]("<Kafka broker list, e.g. localhost:9092>", required = true),
- DEFAULT_FS -> CLIOption[String]("<name of the default file system, e.g. hdfs://localhost:9000>",
- required = true)
- )
-
- def application(config: ParseResult)(implicit system: ActorSystem): StreamApplication = {
- val hadoopConfig = new Configuration
- hadoopConfig.set("fs.defaultFS", config.getString(DEFAULT_FS))
- val checkpointStoreFactory = new HadoopCheckpointStoreFactory("MessageCount", hadoopConfig,
- // Rotates on 1KB
- new FileSizeRotation(1000))
- val taskConfig = UserConfig.empty
- .withBoolean(PersistentStateConfig.STATE_CHECKPOINT_ENABLE, true)
- .withLong(PersistentStateConfig.STATE_CHECKPOINT_INTERVAL_MS, 1000L)
- .withValue(PersistentStateConfig.STATE_CHECKPOINT_STORE_FACTORY, checkpointStoreFactory)
-
- val zookeeperConnect = config.getString(ZOOKEEPER_CONNECT)
- val brokerList = config.getString(BROKER_LIST)
- val offsetStorageFactory = new KafkaStorageFactory(zookeeperConnect, brokerList)
- val sourceTopic = config.getString(SOURCE_TOPIC)
- val kafkaSource = new KafkaSource(sourceTopic, zookeeperConnect, offsetStorageFactory)
- val sourceProcessor = DataSourceProcessor(kafkaSource, config.getInt(SOURCE_TASK))
- val countProcessor = Processor[CountProcessor](config.getInt(COUNT_TASK), taskConf = taskConfig)
- val kafkaSink = new KafkaSink(config.getString(SINK_TOPIC), brokerList)
- val sinkProcessor = DataSinkProcessor(kafkaSink, config.getInt(SINK_TASK))
- val partitioner = new HashPartitioner()
- val graph = Graph(sourceProcessor ~ partitioner
- ~> countProcessor ~ partitioner ~> sinkProcessor)
- val app = StreamApplication("MessageCount", graph, UserConfig.empty)
- app
- }
-
- def main(akkaConf: Config, args: Array[String]): Unit = {
-
- val config = parse(args)
- val context = ClientContext(akkaConf)
- implicit val system = context.system
- val appId = context.submit(application(config))
- context.close()
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/state/src/main/scala/io/gearpump/streaming/examples/state/WindowAverageApp.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/state/src/main/scala/io/gearpump/streaming/examples/state/WindowAverageApp.scala b/examples/streaming/state/src/main/scala/io/gearpump/streaming/examples/state/WindowAverageApp.scala
deleted file mode 100644
index 6f3bc79..0000000
--- a/examples/streaming/state/src/main/scala/io/gearpump/streaming/examples/state/WindowAverageApp.scala
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.state
-
-import akka.actor.ActorSystem
-import org.apache.hadoop.conf.Configuration
-
-import io.gearpump.cluster.UserConfig
-import io.gearpump.cluster.client.ClientContext
-import io.gearpump.cluster.main.{ArgumentsParser, CLIOption, ParseResult}
-import io.gearpump.partitioner.HashPartitioner
-import io.gearpump.streaming.examples.state.processor.{NumberGeneratorProcessor, WindowAverageProcessor}
-import io.gearpump.streaming.hadoop.HadoopCheckpointStoreFactory
-import io.gearpump.streaming.state.impl.{PersistentStateConfig, WindowConfig}
-import io.gearpump.streaming.{Processor, StreamApplication}
-import io.gearpump.util.Graph.Node
-import io.gearpump.util.{AkkaApp, Graph}
-
-/** Does exactly-once sliding window based average aggregation */
-object WindowAverageApp extends AkkaApp with ArgumentsParser {
-
- override val options: Array[(String, CLIOption[Any])] = Array(
- "gen" -> CLIOption("<how many gen tasks>", required = false, defaultValue = Some(1)),
- "window" -> CLIOption("<how mange window tasks", required = false, defaultValue = Some(1)),
- "window_size" -> CLIOption("<window size in milliseconds>", required = false,
- defaultValue = Some(5000)),
- "window_step" -> CLIOption("<window step in milliseconds>", required = false,
- defaultValue = Some(5000))
- )
-
- def application(config: ParseResult)(implicit system: ActorSystem): StreamApplication = {
- val windowSize = config.getInt("window_size")
- val windowStep = config.getInt("window_step")
- val checkpointStoreFactory = new HadoopCheckpointStoreFactory("MessageCount", new Configuration)
- val taskConfig = UserConfig.empty.
- withBoolean(PersistentStateConfig.STATE_CHECKPOINT_ENABLE, true)
- .withLong(PersistentStateConfig.STATE_CHECKPOINT_INTERVAL_MS, 1000L)
- .withValue(PersistentStateConfig.STATE_CHECKPOINT_STORE_FACTORY, checkpointStoreFactory)
- .withValue(WindowConfig.NAME, WindowConfig(windowSize, windowStep))
- val gen = Processor[NumberGeneratorProcessor](config.getInt("gen"))
- val count = Processor[WindowAverageProcessor](config.getInt("window"), taskConf = taskConfig)
- val partitioner = new HashPartitioner()
- val app = StreamApplication("WindowAverage", Graph(gen ~ partitioner ~> count),
- UserConfig.empty)
- app
- }
-
- override def main(akkaConf: Config, args: Array[String]): Unit = {
- val config = parse(args)
- val context = ClientContext(akkaConf)
-
- implicit val system = context.system
- val appId = context.submit(application(config))
- context.close()
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/state/src/main/scala/io/gearpump/streaming/examples/state/processor/CountProcessor.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/state/src/main/scala/io/gearpump/streaming/examples/state/processor/CountProcessor.scala b/examples/streaming/state/src/main/scala/io/gearpump/streaming/examples/state/processor/CountProcessor.scala
deleted file mode 100644
index 6610b91..0000000
--- a/examples/streaming/state/src/main/scala/io/gearpump/streaming/examples/state/processor/CountProcessor.scala
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.state.processor
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.monoid.AlgebirdMonoid
-import io.gearpump.streaming.serializer.ChillSerializer
-import io.gearpump.streaming.state.api.{PersistentState, PersistentTask}
-import io.gearpump.streaming.state.impl.NonWindowState
-import io.gearpump.streaming.task.TaskContext
-
-class CountProcessor(taskContext: TaskContext, conf: UserConfig)
- extends PersistentTask[Int](taskContext, conf) {
-
- override def persistentState: PersistentState[Int] = {
- import com.twitter.algebird.Monoid.intMonoid
- new NonWindowState[Int](new AlgebirdMonoid(intMonoid), new ChillSerializer[Int])
- }
-
- override def processMessage(state: PersistentState[Int], message: Message): Unit = {
- state.update(message.timestamp, 1)
- }
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/state/src/main/scala/io/gearpump/streaming/examples/state/processor/NumberGeneratorProcessor.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/state/src/main/scala/io/gearpump/streaming/examples/state/processor/NumberGeneratorProcessor.scala b/examples/streaming/state/src/main/scala/io/gearpump/streaming/examples/state/processor/NumberGeneratorProcessor.scala
deleted file mode 100644
index fa9854f..0000000
--- a/examples/streaming/state/src/main/scala/io/gearpump/streaming/examples/state/processor/NumberGeneratorProcessor.scala
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.state.processor
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.task.{StartTime, Task, TaskContext}
-
-class NumberGeneratorProcessor(taskContext: TaskContext, conf: UserConfig)
- extends Task(taskContext, conf) {
- import taskContext.output
-
- private var num = 0L
- override def onStart(startTime: StartTime): Unit = {
- num = startTime.startTime
- self ! Message("start")
- }
-
- override def onNext(msg: Message): Unit = {
- output(Message(num + "", num))
- num += 1
-
- import scala.concurrent.duration._
- taskContext.scheduleOnce(Duration(1, MILLISECONDS))(self ! Message("next"))
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/state/src/main/scala/io/gearpump/streaming/examples/state/processor/WindowAverageProcessor.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/state/src/main/scala/io/gearpump/streaming/examples/state/processor/WindowAverageProcessor.scala b/examples/streaming/state/src/main/scala/io/gearpump/streaming/examples/state/processor/WindowAverageProcessor.scala
deleted file mode 100644
index e7ac9b3..0000000
--- a/examples/streaming/state/src/main/scala/io/gearpump/streaming/examples/state/processor/WindowAverageProcessor.scala
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.state.processor
-
-import scala.collection.immutable.TreeMap
-
-import com.twitter.algebird.{AveragedGroup, AveragedValue}
-import org.slf4j.Logger
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.monoid.AlgebirdGroup
-import io.gearpump.streaming.serializer.ChillSerializer
-import io.gearpump.streaming.state.api.{PersistentState, PersistentTask}
-import io.gearpump.streaming.state.impl.{Interval, Window, WindowConfig, WindowState}
-import io.gearpump.streaming.task.TaskContext
-import io.gearpump.util.LogUtil
-
-object WindowAverageProcessor {
- val LOG: Logger = LogUtil.getLogger(classOf[WindowAverageProcessor])
-}
-
-class WindowAverageProcessor(taskContext: TaskContext, conf: UserConfig)
- extends PersistentTask[AveragedValue](taskContext, conf) {
-
- override def persistentState: PersistentState[AveragedValue] = {
- val group = new AlgebirdGroup(AveragedGroup)
- val serializer = new ChillSerializer[TreeMap[Interval, AveragedValue]]
- val window = new Window(conf.getValue[WindowConfig](WindowConfig.NAME).get)
- new WindowState[AveragedValue](group, serializer, taskContext, window)
- }
-
- override def processMessage(state: PersistentState[AveragedValue],
- message: Message): Unit = {
- val value = AveragedValue(message.msg.asInstanceOf[String].toLong)
- state.update(message.timestamp, value)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/state/src/main/scala/org/apache/gearpump/streaming/examples/state/MessageCountApp.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/state/src/main/scala/org/apache/gearpump/streaming/examples/state/MessageCountApp.scala b/examples/streaming/state/src/main/scala/org/apache/gearpump/streaming/examples/state/MessageCountApp.scala
new file mode 100644
index 0000000..13bef0d
--- /dev/null
+++ b/examples/streaming/state/src/main/scala/org/apache/gearpump/streaming/examples/state/MessageCountApp.scala
@@ -0,0 +1,100 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.state
+
+import akka.actor.ActorSystem
+import org.apache.hadoop.conf.Configuration
+
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.cluster.client.ClientContext
+import org.apache.gearpump.cluster.main.{ArgumentsParser, CLIOption, ParseResult}
+import org.apache.gearpump.partitioner.HashPartitioner
+import org.apache.gearpump.streaming.examples.state.processor.CountProcessor
+import org.apache.gearpump.streaming.hadoop.HadoopCheckpointStoreFactory
+import org.apache.gearpump.streaming.hadoop.lib.rotation.FileSizeRotation
+import org.apache.gearpump.streaming.kafka.{KafkaSink, KafkaSource, KafkaStorageFactory}
+import org.apache.gearpump.streaming.sink.DataSinkProcessor
+import org.apache.gearpump.streaming.source.DataSourceProcessor
+import org.apache.gearpump.streaming.state.impl.PersistentStateConfig
+import org.apache.gearpump.streaming.{Processor, StreamApplication}
+import org.apache.gearpump.util.Graph.Node
+import org.apache.gearpump.util.{AkkaApp, Graph}
+
+/** Does exactly-once message count */
+object MessageCountApp extends AkkaApp with ArgumentsParser {
+ val SOURCE_TASK = "sourceTask"
+ val COUNT_TASK = "countTask"
+ val SINK_TASK = "sinkTask"
+ val SOURCE_TOPIC = "sourceTopic"
+ val SINK_TOPIC = "sinkTopic"
+ val ZOOKEEPER_CONNECT = "zookeeperConnect"
+ val BROKER_LIST = "brokerList"
+ val DEFAULT_FS = "defaultFS"
+
+ override val options: Array[(String, CLIOption[Any])] = Array(
+ SOURCE_TASK -> CLIOption[Int]("<how many kafka source tasks>", required = false,
+ defaultValue = Some(1)),
+ COUNT_TASK -> CLIOption("<how many count tasks>", required = false, defaultValue = Some(1)),
+ SINK_TASK -> CLIOption[Int]("<how many kafka sink tasks>", required = false,
+ defaultValue = Some(1)),
+ SOURCE_TOPIC -> CLIOption[String]("<kafka source topic>", required = true),
+ SINK_TOPIC -> CLIOption[String]("<kafka sink topic>", required = true),
+ ZOOKEEPER_CONNECT -> CLIOption[String]("<Zookeeper connect string, e.g. localhost:2181/kafka>",
+ required = true),
+ BROKER_LIST -> CLIOption[String]("<Kafka broker list, e.g. localhost:9092>", required = true),
+ DEFAULT_FS -> CLIOption[String]("<name of the default file system, e.g. hdfs://localhost:9000>",
+ required = true)
+ )
+
+ def application(config: ParseResult)(implicit system: ActorSystem): StreamApplication = {
+ val hadoopConfig = new Configuration
+ hadoopConfig.set("fs.defaultFS", config.getString(DEFAULT_FS))
+ val checkpointStoreFactory = new HadoopCheckpointStoreFactory("MessageCount", hadoopConfig,
+ // Rotates on 1KB
+ new FileSizeRotation(1000))
+ val taskConfig = UserConfig.empty
+ .withBoolean(PersistentStateConfig.STATE_CHECKPOINT_ENABLE, true)
+ .withLong(PersistentStateConfig.STATE_CHECKPOINT_INTERVAL_MS, 1000L)
+ .withValue(PersistentStateConfig.STATE_CHECKPOINT_STORE_FACTORY, checkpointStoreFactory)
+
+ val zookeeperConnect = config.getString(ZOOKEEPER_CONNECT)
+ val brokerList = config.getString(BROKER_LIST)
+ val offsetStorageFactory = new KafkaStorageFactory(zookeeperConnect, brokerList)
+ val sourceTopic = config.getString(SOURCE_TOPIC)
+ val kafkaSource = new KafkaSource(sourceTopic, zookeeperConnect, offsetStorageFactory)
+ val sourceProcessor = DataSourceProcessor(kafkaSource, config.getInt(SOURCE_TASK))
+ val countProcessor = Processor[CountProcessor](config.getInt(COUNT_TASK), taskConf = taskConfig)
+ val kafkaSink = new KafkaSink(config.getString(SINK_TOPIC), brokerList)
+ val sinkProcessor = DataSinkProcessor(kafkaSink, config.getInt(SINK_TASK))
+ val partitioner = new HashPartitioner()
+ val graph = Graph(sourceProcessor ~ partitioner
+ ~> countProcessor ~ partitioner ~> sinkProcessor)
+ val app = StreamApplication("MessageCount", graph, UserConfig.empty)
+ app
+ }
+
+ def main(akkaConf: Config, args: Array[String]): Unit = {
+
+ val config = parse(args)
+ val context = ClientContext(akkaConf)
+ implicit val system = context.system
+ val appId = context.submit(application(config))
+ context.close()
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/state/src/main/scala/org/apache/gearpump/streaming/examples/state/WindowAverageApp.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/state/src/main/scala/org/apache/gearpump/streaming/examples/state/WindowAverageApp.scala b/examples/streaming/state/src/main/scala/org/apache/gearpump/streaming/examples/state/WindowAverageApp.scala
new file mode 100644
index 0000000..629deb7
--- /dev/null
+++ b/examples/streaming/state/src/main/scala/org/apache/gearpump/streaming/examples/state/WindowAverageApp.scala
@@ -0,0 +1,72 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.state
+
+import akka.actor.ActorSystem
+import org.apache.hadoop.conf.Configuration
+
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.cluster.client.ClientContext
+import org.apache.gearpump.cluster.main.{ArgumentsParser, CLIOption, ParseResult}
+import org.apache.gearpump.partitioner.HashPartitioner
+import org.apache.gearpump.streaming.examples.state.processor.{NumberGeneratorProcessor, WindowAverageProcessor}
+import org.apache.gearpump.streaming.hadoop.HadoopCheckpointStoreFactory
+import org.apache.gearpump.streaming.state.impl.{PersistentStateConfig, WindowConfig}
+import org.apache.gearpump.streaming.{Processor, StreamApplication}
+import org.apache.gearpump.util.Graph.Node
+import org.apache.gearpump.util.{AkkaApp, Graph}
+
+/** Does exactly-once sliding window based average aggregation */
+object WindowAverageApp extends AkkaApp with ArgumentsParser {
+
+ override val options: Array[(String, CLIOption[Any])] = Array(
+ "gen" -> CLIOption("<how many gen tasks>", required = false, defaultValue = Some(1)),
+ "window" -> CLIOption("<how mange window tasks", required = false, defaultValue = Some(1)),
+ "window_size" -> CLIOption("<window size in milliseconds>", required = false,
+ defaultValue = Some(5000)),
+ "window_step" -> CLIOption("<window step in milliseconds>", required = false,
+ defaultValue = Some(5000))
+ )
+
+ def application(config: ParseResult)(implicit system: ActorSystem): StreamApplication = {
+ val windowSize = config.getInt("window_size")
+ val windowStep = config.getInt("window_step")
+ val checkpointStoreFactory = new HadoopCheckpointStoreFactory("MessageCount", new Configuration)
+ val taskConfig = UserConfig.empty.
+ withBoolean(PersistentStateConfig.STATE_CHECKPOINT_ENABLE, true)
+ .withLong(PersistentStateConfig.STATE_CHECKPOINT_INTERVAL_MS, 1000L)
+ .withValue(PersistentStateConfig.STATE_CHECKPOINT_STORE_FACTORY, checkpointStoreFactory)
+ .withValue(WindowConfig.NAME, WindowConfig(windowSize, windowStep))
+ val gen = Processor[NumberGeneratorProcessor](config.getInt("gen"))
+ val count = Processor[WindowAverageProcessor](config.getInt("window"), taskConf = taskConfig)
+ val partitioner = new HashPartitioner()
+ val app = StreamApplication("WindowAverage", Graph(gen ~ partitioner ~> count),
+ UserConfig.empty)
+ app
+ }
+
+ override def main(akkaConf: Config, args: Array[String]): Unit = {
+ val config = parse(args)
+ val context = ClientContext(akkaConf)
+
+ implicit val system = context.system
+ val appId = context.submit(application(config))
+ context.close()
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/state/src/main/scala/org/apache/gearpump/streaming/examples/state/processor/CountProcessor.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/state/src/main/scala/org/apache/gearpump/streaming/examples/state/processor/CountProcessor.scala b/examples/streaming/state/src/main/scala/org/apache/gearpump/streaming/examples/state/processor/CountProcessor.scala
new file mode 100644
index 0000000..9650a0a
--- /dev/null
+++ b/examples/streaming/state/src/main/scala/org/apache/gearpump/streaming/examples/state/processor/CountProcessor.scala
@@ -0,0 +1,41 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.state.processor
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.monoid.AlgebirdMonoid
+import org.apache.gearpump.streaming.serializer.ChillSerializer
+import org.apache.gearpump.streaming.state.api.{PersistentState, PersistentTask}
+import org.apache.gearpump.streaming.state.impl.NonWindowState
+import org.apache.gearpump.streaming.task.TaskContext
+
+class CountProcessor(taskContext: TaskContext, conf: UserConfig)
+ extends PersistentTask[Int](taskContext, conf) {
+
+ override def persistentState: PersistentState[Int] = {
+ import com.twitter.algebird.Monoid.intMonoid
+ new NonWindowState[Int](new AlgebirdMonoid(intMonoid), new ChillSerializer[Int])
+ }
+
+ override def processMessage(state: PersistentState[Int], message: Message): Unit = {
+ state.update(message.timestamp, 1)
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/state/src/main/scala/org/apache/gearpump/streaming/examples/state/processor/NumberGeneratorProcessor.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/state/src/main/scala/org/apache/gearpump/streaming/examples/state/processor/NumberGeneratorProcessor.scala b/examples/streaming/state/src/main/scala/org/apache/gearpump/streaming/examples/state/processor/NumberGeneratorProcessor.scala
new file mode 100644
index 0000000..0e85f32
--- /dev/null
+++ b/examples/streaming/state/src/main/scala/org/apache/gearpump/streaming/examples/state/processor/NumberGeneratorProcessor.scala
@@ -0,0 +1,42 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.state.processor
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.task.{StartTime, Task, TaskContext}
+
+class NumberGeneratorProcessor(taskContext: TaskContext, conf: UserConfig)
+ extends Task(taskContext, conf) {
+ import taskContext.output
+
+ private var num = 0L
+ override def onStart(startTime: StartTime): Unit = {
+ num = startTime.startTime
+ self ! Message("start")
+ }
+
+ override def onNext(msg: Message): Unit = {
+ output(Message(num + "", num))
+ num += 1
+
+ import scala.concurrent.duration._
+ taskContext.scheduleOnce(Duration(1, MILLISECONDS))(self ! Message("next"))
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/state/src/main/scala/org/apache/gearpump/streaming/examples/state/processor/WindowAverageProcessor.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/state/src/main/scala/org/apache/gearpump/streaming/examples/state/processor/WindowAverageProcessor.scala b/examples/streaming/state/src/main/scala/org/apache/gearpump/streaming/examples/state/processor/WindowAverageProcessor.scala
new file mode 100644
index 0000000..eea2504
--- /dev/null
+++ b/examples/streaming/state/src/main/scala/org/apache/gearpump/streaming/examples/state/processor/WindowAverageProcessor.scala
@@ -0,0 +1,54 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.state.processor
+
+import scala.collection.immutable.TreeMap
+
+import com.twitter.algebird.{AveragedGroup, AveragedValue}
+import org.slf4j.Logger
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.monoid.AlgebirdGroup
+import org.apache.gearpump.streaming.serializer.ChillSerializer
+import org.apache.gearpump.streaming.state.api.{PersistentState, PersistentTask}
+import org.apache.gearpump.streaming.state.impl.{Interval, Window, WindowConfig, WindowState}
+import org.apache.gearpump.streaming.task.TaskContext
+import org.apache.gearpump.util.LogUtil
+
+object WindowAverageProcessor {
+ val LOG: Logger = LogUtil.getLogger(classOf[WindowAverageProcessor])
+}
+
+class WindowAverageProcessor(taskContext: TaskContext, conf: UserConfig)
+ extends PersistentTask[AveragedValue](taskContext, conf) {
+
+ override def persistentState: PersistentState[AveragedValue] = {
+ val group = new AlgebirdGroup(AveragedGroup)
+ val serializer = new ChillSerializer[TreeMap[Interval, AveragedValue]]
+ val window = new Window(conf.getValue[WindowConfig](WindowConfig.NAME).get)
+ new WindowState[AveragedValue](group, serializer, taskContext, window)
+ }
+
+ override def processMessage(state: PersistentState[AveragedValue],
+ message: Message): Unit = {
+ val value = AveragedValue(message.msg.asInstanceOf[String].toLong)
+ state.update(message.timestamp, value)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/state/src/test/scala/io/gearpump/streaming/examples/state/MessageCountAppSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/state/src/test/scala/io/gearpump/streaming/examples/state/MessageCountAppSpec.scala b/examples/streaming/state/src/test/scala/io/gearpump/streaming/examples/state/MessageCountAppSpec.scala
deleted file mode 100644
index 040c343..0000000
--- a/examples/streaming/state/src/test/scala/io/gearpump/streaming/examples/state/MessageCountAppSpec.scala
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.state
-
-import scala.concurrent.Future
-import scala.util.Success
-
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{BeforeAndAfter, Matchers, PropSpec}
-
-import io.gearpump.cluster.ClientToMaster.SubmitApplication
-import io.gearpump.cluster.MasterToClient.SubmitApplicationResult
-import io.gearpump.cluster.{MasterHarness, TestUtil}
-import io.gearpump.streaming.examples.state.MessageCountApp._
-
-class MessageCountAppSpec
- extends PropSpec with PropertyChecks with Matchers with BeforeAndAfter with MasterHarness {
-
- before {
- startActorSystem()
- }
-
- after {
- shutdownActorSystem()
- }
-
- protected override def config = TestUtil.DEFAULT_CONFIG
-
- property("MessageCount should succeed to submit application with required arguments") {
- val requiredArgs = Array(
- s"-$SOURCE_TOPIC", "source",
- s"-$SINK_TOPIC", "sink",
- s"-$ZOOKEEPER_CONNECT", "localhost:2181",
- s"-$BROKER_LIST", "localhost:9092",
- s"-$DEFAULT_FS", "hdfs://localhost:9000"
- )
- val optionalArgs = Array(
- s"-$SOURCE_TASK", "2",
- s"-$COUNT_TASK", "2",
- s"-$SINK_TASK", "2"
- )
-
- val args = {
- Table(
- ("requiredArgs", "optionalArgs"),
- (requiredArgs, optionalArgs.take(0)),
- (requiredArgs, optionalArgs.take(2)),
- (requiredArgs, optionalArgs.take(4)),
- (requiredArgs, optionalArgs)
- )
- }
-
- val masterReceiver = createMockMaster()
- forAll(args) { (requiredArgs: Array[String], optionalArgs: Array[String]) =>
- val args = requiredArgs ++ optionalArgs
- Future {
- MessageCountApp.main(masterConfig, args)
- }
- masterReceiver.expectMsgType[SubmitApplication](PROCESS_BOOT_TIME)
- masterReceiver.reply(SubmitApplicationResult(Success(0)))
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/state/src/test/scala/io/gearpump/streaming/examples/state/WindowAverageAppSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/state/src/test/scala/io/gearpump/streaming/examples/state/WindowAverageAppSpec.scala b/examples/streaming/state/src/test/scala/io/gearpump/streaming/examples/state/WindowAverageAppSpec.scala
deleted file mode 100644
index 7c1c798..0000000
--- a/examples/streaming/state/src/test/scala/io/gearpump/streaming/examples/state/WindowAverageAppSpec.scala
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.state
-
-import scala.concurrent.Future
-import scala.util.Success
-
-import com.typesafe.config.Config
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{BeforeAndAfter, Matchers, PropSpec}
-
-import io.gearpump.cluster.ClientToMaster.SubmitApplication
-import io.gearpump.cluster.MasterToClient.SubmitApplicationResult
-import io.gearpump.cluster.{MasterHarness, TestUtil}
-
-class WindowAverageAppSpec
- extends PropSpec with PropertyChecks with Matchers with BeforeAndAfter with MasterHarness {
-
- before {
- startActorSystem()
- }
-
- after {
- shutdownActorSystem()
- }
-
- override def config: Config = TestUtil.DEFAULT_CONFIG
-
- property("WindowAverage should succeed to submit application with required arguments") {
- val requiredArgs = Array.empty[String]
- val optionalArgs = Array(
- "-gen", "2",
- "-window", "2",
- "-window_size", "5000",
- "-window_step", "5000"
- )
-
- val args = {
- Table(
- ("requiredArgs", "optionalArgs"),
- (requiredArgs, optionalArgs.take(0)),
- (requiredArgs, optionalArgs.take(2)),
- (requiredArgs, optionalArgs.take(4)),
- (requiredArgs, optionalArgs.take(6)),
- (requiredArgs, optionalArgs)
- )
- }
- val masterReceiver = createMockMaster()
- forAll(args) { (requiredArgs: Array[String], optionalArgs: Array[String]) =>
- val args = requiredArgs ++ optionalArgs
-
- Future {
- WindowAverageApp.main(masterConfig, args)
- }
-
- masterReceiver.expectMsgType[SubmitApplication](PROCESS_BOOT_TIME)
- masterReceiver.reply(SubmitApplicationResult(Success(0)))
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/state/src/test/scala/io/gearpump/streaming/examples/state/processor/CountProcessorSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/state/src/test/scala/io/gearpump/streaming/examples/state/processor/CountProcessorSpec.scala b/examples/streaming/state/src/test/scala/io/gearpump/streaming/examples/state/processor/CountProcessorSpec.scala
deleted file mode 100644
index a69116b..0000000
--- a/examples/streaming/state/src/test/scala/io/gearpump/streaming/examples/state/processor/CountProcessorSpec.scala
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.state.processor
-
-import scala.concurrent.Await
-import scala.concurrent.duration._
-
-import akka.actor.ActorSystem
-import akka.testkit.TestProbe
-import org.mockito.Mockito._
-import org.scalacheck.Gen
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{Matchers, PropSpec}
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.MockUtil
-import io.gearpump.streaming.state.api.PersistentTask
-import io.gearpump.streaming.state.impl.{InMemoryCheckpointStoreFactory, PersistentStateConfig}
-import io.gearpump.streaming.task.{ReportCheckpointClock, StartTime}
-import io.gearpump.streaming.transaction.api.CheckpointStoreFactory
-
-class CountProcessorSpec extends PropSpec with PropertyChecks with Matchers {
-
- property("CountProcessor should update state") {
-
- val taskContext = MockUtil.mockTaskContext
-
- implicit val system = ActorSystem("test")
-
- val longGen = Gen.chooseNum[Long](1, 1000)
- forAll(longGen) {
- (num: Long) =>
-
- val conf = UserConfig.empty
- .withBoolean(PersistentStateConfig.STATE_CHECKPOINT_ENABLE, true)
- .withLong(PersistentStateConfig.STATE_CHECKPOINT_INTERVAL_MS, num)
- .withValue[CheckpointStoreFactory](PersistentStateConfig.STATE_CHECKPOINT_STORE_FACTORY,
- new InMemoryCheckpointStoreFactory)
-
- val count = new CountProcessor(taskContext, conf)
-
- val appMaster = TestProbe()(system)
- when(taskContext.appMaster).thenReturn(appMaster.ref)
-
- count.onStart(StartTime(0L))
- appMaster.expectMsg(ReportCheckpointClock(taskContext.taskId, 0L))
-
- for (i <- 0L to num) {
- count.onNext(Message("", i))
- count.state.get shouldBe Some(i + 1)
- }
- // Next checkpoint time is not arrived yet
- when(taskContext.upstreamMinClock).thenReturn(0L)
- count.onNext(PersistentTask.CHECKPOINT)
- appMaster.expectNoMsg(10.milliseconds)
-
- // Time to checkpoint
- when(taskContext.upstreamMinClock).thenReturn(num)
- count.onNext(PersistentTask.CHECKPOINT)
- // Only the state before checkpoint time is checkpointed
- appMaster.expectMsg(ReportCheckpointClock(taskContext.taskId, num))
- }
-
- system.terminate()
- Await.result(system.whenTerminated, Duration.Inf)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/state/src/test/scala/io/gearpump/streaming/examples/state/processor/NumberGeneratorProcessorSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/state/src/test/scala/io/gearpump/streaming/examples/state/processor/NumberGeneratorProcessorSpec.scala b/examples/streaming/state/src/test/scala/io/gearpump/streaming/examples/state/processor/NumberGeneratorProcessorSpec.scala
deleted file mode 100644
index 18a49ac..0000000
--- a/examples/streaming/state/src/test/scala/io/gearpump/streaming/examples/state/processor/NumberGeneratorProcessorSpec.scala
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.state.processor
-
-import scala.concurrent.Await
-import scala.concurrent.duration.Duration
-
-import akka.actor.ActorSystem
-import akka.testkit.TestProbe
-import org.mockito.Mockito._
-import org.mockito.{Matchers => MockitoMatchers}
-import org.scalatest.{Matchers, WordSpec}
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.MockUtil
-import io.gearpump.streaming.task.StartTime
-
-class NumberGeneratorProcessorSpec extends WordSpec with Matchers {
- "NumberGeneratorProcessor" should {
- "send random numbers" in {
-
- val taskContext = MockUtil.mockTaskContext
-
- implicit val system = ActorSystem("test")
-
- val mockTaskActor = TestProbe()
-
- // Mock self ActorRef
- when(taskContext.self).thenReturn(mockTaskActor.ref)
-
- val conf = UserConfig.empty
- val genNum = new NumberGeneratorProcessor(taskContext, conf)
- genNum.onStart(StartTime(0))
- mockTaskActor.expectMsgType[Message]
-
- genNum.onNext(Message("next"))
- verify(taskContext).output(MockitoMatchers.any[Message])
- // mockTaskActor.expectMsgType[Message]
-
- system.terminate()
- Await.result(system.whenTerminated, Duration.Inf)
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/state/src/test/scala/io/gearpump/streaming/examples/state/processor/WindowAverageProcessorSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/state/src/test/scala/io/gearpump/streaming/examples/state/processor/WindowAverageProcessorSpec.scala b/examples/streaming/state/src/test/scala/io/gearpump/streaming/examples/state/processor/WindowAverageProcessorSpec.scala
deleted file mode 100644
index a9c52aa..0000000
--- a/examples/streaming/state/src/test/scala/io/gearpump/streaming/examples/state/processor/WindowAverageProcessorSpec.scala
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.state.processor
-
-import scala.concurrent.Await
-import scala.concurrent.duration._
-
-import akka.actor.ActorSystem
-import akka.testkit.TestProbe
-import com.twitter.algebird.AveragedValue
-import org.mockito.Mockito._
-import org.scalacheck.Gen
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{Matchers, PropSpec}
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.MockUtil
-import io.gearpump.streaming.state.api.PersistentTask
-import io.gearpump.streaming.state.impl.{InMemoryCheckpointStoreFactory, PersistentStateConfig, WindowConfig}
-import io.gearpump.streaming.task.{ReportCheckpointClock, StartTime}
-import io.gearpump.streaming.transaction.api.CheckpointStoreFactory
-
-class WindowAverageProcessorSpec extends PropSpec with PropertyChecks with Matchers {
- property("WindowAverageProcessor should update state") {
-
- implicit val system = ActorSystem("test")
- val longGen = Gen.chooseNum[Long](1, 1000)
- forAll(longGen, longGen) {
- (data: Long, num: Long) =>
- val taskContext = MockUtil.mockTaskContext
-
- val windowSize = num
- val windowStep = num
-
- val conf = UserConfig.empty
- .withBoolean(PersistentStateConfig.STATE_CHECKPOINT_ENABLE, true)
- .withLong(PersistentStateConfig.STATE_CHECKPOINT_INTERVAL_MS, num)
- .withValue[CheckpointStoreFactory](PersistentStateConfig.STATE_CHECKPOINT_STORE_FACTORY,
- new InMemoryCheckpointStoreFactory)
- .withValue(WindowConfig.NAME, WindowConfig(windowSize, windowStep))
-
- val windowAverage = new WindowAverageProcessor(taskContext, conf)
-
- val appMaster = TestProbe()(system)
- when(taskContext.appMaster).thenReturn(appMaster.ref)
-
- windowAverage.onStart(StartTime(0L))
- appMaster.expectMsg(ReportCheckpointClock(taskContext.taskId, 0L))
-
- for (i <- 0L until num) {
- windowAverage.onNext(Message("" + data, i))
- windowAverage.state.get shouldBe Some(AveragedValue(i + 1, data))
- }
-
- // Next checkpoint time is not arrived yet
- when(taskContext.upstreamMinClock).thenReturn(0L)
- windowAverage.onNext(PersistentTask.CHECKPOINT)
- appMaster.expectNoMsg(10.milliseconds)
-
- // Time to checkpoint
- when(taskContext.upstreamMinClock).thenReturn(num)
- windowAverage.onNext(PersistentTask.CHECKPOINT)
- appMaster.expectMsg(ReportCheckpointClock(taskContext.taskId, num))
- }
-
- system.terminate()
- Await.result(system.whenTerminated, Duration.Inf)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/state/src/test/scala/org/apache/gearpump/streaming/examples/state/MessageCountAppSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/state/src/test/scala/org/apache/gearpump/streaming/examples/state/MessageCountAppSpec.scala b/examples/streaming/state/src/test/scala/org/apache/gearpump/streaming/examples/state/MessageCountAppSpec.scala
new file mode 100644
index 0000000..729994e
--- /dev/null
+++ b/examples/streaming/state/src/test/scala/org/apache/gearpump/streaming/examples/state/MessageCountAppSpec.scala
@@ -0,0 +1,79 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.state
+
+import scala.concurrent.Future
+import scala.util.Success
+
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{BeforeAndAfter, Matchers, PropSpec}
+
+import org.apache.gearpump.cluster.ClientToMaster.SubmitApplication
+import org.apache.gearpump.cluster.MasterToClient.SubmitApplicationResult
+import org.apache.gearpump.cluster.{MasterHarness, TestUtil}
+import org.apache.gearpump.streaming.examples.state.MessageCountApp._
+
+class MessageCountAppSpec
+ extends PropSpec with PropertyChecks with Matchers with BeforeAndAfter with MasterHarness {
+
+ before {
+ startActorSystem()
+ }
+
+ after {
+ shutdownActorSystem()
+ }
+
+ protected override def config = TestUtil.DEFAULT_CONFIG
+
+ property("MessageCount should succeed to submit application with required arguments") {
+ val requiredArgs = Array(
+ s"-$SOURCE_TOPIC", "source",
+ s"-$SINK_TOPIC", "sink",
+ s"-$ZOOKEEPER_CONNECT", "localhost:2181",
+ s"-$BROKER_LIST", "localhost:9092",
+ s"-$DEFAULT_FS", "hdfs://localhost:9000"
+ )
+ val optionalArgs = Array(
+ s"-$SOURCE_TASK", "2",
+ s"-$COUNT_TASK", "2",
+ s"-$SINK_TASK", "2"
+ )
+
+ val args = {
+ Table(
+ ("requiredArgs", "optionalArgs"),
+ (requiredArgs, optionalArgs.take(0)),
+ (requiredArgs, optionalArgs.take(2)),
+ (requiredArgs, optionalArgs.take(4)),
+ (requiredArgs, optionalArgs)
+ )
+ }
+
+ val masterReceiver = createMockMaster()
+ forAll(args) { (requiredArgs: Array[String], optionalArgs: Array[String]) =>
+ val args = requiredArgs ++ optionalArgs
+ Future {
+ MessageCountApp.main(masterConfig, args)
+ }
+ masterReceiver.expectMsgType[SubmitApplication](PROCESS_BOOT_TIME)
+ masterReceiver.reply(SubmitApplicationResult(Success(0)))
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/state/src/test/scala/org/apache/gearpump/streaming/examples/state/WindowAverageAppSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/state/src/test/scala/org/apache/gearpump/streaming/examples/state/WindowAverageAppSpec.scala b/examples/streaming/state/src/test/scala/org/apache/gearpump/streaming/examples/state/WindowAverageAppSpec.scala
new file mode 100644
index 0000000..00cb290
--- /dev/null
+++ b/examples/streaming/state/src/test/scala/org/apache/gearpump/streaming/examples/state/WindowAverageAppSpec.scala
@@ -0,0 +1,76 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.state
+
+import scala.concurrent.Future
+import scala.util.Success
+
+import com.typesafe.config.Config
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{BeforeAndAfter, Matchers, PropSpec}
+
+import org.apache.gearpump.cluster.ClientToMaster.SubmitApplication
+import org.apache.gearpump.cluster.MasterToClient.SubmitApplicationResult
+import org.apache.gearpump.cluster.{MasterHarness, TestUtil}
+
+class WindowAverageAppSpec
+ extends PropSpec with PropertyChecks with Matchers with BeforeAndAfter with MasterHarness {
+
+ before {
+ startActorSystem()
+ }
+
+ after {
+ shutdownActorSystem()
+ }
+
+ override def config: Config = TestUtil.DEFAULT_CONFIG
+
+ property("WindowAverage should succeed to submit application with required arguments") {
+ val requiredArgs = Array.empty[String]
+ val optionalArgs = Array(
+ "-gen", "2",
+ "-window", "2",
+ "-window_size", "5000",
+ "-window_step", "5000"
+ )
+
+ val args = {
+ Table(
+ ("requiredArgs", "optionalArgs"),
+ (requiredArgs, optionalArgs.take(0)),
+ (requiredArgs, optionalArgs.take(2)),
+ (requiredArgs, optionalArgs.take(4)),
+ (requiredArgs, optionalArgs.take(6)),
+ (requiredArgs, optionalArgs)
+ )
+ }
+ val masterReceiver = createMockMaster()
+ forAll(args) { (requiredArgs: Array[String], optionalArgs: Array[String]) =>
+ val args = requiredArgs ++ optionalArgs
+
+ Future {
+ WindowAverageApp.main(masterConfig, args)
+ }
+
+ masterReceiver.expectMsgType[SubmitApplication](PROCESS_BOOT_TIME)
+ masterReceiver.reply(SubmitApplicationResult(Success(0)))
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/state/src/test/scala/org/apache/gearpump/streaming/examples/state/processor/CountProcessorSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/state/src/test/scala/org/apache/gearpump/streaming/examples/state/processor/CountProcessorSpec.scala b/examples/streaming/state/src/test/scala/org/apache/gearpump/streaming/examples/state/processor/CountProcessorSpec.scala
new file mode 100644
index 0000000..cdc8cb2
--- /dev/null
+++ b/examples/streaming/state/src/test/scala/org/apache/gearpump/streaming/examples/state/processor/CountProcessorSpec.scala
@@ -0,0 +1,84 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.state.processor
+
+import scala.concurrent.Await
+import scala.concurrent.duration._
+
+import akka.actor.ActorSystem
+import akka.testkit.TestProbe
+import org.mockito.Mockito._
+import org.scalacheck.Gen
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{Matchers, PropSpec}
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.MockUtil
+import org.apache.gearpump.streaming.state.api.PersistentTask
+import org.apache.gearpump.streaming.state.impl.{InMemoryCheckpointStoreFactory, PersistentStateConfig}
+import org.apache.gearpump.streaming.task.{ReportCheckpointClock, StartTime}
+import org.apache.gearpump.streaming.transaction.api.CheckpointStoreFactory
+
+class CountProcessorSpec extends PropSpec with PropertyChecks with Matchers {
+
+ property("CountProcessor should update state") {
+
+ val taskContext = MockUtil.mockTaskContext
+
+ implicit val system = ActorSystem("test")
+
+ val longGen = Gen.chooseNum[Long](1, 1000)
+ forAll(longGen) {
+ (num: Long) =>
+
+ val conf = UserConfig.empty
+ .withBoolean(PersistentStateConfig.STATE_CHECKPOINT_ENABLE, true)
+ .withLong(PersistentStateConfig.STATE_CHECKPOINT_INTERVAL_MS, num)
+ .withValue[CheckpointStoreFactory](PersistentStateConfig.STATE_CHECKPOINT_STORE_FACTORY,
+ new InMemoryCheckpointStoreFactory)
+
+ val count = new CountProcessor(taskContext, conf)
+
+ val appMaster = TestProbe()(system)
+ when(taskContext.appMaster).thenReturn(appMaster.ref)
+
+ count.onStart(StartTime(0L))
+ appMaster.expectMsg(ReportCheckpointClock(taskContext.taskId, 0L))
+
+ for (i <- 0L to num) {
+ count.onNext(Message("", i))
+ count.state.get shouldBe Some(i + 1)
+ }
+ // Next checkpoint time is not arrived yet
+ when(taskContext.upstreamMinClock).thenReturn(0L)
+ count.onNext(PersistentTask.CHECKPOINT)
+ appMaster.expectNoMsg(10.milliseconds)
+
+ // Time to checkpoint
+ when(taskContext.upstreamMinClock).thenReturn(num)
+ count.onNext(PersistentTask.CHECKPOINT)
+ // Only the state before checkpoint time is checkpointed
+ appMaster.expectMsg(ReportCheckpointClock(taskContext.taskId, num))
+ }
+
+ system.terminate()
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/state/src/test/scala/org/apache/gearpump/streaming/examples/state/processor/NumberGeneratorProcessorSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/state/src/test/scala/org/apache/gearpump/streaming/examples/state/processor/NumberGeneratorProcessorSpec.scala b/examples/streaming/state/src/test/scala/org/apache/gearpump/streaming/examples/state/processor/NumberGeneratorProcessorSpec.scala
new file mode 100644
index 0000000..2268994
--- /dev/null
+++ b/examples/streaming/state/src/test/scala/org/apache/gearpump/streaming/examples/state/processor/NumberGeneratorProcessorSpec.scala
@@ -0,0 +1,61 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.state.processor
+
+import scala.concurrent.Await
+import scala.concurrent.duration.Duration
+
+import akka.actor.ActorSystem
+import akka.testkit.TestProbe
+import org.mockito.Mockito._
+import org.mockito.{Matchers => MockitoMatchers}
+import org.scalatest.{Matchers, WordSpec}
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.MockUtil
+import org.apache.gearpump.streaming.task.StartTime
+
+class NumberGeneratorProcessorSpec extends WordSpec with Matchers {
+ "NumberGeneratorProcessor" should {
+ "send random numbers" in {
+
+ val taskContext = MockUtil.mockTaskContext
+
+ implicit val system = ActorSystem("test")
+
+ val mockTaskActor = TestProbe()
+
+ // Mock self ActorRef
+ when(taskContext.self).thenReturn(mockTaskActor.ref)
+
+ val conf = UserConfig.empty
+ val genNum = new NumberGeneratorProcessor(taskContext, conf)
+ genNum.onStart(StartTime(0))
+ mockTaskActor.expectMsgType[Message]
+
+ genNum.onNext(Message("next"))
+ verify(taskContext).output(MockitoMatchers.any[Message])
+ // mockTaskActor.expectMsgType[Message]
+
+ system.terminate()
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+ }
+}
[30/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/state/src/test/scala/org/apache/gearpump/streaming/examples/state/processor/WindowAverageProcessorSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/state/src/test/scala/org/apache/gearpump/streaming/examples/state/processor/WindowAverageProcessorSpec.scala b/examples/streaming/state/src/test/scala/org/apache/gearpump/streaming/examples/state/processor/WindowAverageProcessorSpec.scala
new file mode 100644
index 0000000..a488c9f
--- /dev/null
+++ b/examples/streaming/state/src/test/scala/org/apache/gearpump/streaming/examples/state/processor/WindowAverageProcessorSpec.scala
@@ -0,0 +1,86 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.state.processor
+
+import scala.concurrent.Await
+import scala.concurrent.duration._
+
+import akka.actor.ActorSystem
+import akka.testkit.TestProbe
+import com.twitter.algebird.AveragedValue
+import org.mockito.Mockito._
+import org.scalacheck.Gen
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{Matchers, PropSpec}
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.MockUtil
+import org.apache.gearpump.streaming.state.api.PersistentTask
+import org.apache.gearpump.streaming.state.impl.{InMemoryCheckpointStoreFactory, PersistentStateConfig, WindowConfig}
+import org.apache.gearpump.streaming.task.{ReportCheckpointClock, StartTime}
+import org.apache.gearpump.streaming.transaction.api.CheckpointStoreFactory
+
+class WindowAverageProcessorSpec extends PropSpec with PropertyChecks with Matchers {
+ property("WindowAverageProcessor should update state") {
+
+ implicit val system = ActorSystem("test")
+ val longGen = Gen.chooseNum[Long](1, 1000)
+ forAll(longGen, longGen) {
+ (data: Long, num: Long) =>
+ val taskContext = MockUtil.mockTaskContext
+
+ val windowSize = num
+ val windowStep = num
+
+ val conf = UserConfig.empty
+ .withBoolean(PersistentStateConfig.STATE_CHECKPOINT_ENABLE, true)
+ .withLong(PersistentStateConfig.STATE_CHECKPOINT_INTERVAL_MS, num)
+ .withValue[CheckpointStoreFactory](PersistentStateConfig.STATE_CHECKPOINT_STORE_FACTORY,
+ new InMemoryCheckpointStoreFactory)
+ .withValue(WindowConfig.NAME, WindowConfig(windowSize, windowStep))
+
+ val windowAverage = new WindowAverageProcessor(taskContext, conf)
+
+ val appMaster = TestProbe()(system)
+ when(taskContext.appMaster).thenReturn(appMaster.ref)
+
+ windowAverage.onStart(StartTime(0L))
+ appMaster.expectMsg(ReportCheckpointClock(taskContext.taskId, 0L))
+
+ for (i <- 0L until num) {
+ windowAverage.onNext(Message("" + data, i))
+ windowAverage.state.get shouldBe Some(AveragedValue(i + 1, data))
+ }
+
+ // Next checkpoint time is not arrived yet
+ when(taskContext.upstreamMinClock).thenReturn(0L)
+ windowAverage.onNext(PersistentTask.CHECKPOINT)
+ appMaster.expectNoMsg(10.milliseconds)
+
+ // Time to checkpoint
+ when(taskContext.upstreamMinClock).thenReturn(num)
+ windowAverage.onNext(PersistentTask.CHECKPOINT)
+ appMaster.expectMsg(ReportCheckpointClock(taskContext.taskId, num))
+ }
+
+ system.terminate()
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/stockcrawler/README.md
----------------------------------------------------------------------
diff --git a/examples/streaming/stockcrawler/README.md b/examples/streaming/stockcrawler/README.md
index 4aea13d..b51590f 100644
--- a/examples/streaming/stockcrawler/README.md
+++ b/examples/streaming/stockcrawler/README.md
@@ -6,12 +6,12 @@ How to use
```
2. Submit the stock crawler
```
- bin\gear app -jar examples\gearpump-examples-assembly-0.3.2-SNAPSHOT.jar io.gearpump.streaming.examples.stock.main.Stock
+ bin\gear app -jar examples\gearpump-examples-assembly-0.3.2-SNAPSHOT.jar org.apache.gearpump.streaming.examples.stock.main.Stock
```
If you are behind a proxy, you need to set the proxy address
```
- bin\gear app -jar examples\gearpump-examples-assembly-0.3.2-SNAPSHOT.jar io.gearpump.streaming.examples.stock.main.Stock -proxy host:port
+ bin\gear app -jar examples\gearpump-examples-assembly-0.3.2-SNAPSHOT.jar org.apache.gearpump.streaming.examples.stock.main.Stock -proxy host:port
```
3. Check the UI
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/stockcrawler/src/main/resources/geardefault.conf
----------------------------------------------------------------------
diff --git a/examples/streaming/stockcrawler/src/main/resources/geardefault.conf b/examples/streaming/stockcrawler/src/main/resources/geardefault.conf
index f557d66..acee3bd 100644
--- a/examples/streaming/stockcrawler/src/main/resources/geardefault.conf
+++ b/examples/streaming/stockcrawler/src/main/resources/geardefault.conf
@@ -1,6 +1,6 @@
gearpump {
serializers {
- "io.gearpump.streaming.examples.stock.StockPrice" = ""
+ "org.apache.gearpump.streaming.examples.stock.StockPrice" = ""
}
}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/stockcrawler/src/main/scala/io/gearpump/streaming/examples/stock/Analyzer.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/stockcrawler/src/main/scala/io/gearpump/streaming/examples/stock/Analyzer.scala b/examples/streaming/stockcrawler/src/main/scala/io/gearpump/streaming/examples/stock/Analyzer.scala
deleted file mode 100644
index 1aea563..0000000
--- a/examples/streaming/stockcrawler/src/main/scala/io/gearpump/streaming/examples/stock/Analyzer.scala
+++ /dev/null
@@ -1,170 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.stock
-
-import scala.collection.immutable
-
-import akka.actor.Actor.Receive
-import org.joda.time.DateTime
-import org.joda.time.format.{DateTimeFormat, DateTimeFormatter}
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.examples.stock.Analyzer.HistoricalStates
-import io.gearpump.streaming.examples.stock.Price._
-import io.gearpump.streaming.task.{StartTime, Task, TaskContext}
-import io.gearpump.util.LogUtil
-
-/**
- * Dradown analyzer
- * Definition: http://en.wikipedia.org/wiki/Drawdown_(economics)
- */
-class Analyzer(taskContext: TaskContext, conf: UserConfig) extends Task(taskContext, conf) {
-
- val dateFormatter = DateTimeFormat forPattern "dd/MM/yyyy"
-
- private var stocksToReport = immutable.Set.empty[String]
- private var stockInfos = new immutable.HashMap[String, StockPrice]
-
- private var currentDownwardsStates = new immutable.HashMap[String, StockPriceState]
- private val historicalStates = new HistoricalStates()
- private var latestTimeStamp: Long = 0L
-
- override def onStart(startTime: StartTime): Unit = {
- LOG.info("analyzer is started")
- }
-
- override def onNext(msg: Message): Unit = {
- msg.msg match {
- case stock: StockPrice =>
- latestTimeStamp = stock.timestamp
- checkDate(stock)
- stockInfos += stock.stockId -> stock
- val downwardsState = updateCurrentStates(stock)
- val maxDrawdown = historicalStates.updatePresentMaximal(downwardsState)
- }
- }
-
- override def receiveUnManagedMessage: Receive = {
- case get@GetReport(stockId, date) =>
- var currentMax = currentDownwardsStates.get(stockId)
-
- val dateTime = Option(date) match {
- case Some(date) =>
- currentMax = None
- parseDate(dateFormatter, date)
- case None =>
- new DateTime(latestTimeStamp).withTimeAtStartOfDay
- }
-
- val historyMax = Option(dateTime).flatMap(handleHistoricalQuery(stockId, _))
- val name = stockInfos.get(stockId).map(_.name).getOrElse("")
- sender ! Report(stockId, name, dateTime.toString, historyMax, currentMax)
- }
-
- private def updateCurrentStates(stock: StockPrice) = {
- var downwardsState: StockPriceState = null
- if (currentDownwardsStates.contains(stock.stockId)) {
- downwardsState = generateNewState(stock, currentDownwardsStates.get(stock.stockId).get)
- } else {
- downwardsState = StockPriceState(stock.stockId, stock, stock, stock)
- }
- currentDownwardsStates += stock.stockId -> downwardsState
- downwardsState
- }
-
- // Update the stock's latest state.
- private def generateNewState(currentPrice: Price, oldState: StockPriceState): StockPriceState = {
- if (currentPrice.price > oldState.max.price) {
- StockPriceState(oldState.stockID, currentPrice, currentPrice, currentPrice)
- } else {
- val newState = StockPriceState(oldState.stockID, oldState.max,
- Price.min(currentPrice, oldState.min), currentPrice)
- newState
- }
- }
-
- private def checkDate(stock: StockPrice) = {
- if (currentDownwardsStates.contains(stock.stockId)) {
- val now = new DateTime(stock.timestamp)
- val lastTime = new DateTime(currentDownwardsStates.get(stock.stockId).get.current.timestamp)
- // New day
- if (now.getDayOfYear > lastTime.getDayOfYear || now.getYear > lastTime.getYear) {
- currentDownwardsStates -= stock.stockId
- }
- }
- }
-
- private def parseDate(format: DateTimeFormatter, input: String): DateTime = {
- format.parseDateTime(input)
- }
-
- private def handleHistoricalQuery(stockId: String, date: DateTime) = {
- val maximal = historicalStates.getHistoricalMaximal(stockId, date)
- maximal
- }
-}
-
-object Analyzer {
-
- class HistoricalStates {
- val LOG = LogUtil.getLogger(getClass)
- val dateFormatter = DateTimeFormat forPattern "dd/MM/yyyy"
- private var historicalMaxRaise = new immutable.HashMap[(String, DateTime), StockPriceState]
- private var historicalMaxDrawdown = new immutable.HashMap[(String, DateTime), StockPriceState]
-
- def updatePresentMaximal(newState: StockPriceState): Option[StockPriceState] = {
- val date = Analyzer.getDateFromTimeStamp(newState.current.timestamp)
- var newMaximalState: Option[StockPriceState] = null
- if (newState.max.price < Float.MinPositiveValue) {
- newMaximalState = generateNewMaximal(newState, date, historicalMaxRaise)
- if (newMaximalState.nonEmpty) {
- historicalMaxRaise += (newState.stockID, date) -> newMaximalState.get
- }
- } else {
- newMaximalState = generateNewMaximal(newState, date, historicalMaxDrawdown)
- if (newMaximalState.nonEmpty) {
- historicalMaxDrawdown += (newState.stockID, date) -> newMaximalState.get
- }
- }
- newMaximalState
- }
-
- def getHistoricalMaximal(stockId: String, date: DateTime): Option[StockPriceState] = {
- historicalMaxDrawdown.get((stockId, date))
- }
-
- private def generateNewMaximal(
- state: StockPriceState,
- date: DateTime,
- map: immutable.HashMap[(String, DateTime), StockPriceState])
- : Option[StockPriceState] = {
- val maximal = map.get((state.stockID, date))
- if (maximal.nonEmpty && maximal.get.drawDown > state.drawDown) {
- None
- } else {
- Some(state)
- }
- }
- }
-
- def getDateFromTimeStamp(timestamp: Long): DateTime = {
- new DateTime(timestamp).withTimeAtStartOfDay()
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/stockcrawler/src/main/scala/io/gearpump/streaming/examples/stock/Crawler.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/stockcrawler/src/main/scala/io/gearpump/streaming/examples/stock/Crawler.scala b/examples/streaming/stockcrawler/src/main/scala/io/gearpump/streaming/examples/stock/Crawler.scala
deleted file mode 100644
index da5ab63..0000000
--- a/examples/streaming/stockcrawler/src/main/scala/io/gearpump/streaming/examples/stock/Crawler.scala
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.stock
-
-import scala.concurrent.duration._
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.task.{StartTime, Task, TaskContext}
-
-class Crawler(taskContext: TaskContext, conf: UserConfig) extends Task(taskContext, conf) {
-
- import taskContext._
-
- val FetchStockPrice = Message("FetchStockPrice")
-
- lazy val stocks = {
- val stockIds = conf.getValue[Array[String]]("StockId").get
- val size = if (stockIds.length % parallelism > 0) {
- stockIds.length / parallelism + 1
- } else {
- stockIds.length / parallelism
- }
-
- val start = taskId.index * size
- val end = (taskId.index + 1) * size
- stockIds.slice(start, end)
- }
-
- scheduleOnce(1.seconds)(self ! FetchStockPrice)
-
- val stockMarket = conf.getValue[StockMarket](classOf[StockMarket].getName).get
-
- override def onStart(startTime: StartTime): Unit = {
- // Nothing
- }
-
- override def onNext(msg: Message): Unit = {
- stockMarket.getPrice(stocks).foreach { price =>
- output(new Message(price, price.timestamp))
- }
- scheduleOnce(5.seconds)(self ! FetchStockPrice)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/stockcrawler/src/main/scala/io/gearpump/streaming/examples/stock/Data.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/stockcrawler/src/main/scala/io/gearpump/streaming/examples/stock/Data.scala b/examples/streaming/stockcrawler/src/main/scala/io/gearpump/streaming/examples/stock/Data.scala
deleted file mode 100644
index 5525524..0000000
--- a/examples/streaming/stockcrawler/src/main/scala/io/gearpump/streaming/examples/stock/Data.scala
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.stock
-
-// scalastyle:off equals.hash.code case class has equals defined
-case class StockPrice(
- stockId: String, name: String, price: String, delta: String, pecent: String, volume: String,
- money: String, timestamp: Long) {
- override def hashCode: Int = stockId.hashCode
-}
-// scalastyle:on equals.hash.code case class has equals defined
-
-case class Price(price: Float, timestamp: Long)
-
-object Price {
-
- import scala.language.implicitConversions
-
- implicit def StockPriceToPrice(stock: StockPrice): Price = {
- Price(stock.price.toFloat, stock.timestamp)
- }
-
- def min(first: Price, second: Price): Price = {
- if (first.price < second.price) {
- first
- } else {
- second
- }
- }
-}
-
-case class StockPriceState(stockID: String, max: Price, min: Price, current: Price) {
-
- def drawDownPeriod: Long = min.timestamp - max.timestamp
-
- def recoveryPeriod: Long = current.timestamp - min.timestamp
-
- def drawDown: Float = max.price - min.price
-}
-
-case class GetReport(stockId: String, date: String)
-
-case class Report(
- stockId: String, name: String, date: String, historyMax: Option[StockPriceState],
- currentMax: Option[StockPriceState])
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/stockcrawler/src/main/scala/io/gearpump/streaming/examples/stock/QueryServer.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/stockcrawler/src/main/scala/io/gearpump/streaming/examples/stock/QueryServer.scala b/examples/streaming/stockcrawler/src/main/scala/io/gearpump/streaming/examples/stock/QueryServer.scala
deleted file mode 100644
index 33db128..0000000
--- a/examples/streaming/stockcrawler/src/main/scala/io/gearpump/streaming/examples/stock/QueryServer.scala
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.stock
-
-import java.util.concurrent.TimeUnit
-import scala.concurrent.{ExecutionContext, Future}
-import scala.util.{Failure, Success}
-
-import akka.actor.Actor._
-import akka.actor.{Actor, ActorRefFactory, Props}
-import akka.io.IO
-import akka.pattern.ask
-import spray.can.Http
-import spray.http.StatusCodes
-import spray.json._
-import spray.routing.{HttpService, Route}
-import upickle.default.write
-
-import io.gearpump.Message
-import io.gearpump.cluster.MasterToAppMaster.AppMasterDataDetailRequest
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.ProcessorId
-import io.gearpump.streaming.appmaster.AppMaster.{LookupTaskActorRef, TaskActorRef}
-import io.gearpump.streaming.appmaster.{ProcessorSummary, StreamAppMasterSummary}
-import io.gearpump.streaming.examples.stock.QueryServer.WebServer
-import io.gearpump.streaming.task.{StartTime, Task, TaskContext, TaskId}
-
-class QueryServer(taskContext: TaskContext, conf: UserConfig) extends Task(taskContext, conf) {
- import scala.concurrent.ExecutionContext.Implicits.global
-
- import taskContext.{appId, appMaster}
-
- var analyzer: (ProcessorId, ProcessorSummary) = null
- implicit val timeOut = akka.util.Timeout(3, TimeUnit.SECONDS)
-
- override def onStart(startTime: StartTime): Unit = {
- appMaster ! AppMasterDataDetailRequest(appId)
- taskContext.actorOf(Props(new WebServer))
- }
-
- override def onNext(msg: Message): Unit = {
- // Skip
- }
-
- override def receiveUnManagedMessage: Receive = messageHandler
-
- def messageHandler: Receive = {
- case detail: StreamAppMasterSummary =>
- analyzer = detail.processors.find { kv =>
- val (processorId, processor) = kv
- processor.taskClass == classOf[Analyzer].getName
- }.get
- case getReport@GetReport(stockId, date) =>
- val parallism = analyzer._2.parallelism
- val processorId = analyzer._1
- val analyzerTaskId = TaskId(processorId, (stockId.hashCode & Integer.MAX_VALUE) % parallism)
- val requester = sender
- import scala.concurrent.Future
- (appMaster ? LookupTaskActorRef(analyzerTaskId))
- .asInstanceOf[Future[TaskActorRef]].flatMap { task =>
-
- (task.task ? getReport).asInstanceOf[Future[Report]]
- }.map { report =>
- LOG.info(s"reporting $report")
- requester ! report
- }
- case _ =>
- // Ignore
- }
-}
-
-object QueryServer {
- class WebServer extends Actor with HttpService {
-
- import context.dispatcher
- implicit val timeOut = akka.util.Timeout(3, TimeUnit.SECONDS)
- def actorRefFactory: ActorRefFactory = context
- implicit val system = context.system
-
- IO(Http) ! Http.Bind(self, interface = "localhost", port = 8080)
-
- override def receive: Receive = runRoute(webServer ~ staticRoute)
-
- def webServer: Route = {
- path("report" / Segment) { stockId =>
- get {
- onComplete((context.parent ? GetReport(stockId, null)).asInstanceOf[Future[Report]]) {
- case Success(report: Report) =>
- val json = write(report)
- complete(pretty(json))
- case Failure(ex) => complete(StatusCodes.InternalServerError,
- s"An error occurred: ${ex.getMessage}")
- }
- }
- }
- }
-
- val staticRoute = {
- pathEndOrSingleSlash {
- getFromResource("stock/stock.html")
- } ~
- pathPrefix("css") {
- get {
- getFromResourceDirectory("stock/css")
- }
- } ~
- pathPrefix("js") {
- get {
- getFromResourceDirectory("stock/js")
- }
- }
- }
-
- private def pretty(json: String): String = {
- json.parseJson.prettyPrint
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/stockcrawler/src/main/scala/io/gearpump/streaming/examples/stock/StockMarket.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/stockcrawler/src/main/scala/io/gearpump/streaming/examples/stock/StockMarket.scala b/examples/streaming/stockcrawler/src/main/scala/io/gearpump/streaming/examples/stock/StockMarket.scala
deleted file mode 100644
index 508c282..0000000
--- a/examples/streaming/stockcrawler/src/main/scala/io/gearpump/streaming/examples/stock/StockMarket.scala
+++ /dev/null
@@ -1,155 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.stock
-
-import java.nio.charset.Charset
-import scala.io.Codec
-
-import org.apache.commons.httpclient.methods.GetMethod
-import org.apache.commons.httpclient.{HttpClient, MultiThreadedHttpConnectionManager}
-import org.htmlcleaner.{HtmlCleaner, TagNode}
-import org.joda.time.{DateTime, DateTimeZone}
-
-import io.gearpump.streaming.examples.stock.StockMarket.ServiceHour
-import io.gearpump.transport.HostPort
-import io.gearpump.util.LogUtil
-
-class StockMarket(service: ServiceHour, proxy: HostPort = null) extends Serializable {
-
- private def LOG = LogUtil.getLogger(getClass)
-
- @transient
- private var connectionManager: MultiThreadedHttpConnectionManager = null
-
- private val eastMoneyStockPage = "http://quote.eastmoney.com/stocklist.html"
-
- private val stockPriceParser =
- """^var\shq_str_s_([a-z0-9A-Z]+)="([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+)";$""".r
-
- def shutdown(): Unit = {
- Option(connectionManager).map(_.shutdown())
- }
-
- @transient
- private var _client: HttpClient = null
-
- private def client: HttpClient = {
- _client = Option(_client).getOrElse {
- val connectionManager = new MultiThreadedHttpConnectionManager()
- val client = new HttpClient(connectionManager)
- Option(proxy).map(host => client.getHostConfiguration().setProxy(host.host, host.port))
- client
- }
- _client
- }
-
- def getPrice(stocks: Array[String]): Array[StockPrice] = {
-
- LOG.info(s"getPrice 1")
-
- val query = "http://hq.sinajs.cn/list=" + stocks.map("s_" + _).mkString(",")
- if (service.inService) {
-
- LOG.info(s"getPrice 2")
-
- val get = new GetMethod(query)
- client.executeMethod(get)
- val current = System.currentTimeMillis()
-
- val output = scala.io.Source.fromInputStream(get.getResponseBodyAsStream)(
- new Codec(Charset forName "GBK")).getLines().flatMap { line =>
- line match {
- case stockPriceParser(stockId, name, price, delta, pecent, volume, money) =>
- Some(StockPrice(stockId, name, price, delta, pecent, volume, money, current))
- case _ =>
- None
- }
- }.toArray
-
- LOG.info(s"getPrice 3 ${output.length}")
-
- output
- } else {
- Array.empty[StockPrice]
- }
- }
-
- private val urlPattern = """^.*/([a-zA-Z0-9]+)\.html$""".r
-
- def getStockIdList: Array[String] = {
- val cleaner = new HtmlCleaner
- val props = cleaner.getProperties
-
- val get = new GetMethod(eastMoneyStockPage)
- client.executeMethod(get)
-
- val root = cleaner.clean(get.getResponseBodyAsStream)
-
- val stockUrls = root.evaluateXPath("//div[@id='quotesearch']//li//a[@href]")
-
- val elements = root.getElementsByName("a", true)
-
- val hrefs = (0 until stockUrls.length)
- .map(stockUrls(_).asInstanceOf[TagNode].getAttributeByName("href"))
- .map { url =>
- url match {
- case urlPattern(code) => code
- case _ => null
- }
- }.toArray
- hrefs
- }
-}
-
-object StockMarket {
-
- class ServiceHour(all: Boolean) extends Serializable {
-
- /**
- * Morning openning: 9:30 am - 11:30 am
- */
- val morningStart = GMT8(new DateTime(0, 1, 1, 9, 30)).getMillis
- val morningEnd = GMT8(new DateTime(0, 1, 1, 11, 30)).getMillis
-
- /**
- * After noon openning: 13:00 pm - 15:00 pm
- */
- val afternoonStart = GMT8(new DateTime(0, 1, 1, 13, 0)).getMillis
- val afternoonEnd = GMT8(new DateTime(0, 1, 1, 15, 0)).getMillis
-
- def inService: Boolean = {
-
- if (all) {
- true
- } else {
- val now = GMT8(DateTime.now()).withDate(0, 1, 1).getMillis
- if (now >= morningStart && now <= morningEnd ||
- now >= afternoonStart && now <= afternoonEnd) {
- true
- } else {
- false
- }
- }
- }
-
- private def GMT8(time: DateTime): DateTime = {
- time.withZone(DateTimeZone.UTC).plusHours(8)
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/stockcrawler/src/main/scala/io/gearpump/streaming/examples/stock/main/Stock.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/stockcrawler/src/main/scala/io/gearpump/streaming/examples/stock/main/Stock.scala b/examples/streaming/stockcrawler/src/main/scala/io/gearpump/streaming/examples/stock/main/Stock.scala
deleted file mode 100644
index 638dc4e..0000000
--- a/examples/streaming/stockcrawler/src/main/scala/io/gearpump/streaming/examples/stock/main/Stock.scala
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.stock.main
-
-import akka.actor.ActorSystem
-import org.slf4j.Logger
-
-import io.gearpump.cluster.UserConfig
-import io.gearpump.cluster.client.ClientContext
-import io.gearpump.cluster.main.{ArgumentsParser, CLIOption, ParseResult}
-import io.gearpump.partitioner.HashPartitioner
-import io.gearpump.streaming.examples.stock.StockMarket.ServiceHour
-import io.gearpump.streaming.examples.stock.{Analyzer, Crawler, QueryServer, StockMarket}
-import io.gearpump.streaming.{Processor, StreamApplication}
-import io.gearpump.transport.HostPort
-import io.gearpump.util.Graph.Node
-import io.gearpump.util.{AkkaApp, Graph, LogUtil}
-
-/** Tracks the China's stock market index change */
-object Stock extends AkkaApp with ArgumentsParser {
-
- private val LOG: Logger = LogUtil.getLogger(getClass)
-
- override val options: Array[(String, CLIOption[Any])] = Array(
- "crawler" -> CLIOption[Int]("<how many fetcher to get data from remote>",
- required = false, defaultValue = Some(10)),
- "analyzer" -> CLIOption[Int]("<parallism of analyzer>",
- required = false, defaultValue = Some(1)),
- "proxy" -> CLIOption[String]("proxy setting host:port, for example: 127.0.0.1:8443",
- required = false, defaultValue = Some("")))
-
- def crawler(config: ParseResult)(implicit system: ActorSystem): StreamApplication = {
- val crawler = Processor[Crawler](config.getInt("crawler"))
- val analyzer = Processor[Analyzer](config.getInt("analyzer"))
- val queryServer = Processor[QueryServer](1)
-
- val proxySetting = config.getString("proxy")
- val proxy = if (proxySetting.isEmpty) {
- null
- } else HostPort(proxySetting)
- val stockMarket = new StockMarket(new ServiceHour(true), proxy)
- val stocks = stockMarket.getStockIdList
-
- // scalastyle:off println
- Console.println(s"Successfully fetched stock id for ${stocks.length} stocks")
- // scalastyle:on println
-
- val userConfig = UserConfig.empty.withValue("StockId", stocks)
- .withValue[StockMarket](classOf[StockMarket].getName, stockMarket)
- val partitioner = new HashPartitioner
-
- val p1 = crawler ~ partitioner ~> analyzer
- val p2 = Node(queryServer)
- val graph = Graph(p1, p2)
- val app = StreamApplication("stock_direct_analyzer", graph, userConfig
- )
- app
- }
-
- override def main(akkaConf: Config, args: Array[String]): Unit = {
- val config = parse(args)
- val context = ClientContext(akkaConf)
-
- implicit val system = context.system
-
- val app = crawler(config)
- val appId = context.submit(app)
- context.close()
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/stockcrawler/src/main/scala/org/apache/gearpump/streaming/examples/stock/Analyzer.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/stockcrawler/src/main/scala/org/apache/gearpump/streaming/examples/stock/Analyzer.scala b/examples/streaming/stockcrawler/src/main/scala/org/apache/gearpump/streaming/examples/stock/Analyzer.scala
new file mode 100644
index 0000000..f6fdff2
--- /dev/null
+++ b/examples/streaming/stockcrawler/src/main/scala/org/apache/gearpump/streaming/examples/stock/Analyzer.scala
@@ -0,0 +1,170 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.stock
+
+import scala.collection.immutable
+
+import akka.actor.Actor.Receive
+import org.joda.time.DateTime
+import org.joda.time.format.{DateTimeFormat, DateTimeFormatter}
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.examples.stock.Analyzer.HistoricalStates
+import org.apache.gearpump.streaming.examples.stock.Price._
+import org.apache.gearpump.streaming.task.{StartTime, Task, TaskContext}
+import org.apache.gearpump.util.LogUtil
+
+/**
+ * Dradown analyzer
+ * Definition: http://en.wikipedia.org/wiki/Drawdown_(economics)
+ */
+class Analyzer(taskContext: TaskContext, conf: UserConfig) extends Task(taskContext, conf) {
+
+ val dateFormatter = DateTimeFormat forPattern "dd/MM/yyyy"
+
+ private var stocksToReport = immutable.Set.empty[String]
+ private var stockInfos = new immutable.HashMap[String, StockPrice]
+
+ private var currentDownwardsStates = new immutable.HashMap[String, StockPriceState]
+ private val historicalStates = new HistoricalStates()
+ private var latestTimeStamp: Long = 0L
+
+ override def onStart(startTime: StartTime): Unit = {
+ LOG.info("analyzer is started")
+ }
+
+ override def onNext(msg: Message): Unit = {
+ msg.msg match {
+ case stock: StockPrice =>
+ latestTimeStamp = stock.timestamp
+ checkDate(stock)
+ stockInfos += stock.stockId -> stock
+ val downwardsState = updateCurrentStates(stock)
+ val maxDrawdown = historicalStates.updatePresentMaximal(downwardsState)
+ }
+ }
+
+ override def receiveUnManagedMessage: Receive = {
+ case get@GetReport(stockId, date) =>
+ var currentMax = currentDownwardsStates.get(stockId)
+
+ val dateTime = Option(date) match {
+ case Some(date) =>
+ currentMax = None
+ parseDate(dateFormatter, date)
+ case None =>
+ new DateTime(latestTimeStamp).withTimeAtStartOfDay
+ }
+
+ val historyMax = Option(dateTime).flatMap(handleHistoricalQuery(stockId, _))
+ val name = stockInfos.get(stockId).map(_.name).getOrElse("")
+ sender ! Report(stockId, name, dateTime.toString, historyMax, currentMax)
+ }
+
+ private def updateCurrentStates(stock: StockPrice) = {
+ var downwardsState: StockPriceState = null
+ if (currentDownwardsStates.contains(stock.stockId)) {
+ downwardsState = generateNewState(stock, currentDownwardsStates.get(stock.stockId).get)
+ } else {
+ downwardsState = StockPriceState(stock.stockId, stock, stock, stock)
+ }
+ currentDownwardsStates += stock.stockId -> downwardsState
+ downwardsState
+ }
+
+ // Update the stock's latest state.
+ private def generateNewState(currentPrice: Price, oldState: StockPriceState): StockPriceState = {
+ if (currentPrice.price > oldState.max.price) {
+ StockPriceState(oldState.stockID, currentPrice, currentPrice, currentPrice)
+ } else {
+ val newState = StockPriceState(oldState.stockID, oldState.max,
+ Price.min(currentPrice, oldState.min), currentPrice)
+ newState
+ }
+ }
+
+ private def checkDate(stock: StockPrice) = {
+ if (currentDownwardsStates.contains(stock.stockId)) {
+ val now = new DateTime(stock.timestamp)
+ val lastTime = new DateTime(currentDownwardsStates.get(stock.stockId).get.current.timestamp)
+ // New day
+ if (now.getDayOfYear > lastTime.getDayOfYear || now.getYear > lastTime.getYear) {
+ currentDownwardsStates -= stock.stockId
+ }
+ }
+ }
+
+ private def parseDate(format: DateTimeFormatter, input: String): DateTime = {
+ format.parseDateTime(input)
+ }
+
+ private def handleHistoricalQuery(stockId: String, date: DateTime) = {
+ val maximal = historicalStates.getHistoricalMaximal(stockId, date)
+ maximal
+ }
+}
+
+object Analyzer {
+
+ class HistoricalStates {
+ val LOG = LogUtil.getLogger(getClass)
+ val dateFormatter = DateTimeFormat forPattern "dd/MM/yyyy"
+ private var historicalMaxRaise = new immutable.HashMap[(String, DateTime), StockPriceState]
+ private var historicalMaxDrawdown = new immutable.HashMap[(String, DateTime), StockPriceState]
+
+ def updatePresentMaximal(newState: StockPriceState): Option[StockPriceState] = {
+ val date = Analyzer.getDateFromTimeStamp(newState.current.timestamp)
+ var newMaximalState: Option[StockPriceState] = null
+ if (newState.max.price < Float.MinPositiveValue) {
+ newMaximalState = generateNewMaximal(newState, date, historicalMaxRaise)
+ if (newMaximalState.nonEmpty) {
+ historicalMaxRaise += (newState.stockID, date) -> newMaximalState.get
+ }
+ } else {
+ newMaximalState = generateNewMaximal(newState, date, historicalMaxDrawdown)
+ if (newMaximalState.nonEmpty) {
+ historicalMaxDrawdown += (newState.stockID, date) -> newMaximalState.get
+ }
+ }
+ newMaximalState
+ }
+
+ def getHistoricalMaximal(stockId: String, date: DateTime): Option[StockPriceState] = {
+ historicalMaxDrawdown.get((stockId, date))
+ }
+
+ private def generateNewMaximal(
+ state: StockPriceState,
+ date: DateTime,
+ map: immutable.HashMap[(String, DateTime), StockPriceState])
+ : Option[StockPriceState] = {
+ val maximal = map.get((state.stockID, date))
+ if (maximal.nonEmpty && maximal.get.drawDown > state.drawDown) {
+ None
+ } else {
+ Some(state)
+ }
+ }
+ }
+
+ def getDateFromTimeStamp(timestamp: Long): DateTime = {
+ new DateTime(timestamp).withTimeAtStartOfDay()
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/stockcrawler/src/main/scala/org/apache/gearpump/streaming/examples/stock/Crawler.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/stockcrawler/src/main/scala/org/apache/gearpump/streaming/examples/stock/Crawler.scala b/examples/streaming/stockcrawler/src/main/scala/org/apache/gearpump/streaming/examples/stock/Crawler.scala
new file mode 100644
index 0000000..bb444dd
--- /dev/null
+++ b/examples/streaming/stockcrawler/src/main/scala/org/apache/gearpump/streaming/examples/stock/Crawler.scala
@@ -0,0 +1,60 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.stock
+
+import scala.concurrent.duration._
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.task.{StartTime, Task, TaskContext}
+
+class Crawler(taskContext: TaskContext, conf: UserConfig) extends Task(taskContext, conf) {
+
+ import taskContext._
+
+ val FetchStockPrice = Message("FetchStockPrice")
+
+ lazy val stocks = {
+ val stockIds = conf.getValue[Array[String]]("StockId").get
+ val size = if (stockIds.length % parallelism > 0) {
+ stockIds.length / parallelism + 1
+ } else {
+ stockIds.length / parallelism
+ }
+
+ val start = taskId.index * size
+ val end = (taskId.index + 1) * size
+ stockIds.slice(start, end)
+ }
+
+ scheduleOnce(1.seconds)(self ! FetchStockPrice)
+
+ val stockMarket = conf.getValue[StockMarket](classOf[StockMarket].getName).get
+
+ override def onStart(startTime: StartTime): Unit = {
+ // Nothing
+ }
+
+ override def onNext(msg: Message): Unit = {
+ stockMarket.getPrice(stocks).foreach { price =>
+ output(new Message(price, price.timestamp))
+ }
+ scheduleOnce(5.seconds)(self ! FetchStockPrice)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/stockcrawler/src/main/scala/org/apache/gearpump/streaming/examples/stock/Data.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/stockcrawler/src/main/scala/org/apache/gearpump/streaming/examples/stock/Data.scala b/examples/streaming/stockcrawler/src/main/scala/org/apache/gearpump/streaming/examples/stock/Data.scala
new file mode 100644
index 0000000..94a85ff
--- /dev/null
+++ b/examples/streaming/stockcrawler/src/main/scala/org/apache/gearpump/streaming/examples/stock/Data.scala
@@ -0,0 +1,61 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.stock
+
+// scalastyle:off equals.hash.code case class has equals defined
+case class StockPrice(
+ stockId: String, name: String, price: String, delta: String, pecent: String, volume: String,
+ money: String, timestamp: Long) {
+ override def hashCode: Int = stockId.hashCode
+}
+// scalastyle:on equals.hash.code case class has equals defined
+
+case class Price(price: Float, timestamp: Long)
+
+object Price {
+
+ import scala.language.implicitConversions
+
+ implicit def StockPriceToPrice(stock: StockPrice): Price = {
+ Price(stock.price.toFloat, stock.timestamp)
+ }
+
+ def min(first: Price, second: Price): Price = {
+ if (first.price < second.price) {
+ first
+ } else {
+ second
+ }
+ }
+}
+
+case class StockPriceState(stockID: String, max: Price, min: Price, current: Price) {
+
+ def drawDownPeriod: Long = min.timestamp - max.timestamp
+
+ def recoveryPeriod: Long = current.timestamp - min.timestamp
+
+ def drawDown: Float = max.price - min.price
+}
+
+case class GetReport(stockId: String, date: String)
+
+case class Report(
+ stockId: String, name: String, date: String, historyMax: Option[StockPriceState],
+ currentMax: Option[StockPriceState])
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/stockcrawler/src/main/scala/org/apache/gearpump/streaming/examples/stock/QueryServer.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/stockcrawler/src/main/scala/org/apache/gearpump/streaming/examples/stock/QueryServer.scala b/examples/streaming/stockcrawler/src/main/scala/org/apache/gearpump/streaming/examples/stock/QueryServer.scala
new file mode 100644
index 0000000..01ccb3e
--- /dev/null
+++ b/examples/streaming/stockcrawler/src/main/scala/org/apache/gearpump/streaming/examples/stock/QueryServer.scala
@@ -0,0 +1,134 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.stock
+
+import java.util.concurrent.TimeUnit
+import scala.concurrent.{ExecutionContext, Future}
+import scala.util.{Failure, Success}
+
+import akka.actor.Actor._
+import akka.actor.{Actor, ActorRefFactory, Props}
+import akka.io.IO
+import akka.pattern.ask
+import spray.can.Http
+import spray.http.StatusCodes
+import spray.json._
+import spray.routing.{HttpService, Route}
+import upickle.default.write
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.MasterToAppMaster.AppMasterDataDetailRequest
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.ProcessorId
+import org.apache.gearpump.streaming.appmaster.AppMaster.{LookupTaskActorRef, TaskActorRef}
+import org.apache.gearpump.streaming.appmaster.{ProcessorSummary, StreamAppMasterSummary}
+import org.apache.gearpump.streaming.examples.stock.QueryServer.WebServer
+import org.apache.gearpump.streaming.task.{StartTime, Task, TaskContext, TaskId}
+
+class QueryServer(taskContext: TaskContext, conf: UserConfig) extends Task(taskContext, conf) {
+ import scala.concurrent.ExecutionContext.Implicits.global
+
+ import taskContext.{appId, appMaster}
+
+ var analyzer: (ProcessorId, ProcessorSummary) = null
+ implicit val timeOut = akka.util.Timeout(3, TimeUnit.SECONDS)
+
+ override def onStart(startTime: StartTime): Unit = {
+ appMaster ! AppMasterDataDetailRequest(appId)
+ taskContext.actorOf(Props(new WebServer))
+ }
+
+ override def onNext(msg: Message): Unit = {
+ // Skip
+ }
+
+ override def receiveUnManagedMessage: Receive = messageHandler
+
+ def messageHandler: Receive = {
+ case detail: StreamAppMasterSummary =>
+ analyzer = detail.processors.find { kv =>
+ val (processorId, processor) = kv
+ processor.taskClass == classOf[Analyzer].getName
+ }.get
+ case getReport@GetReport(stockId, date) =>
+ val parallism = analyzer._2.parallelism
+ val processorId = analyzer._1
+ val analyzerTaskId = TaskId(processorId, (stockId.hashCode & Integer.MAX_VALUE) % parallism)
+ val requester = sender
+ import scala.concurrent.Future
+ (appMaster ? LookupTaskActorRef(analyzerTaskId))
+ .asInstanceOf[Future[TaskActorRef]].flatMap { task =>
+
+ (task.task ? getReport).asInstanceOf[Future[Report]]
+ }.map { report =>
+ LOG.info(s"reporting $report")
+ requester ! report
+ }
+ case _ =>
+ // Ignore
+ }
+}
+
+object QueryServer {
+ class WebServer extends Actor with HttpService {
+
+ import context.dispatcher
+ implicit val timeOut = akka.util.Timeout(3, TimeUnit.SECONDS)
+ def actorRefFactory: ActorRefFactory = context
+ implicit val system = context.system
+
+ IO(Http) ! Http.Bind(self, interface = "localhost", port = 8080)
+
+ override def receive: Receive = runRoute(webServer ~ staticRoute)
+
+ def webServer: Route = {
+ path("report" / Segment) { stockId =>
+ get {
+ onComplete((context.parent ? GetReport(stockId, null)).asInstanceOf[Future[Report]]) {
+ case Success(report: Report) =>
+ val json = write(report)
+ complete(pretty(json))
+ case Failure(ex) => complete(StatusCodes.InternalServerError,
+ s"An error occurred: ${ex.getMessage}")
+ }
+ }
+ }
+ }
+
+ val staticRoute = {
+ pathEndOrSingleSlash {
+ getFromResource("stock/stock.html")
+ } ~
+ pathPrefix("css") {
+ get {
+ getFromResourceDirectory("stock/css")
+ }
+ } ~
+ pathPrefix("js") {
+ get {
+ getFromResourceDirectory("stock/js")
+ }
+ }
+ }
+
+ private def pretty(json: String): String = {
+ json.parseJson.prettyPrint
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/stockcrawler/src/main/scala/org/apache/gearpump/streaming/examples/stock/StockMarket.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/stockcrawler/src/main/scala/org/apache/gearpump/streaming/examples/stock/StockMarket.scala b/examples/streaming/stockcrawler/src/main/scala/org/apache/gearpump/streaming/examples/stock/StockMarket.scala
new file mode 100644
index 0000000..24e050b
--- /dev/null
+++ b/examples/streaming/stockcrawler/src/main/scala/org/apache/gearpump/streaming/examples/stock/StockMarket.scala
@@ -0,0 +1,155 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.stock
+
+import java.nio.charset.Charset
+import scala.io.Codec
+
+import org.apache.commons.httpclient.methods.GetMethod
+import org.apache.commons.httpclient.{HttpClient, MultiThreadedHttpConnectionManager}
+import org.htmlcleaner.{HtmlCleaner, TagNode}
+import org.joda.time.{DateTime, DateTimeZone}
+
+import org.apache.gearpump.streaming.examples.stock.StockMarket.ServiceHour
+import org.apache.gearpump.transport.HostPort
+import org.apache.gearpump.util.LogUtil
+
+class StockMarket(service: ServiceHour, proxy: HostPort = null) extends Serializable {
+
+ private def LOG = LogUtil.getLogger(getClass)
+
+ @transient
+ private var connectionManager: MultiThreadedHttpConnectionManager = null
+
+ private val eastMoneyStockPage = "http://quote.eastmoney.com/stocklist.html"
+
+ private val stockPriceParser =
+ """^var\shq_str_s_([a-z0-9A-Z]+)="([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+)";$""".r
+
+ def shutdown(): Unit = {
+ Option(connectionManager).map(_.shutdown())
+ }
+
+ @transient
+ private var _client: HttpClient = null
+
+ private def client: HttpClient = {
+ _client = Option(_client).getOrElse {
+ val connectionManager = new MultiThreadedHttpConnectionManager()
+ val client = new HttpClient(connectionManager)
+ Option(proxy).map(host => client.getHostConfiguration().setProxy(host.host, host.port))
+ client
+ }
+ _client
+ }
+
+ def getPrice(stocks: Array[String]): Array[StockPrice] = {
+
+ LOG.info(s"getPrice 1")
+
+ val query = "http://hq.sinajs.cn/list=" + stocks.map("s_" + _).mkString(",")
+ if (service.inService) {
+
+ LOG.info(s"getPrice 2")
+
+ val get = new GetMethod(query)
+ client.executeMethod(get)
+ val current = System.currentTimeMillis()
+
+ val output = scala.io.Source.fromInputStream(get.getResponseBodyAsStream)(
+ new Codec(Charset forName "GBK")).getLines().flatMap { line =>
+ line match {
+ case stockPriceParser(stockId, name, price, delta, pecent, volume, money) =>
+ Some(StockPrice(stockId, name, price, delta, pecent, volume, money, current))
+ case _ =>
+ None
+ }
+ }.toArray
+
+ LOG.info(s"getPrice 3 ${output.length}")
+
+ output
+ } else {
+ Array.empty[StockPrice]
+ }
+ }
+
+ private val urlPattern = """^.*/([a-zA-Z0-9]+)\.html$""".r
+
+ def getStockIdList: Array[String] = {
+ val cleaner = new HtmlCleaner
+ val props = cleaner.getProperties
+
+ val get = new GetMethod(eastMoneyStockPage)
+ client.executeMethod(get)
+
+ val root = cleaner.clean(get.getResponseBodyAsStream)
+
+ val stockUrls = root.evaluateXPath("//div[@id='quotesearch']//li//a[@href]")
+
+ val elements = root.getElementsByName("a", true)
+
+ val hrefs = (0 until stockUrls.length)
+ .map(stockUrls(_).asInstanceOf[TagNode].getAttributeByName("href"))
+ .map { url =>
+ url match {
+ case urlPattern(code) => code
+ case _ => null
+ }
+ }.toArray
+ hrefs
+ }
+}
+
+object StockMarket {
+
+ class ServiceHour(all: Boolean) extends Serializable {
+
+ /**
+ * Morning openning: 9:30 am - 11:30 am
+ */
+ val morningStart = GMT8(new DateTime(0, 1, 1, 9, 30)).getMillis
+ val morningEnd = GMT8(new DateTime(0, 1, 1, 11, 30)).getMillis
+
+ /**
+ * After noon openning: 13:00 pm - 15:00 pm
+ */
+ val afternoonStart = GMT8(new DateTime(0, 1, 1, 13, 0)).getMillis
+ val afternoonEnd = GMT8(new DateTime(0, 1, 1, 15, 0)).getMillis
+
+ def inService: Boolean = {
+
+ if (all) {
+ true
+ } else {
+ val now = GMT8(DateTime.now()).withDate(0, 1, 1).getMillis
+ if (now >= morningStart && now <= morningEnd ||
+ now >= afternoonStart && now <= afternoonEnd) {
+ true
+ } else {
+ false
+ }
+ }
+ }
+
+ private def GMT8(time: DateTime): DateTime = {
+ time.withZone(DateTimeZone.UTC).plusHours(8)
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/stockcrawler/src/main/scala/org/apache/gearpump/streaming/examples/stock/main/Stock.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/stockcrawler/src/main/scala/org/apache/gearpump/streaming/examples/stock/main/Stock.scala b/examples/streaming/stockcrawler/src/main/scala/org/apache/gearpump/streaming/examples/stock/main/Stock.scala
new file mode 100644
index 0000000..6d17c20
--- /dev/null
+++ b/examples/streaming/stockcrawler/src/main/scala/org/apache/gearpump/streaming/examples/stock/main/Stock.scala
@@ -0,0 +1,86 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.stock.main
+
+import akka.actor.ActorSystem
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.cluster.client.ClientContext
+import org.apache.gearpump.cluster.main.{ArgumentsParser, CLIOption, ParseResult}
+import org.apache.gearpump.partitioner.HashPartitioner
+import org.apache.gearpump.streaming.examples.stock.StockMarket.ServiceHour
+import org.apache.gearpump.streaming.examples.stock.{Analyzer, Crawler, QueryServer, StockMarket}
+import org.apache.gearpump.streaming.{Processor, StreamApplication}
+import org.apache.gearpump.transport.HostPort
+import org.apache.gearpump.util.Graph.Node
+import org.apache.gearpump.util.{AkkaApp, Graph, LogUtil}
+
+/** Tracks the China's stock market index change */
+object Stock extends AkkaApp with ArgumentsParser {
+
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+
+ override val options: Array[(String, CLIOption[Any])] = Array(
+ "crawler" -> CLIOption[Int]("<how many fetcher to get data from remote>",
+ required = false, defaultValue = Some(10)),
+ "analyzer" -> CLIOption[Int]("<parallism of analyzer>",
+ required = false, defaultValue = Some(1)),
+ "proxy" -> CLIOption[String]("proxy setting host:port, for example: 127.0.0.1:8443",
+ required = false, defaultValue = Some("")))
+
+ def crawler(config: ParseResult)(implicit system: ActorSystem): StreamApplication = {
+ val crawler = Processor[Crawler](config.getInt("crawler"))
+ val analyzer = Processor[Analyzer](config.getInt("analyzer"))
+ val queryServer = Processor[QueryServer](1)
+
+ val proxySetting = config.getString("proxy")
+ val proxy = if (proxySetting.isEmpty) {
+ null
+ } else HostPort(proxySetting)
+ val stockMarket = new StockMarket(new ServiceHour(true), proxy)
+ val stocks = stockMarket.getStockIdList
+
+ // scalastyle:off println
+ Console.println(s"Successfully fetched stock id for ${stocks.length} stocks")
+ // scalastyle:on println
+
+ val userConfig = UserConfig.empty.withValue("StockId", stocks)
+ .withValue[StockMarket](classOf[StockMarket].getName, stockMarket)
+ val partitioner = new HashPartitioner
+
+ val p1 = crawler ~ partitioner ~> analyzer
+ val p2 = Node(queryServer)
+ val graph = Graph(p1, p2)
+ val app = StreamApplication("stock_direct_analyzer", graph, userConfig
+ )
+ app
+ }
+
+ override def main(akkaConf: Config, args: Array[String]): Unit = {
+ val config = parse(args)
+ val context = ClientContext(akkaConf)
+
+ implicit val system = context.system
+
+ val app = crawler(config)
+ val appId = context.submit(app)
+ context.close()
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/transport/src/main/resources/geardefault.conf
----------------------------------------------------------------------
diff --git a/examples/streaming/transport/src/main/resources/geardefault.conf b/examples/streaming/transport/src/main/resources/geardefault.conf
index 165bce5..0c8f421 100644
--- a/examples/streaming/transport/src/main/resources/geardefault.conf
+++ b/examples/streaming/transport/src/main/resources/geardefault.conf
@@ -2,8 +2,8 @@ gearpump {
serializers {
## Follow this format when adding new serializer for new message types
- ## "io.gearpump.Message" = "io.gearpump.streaming.MessageSerializer"
- "io.gearpump.streaming.examples.transport.PassRecord" = ""
+ ## "org.apache.gearpump.Message" = "org.apache.gearpump.streaming.MessageSerializer"
+ "org.apache.gearpump.streaming.examples.transport.PassRecord" = ""
}
}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/transport/src/main/scala/io/gearpump/streaming/examples/transport/Data.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/transport/src/main/scala/io/gearpump/streaming/examples/transport/Data.scala b/examples/streaming/transport/src/main/scala/io/gearpump/streaming/examples/transport/Data.scala
deleted file mode 100644
index 788f92a..0000000
--- a/examples/streaming/transport/src/main/scala/io/gearpump/streaming/examples/transport/Data.scala
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.examples.transport
-
-case class LocationInfo(id: String, row: Int, column: Int)
-
-// scalastyle:off equals.hash.code
-case class PassRecord(vehicleId: String, locationId: String, timeStamp: Long) {
- override def hashCode: Int = vehicleId.hashCode
-}
-// scalastyle:on equals.hash.code
-
-case class GetTrace(vehicleId: String)
-
-case class VehicleTrace(records: Array[PassRecord])
-
-case class OverSpeedReport(vehicleId: String, speed: String, timestamp: Long, locationId: String)
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/transport/src/main/scala/io/gearpump/streaming/examples/transport/DataSource.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/transport/src/main/scala/io/gearpump/streaming/examples/transport/DataSource.scala b/examples/streaming/transport/src/main/scala/io/gearpump/streaming/examples/transport/DataSource.scala
deleted file mode 100644
index 33d7b54..0000000
--- a/examples/streaming/transport/src/main/scala/io/gearpump/streaming/examples/transport/DataSource.scala
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.examples.transport
-
-import scala.concurrent.duration._
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.examples.transport.generator.{MockCity, PassRecordGenerator}
-import io.gearpump.streaming.task.{StartTime, Task, TaskContext, TaskId}
-
-class DataSource(taskContext: TaskContext, conf: UserConfig) extends Task(taskContext, conf) {
- import taskContext.{output, parallelism, scheduleOnce, taskId}
- private val overdriveThreshold = conf.getInt(VelocityInspector.OVER_DRIVE_THRESHOLD).get
- private val vehicleNum = conf.getInt(DataSource.VEHICLE_NUM).get / parallelism
- private val citySize = conf.getInt(DataSource.MOCK_CITY_SIZE).get
- private val mockCity = new MockCity(citySize)
- private val recordGenerators: Array[PassRecordGenerator] =
- PassRecordGenerator.create(vehicleNum, getIdentifier(taskId), mockCity, overdriveThreshold)
-
- override def onStart(startTime: StartTime): Unit = {
- self ! Message("start", System.currentTimeMillis())
- }
-
- override def onNext(msg: Message): Unit = {
- recordGenerators.foreach(generator =>
- output(Message(generator.getNextPassRecord(), System.currentTimeMillis())))
- scheduleOnce(1.second)(self ! Message("continue", System.currentTimeMillis()))
- }
-
- private def getIdentifier(taskId: TaskId): String = {
- // scalastyle:off non.ascii.character.disallowed
- s"\u6caaA${taskId.processorId}${taskId.index}"
- // scalastyle:on non.ascii.character.disallowed
- }
-}
-
-object DataSource {
- final val VEHICLE_NUM = "vehicle.number"
- final val MOCK_CITY_SIZE = "mock.city.size"
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/transport/src/main/scala/io/gearpump/streaming/examples/transport/QueryServer.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/transport/src/main/scala/io/gearpump/streaming/examples/transport/QueryServer.scala b/examples/streaming/transport/src/main/scala/io/gearpump/streaming/examples/transport/QueryServer.scala
deleted file mode 100644
index f9dbbde..0000000
--- a/examples/streaming/transport/src/main/scala/io/gearpump/streaming/examples/transport/QueryServer.scala
+++ /dev/null
@@ -1,154 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.examples.transport
-
-import java.util.concurrent.TimeUnit
-import scala.concurrent.Future
-import scala.util.{Failure, Success}
-
-import akka.actor.Actor._
-import akka.actor.{Actor, ActorRefFactory, Props}
-import akka.io.IO
-import akka.pattern.ask
-import spray.can.Http
-import spray.http.StatusCodes
-import spray.json._
-import spray.routing.{HttpService, Route}
-import upickle.default.write
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.partitioner.PartitionerDescription
-import io.gearpump.streaming.appmaster.AppMaster.{LookupTaskActorRef, TaskActorRef}
-import io.gearpump.streaming.examples.transport.QueryServer.{GetAllRecords, WebServer}
-import io.gearpump.streaming.task.{StartTime, Task, TaskContext, TaskId}
-import io.gearpump.streaming.{DAG, ProcessorDescription, ProcessorId, StreamApplication}
-import io.gearpump.util.Graph
-
-class QueryServer(taskContext: TaskContext, conf: UserConfig) extends Task(taskContext, conf) {
- import system.dispatcher
- import taskContext.appMaster
-
- var inspector: (ProcessorId, ProcessorDescription) = null
- implicit val timeOut = akka.util.Timeout(3, TimeUnit.SECONDS)
- private var overSpeedRecords = List.empty[OverSpeedReport]
-
- override def onStart(startTime: StartTime): Unit = {
- val dag = DAG(conf.getValue[Graph[ProcessorDescription, PartitionerDescription]](
- StreamApplication.DAG).get)
- inspector = dag.processors.find { kv =>
- val (_, processor) = kv
- processor.taskClass == classOf[VelocityInspector].getName
- }.get
- taskContext.actorOf(Props(new WebServer))
- }
-
- override def onNext(msg: Message): Unit = {
- }
-
- override def receiveUnManagedMessage: Receive = {
- case getTrace@GetTrace(vehicleId: String) =>
- val parallism = inspector._2.parallelism
- val processorId = inspector._1
- val analyzerTaskId = TaskId(processorId, (vehicleId.hashCode & Integer.MAX_VALUE) % parallism)
- val requester = sender
- (appMaster ? LookupTaskActorRef(analyzerTaskId))
- .asInstanceOf[Future[TaskActorRef]].flatMap { task =>
- (task.task ? getTrace).asInstanceOf[Future[VehicleTrace]]
- }.map { trace =>
- LOG.info(s"reporting $trace")
- requester ! trace
- }
- case record@OverSpeedReport(vehicleId, speed, timestamp, locationId) =>
- LOG.info(s"vehicle $vehicleId is over speed, the speed is $speed km/h")
- overSpeedRecords :+= record
- case GetAllRecords =>
- sender ! QueryServer.OverSpeedRecords(overSpeedRecords.toArray.sortBy(_.timestamp))
- overSpeedRecords = List.empty[OverSpeedReport]
- case _ =>
- // Ignore
- }
-}
-
-object QueryServer {
- object GetAllRecords
-
- case class OverSpeedRecords(records: Array[OverSpeedReport])
-
- class WebServer extends Actor with HttpService {
-
- import context.dispatcher
- implicit val timeOut = akka.util.Timeout(3, TimeUnit.SECONDS)
- def actorRefFactory: ActorRefFactory = context
- implicit val system = context.system
-
- IO(Http) ! Http.Bind(self, interface = "0.0.0.0", port = 8080)
-
- override def receive: Receive = runRoute(webServer ~ staticRoute)
-
- def webServer: Route = {
- path("trace" / Segment) { vehicleId =>
- get {
- onComplete((context.parent ? GetTrace(vehicleId)).asInstanceOf[Future[VehicleTrace]]) {
- case Success(trace: VehicleTrace) =>
- val json = write(trace)
- complete(pretty(json))
- case Failure(ex) => complete(StatusCodes.InternalServerError,
- s"An error occurred: ${ex.getMessage}")
- }
- }
- } ~
- path("records") {
- get {
- onComplete((context.parent ? GetAllRecords).asInstanceOf[Future[OverSpeedRecords]]) {
- case Success(records: OverSpeedRecords) =>
- val json = write(records)
- complete(pretty(json))
- case Failure(ex) => complete(StatusCodes.InternalServerError,
- s"An error occurred: ${ex.getMessage}")
- }
- }
- }
- }
-
- val staticRoute = {
- pathEndOrSingleSlash {
- getFromResource("transport/transport.html")
- } ~
- pathPrefix("css") {
- get {
- getFromResourceDirectory("transport/css")
- }
- } ~
- pathPrefix("svg") {
- get {
- getFromResourceDirectory("transport/svg")
- }
- } ~
- pathPrefix("js") {
- get {
- getFromResourceDirectory("transport/js")
- }
- }
- }
-
- private def pretty(json: String): String = {
- json.parseJson.prettyPrint
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/transport/src/main/scala/io/gearpump/streaming/examples/transport/Transport.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/transport/src/main/scala/io/gearpump/streaming/examples/transport/Transport.scala b/examples/streaming/transport/src/main/scala/io/gearpump/streaming/examples/transport/Transport.scala
deleted file mode 100644
index a795277..0000000
--- a/examples/streaming/transport/src/main/scala/io/gearpump/streaming/examples/transport/Transport.scala
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.examples.transport
-
-import io.gearpump.cluster.UserConfig
-import io.gearpump.cluster.client.ClientContext
-import io.gearpump.cluster.main.{ArgumentsParser, CLIOption, ParseResult}
-import io.gearpump.partitioner.HashPartitioner
-import io.gearpump.streaming.{Processor, StreamApplication}
-import io.gearpump.util.Graph._
-import io.gearpump.util.{AkkaApp, Graph}
-
-/** A city smart transportation streaming application */
-object Transport extends AkkaApp with ArgumentsParser {
- override val options: Array[(String, CLIOption[Any])] = Array(
- "source" -> CLIOption[Int]("<how many task to generate data>", required = false,
- defaultValue = Some(10)),
- "inspector" -> CLIOption[Int]("<how many over speed inspector>", required = false,
- defaultValue = Some(4)),
- "vehicle" -> CLIOption[Int]("<how many vehicles's to generate>", required = false,
- defaultValue = Some(1000)),
- "citysize" -> CLIOption[Int]("<the blocks number of the mock city>", required = false,
- defaultValue = Some(10)),
- "threshold" -> CLIOption[Int]("<overdrive threshold, km/h>", required = false,
- defaultValue = Some(60)))
-
- def application(config: ParseResult): StreamApplication = {
- val sourceNum = config.getInt("source")
- val inspectorNum = config.getInt("inspector")
- val vehicleNum = config.getInt("vehicle")
- val citysize = config.getInt("citysize")
- val threshold = config.getInt("threshold")
- val source = Processor[DataSource](sourceNum)
- val inspector = Processor[VelocityInspector](inspectorNum)
- val queryServer = Processor[QueryServer](1)
- val partitioner = new HashPartitioner
-
- val userConfig = UserConfig.empty.withInt(DataSource.VEHICLE_NUM, vehicleNum).
- withInt(DataSource.MOCK_CITY_SIZE, citysize).
- withInt(VelocityInspector.OVER_DRIVE_THRESHOLD, threshold).
- withInt(VelocityInspector.FAKE_PLATE_THRESHOLD, 200)
- StreamApplication("transport", Graph(source ~ partitioner ~> inspector,
- Node(queryServer)), userConfig)
- }
-
- override def main(akkaConf: Config, args: Array[String]): Unit = {
- val config = parse(args)
- val context = ClientContext(akkaConf)
- implicit val system = context.system
- context.submit(application(config))
- context.close()
- }
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/transport/src/main/scala/io/gearpump/streaming/examples/transport/VelocityInspector.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/transport/src/main/scala/io/gearpump/streaming/examples/transport/VelocityInspector.scala b/examples/streaming/transport/src/main/scala/io/gearpump/streaming/examples/transport/VelocityInspector.scala
deleted file mode 100644
index b9be8d7..0000000
--- a/examples/streaming/transport/src/main/scala/io/gearpump/streaming/examples/transport/VelocityInspector.scala
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.examples.transport
-
-import java.util.concurrent.TimeUnit
-import scala.collection.immutable.Queue
-import scala.collection.mutable
-import scala.concurrent.Future
-
-import akka.actor.Actor._
-import akka.actor.ActorRef
-import akka.pattern.ask
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.partitioner.PartitionerDescription
-import io.gearpump.streaming.appmaster.AppMaster.{LookupTaskActorRef, TaskActorRef}
-import io.gearpump.streaming.examples.transport.generator.MockCity
-import io.gearpump.streaming.task.{StartTime, Task, TaskContext, TaskId}
-import io.gearpump.streaming.{DAG, ProcessorDescription, StreamApplication}
-import io.gearpump.util.Graph
-
-class VelocityInspector(taskContext: TaskContext, conf: UserConfig)
- extends Task(taskContext, conf) {
-
- import system.dispatcher
- import taskContext.appMaster
- implicit val timeOut = akka.util.Timeout(3, TimeUnit.SECONDS)
- private val passRecords = mutable.Map.empty[String, Queue[PassRecord]]
- private val fakePlateThreshold = conf.getInt(VelocityInspector.FAKE_PLATE_THRESHOLD).get
- private val overdriveThreshold = conf.getInt(VelocityInspector.OVER_DRIVE_THRESHOLD).get
- private val citySize = conf.getInt(DataSource.MOCK_CITY_SIZE).get
- private val mockCity = new MockCity(citySize)
- private var queryServerActor: ActorRef = null
-
- override def onStart(startTime: StartTime): Unit = {
- val dag = DAG(conf.getValue[Graph[ProcessorDescription, PartitionerDescription]](
- StreamApplication.DAG).get)
- val queryServer = dag.processors.find { kv =>
- val (_, processor) = kv
- processor.taskClass == classOf[QueryServer].getName
- }.get
- val queryServerTaskId = TaskId(queryServer._1, 0)
- (appMaster ? LookupTaskActorRef(queryServerTaskId)).asInstanceOf[Future[TaskActorRef]]
- .map { task =>
- queryServerActor = task.task
- }
- }
-
- import io.gearpump.streaming.examples.transport.VelocityInspector._
- override def onNext(msg: Message): Unit = {
- msg.msg match {
- case passRecord: PassRecord =>
- val records = passRecords.getOrElse(passRecord.vehicleId, Queue.empty[PassRecord])
- if (records.size > 0) {
- val velocity = getVelocity(passRecord, records.last)
- val formatted = "%.2f".format(velocity)
- if (velocity > overdriveThreshold) {
- if (velocity > fakePlateThreshold) {
- LOG.info(s"vehicle ${passRecord.vehicleId} maybe a fake plate, " +
- s"the speed is $formatted km/h")
- }
- if (queryServerActor != null) {
- queryServerActor ! OverSpeedReport(passRecord.vehicleId, formatted,
- passRecord.timeStamp, passRecord.locationId)
- }
- }
- }
- passRecords.update(passRecord.vehicleId, records.enqueueFinite(passRecord, RECORDS_NUM))
- }
- }
-
- override def receiveUnManagedMessage: Receive = {
- case GetTrace(vehicleId) =>
- val records = passRecords.getOrElse(vehicleId, Queue.empty[PassRecord])
- sender ! VehicleTrace(records.toArray.sortBy(_.timeStamp))
- }
-
- private def getVelocity(passRecord: PassRecord, lastPassRecord: PassRecord): Float = {
- val distanceInKm = getDistance(lastPassRecord.locationId, passRecord.locationId)
- val timeInHour = (passRecord.timeStamp - lastPassRecord.timeStamp).toFloat / (1000 * 60 * 60)
- distanceInKm / timeInHour
- }
-
- private def getDistance(location1: String, location2: String): Long = {
- mockCity.getDistance(location1, location2)
- }
-}
-
-object VelocityInspector {
- final val OVER_DRIVE_THRESHOLD = "overdrive.threshold"
- final val FAKE_PLATE_THRESHOLD = "fakeplate.threshold"
- final val RECORDS_NUM = 20
-
- class FiniteQueue[T](q: Queue[T]) {
- def enqueueFinite[B >: T](elem: B, maxSize: Int): Queue[B] = {
- var result = q.enqueue(elem)
- while (result.size > maxSize) {
- result = result.dequeue._2
- }
- result
- }
- }
-
- import scala.language.implicitConversions
-
- implicit def queue2FiniteQueue[T](q: Queue[T]): FiniteQueue[T] = new FiniteQueue[T](q)
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/transport/src/main/scala/io/gearpump/streaming/examples/transport/generator/MockCity.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/transport/src/main/scala/io/gearpump/streaming/examples/transport/generator/MockCity.scala b/examples/streaming/transport/src/main/scala/io/gearpump/streaming/examples/transport/generator/MockCity.scala
deleted file mode 100644
index ff78679..0000000
--- a/examples/streaming/transport/src/main/scala/io/gearpump/streaming/examples/transport/generator/MockCity.scala
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.examples.transport.generator
-
-import scala.util.Random
-
-import io.gearpump.streaming.examples.transport.generator.MockCity._
-
-class MockCity(size: Int) {
- private val random = new Random()
- private val directions = Array(UP, DOWN, LEFT, RIGHT)
-
- def nextLocation(currentLocationId: String): String = {
- val coordinate = idToCoordinate(currentLocationId)
- val direction = directions(random.nextInt(4))
- val newCoordinate = coordinate.addOffset(direction)
- if (inCity(newCoordinate)) {
- coordinateToId(newCoordinate)
- } else {
- nextLocation(currentLocationId)
- }
- }
-
- def getDistance(locationId1: String, locationId2: String): Long = {
- val coordinate1 = idToCoordinate(locationId1)
- val coordinate2 = idToCoordinate(locationId2)
- val blocks = Math.abs(coordinate1.row - coordinate2.row) +
- Math.abs(coordinate1.column - coordinate2.column)
- blocks * LENGTH_PER_BLOCK
- }
-
- def randomLocationId(): String = {
- val row = random.nextInt(size)
- val column = random.nextInt(size)
- coordinateToId(Coordinate(row, column))
- }
-
- private def coordinateToId(coordinate: Coordinate): String = {
- s"Id_${coordinate.row}_${coordinate.column}"
- }
-
- private def idToCoordinate(locationId: String): Coordinate = {
- val attr = locationId.split("_")
- val row = attr(1).toInt
- val column = attr(2).toInt
- Coordinate(row, column)
- }
-
- private def inCity(coordinate: Coordinate): Boolean = {
- coordinate.row >= 0 &&
- coordinate.row < size &&
- coordinate.column >= 0 &&
- coordinate.column < size
- }
-}
-
-object MockCity {
- // The length of the mock city, km
- final val LENGTH_PER_BLOCK = 5
- // The minimal speed, km/h
- final val MINIMAL_SPEED = 10
-
- final val UP = Coordinate(0, 1)
- final val DOWN = Coordinate(0, -1)
- final val LEFT = Coordinate(-1, 0)
- final val RIGHT = Coordinate(1, 0)
-
- case class Coordinate(row: Int, column: Int) {
- def addOffset(coordinate: Coordinate): Coordinate = {
- Coordinate(this.row + coordinate.row, this.column + coordinate.column)
- }
- }
-}
[48/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/java/io/gearpump/transport/netty/WrappedChannelBuffer.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/io/gearpump/transport/netty/WrappedChannelBuffer.java b/core/src/main/java/io/gearpump/transport/netty/WrappedChannelBuffer.java
deleted file mode 100644
index 3531f3b..0000000
--- a/core/src/main/java/io/gearpump/transport/netty/WrappedChannelBuffer.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.transport.netty;
-
-import org.jboss.netty.buffer.ChannelBuffer;
-
-import java.io.DataInput;
-import java.io.IOException;
-
-/** Wrap ChannelBuffer as a DataInput */
-public class WrappedChannelBuffer implements DataInput {
- private ChannelBuffer channelBuffer;
-
- public WrappedChannelBuffer() {
- }
-
- public WrappedChannelBuffer(ChannelBuffer channelBuffer) {
- this.channelBuffer = channelBuffer;
- }
-
- public void setChannelBuffer(ChannelBuffer channelBuffer) {
- this.channelBuffer = channelBuffer;
- }
-
- @Override
- public void readFully(byte[] b) throws IOException {
- channelBuffer.readBytes(b);
- }
-
- @Override
- public void readFully(byte[] b, int off, int len) throws IOException {
- channelBuffer.readBytes(b, off, len);
- }
-
- @Override
- public int skipBytes(int n) throws IOException {
- channelBuffer.skipBytes(n);
- return n;
- }
-
- @Override
- public boolean readBoolean() throws IOException {
- return channelBuffer.readByte() != 0;
- }
-
- @Override
- public byte readByte() throws IOException {
- return channelBuffer.readByte();
- }
-
- @Override
- public int readUnsignedByte() throws IOException {
- return channelBuffer.readUnsignedByte();
- }
-
- @Override
- public short readShort() throws IOException {
- return channelBuffer.readShort();
- }
-
- @Override
- public int readUnsignedShort() throws IOException {
- return channelBuffer.readUnsignedShort();
- }
-
- @Override
- public char readChar() throws IOException {
- return channelBuffer.readChar();
- }
-
- @Override
- public int readInt() throws IOException {
- return channelBuffer.readInt();
- }
-
- @Override
- public long readLong() throws IOException {
- return channelBuffer.readLong();
- }
-
- @Override
- public float readFloat() throws IOException {
- return channelBuffer.readFloat();
- }
-
- @Override
- public double readDouble() throws IOException {
- return channelBuffer.readDouble();
- }
-
- @Override
- public String readLine() throws IOException {
- throw new UnsupportedOperationException("readLine is not supported");
- }
-
- @Override
- public String readUTF() throws IOException {
- throw new UnsupportedOperationException("readUTF is not supported");
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/java/io/gearpump/util/AkkaHelper.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/io/gearpump/util/AkkaHelper.java b/core/src/main/java/io/gearpump/util/AkkaHelper.java
deleted file mode 100644
index 286fabf..0000000
--- a/core/src/main/java/io/gearpump/util/AkkaHelper.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.util;
-
-import akka.actor.ActorRef;
-import akka.actor.ActorSystem;
-
-public class AkkaHelper {
-
- /**
- * Helper util to access the private[akka] system.actorFor method
- *
- * This is used for performance optimization, we encode the session Id
- * in the ActorRef path. Session Id is used to identity sender Task.
- *
- * @param system ActorSystem
- * @param path Relative or absolute path of this Actor System.
- * @return Full qualified ActorRef.
- */
- @SuppressWarnings("deprecation")
- public static ActorRef actorFor(ActorSystem system, String path) {
- return system.actorFor(path);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/java/io/gearpump/util/HadoopFSLogAppender.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/io/gearpump/util/HadoopFSLogAppender.java b/core/src/main/java/io/gearpump/util/HadoopFSLogAppender.java
deleted file mode 100644
index 93b65e8..0000000
--- a/core/src/main/java/io/gearpump/util/HadoopFSLogAppender.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.util;
-
-import org.apache.log4j.RollingFileAppender;
-
-/**
- * Log4j appender for to write to user specified Hadoop filesystem.
- */
-public class HadoopFSLogAppender extends RollingFileAppender {
- //TODO: implement Log appender on Hadoop filesystem
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/java/io/gearpump/util/RecreateRollingFileAppender.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/io/gearpump/util/RecreateRollingFileAppender.java b/core/src/main/java/io/gearpump/util/RecreateRollingFileAppender.java
deleted file mode 100644
index acbd1cb..0000000
--- a/core/src/main/java/io/gearpump/util/RecreateRollingFileAppender.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.util;
-
-import org.apache.log4j.RollingFileAppender;
-import org.apache.log4j.spi.LoggingEvent;
-
-import java.io.File;
-
-/** When log file is deleted, tried to recreate it in file system */
-public class RecreateRollingFileAppender extends RollingFileAppender {
-
- protected long checkFileInterval = 60L;
- private long lastCheckTime = 0L;
-
- @Override
- public void append(LoggingEvent event) {
- checkInterval();
- super.append(event);
- }
-
- private void checkInterval() {
- long currentTime = System.currentTimeMillis();
- if ((currentTime - lastCheckTime) > (checkFileInterval * 1000)) {
- checkLogFileExist();
- lastCheckTime = currentTime;
- }
- }
-
- private void checkLogFileExist() {
- String fileName = super.fileName;
- if (fileName != null) {
- File logFile = new File(fileName);
- if (!logFile.exists()) {
- this.setFile(fileName);
- this.activateOptions();
- }
- }
- }
-
- public long getCheckFileInterval() {
- return this.checkFileInterval;
- }
-
- public void setCheckFileInterval(long checkFileInterval) {
- this.checkFileInterval = checkFileInterval;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/java/org/apache/gearpump/transport/netty/ITransportMessageSerializer.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/gearpump/transport/netty/ITransportMessageSerializer.java b/core/src/main/java/org/apache/gearpump/transport/netty/ITransportMessageSerializer.java
new file mode 100644
index 0000000..8d3415c
--- /dev/null
+++ b/core/src/main/java/org/apache/gearpump/transport/netty/ITransportMessageSerializer.java
@@ -0,0 +1,31 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.transport.netty;
+
+import java.io.DataInput;
+import java.io.DataOutput;
+
+public interface ITransportMessageSerializer {
+
+ int getLength(Object obj);
+
+ void serialize(DataOutput dataOutput, Object transportMessage);
+
+ Object deserialize(DataInput dataInput, int length);
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/java/org/apache/gearpump/transport/netty/MessageBatch.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/gearpump/transport/netty/MessageBatch.java b/core/src/main/java/org/apache/gearpump/transport/netty/MessageBatch.java
new file mode 100644
index 0000000..7ee85f3
--- /dev/null
+++ b/core/src/main/java/org/apache/gearpump/transport/netty/MessageBatch.java
@@ -0,0 +1,152 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.transport.netty;
+
+import io.gearpump.google.common.io.Closeables;
+import org.jboss.netty.buffer.ChannelBuffer;
+import org.jboss.netty.buffer.ChannelBufferOutputStream;
+import org.jboss.netty.buffer.ChannelBuffers;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Netty message on the wire is wrapped as MessageBatch
+ */
+public class MessageBatch {
+ private static final Logger log = LoggerFactory.getLogger(MessageBatch.class);
+
+ private int buffer_size;
+ private List<TaskMessage> messages;
+ private int encoded_length;
+ private ITransportMessageSerializer serializer;
+
+ MessageBatch(int buffer_size, ITransportMessageSerializer serializer) {
+ this.buffer_size = buffer_size;
+ messages = new ArrayList<TaskMessage>();
+ encoded_length = 0;
+ this.serializer = serializer;
+ }
+
+ void add(TaskMessage taskMessage) {
+ if (taskMessage == null) {
+ throw new RuntimeException("null object forbidden in a message batch");
+ }
+
+ messages.add(taskMessage);
+ encoded_length += msgEncodeLength(taskMessage);
+ }
+
+ TaskMessage get(int index) {
+ return messages.get(index);
+ }
+
+ /**
+ * try to add a TaskMessage to a batch
+ *
+ * @param taskMsg - {@link org.apache.gearpump.transport.netty.TaskMessage}
+ * @return false if the msg could not be added due to buffer size limit; true otherwise
+ */
+ boolean tryAdd(TaskMessage taskMsg) {
+ if ((encoded_length + msgEncodeLength(taskMsg)) <= buffer_size) {
+ add(taskMsg);
+ return true;
+ }
+ return false;
+ }
+
+ private int msgEncodeLength(TaskMessage taskMsg) {
+ int size = 0;
+ if (taskMsg != null) {
+ size = 24; //sessionId(INT) + sourceTask(LONG) + targetTask(LONG) + messageLength(INT)
+ if (taskMsg.message() != null) {
+ size += serializer.getLength(taskMsg.message());
+ }
+ }
+ return size;
+ }
+
+ /**
+ * @return true, if allowed buffer is Full
+ */
+ boolean isFull() {
+ return encoded_length >= buffer_size;
+ }
+
+ /**
+ * @return true, if no messages in this batch
+ */
+ boolean isEmpty() {
+ return messages.isEmpty();
+ }
+
+ /**
+ * @return number of messages available in this batch
+ */
+ int size() {
+ return messages.size();
+ }
+
+ /**
+ * create a buffer containing the encoding of this batch
+ */
+ ChannelBuffer buffer() throws IOException {
+ ChannelBufferOutputStream bout =
+ new ChannelBufferOutputStream(ChannelBuffers.directBuffer(encoded_length));
+
+ try {
+ for (TaskMessage msg : messages) {
+ writeTaskMessage(bout, msg);
+ }
+ return bout.buffer();
+ } catch (IOException e) {
+ log.error("Error while writing Tasks to Channel Buffer - {}", e.getMessage());
+ } finally {
+ Closeables.close(bout, false);
+ }
+ return null;
+ }
+
+ /**
+ * write a TaskMessage into a stream
+ * <p>
+ * Each TaskMessage is encoded as:
+ * sessionId ... int(4)
+ * source task ... Long(8)
+ * target task ... long(8)
+ * len ... int(4)
+ * payload ... byte[] *
+ */
+ private void writeTaskMessage(ChannelBufferOutputStream bout,
+ TaskMessage message) throws IOException {
+ long target_id = message.targetTask();
+ long source_id = message.sourceTask();
+ int sessionId = message.sessionId();
+ int msgLength = serializer.getLength(message.message());
+
+ bout.writeInt(sessionId);
+ bout.writeLong(target_id);
+ bout.writeLong(source_id);
+ bout.writeInt(msgLength);
+ serializer.serialize(bout, message.message());
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/java/org/apache/gearpump/transport/netty/MessageDecoder.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/gearpump/transport/netty/MessageDecoder.java b/core/src/main/java/org/apache/gearpump/transport/netty/MessageDecoder.java
new file mode 100644
index 0000000..761bb38
--- /dev/null
+++ b/core/src/main/java/org/apache/gearpump/transport/netty/MessageDecoder.java
@@ -0,0 +1,104 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.transport.netty;
+
+import org.jboss.netty.buffer.ChannelBuffer;
+import org.jboss.netty.channel.Channel;
+import org.jboss.netty.channel.ChannelHandlerContext;
+import org.jboss.netty.handler.codec.frame.FrameDecoder;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class MessageDecoder extends FrameDecoder {
+ private ITransportMessageSerializer serializer;
+ private WrappedChannelBuffer dataInput = new WrappedChannelBuffer();
+
+ public MessageDecoder(ITransportMessageSerializer serializer) {
+ this.serializer = serializer;
+ }
+
+ /*
+ * Each TaskMessage is encoded as:
+ * sessionId ... int(4)
+ * source task ... long(8)
+ * target task ... long(8)
+ * len ... int(4)
+ * payload ... byte[] *
+ */
+ protected List<TaskMessage> decode(ChannelHandlerContext ctx, Channel channel,
+ ChannelBuffer buf) {
+ this.dataInput.setChannelBuffer(buf);
+
+ final int SESION_LENGTH = 4; //int
+ final int SOURCE_TASK_LENGTH = 8; //long
+ final int TARGET_TASK_LENGTH = 8; //long
+ final int MESSAGE_LENGTH = 4; //int
+ final int HEADER_LENGTH = SESION_LENGTH + SOURCE_TASK_LENGTH + TARGET_TASK_LENGTH + MESSAGE_LENGTH;
+
+ // Make sure that we have received at least a short message
+ long available = buf.readableBytes();
+ if (available < HEADER_LENGTH) {
+ //need more data
+ return null;
+ }
+
+ List<TaskMessage> taskMessageList = new ArrayList<TaskMessage>();
+
+ // Use while loop, try to decode as more messages as possible in single call
+ while (available >= HEADER_LENGTH) {
+
+ // Mark the current buffer position before reading task/len field
+ // because the whole frame might not be in the buffer yet.
+ // We will reset the buffer position to the marked position if
+ // there's not enough bytes in the buffer.
+ buf.markReaderIndex();
+
+ int sessionId = buf.readInt();
+ long targetTask = buf.readLong();
+ long sourceTask = buf.readLong();
+ // Read the length field.
+ int length = buf.readInt();
+
+ available -= HEADER_LENGTH;
+
+ if (length <= 0) {
+ taskMessageList.add(new TaskMessage(sessionId, targetTask, sourceTask, null));
+ break;
+ }
+
+ // Make sure if there's enough bytes in the buffer.
+ if (available < length) {
+ // The whole bytes were not received yet - return null.
+ buf.resetReaderIndex();
+ break;
+ }
+ available -= length;
+
+ // There's enough bytes in the buffer. Read it.
+ Object message = serializer.deserialize(dataInput, length);
+
+ // Successfully decoded a frame.
+ // Return a TaskMessage object
+ taskMessageList.add(new TaskMessage(sessionId, targetTask, sourceTask, message));
+ }
+
+ return taskMessageList.size() == 0 ? null : taskMessageList;
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/java/org/apache/gearpump/transport/netty/MessageEncoder.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/gearpump/transport/netty/MessageEncoder.java b/core/src/main/java/org/apache/gearpump/transport/netty/MessageEncoder.java
new file mode 100644
index 0000000..008c19d
--- /dev/null
+++ b/core/src/main/java/org/apache/gearpump/transport/netty/MessageEncoder.java
@@ -0,0 +1,34 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.transport.netty;
+
+import org.jboss.netty.channel.Channel;
+import org.jboss.netty.channel.ChannelHandlerContext;
+import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;
+
+public class MessageEncoder extends OneToOneEncoder {
+ @Override
+ protected Object encode(ChannelHandlerContext ctx, Channel channel, Object obj) throws Exception {
+ if (obj instanceof MessageBatch) {
+ return ((MessageBatch) obj).buffer();
+ }
+
+ throw new RuntimeException("Unsupported encoding of object of class " + obj.getClass().getName());
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/java/org/apache/gearpump/transport/netty/NettyRenameThreadFactory.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/gearpump/transport/netty/NettyRenameThreadFactory.java b/core/src/main/java/org/apache/gearpump/transport/netty/NettyRenameThreadFactory.java
new file mode 100644
index 0000000..270a358
--- /dev/null
+++ b/core/src/main/java/org/apache/gearpump/transport/netty/NettyRenameThreadFactory.java
@@ -0,0 +1,53 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.transport.netty;
+
+import org.jboss.netty.util.ThreadNameDeterminer;
+import org.jboss.netty.util.ThreadRenamingRunnable;
+
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.atomic.AtomicInteger;
+
+public class NettyRenameThreadFactory implements ThreadFactory {
+
+ static {
+ //Rename Netty threads
+ ThreadRenamingRunnable.setThreadNameDeterminer(ThreadNameDeterminer.CURRENT);
+ }
+
+ final ThreadGroup group;
+ final AtomicInteger index = new AtomicInteger(1);
+ final String name;
+
+ NettyRenameThreadFactory(String name) {
+ SecurityManager s = System.getSecurityManager();
+ group = (s != null) ? s.getThreadGroup() :
+ Thread.currentThread().getThreadGroup();
+ this.name = name;
+ }
+
+ public Thread newThread(Runnable r) {
+ Thread t = new Thread(group, r, name + "-" + index.getAndIncrement(), 0);
+ if (t.isDaemon())
+ t.setDaemon(false);
+ if (t.getPriority() != Thread.NORM_PRIORITY)
+ t.setPriority(Thread.NORM_PRIORITY);
+ return t;
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/java/org/apache/gearpump/transport/netty/TaskMessage.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/gearpump/transport/netty/TaskMessage.java b/core/src/main/java/org/apache/gearpump/transport/netty/TaskMessage.java
new file mode 100644
index 0000000..beb5b0d
--- /dev/null
+++ b/core/src/main/java/org/apache/gearpump/transport/netty/TaskMessage.java
@@ -0,0 +1,56 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.transport.netty;
+
+public class TaskMessage {
+
+ // When network partition happen, there may be several task instances of
+ // same taskId co-existing for a short period of time. When they send messages
+ // to same target task, it may cause confusion.
+ // With sessionId, we can know which messages are from an old session, and which
+ // are from new session. Messages of old sesson will be dropped.
+
+ private int _sessionId;
+ private long _targetTask;
+ private long _sourceTask;
+ private Object _message;
+
+ public TaskMessage(int sessionId, long targetTask, long sourceTask, Object message) {
+ _sessionId = sessionId;
+ _targetTask = targetTask;
+ _sourceTask = sourceTask;
+ _message = message;
+ }
+
+ public int sessionId() {
+ return _sessionId;
+ }
+
+ public long targetTask() {
+ return _targetTask;
+ }
+
+ public long sourceTask() {
+ return _sourceTask;
+ }
+
+ public Object message() {
+ return _message;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/java/org/apache/gearpump/transport/netty/WrappedChannelBuffer.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/gearpump/transport/netty/WrappedChannelBuffer.java b/core/src/main/java/org/apache/gearpump/transport/netty/WrappedChannelBuffer.java
new file mode 100644
index 0000000..878ae09
--- /dev/null
+++ b/core/src/main/java/org/apache/gearpump/transport/netty/WrappedChannelBuffer.java
@@ -0,0 +1,116 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.transport.netty;
+
+import org.jboss.netty.buffer.ChannelBuffer;
+
+import java.io.DataInput;
+import java.io.IOException;
+
+/** Wrap ChannelBuffer as a DataInput */
+public class WrappedChannelBuffer implements DataInput {
+ private ChannelBuffer channelBuffer;
+
+ public WrappedChannelBuffer() {
+ }
+
+ public WrappedChannelBuffer(ChannelBuffer channelBuffer) {
+ this.channelBuffer = channelBuffer;
+ }
+
+ public void setChannelBuffer(ChannelBuffer channelBuffer) {
+ this.channelBuffer = channelBuffer;
+ }
+
+ @Override
+ public void readFully(byte[] b) throws IOException {
+ channelBuffer.readBytes(b);
+ }
+
+ @Override
+ public void readFully(byte[] b, int off, int len) throws IOException {
+ channelBuffer.readBytes(b, off, len);
+ }
+
+ @Override
+ public int skipBytes(int n) throws IOException {
+ channelBuffer.skipBytes(n);
+ return n;
+ }
+
+ @Override
+ public boolean readBoolean() throws IOException {
+ return channelBuffer.readByte() != 0;
+ }
+
+ @Override
+ public byte readByte() throws IOException {
+ return channelBuffer.readByte();
+ }
+
+ @Override
+ public int readUnsignedByte() throws IOException {
+ return channelBuffer.readUnsignedByte();
+ }
+
+ @Override
+ public short readShort() throws IOException {
+ return channelBuffer.readShort();
+ }
+
+ @Override
+ public int readUnsignedShort() throws IOException {
+ return channelBuffer.readUnsignedShort();
+ }
+
+ @Override
+ public char readChar() throws IOException {
+ return channelBuffer.readChar();
+ }
+
+ @Override
+ public int readInt() throws IOException {
+ return channelBuffer.readInt();
+ }
+
+ @Override
+ public long readLong() throws IOException {
+ return channelBuffer.readLong();
+ }
+
+ @Override
+ public float readFloat() throws IOException {
+ return channelBuffer.readFloat();
+ }
+
+ @Override
+ public double readDouble() throws IOException {
+ return channelBuffer.readDouble();
+ }
+
+ @Override
+ public String readLine() throws IOException {
+ throw new UnsupportedOperationException("readLine is not supported");
+ }
+
+ @Override
+ public String readUTF() throws IOException {
+ throw new UnsupportedOperationException("readUTF is not supported");
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/java/org/apache/gearpump/util/AkkaHelper.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/gearpump/util/AkkaHelper.java b/core/src/main/java/org/apache/gearpump/util/AkkaHelper.java
new file mode 100644
index 0000000..2b5a9e6
--- /dev/null
+++ b/core/src/main/java/org/apache/gearpump/util/AkkaHelper.java
@@ -0,0 +1,40 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.util;
+
+import akka.actor.ActorRef;
+import akka.actor.ActorSystem;
+
+public class AkkaHelper {
+
+ /**
+ * Helper util to access the private[akka] system.actorFor method
+ *
+ * This is used for performance optimization, we encode the session Id
+ * in the ActorRef path. Session Id is used to identity sender Task.
+ *
+ * @param system ActorSystem
+ * @param path Relative or absolute path of this Actor System.
+ * @return Full qualified ActorRef.
+ */
+ @SuppressWarnings("deprecation")
+ public static ActorRef actorFor(ActorSystem system, String path) {
+ return system.actorFor(path);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/java/org/apache/gearpump/util/HadoopFSLogAppender.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/gearpump/util/HadoopFSLogAppender.java b/core/src/main/java/org/apache/gearpump/util/HadoopFSLogAppender.java
new file mode 100644
index 0000000..bf1e618
--- /dev/null
+++ b/core/src/main/java/org/apache/gearpump/util/HadoopFSLogAppender.java
@@ -0,0 +1,28 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.util;
+
+import org.apache.log4j.RollingFileAppender;
+
+/**
+ * Log4j appender for to write to user specified Hadoop filesystem.
+ */
+public class HadoopFSLogAppender extends RollingFileAppender {
+ //TODO: implement Log appender on Hadoop filesystem
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/java/org/apache/gearpump/util/RecreateRollingFileAppender.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/gearpump/util/RecreateRollingFileAppender.java b/core/src/main/java/org/apache/gearpump/util/RecreateRollingFileAppender.java
new file mode 100644
index 0000000..594ccf9
--- /dev/null
+++ b/core/src/main/java/org/apache/gearpump/util/RecreateRollingFileAppender.java
@@ -0,0 +1,64 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.util;
+
+import org.apache.log4j.RollingFileAppender;
+import org.apache.log4j.spi.LoggingEvent;
+
+import java.io.File;
+
+/** When log file is deleted, tried to recreate it in file system */
+public class RecreateRollingFileAppender extends RollingFileAppender {
+
+ protected long checkFileInterval = 60L;
+ private long lastCheckTime = 0L;
+
+ @Override
+ public void append(LoggingEvent event) {
+ checkInterval();
+ super.append(event);
+ }
+
+ private void checkInterval() {
+ long currentTime = System.currentTimeMillis();
+ if ((currentTime - lastCheckTime) > (checkFileInterval * 1000)) {
+ checkLogFileExist();
+ lastCheckTime = currentTime;
+ }
+ }
+
+ private void checkLogFileExist() {
+ String fileName = super.fileName;
+ if (fileName != null) {
+ File logFile = new File(fileName);
+ if (!logFile.exists()) {
+ this.setFile(fileName);
+ this.activateOptions();
+ }
+ }
+ }
+
+ public long getCheckFileInterval() {
+ return this.checkFileInterval;
+ }
+
+ public void setCheckFileInterval(long checkFileInterval) {
+ this.checkFileInterval = checkFileInterval;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/resources/geardefault.conf
----------------------------------------------------------------------
diff --git a/core/src/main/resources/geardefault.conf b/core/src/main/resources/geardefault.conf
index 4eecf3a..19ffb5f 100644
--- a/core/src/main/resources/geardefault.conf
+++ b/core/src/main/resources/geardefault.conf
@@ -30,14 +30,14 @@ gearpump {
## The installation folder of gearpump
home = ""
- serializer.pool = "io.gearpump.serializer.FastKryoSerializerPool"
+ serializer.pool = "org.apache.gearpump.serializer.FastKryoSerializerPool"
## How many slots each worker contains
worker.slots = 1000
## The class responsable for launching the executor process.
- ## User can switch to "io.gearpump.cluster.worker.CGroupProcessLauncher" to enable CGroup support.
- worker.executor-process-launcher = "io.gearpump.cluster.worker.DefaultExecutorProcessLauncher"
+ ## User can switch to "org.apache.gearpump.cluster.worker.CGroupProcessLauncher" to enable CGroup support.
+ worker.executor-process-launcher = "org.apache.gearpump.cluster.worker.DefaultExecutorProcessLauncher"
## Number of executors to launch when starting an application
application.executor-num = 1
@@ -57,7 +57,7 @@ gearpump {
master-resource-manager-container-id = ""
## To enable worker use cgroup to make resource isolation,
- ## set gearpump.worker.executor-process-launcher = "io.gearpump.cluster.worker.CGroupProcessLauncher"
+ ## set gearpump.worker.executor-process-launcher = "org.apache.gearpump.cluster.worker.CGroupProcessLauncher"
##
## Before enable it, you should also make sure:
## 1. Linux version (>= 2.6.18)
@@ -176,7 +176,7 @@ gearpump {
### Whitelist for Metrics Aggregator class.
### See class [[MetricsAggregator]] for more information.
metrics-aggregator-class {
- ## Format io.gearpump.KeyFullClassName = ""
+ ## Format org.apache.gearpump.KeyFullClassName = ""
}
}
}
@@ -219,9 +219,9 @@ gearpump {
### Gearpump has built-in serialization framework using Kryo.
### User are allowed to use a different serialization framework, like Protobuf
- ### See [io.gearpump.serializer.FastKryoSerializationFramework] to find how
+ ### See [org.apache.gearpump.serializer.FastKryoSerializationFramework] to find how
### a custom serialization framework can be defined.
- serialization-framework = "io.gearpump.serializer.FastKryoSerializationFramework"
+ serialization-framework = "org.apache.gearpump.serializer.FastKryoSerializationFramework"
### Define where the submitted jar file will be stored at
@@ -238,7 +238,7 @@ gearpump {
### If you don't know what is this about, don't change it
#########################
scheduling {
- scheduler-class = "io.gearpump.cluster.scheduler.PriorityScheduler"
+ scheduler-class = "org.apache.gearpump.cluster.scheduler.PriorityScheduler"
}
#############################################
@@ -396,15 +396,15 @@ gearpump-ui {
## authentication channel like OAuth2.
##
## User can replace this with a custom User-Password based authenticator,
- ## which implements interface io.gearpump.security.Authenticator
+ ## which implements interface org.apache.gearpump.security.Authenticator
##
- authenticator = "io.gearpump.security.ConfigFileBasedAuthenticator"
+ authenticator = "org.apache.gearpump.security.ConfigFileBasedAuthenticator"
- ## Configuration options for authenticator io.gearpump.security.ConfigFileBasedAuthenticator
+ ## Configuration options for authenticator org.apache.gearpump.security.ConfigFileBasedAuthenticator
config-file-based-authenticator = {
## Format: username = "password_hash_value"
## password_hash_value can be generated by running shell tool:
- ## bin/gear io.gearpump.security.PasswordUtil -password <your raw password>
+ ## bin/gear org.apache.gearpump.security.PasswordUtil -password <your raw password>
## Admin users have super permission to do everything
admins = {
@@ -456,7 +456,7 @@ gearpump-ui {
## For steps to enable OAuth2 Authentication on Google, please view docs/deployment-ui-authentication.md
##
"google" {
- "class" = "io.gearpump.services.security.oauth2.impl.GoogleOAuth2Authenticator"
+ "class" = "org.apache.gearpump.services.security.oauth2.impl.GoogleOAuth2Authenticator"
## Please replace "127.0.0.1:8090" with your address of UI service.
"callback" = "http://127.0.0.1:8090/login/oauth2/google/callback"
@@ -487,7 +487,7 @@ gearpump-ui {
## For steps to enable OAuth2 Authentication for UAA, please view docs/deployment-ui-authentication.md
##
"cloudfoundryuaa" {
- "class" = "io.gearpump.services.security.oauth2.impl.CloudFoundryUAAOAuth2Authenticator"
+ "class" = "org.apache.gearpump.services.security.oauth2.impl.CloudFoundryUAAOAuth2Authenticator"
## Please replace "127.0.0.1:8090" with your address of UI service.
"callback" = "http://127.0.0.1:8090/login/oauth2/cloudfoundryuaa/callback"
@@ -525,7 +525,7 @@ gearpump-ui {
## Define how to do additional authorization check. The class should implement
## interface CloudFoundryUAAOAuth2Authenticator.AdditionalAuthenticator
additional-authenticator = {
- "class" = "io.gearpump.services.security.oauth2.impl.CloudFoundryUAAOAuth2Authenticator$OrganizationAccessChecker"
+ "class" = "org.apache.gearpump.services.security.oauth2.impl.CloudFoundryUAAOAuth2Authenticator$OrganizationAccessChecker"
## Please fill the Cloud Foundry API endpoint and organization GUID
"organization-url" = "http://<cloud foundry api endpoint>/v2/organizations/<organization-guid>"
@@ -593,8 +593,8 @@ akka {
daemonic = on
extensions = [
- "io.gearpump.transport.Express$",
- "io.gearpump.metrics.Metrics$"
+ "org.apache.gearpump.transport.Express$",
+ "org.apache.gearpump.metrics.Metrics$"
]
loglevel = "INFO"
loggers = ["akka.event.slf4j.Slf4jLogger"]
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/resources/log4j.properties
----------------------------------------------------------------------
diff --git a/core/src/main/resources/log4j.properties b/core/src/main/resources/log4j.properties
index 682a11b..cbe0749 100644
--- a/core/src/main/resources/log4j.properties
+++ b/core/src/main/resources/log4j.properties
@@ -61,7 +61,7 @@ log4j.threshhold=ALL
# Rolling File Appender
#
#log4j.appender.RollingFileAppender=org.apache.log4j.RollingFileAppender
-log4j.appender.RollingFileAppender=io.gearpump.util.RecreateRollingFileAppender
+log4j.appender.RollingFileAppender=org.apache.gearpump.util.RecreateRollingFileAppender
log4j.appender.RollingFileAppender.File=${gearpump.log.dir}/${gearpump.log.file}
log4j.appender.RollingFileAppender.checkFileInterval=60
log4j.appender.RollingFileAppender.layout=org.apache.log4j.PatternLayout
@@ -86,7 +86,7 @@ log4j.appender.console.layout.ConversionPattern=[%p] [%d{MM/dd/yyyy HH:mm:ss.SSS
#
# Application Log Appender
#
-log4j.appender.ApplicationLogAppender=io.gearpump.util.RecreateRollingFileAppender
+log4j.appender.ApplicationLogAppender=org.apache.gearpump.util.RecreateRollingFileAppender
log4j.appender.ApplicationLogAppender.File=${gearpump.application.log.dir}/${gearpump.application.log.file}
log4j.appender.ApplicationLogAppender.checkFileInterval=60
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/Message.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/Message.scala b/core/src/main/scala/io/gearpump/Message.scala
deleted file mode 100644
index aec8089..0000000
--- a/core/src/main/scala/io/gearpump/Message.scala
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump
-
-/**
- * Each message contains a immutable timestamp.
- *
- * For example, if you take a picture, the time you take the picture is the
- * message's timestamp.
- * @param msg Accept any type except Null, Nothing and Unit
- */
-case class Message(msg: Any, timestamp: TimeStamp = Message.noTimeStamp)
-
-object Message {
- val noTimeStamp: TimeStamp = 0L
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/cluster/AppDescription.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/cluster/AppDescription.scala b/core/src/main/scala/io/gearpump/cluster/AppDescription.scala
deleted file mode 100644
index 799c20a..0000000
--- a/core/src/main/scala/io/gearpump/cluster/AppDescription.scala
+++ /dev/null
@@ -1,145 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster
-
-import scala.reflect.ClassTag
-
-import akka.actor.{Actor, ActorRef, ActorSystem}
-import com.typesafe.config.{Config, ConfigFactory}
-
-import io.gearpump.cluster.appmaster.WorkerInfo
-import io.gearpump.cluster.scheduler.Resource
-import io.gearpump.jarstore.FilePath
-
-/**
- * This contains all information to run an application
- *
- * @param name The name of this application
- * @param appMaster The class name of AppMaster Actor
- * @param userConfig user configuration.
- * @param clusterConfig User provided cluster config, it overrides gear.conf when starting
- * new applications. In most cases, you should not need to change it. If you do
- * really need to change it, please use ClusterConfigSource(filePath) to
- * construct the object, while filePath points to the .conf file.
- */
-case class AppDescription(
- name: String, appMaster: String, userConfig: UserConfig,
- clusterConfig: Config = ConfigFactory.empty())
-
-/**
- * Each job, streaming or not streaming, need to provide an Application class.
- * The master uses this class to start AppMaster.
- */
-trait Application {
-
- /** Name of this application, must be unique in the system */
- def name: String
-
- /** Custom user configuration */
- def userConfig(implicit system: ActorSystem): UserConfig
-
- /**
- * AppMaster class, must have a constructor like this:
- * this(appContext: AppMasterContext, app: AppDescription)
- */
- def appMaster: Class[_ <: ApplicationMaster]
-}
-
-object Application {
- def apply[T <: ApplicationMaster](
- name: String, userConfig: UserConfig)(implicit tag: ClassTag[T]): Application = {
- new DefaultApplication(name, userConfig,
- tag.runtimeClass.asInstanceOf[Class[_ <: ApplicationMaster]])
- }
-
- class DefaultApplication(
- override val name: String, inputUserConfig: UserConfig,
- val appMaster: Class[_ <: ApplicationMaster]) extends Application {
- override def userConfig(implicit system: ActorSystem): UserConfig = inputUserConfig
- }
-
- def ApplicationToAppDescription(app: Application)(implicit system: ActorSystem)
- : AppDescription = {
- val filterJvmReservedKeys = ClusterConfig.filterOutDefaultConfig(system.settings.config)
- AppDescription(app.name, app.appMaster.getName, app.userConfig, filterJvmReservedKeys)
- }
-}
-
-/**
- * Used for verification. All AppMaster must extend this interface
- */
-abstract class ApplicationMaster extends Actor
-
-/**
- * This contains context information when starting an AppMaster
- *
- * @param appId application instance id assigned, it is unique in the cluster
- * @param username The username who submitted this application
- * @param resource Resouce allocated to start this AppMaster daemon. AppMaster are allowed to
- * request more resource from Master.
- * @param appJar application Jar. If the jar is already in classpath, then it can be None.
- * @param masterProxy The proxy to master actor, it bridges the messages between appmaster
- * and master
- * @param registerData AppMaster are required to send this data to Master by when doing
- * RegisterAppMaster.
- */
-case class AppMasterContext(
- appId: Int,
- username: String,
- resource: Resource,
- workerInfo: WorkerInfo,
- appJar: Option[AppJar],
- masterProxy: ActorRef,
- registerData: AppMasterRegisterData)
-
-/**
- * Jar file container in the cluster
- *
- * @param name A meaningful name to represent this jar
- * @param filePath Where the jar file is stored.
- */
-case class AppJar(name: String, filePath: FilePath)
-
-/**
- * Serves as the context to start an Executor JVM.
- */
-// TODO: ExecutorContext doesn't belong to this package in logic.
-case class ExecutorContext(
- executorId: Int, worker: WorkerInfo, appId: Int, appName: String,
- appMaster: ActorRef, resource: Resource)
-
-/**
- * JVM configurations to start an Executor JVM.
- *
- * @param classPath When executor is created by a worker JVM, executor automatically inherits
- * parent worker's classpath. Sometimes, you still want to add some extra
- * classpath, you can do this by specify classPath option.
- * @param jvmArguments java arguments like -Dxx=yy
- * @param mainClass Executor main class name like io.gearpump.xx.AppMaster
- * @param arguments Executor command line arguments
- * @param jar application jar
- * @param executorAkkaConfig Akka config used to initialize the actor system of this executor.
- * It uses io.gearpump.util.Constants.GEARPUMP_CUSTOM_CONFIG_FILE
- * to pass the config to executor process
- */
-// TODO: ExecutorContext doesn't belong to this package in logic.
-case class ExecutorJVMConfig(
- classPath: Array[String], jvmArguments: Array[String], mainClass: String,
- arguments: Array[String], jar: Option[AppJar], username: String,
- executorAkkaConfig: Config = ConfigFactory.empty())
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/cluster/ClusterConfig.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/cluster/ClusterConfig.scala b/core/src/main/scala/io/gearpump/cluster/ClusterConfig.scala
deleted file mode 100644
index 5cc49e7..0000000
--- a/core/src/main/scala/io/gearpump/cluster/ClusterConfig.scala
+++ /dev/null
@@ -1,184 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster
-
-import java.io.File
-
-import com.typesafe.config._
-
-import io.gearpump.util.Constants._
-import io.gearpump.util.{Constants, FileUtils, LogUtil, Util}
-
-/**
- *
- * All Gearpump application should use this class to load configurations.
- *
- * Compared with Akka built-in com.typesafe.config.ConfigFactory, this class also
- * resolve config from file gear.conf and geardefault.conf.
- *
- * Overriding order:
- * {{{
- * System Properties
- * > Custom configuration file (by using system property -Dgearpump.config.file) >
- * > gear.conf
- * > geardefault.conf
- * > reference.conf
- * }}}
- */
-
-object ClusterConfig {
- /**
- * alias for default
- * default is a reserved word for java
- * @return
- */
- def defaultConfig: Config = {
- default(APPLICATION)
- }
-
- /**
- * default application for user.
- * Usually used when user want to start an client application.
- * @return
- */
- def default(configFile: String = APPLICATION): Config = {
- load(configFile).default
- }
-
- /**
- * configuration for master node
- * @return
- */
- def master(configFile: String = null): Config = {
- load(configFile).master
- }
-
- /*
- * configuration for worker node
- */
- def worker(configFile: String = null): Config = {
- load(configFile).worker
- }
-
- /**
- * configuration for UI server
- * @return
- */
- def ui(configFile: String = null): Config = {
- load(configFile).ui
- }
-
- /**
- * try to load system property gearpump.config.file, or use configFile
- */
- private def load(configFile: String): Configs = {
- val file = Option(System.getProperty(GEARPUMP_CUSTOM_CONFIG_FILE))
- file match {
- case Some(path) =>
- LOG.info("loading config file " + path + "..........")
- load(ClusterConfigSource(path))
- case None =>
- LOG.info("loading config file application.conf...")
- load(ClusterConfigSource(configFile))
- }
- }
-
- val APPLICATION = "application.conf"
- val LOG = LogUtil.getLogger(getClass)
-
- def saveConfig(conf: Config, file: File): Unit = {
- val serialized = conf.root().render()
- FileUtils.write(file, serialized)
- }
-
- def render(config: Config, concise: Boolean = false): String = {
- if (concise) {
- config.root().render(ConfigRenderOptions.concise().setFormatted(true))
- } else {
- config.root().render(ConfigRenderOptions.defaults())
- }
- }
-
- /** filter JVM reserved keys and akka default reference.conf */
- def filterOutDefaultConfig(input: Config): Config = {
- val updated = filterOutJvmReservedKeys(input)
- Util.filterOutOrigin(updated, "reference.conf")
- }
-
- private[gearpump] def load(source: ClusterConfigSource): Configs = {
-
- val systemProperties = getSystemProperties
-
- val user = source.getConfig
-
- val gear = ConfigFactory.parseResourcesAnySyntax("gear.conf",
- ConfigParseOptions.defaults.setAllowMissing(true))
-
- val gearDefault = ConfigFactory.parseResourcesAnySyntax("geardefault.conf",
- ConfigParseOptions.defaults.setAllowMissing(true))
-
- val all = systemProperties.withFallback(user).withFallback(gear).withFallback(gearDefault)
-
- val linux = all.getConfig(LINUX_CONFIG)
-
- var basic = all.withoutPath(MASTER_CONFIG).withoutPath(WORKER_CONFIG).
- withoutPath(UI_CONFIG).withoutPath(LINUX_CONFIG)
-
- if (!akka.util.Helpers.isWindows) {
-
- // Change the akka.scheduler.tick-duration to 1 ms for Linux or Mac
- basic = linux.withFallback(basic)
- }
-
- val master = replaceHost(all.getConfig(MASTER_CONFIG).withFallback(basic))
- val worker = replaceHost(all.getConfig(WORKER_CONFIG).withFallback(basic))
- val ui = replaceHost(all.getConfig(UI_CONFIG).withFallback(basic))
- val app = replaceHost(basic)
-
- new Configs(master, worker, ui, app)
- }
-
- private def replaceHost(config: Config): Config = {
- val hostName = config.getString(Constants.GEARPUMP_HOSTNAME)
- config.withValue(NETTY_TCP_HOSTNAME, ConfigValueFactory.fromAnyRef(hostName))
- }
-
- val JVM_RESERVED_PROPERTIES = List(
- "os", "java", "sun", "boot", "user", "prog", "path", "line", "awt", "file"
- )
-
- private def getSystemProperties: Config = {
- // Excludes default java system properties
- JVM_RESERVED_PROPERTIES.foldLeft(ConfigFactory.systemProperties()) { (config, property) =>
- config.withoutPath(property)
- }
- }
-
- class ConfigValidationException(msg: String) extends Exception(msg: String)
-
- private def filterOutJvmReservedKeys(input: Config): Config = {
- val filterJvmReservedKeys = JVM_RESERVED_PROPERTIES.foldLeft(input) { (config, key) =>
- config.withoutPath(key)
- }
- filterJvmReservedKeys
- }
-
- protected class Configs(
- val master: Config, val worker: Config, val ui: Config, val default: Config)
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/cluster/ClusterConfigSource.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/cluster/ClusterConfigSource.scala b/core/src/main/scala/io/gearpump/cluster/ClusterConfigSource.scala
deleted file mode 100644
index 3a248d7..0000000
--- a/core/src/main/scala/io/gearpump/cluster/ClusterConfigSource.scala
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster
-
-import java.io.File
-import scala.language.implicitConversions
-
-import com.typesafe.config.{Config, ConfigFactory, ConfigParseOptions}
-
-/**
- * Data Source of ClusterConfig
- *
- * Please use ClusterConfigSource.apply(filePath) to construct this object
- */
-sealed trait ClusterConfigSource extends Serializable {
- def getConfig: Config
-}
-
-object ClusterConfigSource {
-
- /**
- * Construct ClusterConfigSource from resource name or file path
- */
- def apply(filePath: String): ClusterConfigSource = {
-
- if (null == filePath) {
- new ClusterConfigSourceImpl(ConfigFactory.empty())
- } else {
- var config = ConfigFactory.parseFileAnySyntax(new File(filePath),
- ConfigParseOptions.defaults.setAllowMissing(true))
-
- if (null == config || config.isEmpty) {
- config = ConfigFactory.parseResourcesAnySyntax(filePath,
- ConfigParseOptions.defaults.setAllowMissing(true))
- }
- new ClusterConfigSourceImpl(config)
- }
- }
-
- implicit def FilePathToClusterConfigSource(filePath: String): ClusterConfigSource = {
- apply(filePath)
- }
-
- private class ClusterConfigSourceImpl(config: Config) extends ClusterConfigSource {
- override def getConfig: Config = config
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/cluster/ClusterMessage.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/cluster/ClusterMessage.scala b/core/src/main/scala/io/gearpump/cluster/ClusterMessage.scala
deleted file mode 100644
index ed187a1..0000000
--- a/core/src/main/scala/io/gearpump/cluster/ClusterMessage.scala
+++ /dev/null
@@ -1,287 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster
-
-import scala.util.Try
-
-import akka.actor.ActorRef
-import com.typesafe.config.Config
-
-import io.gearpump.TimeStamp
-import io.gearpump.cluster.MasterToAppMaster.AppMasterStatus
-import io.gearpump.cluster.master.{MasterNode, MasterSummary}
-import io.gearpump.cluster.scheduler.{Resource, ResourceAllocation, ResourceRequest}
-import io.gearpump.cluster.worker.{WorkerId, WorkerSummary}
-import io.gearpump.metrics.Metrics.MetricType
-
-object ClientToMaster {
- case object AddMaster
- case class AddWorker(count: Int)
- case class RemoveMaster(masterContainerId: String)
- case class RemoveWorker(workerContainerId: String)
-
- /** Command result of AddMaster, RemoveMaster, and etc... */
- case class CommandResult(success: Boolean, exception: String = null) {
- override def toString: String = {
- val tag = getClass.getSimpleName
- if (success) {
- s"$tag(success)"
- } else {
- s"$tag(failure, $exception)"
- }
- }
- }
-
- /** Submit an application to master */
- case class SubmitApplication(
- appDescription: AppDescription, appJar: Option[AppJar],
- username: String = System.getProperty("user.name"))
-
- case class RestartApplication(appId: Int)
- case class ShutdownApplication(appId: Int)
-
- /** Client send ResolveAppId to Master to resolves AppMaster actor path by providing appId */
- case class ResolveAppId(appId: Int)
-
- /** Client send ResolveWorkerId to master to get the Actor path of worker. */
- case class ResolveWorkerId(workerId: WorkerId)
-
- /** Get an active Jar store to upload job jars, like wordcount.jar */
- case object GetJarStoreServer
-
- /** Service address of JarStore */
- case class JarStoreServerAddress(url: String)
-
- /** Query AppMaster config by providing appId */
- case class QueryAppMasterConfig(appId: Int)
-
- /** Query worker config */
- case class QueryWorkerConfig(workerId: WorkerId)
-
- /** Query master config */
- case object QueryMasterConfig
-
- /** Options for read the metrics from the cluster */
- object ReadOption {
- type ReadOption = String
-
- val Key: String = "readOption"
-
- /** Read the latest record of the metrics, only return 1 record for one metric name (id) */
- val ReadLatest: ReadOption = "readLatest"
-
- /** Read recent metrics from cluster, typically it contains metrics in 5 minutes */
- val ReadRecent = "readRecent"
-
- /**
- * Read the history metrics, typically it contains metrics for 48 hours
- *
- * NOTE: Each hour only contain one or two data points.
- */
- val ReadHistory = "readHistory"
- }
-
- /** Query history metrics from master or app master. */
- case class QueryHistoryMetrics(
- path: String, readOption: ReadOption.ReadOption = ReadOption.ReadLatest,
- aggregatorClazz: String = "", options: Map[String, String] = Map.empty[String, String])
-
- /**
- * If there are message loss, the clock would pause for a while. This message is used to
- * pin-point which task has stalling clock value, and usually it means something wrong on
- * that machine.
- */
- case class GetStallingTasks(appId: Int)
-
- /**
- * Request app master for a short list of cluster app that administrators should be aware of.
- */
- case class GetLastFailure(appId: Int)
-}
-
-object MasterToClient {
-
- /** Result of SubmitApplication */
- // TODO: Merge with SubmitApplicationResultValue and change this to (appId: Option, ex: Exception)
- case class SubmitApplicationResult(appId: Try[Int])
-
- case class SubmitApplicationResultValue(appId: Int)
-
- case class ShutdownApplicationResult(appId: Try[Int])
- case class ReplayApplicationResult(appId: Try[Int])
-
- /** Return Actor ref of app master */
- case class ResolveAppIdResult(appMaster: Try[ActorRef])
-
- /** Return Actor ref of worker */
- case class ResolveWorkerIdResult(worker: Try[ActorRef])
-
- case class AppMasterConfig(config: Config)
-
- case class WorkerConfig(config: Config)
-
- case class MasterConfig(config: Config)
-
- case class HistoryMetricsItem(time: TimeStamp, value: MetricType)
-
- /**
- * History metrics returned from master, worker, or app master.
- *
- * All metric items are organized like a tree, path is used to navigate through the tree.
- * For example, when querying with path == "executor0.task1.throughput*", the metrics
- * provider picks metrics whose source matches the path.
- *
- * @param path The path client provided. The returned metrics are the result query of this path.
- * @param metrics The detailed metrics.
- */
- case class HistoryMetrics(path: String, metrics: List[HistoryMetricsItem])
-
- /** Return the last error of this streaming application job */
- case class LastFailure(time: TimeStamp, error: String)
-}
-
-trait AppMasterRegisterData
-
-object AppMasterToMaster {
-
- /**
- * Register an AppMaster by providing a ActorRef, and registerData
- * @param registerData The registerData is provided by Master when starting the app master.
- * App master should return the registerData back to master.
- * Typically registerData hold some context information for this app Master.
- */
-
- case class RegisterAppMaster(appMaster: ActorRef, registerData: AppMasterRegisterData)
-
- case class InvalidAppMaster(appId: Int, appMaster: String, reason: Throwable)
-
- case class RequestResource(appId: Int, request: ResourceRequest)
-
- /**
- * Each application job can save some data in the distributed cluster storage on master nodes.
- *
- * @param appId App Id of the client application who send the request.
- * @param key Key name
- * @param value Value to store on distributed cluster storage on master nodes
- */
- case class SaveAppData(appId: Int, key: String, value: Any)
-
- /** The application specific data is successfully stored */
- case object AppDataSaved
-
- /** Fail to store the application data */
- case object SaveAppDataFailed
-
- /** Fetch the application specific data that stored previously */
- case class GetAppData(appId: Int, key: String)
-
- /** The KV data returned for query GetAppData */
- case class GetAppDataResult(key: String, value: Any)
-
- /**
- * AppMasterSummary returned to REST API query. Streaming and Non-streaming
- * have very different application info. AppMasterSummary is the common interface.
- */
- trait AppMasterSummary {
- def appType: String
- def appId: Int
- def appName: String
- def actorPath: String
- def status: AppMasterStatus
- def startTime: TimeStamp
- def uptime: TimeStamp
- def user: String
- }
-
- /** Represents a generic application that is not a streaming job */
- case class GeneralAppMasterSummary(
- appId: Int,
- appType: String = "general",
- appName: String = null,
- actorPath: String = null,
- status: AppMasterStatus = MasterToAppMaster.AppMasterActive,
- startTime: TimeStamp = 0L,
- uptime: TimeStamp = 0L,
- user: String = null)
- extends AppMasterSummary
-
- /** Fetches the list of workers from Master */
- case object GetAllWorkers
-
- /** Get worker data of workerId */
- case class GetWorkerData(workerId: WorkerId)
-
- /** Response to GetWorkerData */
- case class WorkerData(workerDescription: WorkerSummary)
-
- /** Get Master data */
- case object GetMasterData
-
- /** Response to GetMasterData */
- case class MasterData(masterDescription: MasterSummary)
-}
-
-object MasterToAppMaster {
-
- /** Resource allocated for application xx */
- case class ResourceAllocated(allocations: Array[ResourceAllocation])
-
- /** Master confirm reception of RegisterAppMaster message */
- case class AppMasterRegistered(appId: Int)
-
- /** Shutdown the application job */
- case object ShutdownAppMaster
-
- type AppMasterStatus = String
- val AppMasterActive: AppMasterStatus = "active"
- val AppMasterInActive: AppMasterStatus = "inactive"
- val AppMasterNonExist: AppMasterStatus = "nonexist"
-
- sealed trait StreamingType
- case class AppMasterData(
- status: AppMasterStatus, appId: Int = 0, appName: String = null, appMasterPath: String = null,
- workerPath: String = null, submissionTime: TimeStamp = 0, startTime: TimeStamp = 0,
- finishTime: TimeStamp = 0, user: String = null)
-
- case class AppMasterDataRequest(appId: Int, detail: Boolean = false)
-
- case class AppMastersData(appMasters: List[AppMasterData])
- case object AppMastersDataRequest
- case class AppMasterDataDetailRequest(appId: Int)
- case class AppMasterMetricsRequest(appId: Int) extends StreamingType
-
- case class ReplayFromTimestampWindowTrailingEdge(appId: Int)
-
- case class WorkerList(workers: List[WorkerId])
-}
-
-object AppMasterToWorker {
- case class LaunchExecutor(
- appId: Int, executorId: Int, resource: Resource, executorJvmConfig: ExecutorJVMConfig)
-
- case class ShutdownExecutor(appId: Int, executorId: Int, reason: String)
- case class ChangeExecutorResource(appId: Int, executorId: Int, resource: Resource)
-}
-
-object WorkerToAppMaster {
- case class ExecutorLaunchRejected(reason: String = null, ex: Throwable = null)
- case class ShutdownExecutorSucceed(appId: Int, executorId: Int)
- case class ShutdownExecutorFailed(reason: String = null, ex: Throwable = null)
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/cluster/UserConfig.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/cluster/UserConfig.scala b/core/src/main/scala/io/gearpump/cluster/UserConfig.scala
deleted file mode 100644
index 61de1dd..0000000
--- a/core/src/main/scala/io/gearpump/cluster/UserConfig.scala
+++ /dev/null
@@ -1,162 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster
-
-import akka.actor.{ActorSystem, ExtendedActorSystem}
-import akka.serialization.JavaSerializer
-
-import io.gearpump.google.common.io.BaseEncoding
-
-/**
- * Immutable configuration
- */
-final class UserConfig(private val _config: Map[String, String]) extends Serializable {
-
- def withBoolean(key: String, value: Boolean): UserConfig = {
- new UserConfig(_config + (key -> value.toString))
- }
-
- def withDouble(key: String, value: Double): UserConfig = {
- new UserConfig(_config + (key -> value.toString))
- }
-
- def withFloat(key: String, value: Float): UserConfig = {
- new UserConfig(_config + (key -> value.toString))
- }
-
- def withInt(key: String, value: Int): UserConfig = {
- new UserConfig(_config + (key -> value.toString))
- }
-
- def withLong(key: String, value: Long): UserConfig = {
- new UserConfig(_config + (key -> value.toString))
- }
-
- def withString(key: String, value: String): UserConfig = {
- if (null == value) {
- this
- } else {
- new UserConfig(_config + (key -> value))
- }
- }
-
- def without(key: String): UserConfig = {
- val config = _config - key
- new UserConfig(config)
- }
-
- def filter(p: ((String, String)) => Boolean): UserConfig = {
- val updated = _config.filter(p)
- new UserConfig(updated)
- }
-
- def getBoolean(key: String): Option[Boolean] = {
- _config.get(key).map(_.toBoolean)
- }
-
- def getDouble(key: String): Option[Double] = {
- _config.get(key).map(_.toDouble)
- }
-
- def getFloat(key: String): Option[Float] = {
- _config.get(key).map(_.toFloat)
- }
-
- def getInt(key: String): Option[Int] = {
- _config.get(key).map(_.toInt)
- }
-
- def getLong(key: String): Option[Long] = {
- _config.get(key).map(_.toLong)
- }
-
- def getString(key: String): Option[String] = {
- _config.get(key)
- }
-
- def getBytes(key: String): Option[Array[Byte]] = {
- _config.get(key).map(BaseEncoding.base64().decode(_))
- }
-
- def withBytes(key: String, value: Array[Byte]): UserConfig = {
- if (null == value) {
- this
- } else {
- this.withString(key, BaseEncoding.base64().encode(value))
- }
- }
-
- // scalastyle:off line.size.limit
- /**
- * This de-serializes value to object instance
- *
- * To do de-serialization, this requires an implicit ActorSystem, as
- * the ActorRef and possibly other akka classes deserialization
- * requires an implicit ActorSystem.
- *
- * See Link:
- * http://doc.akka.io/docs/akka/snapshot/scala/serialization.html#A_Word_About_Java_Serialization
- */
-
- def getValue[T](key: String)(implicit system: ActorSystem): Option[T] = {
- val serializer = new JavaSerializer(system.asInstanceOf[ExtendedActorSystem])
- _config.get(key).map(BaseEncoding.base64().decode(_))
- .map(serializer.fromBinary(_).asInstanceOf[T])
- }
-
- /**
- * This serializes the object and store it as string.
- *
- * To do serialization, this requires an implicit ActorSystem, as
- * the ActorRef and possibly other akka classes serialization
- * requires an implicit ActorSystem.
- *
- * See Link:
- * http://doc.akka.io/docs/akka/snapshot/scala/serialization.html#A_Word_About_Java_Serialization
- */
- def withValue[T <: AnyRef](key: String, value: T)(implicit system: ActorSystem): UserConfig = {
-
- if (null == value) {
- this
- } else {
- val serializer = new JavaSerializer(system.asInstanceOf[ExtendedActorSystem])
- val bytes = serializer.toBinary(value)
- val encoded = BaseEncoding.base64().encode(bytes)
- this.withString(key, encoded)
- }
- }
- // scalastyle:on line.size.limit
-
- def withConfig(other: UserConfig): UserConfig = {
- if (null == other) {
- this
- } else {
- new UserConfig(_config ++ other._config)
- }
- }
-}
-
-object UserConfig {
-
- def empty: UserConfig = new UserConfig(Map.empty[String, String])
-
- def apply(config: Map[String, String]): UserConfig = new UserConfig(config)
-
- def unapply(config: UserConfig): Option[Map[String, String]] = Option(config._config)
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/cluster/appmaster/AppMasterRuntimeEnvironment.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/cluster/appmaster/AppMasterRuntimeEnvironment.scala b/core/src/main/scala/io/gearpump/cluster/appmaster/AppMasterRuntimeEnvironment.scala
deleted file mode 100644
index 4e8582b..0000000
--- a/core/src/main/scala/io/gearpump/cluster/appmaster/AppMasterRuntimeEnvironment.scala
+++ /dev/null
@@ -1,195 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.appmaster
-
-import akka.actor._
-
-import io.gearpump.cluster.AppMasterToMaster.RegisterAppMaster
-import io.gearpump.cluster.appmaster.AppMasterRuntimeEnvironment._
-import io.gearpump.cluster.appmaster.ExecutorSystemScheduler.{Session, StartExecutorSystems}
-import io.gearpump.cluster.appmaster.MasterConnectionKeeper.MasterConnectionStatus._
-import io.gearpump.cluster.master.MasterProxy
-import io.gearpump.cluster.{AppDescription, AppMasterContext}
-import io.gearpump.util.LogUtil
-
-/**
- * This serves as runtime environment for AppMaster.
- * When starting an AppMaster, we need to setup the connection to master,
- * and prepare other environments.
- *
- * This also extend the function of Master, by providing a scheduler service for Executor System.
- * AppMaster can ask Master for executor system directly. details like requesting resource,
- * contacting worker to start a process, and then starting an executor system is hidden from
- * AppMaster.
- *
- * Please use AppMasterRuntimeEnvironment.props() to construct this actor.
- */
-private[appmaster]
-class AppMasterRuntimeEnvironment(
- appContextInput: AppMasterContext,
- app: AppDescription,
- masters: Iterable[ActorPath],
- masterFactory: (AppId, MasterActorRef) => Props,
- appMasterFactory: (AppMasterContext, AppDescription) => Props,
- masterConnectionKeeperFactory: (MasterActorRef, RegisterAppMaster, ListenerActorRef) => Props)
- extends Actor {
-
- val appId = appContextInput.appId
- private val LOG = LogUtil.getLogger(getClass, app = appId)
-
- import scala.concurrent.duration._
-
- private val master = context.actorOf(
- masterFactory(appId, context.actorOf(Props(new MasterProxy(masters, 30.seconds)))))
- private val appContext = appContextInput.copy(masterProxy = master)
-
- // Create appMaster proxy to receive command and forward to appmaster
- private val appMaster = context.actorOf(appMasterFactory(appContext, app))
- context.watch(appMaster)
-
- private val registerAppMaster = RegisterAppMaster(appMaster, appContext.registerData)
- private val masterConnectionKeeper = context.actorOf(
- masterConnectionKeeperFactory(master, registerAppMaster, self))
- context.watch(masterConnectionKeeper)
-
- def receive: Receive = {
- case MasterConnected =>
- LOG.info(s"Master is connected, start AppMaster ${appId}...")
- appMaster ! StartAppMaster
- case MasterStopped =>
- LOG.error(s"Master is stopped, stop AppMaster ${appId}...")
- context.stop(self)
- case Terminated(actor) => actor match {
- case `appMaster` =>
- LOG.error(s"AppMaster ${appId} is stopped, shutdown myself")
- context.stop(self)
- case `masterConnectionKeeper` =>
- LOG.error(s"Master connection keeper is stopped, appId: ${appId}, shutdown myself")
- context.stop(self)
- case _ => // Skip
- }
- }
-}
-
-object AppMasterRuntimeEnvironment {
-
- def props(
- masters: Iterable[ActorPath], app: AppDescription, appContextInput: AppMasterContext)
- : Props = {
-
- val master = (appId: AppId, masterProxy: MasterActorRef) =>
- MasterWithExecutorSystemProvider.props(appId, masterProxy)
-
- val appMaster = (appContext: AppMasterContext, app: AppDescription) =>
- LazyStartAppMaster.props(appContext, app)
-
- val masterConnectionKeeper = (master: MasterActorRef, registerAppMaster:
- RegisterAppMaster, listener: ListenerActorRef) => Props(new MasterConnectionKeeper(
- registerAppMaster, master, masterStatusListener = listener))
-
- Props(new AppMasterRuntimeEnvironment(
- appContextInput, app, masters, master, appMaster, masterConnectionKeeper))
- }
-
- /**
- * This behavior like a AppMaster. Under the hood, It start start the real AppMaster in a lazy
- * way. When real AppMaster is not started yet, all messages are stashed. The stashed
- * messages are forwarded to real AppMaster when the real AppMaster is started.
- *
- * Please use LazyStartAppMaster.props to construct this actor
- *
- * @param appMasterProps underlying AppMaster Props
- */
- private[appmaster]
- class LazyStartAppMaster(appId: Int, appMasterProps: Props) extends Actor with Stash {
-
- private val LOG = LogUtil.getLogger(getClass, app = appId)
-
- def receive: Receive = null
-
- context.become(startAppMaster)
-
- def startAppMaster: Receive = {
- case StartAppMaster =>
- val appMaster = context.actorOf(appMasterProps, "appmaster")
- context.watch(appMaster)
- context.become(terminationWatch(appMaster) orElse appMasterService(appMaster))
- unstashAll()
- case _ =>
- stash()
- }
-
- def terminationWatch(appMaster: ActorRef): Receive = {
- case Terminated(appMaster) =>
- LOG.error("appmaster is stopped")
- context.stop(self)
- }
-
- def appMasterService(appMaster: ActorRef): Receive = {
- case msg => appMaster forward msg
- }
- }
-
- private[appmaster]
- object LazyStartAppMaster {
- def props(appContext: AppMasterContext, app: AppDescription): Props = {
- val appMasterProps = Props(Class.forName(app.appMaster), appContext, app)
- Props(new LazyStartAppMaster(appContext.appId, appMasterProps))
- }
- }
-
- private[appmaster] case object StartAppMaster
-
- /**
- * This enhance Master by providing new service: StartExecutorSystems
- *
- * Please use MasterWithExecutorSystemProvider.props to construct this actor
- *
- */
- private[appmaster]
- class MasterWithExecutorSystemProvider(master: ActorRef, executorSystemProviderProps: Props)
- extends Actor {
-
- val executorSystemProvider: ActorRef = context.actorOf(executorSystemProviderProps)
-
- override def receive: Receive = {
- case request: StartExecutorSystems =>
- executorSystemProvider forward request
- case msg =>
- master forward msg
- }
- }
-
- private[appmaster]
- object MasterWithExecutorSystemProvider {
- def props(appId: Int, master: ActorRef): Props = {
-
- val executorSystemLauncher = (appId: Int, session: Session) =>
- Props(new ExecutorSystemLauncher(appId, session))
-
- val scheduler = Props(new ExecutorSystemScheduler(appId, master, executorSystemLauncher))
-
- Props(new MasterWithExecutorSystemProvider(master, scheduler))
- }
- }
-
- private[appmaster] type AppId = Int
- private[appmaster] type MasterActorRef = ActorRef
- private[appmaster] type ListenerActorRef = ActorRef
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/io/gearpump/cluster/appmaster/AppMasterRuntimeInfo.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/io/gearpump/cluster/appmaster/AppMasterRuntimeInfo.scala b/core/src/main/scala/io/gearpump/cluster/appmaster/AppMasterRuntimeInfo.scala
deleted file mode 100644
index 5b3e0c5..0000000
--- a/core/src/main/scala/io/gearpump/cluster/appmaster/AppMasterRuntimeInfo.scala
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster.appmaster
-
-import akka.actor.ActorRef
-import com.typesafe.config.Config
-
-import io.gearpump._
-import io.gearpump.cluster.AppMasterRegisterData
-
-/** Run time info used to start an AppMaster */
-case class AppMasterRuntimeInfo(
- appId: Int,
- // AppName is the unique Id for an application
- appName: String,
- worker: ActorRef = null,
- user: String = null,
- submissionTime: TimeStamp = 0,
- startTime: TimeStamp = 0,
- finishTime: TimeStamp = 0,
- config: Config = null)
- extends AppMasterRegisterData
[34/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/distributedshell/src/test/scala/io/gearpump/examples/distributedshell/DistributedShellSpec.scala
----------------------------------------------------------------------
diff --git a/examples/distributedshell/src/test/scala/io/gearpump/examples/distributedshell/DistributedShellSpec.scala b/examples/distributedshell/src/test/scala/io/gearpump/examples/distributedshell/DistributedShellSpec.scala
deleted file mode 100644
index 6eeba58..0000000
--- a/examples/distributedshell/src/test/scala/io/gearpump/examples/distributedshell/DistributedShellSpec.scala
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.examples.distributedshell
-
-import scala.concurrent.Future
-import scala.util.Success
-
-import com.typesafe.config.Config
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{BeforeAndAfter, Matchers, PropSpec}
-
-import io.gearpump.cluster.ClientToMaster.SubmitApplication
-import io.gearpump.cluster.MasterToClient.SubmitApplicationResult
-import io.gearpump.cluster.{MasterHarness, TestUtil}
-
-class DistributedShellSpec
- extends PropSpec with PropertyChecks with Matchers with BeforeAndAfter with MasterHarness {
-
- before {
- startActorSystem()
- }
-
- after {
- shutdownActorSystem()
- }
-
- override def config: Config = TestUtil.DEFAULT_CONFIG
-
- property("DistributedShell should succeed to submit application with required arguments") {
- val requiredArgs = Array.empty[String]
-
- val masterReceiver = createMockMaster()
-
- Future {
- DistributedShell.main(masterConfig, requiredArgs)
- }
-
- masterReceiver.expectMsgType[SubmitApplication](PROCESS_BOOT_TIME)
- masterReceiver.reply(SubmitApplicationResult(Success(0)))
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/distributedshell/src/test/scala/io/gearpump/examples/distributedshell/ShellCommandResultAggregatorSpec.scala
----------------------------------------------------------------------
diff --git a/examples/distributedshell/src/test/scala/io/gearpump/examples/distributedshell/ShellCommandResultAggregatorSpec.scala b/examples/distributedshell/src/test/scala/io/gearpump/examples/distributedshell/ShellCommandResultAggregatorSpec.scala
deleted file mode 100644
index d59981b..0000000
--- a/examples/distributedshell/src/test/scala/io/gearpump/examples/distributedshell/ShellCommandResultAggregatorSpec.scala
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.examples.distributedshell
-
-import org.scalatest.{BeforeAndAfter, Matchers, WordSpec}
-
-import io.gearpump.examples.distributedshell.DistShellAppMaster.{ShellCommandResult, ShellCommandResultAggregator}
-
-class ShellCommandResultAggregatorSpec extends WordSpec with Matchers with BeforeAndAfter {
- "ShellCommandResultAggregator" should {
- "aggregate ShellCommandResult" in {
- val executorId1 = 1
- val executorId2 = 2
- val responseBuilder = new ShellCommandResultAggregator
- val response1 = ShellCommandResult(executorId1, "task1")
- val response2 = ShellCommandResult(executorId2, "task2")
- val result = responseBuilder.aggregate(response1).aggregate(response2).toString()
- val expected = s"Execute results from executor $executorId1 : \ntask1\n" +
- s"Execute results from executor $executorId2 : \ntask2\n"
- assert(result == expected)
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/distributedshell/src/test/scala/io/gearpump/examples/distributedshell/ShellExecutorSpec.scala
----------------------------------------------------------------------
diff --git a/examples/distributedshell/src/test/scala/io/gearpump/examples/distributedshell/ShellExecutorSpec.scala b/examples/distributedshell/src/test/scala/io/gearpump/examples/distributedshell/ShellExecutorSpec.scala
deleted file mode 100644
index b301973..0000000
--- a/examples/distributedshell/src/test/scala/io/gearpump/examples/distributedshell/ShellExecutorSpec.scala
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.examples.distributedshell
-
-import scala.concurrent.Await
-import scala.concurrent.duration.Duration
-import scala.sys.process._
-import scala.util.{Failure, Success, Try}
-
-import akka.actor.{ActorSystem, Props}
-import akka.testkit.TestProbe
-import org.scalatest.{Matchers, WordSpec}
-
-import io.gearpump.cluster.appmaster.WorkerInfo
-import io.gearpump.cluster.scheduler.Resource
-import io.gearpump.cluster.worker.WorkerId
-import io.gearpump.cluster.{ExecutorContext, TestUtil, UserConfig}
-import io.gearpump.examples.distributedshell.DistShellAppMaster.{ShellCommand, ShellCommandResult}
-
-class ShellExecutorSpec extends WordSpec with Matchers {
-
- "ShellExecutor" should {
- "execute the shell command and return the result" in {
- val executorId = 1
- val workerId = WorkerId(2, 0L)
- val appId = 0
- val appName = "app"
- val resource = Resource(1)
- implicit val system = ActorSystem("ShellExecutor", TestUtil.DEFAULT_CONFIG)
- val mockMaster = TestProbe()(system)
- val worker = TestProbe()
- val workerInfo = WorkerInfo(workerId, worker.ref)
- val executorContext = ExecutorContext(executorId, workerInfo, appId, appName,
- mockMaster.ref, resource)
- val executor = system.actorOf(Props(classOf[ShellExecutor], executorContext,
- UserConfig.empty))
-
- val process = Try(s"ls /".!!)
- val result = process match {
- case Success(msg) => msg
- case Failure(ex) => ex.getMessage
- }
- executor.tell(ShellCommand("ls /"), mockMaster.ref)
- assert(mockMaster.receiveN(1).head.asInstanceOf[ShellCommandResult].equals(
- ShellCommandResult(executorId, result)))
-
- system.terminate()
- Await.result(system.whenTerminated, Duration.Inf)
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/distributedshell/src/test/scala/org/apache/gearpump/examples/distributedshell/DistShellAppMasterSpec.scala
----------------------------------------------------------------------
diff --git a/examples/distributedshell/src/test/scala/org/apache/gearpump/examples/distributedshell/DistShellAppMasterSpec.scala b/examples/distributedshell/src/test/scala/org/apache/gearpump/examples/distributedshell/DistShellAppMasterSpec.scala
new file mode 100644
index 0000000..e22abaf
--- /dev/null
+++ b/examples/distributedshell/src/test/scala/org/apache/gearpump/examples/distributedshell/DistShellAppMasterSpec.scala
@@ -0,0 +1,78 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.examples.distributedshell
+
+import scala.concurrent.Await
+import scala.concurrent.duration.Duration
+
+import akka.actor.ActorSystem
+import akka.testkit.{TestActorRef, TestProbe}
+import org.scalatest.{BeforeAndAfter, Matchers, WordSpec}
+
+import org.apache.gearpump.cluster.AppMasterToMaster.{GetAllWorkers, RegisterAppMaster, RequestResource}
+import org.apache.gearpump.cluster.AppMasterToWorker.LaunchExecutor
+import org.apache.gearpump.cluster.MasterToAppMaster.{AppMasterRegistered, ResourceAllocated, WorkerList}
+import org.apache.gearpump.cluster._
+import org.apache.gearpump.cluster.appmaster.{AppMasterRuntimeEnvironment, AppMasterRuntimeInfo}
+import org.apache.gearpump.cluster.scheduler.{Relaxation, Resource, ResourceAllocation, ResourceRequest}
+import org.apache.gearpump.cluster.worker.WorkerId
+import org.apache.gearpump.util.ActorSystemBooter.RegisterActorSystem
+import org.apache.gearpump.util.ActorUtil
+
+class DistShellAppMasterSpec extends WordSpec with Matchers with BeforeAndAfter {
+ implicit val system = ActorSystem("AppMasterSpec", TestUtil.DEFAULT_CONFIG)
+ val mockMaster = TestProbe()(system)
+ val mockWorker1 = TestProbe()(system)
+ val masterProxy = mockMaster.ref
+ val appId = 0
+ val userName = "test"
+ val masterExecutorId = 0
+ val workerList = List(WorkerId(1, 0L), WorkerId(2, 0L), WorkerId(3, 0L))
+ val resource = Resource(1)
+ val appJar = None
+ val appDescription = AppDescription("app0", classOf[DistShellAppMaster].getName, UserConfig.empty)
+
+ "DistributedShell AppMaster" should {
+ "launch one ShellTask on each worker" in {
+ val appMasterInfo = AppMasterRuntimeInfo(appId, appName = appId.toString)
+ val appMasterContext = AppMasterContext(appId, userName, resource, null, appJar,
+ masterProxy, appMasterInfo)
+ TestActorRef[DistShellAppMaster](
+ AppMasterRuntimeEnvironment.props(List(masterProxy.path), appDescription, appMasterContext))
+ mockMaster.expectMsgType[RegisterAppMaster]
+ mockMaster.reply(AppMasterRegistered(appId))
+ // The DistributedShell AppMaster asks for worker list from Master.
+ mockMaster.expectMsg(GetAllWorkers)
+ mockMaster.reply(WorkerList(workerList))
+ // After worker list is ready, DistributedShell AppMaster requests resource on each worker
+ workerList.foreach { workerId =>
+ mockMaster.expectMsg(RequestResource(appId, ResourceRequest(Resource(1), workerId,
+ relaxation = Relaxation.SPECIFICWORKER)))
+ }
+ mockMaster.reply(ResourceAllocated(
+ Array(ResourceAllocation(resource, mockWorker1.ref, WorkerId(1, 0L)))))
+ mockWorker1.expectMsgClass(classOf[LaunchExecutor])
+ mockWorker1.reply(RegisterActorSystem(ActorUtil.getSystemAddress(system).toString))
+ }
+ }
+
+ after {
+ system.terminate()
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/distributedshell/src/test/scala/org/apache/gearpump/examples/distributedshell/DistributedShellClientSpec.scala
----------------------------------------------------------------------
diff --git a/examples/distributedshell/src/test/scala/org/apache/gearpump/examples/distributedshell/DistributedShellClientSpec.scala b/examples/distributedshell/src/test/scala/org/apache/gearpump/examples/distributedshell/DistributedShellClientSpec.scala
new file mode 100644
index 0000000..7cfd07a
--- /dev/null
+++ b/examples/distributedshell/src/test/scala/org/apache/gearpump/examples/distributedshell/DistributedShellClientSpec.scala
@@ -0,0 +1,66 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.examples.distributedshell
+
+import scala.concurrent.Future
+import scala.util.{Success, Try}
+
+import akka.testkit.TestProbe
+import org.scalatest.{BeforeAndAfter, Matchers, PropSpec}
+
+import org.apache.gearpump.cluster.ClientToMaster.ResolveAppId
+import org.apache.gearpump.cluster.MasterToClient.ResolveAppIdResult
+import org.apache.gearpump.cluster.{MasterHarness, TestUtil}
+import org.apache.gearpump.examples.distributedshell.DistShellAppMaster.ShellCommand
+import org.apache.gearpump.util.LogUtil
+
+class DistributedShellClientSpec
+ extends PropSpec with Matchers with BeforeAndAfter with MasterHarness {
+
+ private val LOG = LogUtil.getLogger(getClass)
+
+ before {
+ startActorSystem()
+ }
+
+ after {
+ shutdownActorSystem()
+ }
+
+ protected override def config = TestUtil.DEFAULT_CONFIG
+
+ property("DistributedShellClient should succeed to submit application with required arguments") {
+ val command = "ls /"
+ val requiredArgs = Array("-appid", "0", "-command", command)
+ val masterReceiver = createMockMaster()
+
+ assert(Try(DistributedShellClient.main(Array.empty[String])).isFailure,
+ "missing required arguments, print usage")
+
+ Future {
+ DistributedShellClient.main(masterConfig, requiredArgs)
+ }
+
+ masterReceiver.expectMsg(PROCESS_BOOT_TIME, ResolveAppId(0))
+ val mockAppMaster = TestProbe()(getActorSystem)
+ masterReceiver.reply(ResolveAppIdResult(Success(mockAppMaster.ref)))
+ LOG.info(s"Reply back ResolveAppIdResult, current actorRef: ${mockAppMaster.ref.path.toString}")
+ mockAppMaster.expectMsg(PROCESS_BOOT_TIME, ShellCommand(command))
+ mockAppMaster.reply("result")
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/distributedshell/src/test/scala/org/apache/gearpump/examples/distributedshell/DistributedShellSpec.scala
----------------------------------------------------------------------
diff --git a/examples/distributedshell/src/test/scala/org/apache/gearpump/examples/distributedshell/DistributedShellSpec.scala b/examples/distributedshell/src/test/scala/org/apache/gearpump/examples/distributedshell/DistributedShellSpec.scala
new file mode 100644
index 0000000..51b5ec3
--- /dev/null
+++ b/examples/distributedshell/src/test/scala/org/apache/gearpump/examples/distributedshell/DistributedShellSpec.scala
@@ -0,0 +1,56 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.examples.distributedshell
+
+import scala.concurrent.Future
+import scala.util.Success
+
+import com.typesafe.config.Config
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{BeforeAndAfter, Matchers, PropSpec}
+
+import org.apache.gearpump.cluster.ClientToMaster.SubmitApplication
+import org.apache.gearpump.cluster.MasterToClient.SubmitApplicationResult
+import org.apache.gearpump.cluster.{MasterHarness, TestUtil}
+
+class DistributedShellSpec
+ extends PropSpec with PropertyChecks with Matchers with BeforeAndAfter with MasterHarness {
+
+ before {
+ startActorSystem()
+ }
+
+ after {
+ shutdownActorSystem()
+ }
+
+ override def config: Config = TestUtil.DEFAULT_CONFIG
+
+ property("DistributedShell should succeed to submit application with required arguments") {
+ val requiredArgs = Array.empty[String]
+
+ val masterReceiver = createMockMaster()
+
+ Future {
+ DistributedShell.main(masterConfig, requiredArgs)
+ }
+
+ masterReceiver.expectMsgType[SubmitApplication](PROCESS_BOOT_TIME)
+ masterReceiver.reply(SubmitApplicationResult(Success(0)))
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/distributedshell/src/test/scala/org/apache/gearpump/examples/distributedshell/ShellCommandResultAggregatorSpec.scala
----------------------------------------------------------------------
diff --git a/examples/distributedshell/src/test/scala/org/apache/gearpump/examples/distributedshell/ShellCommandResultAggregatorSpec.scala b/examples/distributedshell/src/test/scala/org/apache/gearpump/examples/distributedshell/ShellCommandResultAggregatorSpec.scala
new file mode 100644
index 0000000..11350a6
--- /dev/null
+++ b/examples/distributedshell/src/test/scala/org/apache/gearpump/examples/distributedshell/ShellCommandResultAggregatorSpec.scala
@@ -0,0 +1,38 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.examples.distributedshell
+
+import org.scalatest.{BeforeAndAfter, Matchers, WordSpec}
+
+import org.apache.gearpump.examples.distributedshell.DistShellAppMaster.{ShellCommandResult, ShellCommandResultAggregator}
+
+class ShellCommandResultAggregatorSpec extends WordSpec with Matchers with BeforeAndAfter {
+ "ShellCommandResultAggregator" should {
+ "aggregate ShellCommandResult" in {
+ val executorId1 = 1
+ val executorId2 = 2
+ val responseBuilder = new ShellCommandResultAggregator
+ val response1 = ShellCommandResult(executorId1, "task1")
+ val response2 = ShellCommandResult(executorId2, "task2")
+ val result = responseBuilder.aggregate(response1).aggregate(response2).toString()
+ val expected = s"Execute results from executor $executorId1 : \ntask1\n" +
+ s"Execute results from executor $executorId2 : \ntask2\n"
+ assert(result == expected)
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/distributedshell/src/test/scala/org/apache/gearpump/examples/distributedshell/ShellExecutorSpec.scala
----------------------------------------------------------------------
diff --git a/examples/distributedshell/src/test/scala/org/apache/gearpump/examples/distributedshell/ShellExecutorSpec.scala b/examples/distributedshell/src/test/scala/org/apache/gearpump/examples/distributedshell/ShellExecutorSpec.scala
new file mode 100644
index 0000000..e7a3a21
--- /dev/null
+++ b/examples/distributedshell/src/test/scala/org/apache/gearpump/examples/distributedshell/ShellExecutorSpec.scala
@@ -0,0 +1,66 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.examples.distributedshell
+
+import scala.concurrent.Await
+import scala.concurrent.duration.Duration
+import scala.sys.process._
+import scala.util.{Failure, Success, Try}
+
+import akka.actor.{ActorSystem, Props}
+import akka.testkit.TestProbe
+import org.scalatest.{Matchers, WordSpec}
+
+import org.apache.gearpump.cluster.appmaster.WorkerInfo
+import org.apache.gearpump.cluster.scheduler.Resource
+import org.apache.gearpump.cluster.worker.WorkerId
+import org.apache.gearpump.cluster.{ExecutorContext, TestUtil, UserConfig}
+import org.apache.gearpump.examples.distributedshell.DistShellAppMaster.{ShellCommand, ShellCommandResult}
+
+class ShellExecutorSpec extends WordSpec with Matchers {
+
+ "ShellExecutor" should {
+ "execute the shell command and return the result" in {
+ val executorId = 1
+ val workerId = WorkerId(2, 0L)
+ val appId = 0
+ val appName = "app"
+ val resource = Resource(1)
+ implicit val system = ActorSystem("ShellExecutor", TestUtil.DEFAULT_CONFIG)
+ val mockMaster = TestProbe()(system)
+ val worker = TestProbe()
+ val workerInfo = WorkerInfo(workerId, worker.ref)
+ val executorContext = ExecutorContext(executorId, workerInfo, appId, appName,
+ mockMaster.ref, resource)
+ val executor = system.actorOf(Props(classOf[ShellExecutor], executorContext,
+ UserConfig.empty))
+
+ val process = Try(s"ls /".!!)
+ val result = process match {
+ case Success(msg) => msg
+ case Failure(ex) => ex.getMessage
+ }
+ executor.tell(ShellCommand("ls /"), mockMaster.ref)
+ assert(mockMaster.receiveN(1).head.asInstanceOf[ShellCommandResult].equals(
+ ShellCommandResult(executorId, result)))
+
+ system.terminate()
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/distributeservice/README.md
----------------------------------------------------------------------
diff --git a/examples/distributeservice/README.md b/examples/distributeservice/README.md
index 82b3726..65d41f6 100644
--- a/examples/distributeservice/README.md
+++ b/examples/distributeservice/README.md
@@ -6,12 +6,12 @@ In order to run the example:
2. Start the AppMaster:<br>
```bash
- target/pack/bin/gear app -jar experiments/distributeservice/target/$SCALA_VERSION_MAJOR/gearpump-experiments-distributeservice_$VERSION.jar io.gearpump.distributeservice.DistributeService
+ target/pack/bin/gear app -jar experiments/distributeservice/target/$SCALA_VERSION_MAJOR/gearpump-experiments-distributeservice_$VERSION.jar org.apache.gearpump.distributeservice.DistributeService
```
3. Distribute the service:<br>
```bash
target/pack/bin/gear app -jar experiments/distributeservice/target/$SCALA_VERSION_MAJOR/gearpump-experiments-distributeservice_$VERSION.jar
- io.gearpump.distributeservice.DistributeServiceClient -appid $APPID -file ${File_Path}
+ org.apache.gearpump.distributeservice.DistributeServiceClient -appid $APPID -file ${File_Path}
-script ${Script_Path} -serviceName ${Service_Name} -target ${Target_Path} -Dkey1=value1 -Dkey2=value2
```<br>
This command will distribute the service zip file(variable ```file```) to the target path(variable ```target```), then copy the script to
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/distributeservice/src/main/scala/io/gearpump/experiments/distributeservice/DistServiceAppMaster.scala
----------------------------------------------------------------------
diff --git a/examples/distributeservice/src/main/scala/io/gearpump/experiments/distributeservice/DistServiceAppMaster.scala b/examples/distributeservice/src/main/scala/io/gearpump/experiments/distributeservice/DistServiceAppMaster.scala
deleted file mode 100644
index a220dc6..0000000
--- a/examples/distributeservice/src/main/scala/io/gearpump/experiments/distributeservice/DistServiceAppMaster.scala
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.experiments.distributeservice
-
-import java.io.File
-import scala.concurrent.Future
-
-import akka.actor.{Deploy, Props}
-import akka.pattern.{ask, pipe}
-import akka.remote.RemoteScope
-import com.typesafe.config.Config
-import org.slf4j.Logger
-
-import io.gearpump.cluster.ClientToMaster.ShutdownApplication
-import io.gearpump.cluster.appmaster.ExecutorSystemScheduler.{ExecutorSystemJvmConfig, ExecutorSystemStarted, StartExecutorSystemTimeout}
-import io.gearpump.cluster.{AppDescription, AppMasterContext, ApplicationMaster, ExecutorContext}
-import io.gearpump.experiments.distributeservice.DistServiceAppMaster.{FileContainer, GetFileContainer, InstallService}
-import io.gearpump.util._
-
-class DistServiceAppMaster(appContext: AppMasterContext, app: AppDescription)
- extends ApplicationMaster {
- import appContext._
- import context.dispatcher
- implicit val timeout = Constants.FUTURE_TIMEOUT
- private val LOG: Logger = LogUtil.getLogger(getClass, app = appId)
- private var currentExecutorId = 0
- private var fileServerPort = -1
-
- val rootDirectory = new File("/")
- val host = context.system.settings.config.getString(Constants.GEARPUMP_HOSTNAME)
- val server = context.actorOf(Props(classOf[FileServer], rootDirectory, host, 0))
-
- override def preStart(): Unit = {
- LOG.info(s"Distribute Service AppMaster started")
- ActorUtil.launchExecutorOnEachWorker(masterProxy, getExecutorJvmConfig, self)
- }
-
- (server ? FileServer.GetPort).asInstanceOf[Future[FileServer.Port]] pipeTo self
-
- override def receive: Receive = {
- case ExecutorSystemStarted(executorSystem, _) =>
- import executorSystem.{address, resource => executorResource, worker}
- val executorContext = ExecutorContext(currentExecutorId, worker,
- appId, app.name, self, executorResource)
- // start executor
- val executor = context.actorOf(Props(classOf[DistServiceExecutor],
- executorContext, app.userConfig).withDeploy(
- Deploy(scope = RemoteScope(address))), currentExecutorId.toString)
- executorSystem.bindLifeCycleWith(executor)
- currentExecutorId += 1
- case StartExecutorSystemTimeout =>
- LOG.error(s"Failed to allocate resource in time")
- masterProxy ! ShutdownApplication(appId)
- context.stop(self)
- case FileServer.Port(port) =>
- this.fileServerPort = port
- case GetFileContainer =>
- val name = Math.abs(new java.util.Random().nextLong()).toString
- sender ! new FileContainer(s"http://$host:$fileServerPort/$name")
- case installService: InstallService =>
- context.children.foreach(_ ! installService)
- }
-
- private def getExecutorJvmConfig: ExecutorSystemJvmConfig = {
- val config: Config = app.clusterConfig
- val jvmSetting = Util.resolveJvmSetting(
- config.withFallback(context.system.settings.config)).executor
- ExecutorSystemJvmConfig(jvmSetting.classPath, jvmSetting.vmargs,
- appJar, username, config)
- }
-}
-
-object DistServiceAppMaster {
- case object GetFileContainer
-
- case class FileContainer(url: String)
-
- case class InstallService(
- url: String,
- zipFileName: String,
- targetPath: String,
- script: Array[Byte],
- serviceName: String,
- serviceSettings: Map[String, Any])
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/distributeservice/src/main/scala/io/gearpump/experiments/distributeservice/DistServiceExecutor.scala
----------------------------------------------------------------------
diff --git a/examples/distributeservice/src/main/scala/io/gearpump/experiments/distributeservice/DistServiceExecutor.scala b/examples/distributeservice/src/main/scala/io/gearpump/experiments/distributeservice/DistServiceExecutor.scala
deleted file mode 100644
index 4a2a876..0000000
--- a/examples/distributeservice/src/main/scala/io/gearpump/experiments/distributeservice/DistServiceExecutor.scala
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.experiments.distributeservice
-
-import java.io.{File, FileWriter}
-import java.net.InetAddress
-import scala.collection.JavaConverters._
-import scala.io.Source
-import scala.sys.process._
-import scala.util.{Failure, Success, Try}
-
-import akka.actor.Actor
-import org.apache.commons.io.FileUtils
-import org.apache.commons.lang.text.StrSubstitutor
-import org.slf4j.Logger
-
-import io.gearpump.cluster.{ExecutorContext, UserConfig}
-import io.gearpump.experiments.distributeservice.DistServiceAppMaster.InstallService
-import io.gearpump.util.{ActorUtil, LogUtil}
-
-class DistServiceExecutor(executorContext: ExecutorContext, userConf: UserConfig) extends Actor {
- import executorContext._
- private val LOG: Logger = LogUtil.getLogger(getClass, executor = executorId, app = appId)
-
- override def receive: Receive = {
- case InstallService(url, zipFileName, targetPath, scriptData, serviceName, serviceSettings) =>
- LOG.info(s"Executor $executorId receive command to install " +
- s"service $serviceName to $targetPath")
- unzipFile(url, zipFileName, targetPath)
- installService(scriptData, serviceName, serviceSettings)
- }
-
- private def unzipFile(url: String, zipFileName: String, targetPath: String) = {
- val zipFile = File.createTempFile(System.currentTimeMillis().toString, zipFileName)
- val dir = new File(targetPath)
- if (dir.exists()) {
- FileUtils.forceDelete(dir)
- }
- val bytes = FileServer.newClient.get(url).get
- FileUtils.writeByteArrayToFile(zipFile, bytes)
- val result = Try(s"unzip ${zipFile.getAbsolutePath} -d $targetPath".!!)
- result match {
- case Success(msg) => LOG.info(s"Executor $executorId unzip file to $targetPath")
- case Failure(ex) => throw ex
- }
- }
-
- private def installService(
- scriptData: Array[Byte], serviceName: String, serviceSettings: Map[String, Any]) = {
- val tempFile = File.createTempFile("gearpump", serviceName)
- FileUtils.writeByteArrayToFile(tempFile, scriptData)
- val script = new File("/etc/init.d", serviceName)
- writeFileWithEnvVariables(tempFile, script, serviceSettings ++ getEnvSettings)
- val result = Try(s"chkconfig --add $serviceName".!!)
- result match {
- case Success(msg) => LOG.info(s"Executor install service $serviceName successfully!")
- case Failure(ex) => throw ex
- }
- }
-
- private def getEnvSettings: Map[String, Any] = {
- Map("workerId" -> worker,
- "localhost" -> ActorUtil.getSystemAddress(context.system).host.get,
- "hostname" -> InetAddress.getLocalHost.getHostName)
- }
-
- private def writeFileWithEnvVariables(source: File, target: File, envs: Map[String, Any]) = {
- val writer = new FileWriter(target)
- val sub = new StrSubstitutor(envs.asJava)
- sub.setEnableSubstitutionInVariables(true)
- Source.fromFile(source).getLines().foreach(line => writer.write(sub.replace(line) + "\r\n"))
- writer.close()
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/distributeservice/src/main/scala/io/gearpump/experiments/distributeservice/DistributeService.scala
----------------------------------------------------------------------
diff --git a/examples/distributeservice/src/main/scala/io/gearpump/experiments/distributeservice/DistributeService.scala b/examples/distributeservice/src/main/scala/io/gearpump/experiments/distributeservice/DistributeService.scala
deleted file mode 100644
index 522dc5e..0000000
--- a/examples/distributeservice/src/main/scala/io/gearpump/experiments/distributeservice/DistributeService.scala
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.experiments.distributeservice
-
-import org.slf4j.Logger
-
-import io.gearpump.cluster.client.ClientContext
-import io.gearpump.cluster.main.{ArgumentsParser, CLIOption}
-import io.gearpump.cluster.{Application, UserConfig}
-import io.gearpump.util.{AkkaApp, LogUtil}
-
-/** Demo app to remotely deploy and start system service on machines in the cluster */
-object DistributeService extends AkkaApp with ArgumentsParser {
- private val LOG: Logger = LogUtil.getLogger(getClass)
-
- override val options: Array[(String, CLIOption[Any])] = Array.empty
-
- override def main(akkaConf: Config, args: Array[String]): Unit = {
- LOG.info(s"Distribute Service submitting application...")
- val context = ClientContext(akkaConf)
- val appId = context.submit(Application[DistServiceAppMaster]("DistributedService",
- UserConfig.empty))
- context.close()
- LOG.info(s"Distribute Service Application started with appId $appId !")
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/distributeservice/src/main/scala/io/gearpump/experiments/distributeservice/DistributeServiceClient.scala
----------------------------------------------------------------------
diff --git a/examples/distributeservice/src/main/scala/io/gearpump/experiments/distributeservice/DistributeServiceClient.scala b/examples/distributeservice/src/main/scala/io/gearpump/experiments/distributeservice/DistributeServiceClient.scala
deleted file mode 100644
index 0d85001..0000000
--- a/examples/distributeservice/src/main/scala/io/gearpump/experiments/distributeservice/DistributeServiceClient.scala
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.experiments.distributeservice
-
-import java.io.File
-import scala.concurrent.Future
-import scala.util.{Failure, Success}
-
-import akka.pattern.ask
-import org.apache.commons.io.FileUtils
-
-import io.gearpump.cluster.client.ClientContext
-import io.gearpump.cluster.main.{ArgumentsParser, CLIOption}
-import io.gearpump.experiments.distributeservice.DistServiceAppMaster.{FileContainer, GetFileContainer, InstallService}
-import io.gearpump.util.{AkkaApp, Constants}
-
-/** Client to submit the service jar */
-object DistributeServiceClient extends AkkaApp with ArgumentsParser {
- implicit val timeout = Constants.FUTURE_TIMEOUT
-
- override val options: Array[(String, CLIOption[Any])] = Array(
- "appid" -> CLIOption[Int]("<the distributed shell appid>", required = true),
- "file" -> CLIOption[String]("<service zip file path>", required = true),
- "script" -> CLIOption[String](
- "<file path of service script that will be installed to /etc/init.d>", required = true),
- "serviceName" -> CLIOption[String]("<service name>", required = true),
- "target" -> CLIOption[String]("<target path on each machine>", required = true)
- )
-
- override def help(): Unit = {
- super.help()
- // scalastyle:off println
- Console.err.println(s"-D<name>=<value> set a property to the service")
- // scalastyle:on println
- }
-
- override def main(akkaConf: Config, args: Array[String]): Unit = {
- val config = parse(filterCustomOptions(args))
- val context = ClientContext(akkaConf)
- implicit val system = context.system
- implicit val dispatcher = system.dispatcher
- val appid = config.getInt("appid")
- val zipFile = new File(config.getString("file"))
- val script = new File(config.getString("script"))
- val serviceName = config.getString("serviceName")
- val appMaster = context.resolveAppID(appid)
- (appMaster ? GetFileContainer).asInstanceOf[Future[FileContainer]].map { container =>
- val bytes = FileUtils.readFileToByteArray(zipFile)
- val result = FileServer.newClient.save(container.url, bytes)
- result match {
- case Success(_) =>
- appMaster ! InstallService(container.url, zipFile.getName, config.getString("target"),
- FileUtils.readFileToByteArray(script), serviceName, parseServiceConfig(args))
- context.close()
- case Failure(ex) => throw ex
- }
- }
- }
-
- private def filterCustomOptions(args: Array[String]): Array[String] = {
- args.filter(!_.startsWith("-D"))
- }
-
- private def parseServiceConfig(args: Array[String]): Map[String, Any] = {
- val result = Map.empty[String, Any]
- args.foldLeft(result) { (result, argument) =>
- if (argument.startsWith("-D") && argument.contains("=")) {
- val fixedKV = argument.substring(2).split("=")
- result + (fixedKV(0) -> fixedKV(1))
- } else {
- result
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/distributeservice/src/main/scala/io/gearpump/experiments/distributeservice/FileServer.scala
----------------------------------------------------------------------
diff --git a/examples/distributeservice/src/main/scala/io/gearpump/experiments/distributeservice/FileServer.scala b/examples/distributeservice/src/main/scala/io/gearpump/experiments/distributeservice/FileServer.scala
deleted file mode 100644
index ed0b24d..0000000
--- a/examples/distributeservice/src/main/scala/io/gearpump/experiments/distributeservice/FileServer.scala
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.distributeservice
-
-import java.io.File
-import scala.util.{Failure, Success, Try}
-
-import akka.actor.{Actor, Stash}
-import akka.io.IO
-import org.apache.commons.httpclient.HttpClient
-import org.apache.commons.httpclient.methods.{ByteArrayRequestEntity, GetMethod, PostMethod}
-import spray.can.Http
-import spray.http.HttpMethods._
-import spray.http._
-
-import io.gearpump.util.{FileUtils, LogUtil}
-
-/**
- *
- * Should not use this to server too big files(more than 100MB), otherwise OOM may happen.
- *
- * port: set port to 0 if you want to bind to random port
- */
-class FileServer(rootDir: File, host: String, port: Int) extends Actor with Stash {
- private val LOG = LogUtil.getLogger(getClass)
-
- implicit val system = context.system
-
- override def preStart(): Unit = {
- // Creates http server
- IO(Http) ! Http.Bind(self, host, port)
- }
-
- override def postStop(): Unit = {
- // Stop the server
- IO(Http) ! Http.Unbind
- }
-
- override def receive: Receive = {
- case Http.Bound(address) =>
- LOG.info(s"FileServer bound on port: ${address.getPort}")
- context.become(listen(address.getPort))
- unstashAll()
- case _ =>
- stash()
- }
-
- def listen(port: Int): Receive = {
- case FileServer.GetPort => {
- sender ! FileServer.Port(port)
- }
- case Http.Connected(remote, _) =>
- sender ! Http.Register(self)
-
- // Fetches files from remote uri
- case HttpRequest(GET, uri, _, _, _) =>
- val child = uri.path.toString()
- val payload = Try {
- val source = new File(rootDir, child)
- FileUtils.readFileToByteArray(source)
- }
- payload match {
- case Success(data) =>
- sender ! HttpResponse(entity = HttpEntity(data))
- case Failure(ex) =>
- LOG.error("failed to get file " + ex.getMessage)
- sender ! HttpResponse(status = StatusCodes.InternalServerError, entity = ex.getMessage)
- }
- // Save file to remote uri
- case post@HttpRequest(POST, uri, _, _, _) =>
- val child = uri.path.toString()
-
- val status = Try {
- val target = new File(rootDir, child)
- val payload = post.entity.data.toByteArray
- FileUtils.writeByteArrayToFile(target, payload)
- "OK"
- }
- status match {
- case Success(message) => sender ! HttpResponse(entity = message)
- case Failure(ex) =>
- LOG.error("save file failed " + ex.getMessage)
- sender ! HttpResponse(status = StatusCodes.InternalServerError, entity = ex.getMessage)
- }
- }
-}
-
-object FileServer {
- object GetPort
- case class Port(port: Int)
-
- def newClient: Client = new Client
-
- class Client {
- val client = new HttpClient()
-
- def save(uri: String, data: Array[Byte]): Try[Int] = {
- Try {
- val post = new PostMethod(uri)
- val entity = new ByteArrayRequestEntity(data)
- post.setRequestEntity(entity)
- client.executeMethod(post)
- }
- }
-
- def get(uri: String): Try[Array[Byte]] = {
- val get = new GetMethod(uri)
- val status = Try {
- client.executeMethod(get)
- }
-
- val data = status.flatMap { code =>
- if (code == 200) {
- Success(get.getResponseBody())
- } else {
- Failure(new Exception(s"We cannot get the data, the status code is $code"))
- }
- }
- data
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/distributeservice/src/main/scala/org/apache/gearpump/experiments/distributeservice/DistServiceAppMaster.scala
----------------------------------------------------------------------
diff --git a/examples/distributeservice/src/main/scala/org/apache/gearpump/experiments/distributeservice/DistServiceAppMaster.scala b/examples/distributeservice/src/main/scala/org/apache/gearpump/experiments/distributeservice/DistServiceAppMaster.scala
new file mode 100644
index 0000000..ca0ab49
--- /dev/null
+++ b/examples/distributeservice/src/main/scala/org/apache/gearpump/experiments/distributeservice/DistServiceAppMaster.scala
@@ -0,0 +1,100 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.experiments.distributeservice
+
+import java.io.File
+import scala.concurrent.Future
+
+import akka.actor.{Deploy, Props}
+import akka.pattern.{ask, pipe}
+import akka.remote.RemoteScope
+import com.typesafe.config.Config
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.ClientToMaster.ShutdownApplication
+import org.apache.gearpump.cluster.appmaster.ExecutorSystemScheduler.{ExecutorSystemJvmConfig, ExecutorSystemStarted, StartExecutorSystemTimeout}
+import org.apache.gearpump.cluster.{AppDescription, AppMasterContext, ApplicationMaster, ExecutorContext}
+import org.apache.gearpump.experiments.distributeservice.DistServiceAppMaster.{FileContainer, GetFileContainer, InstallService}
+import org.apache.gearpump.util._
+
+class DistServiceAppMaster(appContext: AppMasterContext, app: AppDescription)
+ extends ApplicationMaster {
+ import appContext._
+ import context.dispatcher
+ implicit val timeout = Constants.FUTURE_TIMEOUT
+ private val LOG: Logger = LogUtil.getLogger(getClass, app = appId)
+ private var currentExecutorId = 0
+ private var fileServerPort = -1
+
+ val rootDirectory = new File("/")
+ val host = context.system.settings.config.getString(Constants.GEARPUMP_HOSTNAME)
+ val server = context.actorOf(Props(classOf[FileServer], rootDirectory, host, 0))
+
+ override def preStart(): Unit = {
+ LOG.info(s"Distribute Service AppMaster started")
+ ActorUtil.launchExecutorOnEachWorker(masterProxy, getExecutorJvmConfig, self)
+ }
+
+ (server ? FileServer.GetPort).asInstanceOf[Future[FileServer.Port]] pipeTo self
+
+ override def receive: Receive = {
+ case ExecutorSystemStarted(executorSystem, _) =>
+ import executorSystem.{address, resource => executorResource, worker}
+ val executorContext = ExecutorContext(currentExecutorId, worker,
+ appId, app.name, self, executorResource)
+ // start executor
+ val executor = context.actorOf(Props(classOf[DistServiceExecutor],
+ executorContext, app.userConfig).withDeploy(
+ Deploy(scope = RemoteScope(address))), currentExecutorId.toString)
+ executorSystem.bindLifeCycleWith(executor)
+ currentExecutorId += 1
+ case StartExecutorSystemTimeout =>
+ LOG.error(s"Failed to allocate resource in time")
+ masterProxy ! ShutdownApplication(appId)
+ context.stop(self)
+ case FileServer.Port(port) =>
+ this.fileServerPort = port
+ case GetFileContainer =>
+ val name = Math.abs(new java.util.Random().nextLong()).toString
+ sender ! new FileContainer(s"http://$host:$fileServerPort/$name")
+ case installService: InstallService =>
+ context.children.foreach(_ ! installService)
+ }
+
+ private def getExecutorJvmConfig: ExecutorSystemJvmConfig = {
+ val config: Config = app.clusterConfig
+ val jvmSetting = Util.resolveJvmSetting(
+ config.withFallback(context.system.settings.config)).executor
+ ExecutorSystemJvmConfig(jvmSetting.classPath, jvmSetting.vmargs,
+ appJar, username, config)
+ }
+}
+
+object DistServiceAppMaster {
+ case object GetFileContainer
+
+ case class FileContainer(url: String)
+
+ case class InstallService(
+ url: String,
+ zipFileName: String,
+ targetPath: String,
+ script: Array[Byte],
+ serviceName: String,
+ serviceSettings: Map[String, Any])
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/distributeservice/src/main/scala/org/apache/gearpump/experiments/distributeservice/DistServiceExecutor.scala
----------------------------------------------------------------------
diff --git a/examples/distributeservice/src/main/scala/org/apache/gearpump/experiments/distributeservice/DistServiceExecutor.scala b/examples/distributeservice/src/main/scala/org/apache/gearpump/experiments/distributeservice/DistServiceExecutor.scala
new file mode 100644
index 0000000..248156f
--- /dev/null
+++ b/examples/distributeservice/src/main/scala/org/apache/gearpump/experiments/distributeservice/DistServiceExecutor.scala
@@ -0,0 +1,89 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.experiments.distributeservice
+
+import java.io.{File, FileWriter}
+import java.net.InetAddress
+import scala.collection.JavaConverters._
+import scala.io.Source
+import scala.sys.process._
+import scala.util.{Failure, Success, Try}
+
+import akka.actor.Actor
+import org.apache.commons.io.FileUtils
+import org.apache.commons.lang.text.StrSubstitutor
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.{ExecutorContext, UserConfig}
+import org.apache.gearpump.experiments.distributeservice.DistServiceAppMaster.InstallService
+import org.apache.gearpump.util.{ActorUtil, LogUtil}
+
+class DistServiceExecutor(executorContext: ExecutorContext, userConf: UserConfig) extends Actor {
+ import executorContext._
+ private val LOG: Logger = LogUtil.getLogger(getClass, executor = executorId, app = appId)
+
+ override def receive: Receive = {
+ case InstallService(url, zipFileName, targetPath, scriptData, serviceName, serviceSettings) =>
+ LOG.info(s"Executor $executorId receive command to install " +
+ s"service $serviceName to $targetPath")
+ unzipFile(url, zipFileName, targetPath)
+ installService(scriptData, serviceName, serviceSettings)
+ }
+
+ private def unzipFile(url: String, zipFileName: String, targetPath: String) = {
+ val zipFile = File.createTempFile(System.currentTimeMillis().toString, zipFileName)
+ val dir = new File(targetPath)
+ if (dir.exists()) {
+ FileUtils.forceDelete(dir)
+ }
+ val bytes = FileServer.newClient.get(url).get
+ FileUtils.writeByteArrayToFile(zipFile, bytes)
+ val result = Try(s"unzip ${zipFile.getAbsolutePath} -d $targetPath".!!)
+ result match {
+ case Success(msg) => LOG.info(s"Executor $executorId unzip file to $targetPath")
+ case Failure(ex) => throw ex
+ }
+ }
+
+ private def installService(
+ scriptData: Array[Byte], serviceName: String, serviceSettings: Map[String, Any]) = {
+ val tempFile = File.createTempFile("gearpump", serviceName)
+ FileUtils.writeByteArrayToFile(tempFile, scriptData)
+ val script = new File("/etc/init.d", serviceName)
+ writeFileWithEnvVariables(tempFile, script, serviceSettings ++ getEnvSettings)
+ val result = Try(s"chkconfig --add $serviceName".!!)
+ result match {
+ case Success(msg) => LOG.info(s"Executor install service $serviceName successfully!")
+ case Failure(ex) => throw ex
+ }
+ }
+
+ private def getEnvSettings: Map[String, Any] = {
+ Map("workerId" -> worker,
+ "localhost" -> ActorUtil.getSystemAddress(context.system).host.get,
+ "hostname" -> InetAddress.getLocalHost.getHostName)
+ }
+
+ private def writeFileWithEnvVariables(source: File, target: File, envs: Map[String, Any]) = {
+ val writer = new FileWriter(target)
+ val sub = new StrSubstitutor(envs.asJava)
+ sub.setEnableSubstitutionInVariables(true)
+ Source.fromFile(source).getLines().foreach(line => writer.write(sub.replace(line) + "\r\n"))
+ writer.close()
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/distributeservice/src/main/scala/org/apache/gearpump/experiments/distributeservice/DistributeService.scala
----------------------------------------------------------------------
diff --git a/examples/distributeservice/src/main/scala/org/apache/gearpump/experiments/distributeservice/DistributeService.scala b/examples/distributeservice/src/main/scala/org/apache/gearpump/experiments/distributeservice/DistributeService.scala
new file mode 100644
index 0000000..df7a517
--- /dev/null
+++ b/examples/distributeservice/src/main/scala/org/apache/gearpump/experiments/distributeservice/DistributeService.scala
@@ -0,0 +1,41 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.experiments.distributeservice
+
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.client.ClientContext
+import org.apache.gearpump.cluster.main.{ArgumentsParser, CLIOption}
+import org.apache.gearpump.cluster.{Application, UserConfig}
+import org.apache.gearpump.util.{AkkaApp, LogUtil}
+
+/** Demo app to remotely deploy and start system service on machines in the cluster */
+object DistributeService extends AkkaApp with ArgumentsParser {
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+
+ override val options: Array[(String, CLIOption[Any])] = Array.empty
+
+ override def main(akkaConf: Config, args: Array[String]): Unit = {
+ LOG.info(s"Distribute Service submitting application...")
+ val context = ClientContext(akkaConf)
+ val appId = context.submit(Application[DistServiceAppMaster]("DistributedService",
+ UserConfig.empty))
+ context.close()
+ LOG.info(s"Distribute Service Application started with appId $appId !")
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/distributeservice/src/main/scala/org/apache/gearpump/experiments/distributeservice/DistributeServiceClient.scala
----------------------------------------------------------------------
diff --git a/examples/distributeservice/src/main/scala/org/apache/gearpump/experiments/distributeservice/DistributeServiceClient.scala b/examples/distributeservice/src/main/scala/org/apache/gearpump/experiments/distributeservice/DistributeServiceClient.scala
new file mode 100644
index 0000000..b2c8f11
--- /dev/null
+++ b/examples/distributeservice/src/main/scala/org/apache/gearpump/experiments/distributeservice/DistributeServiceClient.scala
@@ -0,0 +1,90 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.experiments.distributeservice
+
+import java.io.File
+import scala.concurrent.Future
+import scala.util.{Failure, Success}
+
+import akka.pattern.ask
+import org.apache.commons.io.FileUtils
+
+import org.apache.gearpump.cluster.client.ClientContext
+import org.apache.gearpump.cluster.main.{ArgumentsParser, CLIOption}
+import org.apache.gearpump.experiments.distributeservice.DistServiceAppMaster.{FileContainer, GetFileContainer, InstallService}
+import org.apache.gearpump.util.{AkkaApp, Constants}
+
+/** Client to submit the service jar */
+object DistributeServiceClient extends AkkaApp with ArgumentsParser {
+ implicit val timeout = Constants.FUTURE_TIMEOUT
+
+ override val options: Array[(String, CLIOption[Any])] = Array(
+ "appid" -> CLIOption[Int]("<the distributed shell appid>", required = true),
+ "file" -> CLIOption[String]("<service zip file path>", required = true),
+ "script" -> CLIOption[String](
+ "<file path of service script that will be installed to /etc/init.d>", required = true),
+ "serviceName" -> CLIOption[String]("<service name>", required = true),
+ "target" -> CLIOption[String]("<target path on each machine>", required = true)
+ )
+
+ override def help(): Unit = {
+ super.help()
+ // scalastyle:off println
+ Console.err.println(s"-D<name>=<value> set a property to the service")
+ // scalastyle:on println
+ }
+
+ override def main(akkaConf: Config, args: Array[String]): Unit = {
+ val config = parse(filterCustomOptions(args))
+ val context = ClientContext(akkaConf)
+ implicit val system = context.system
+ implicit val dispatcher = system.dispatcher
+ val appid = config.getInt("appid")
+ val zipFile = new File(config.getString("file"))
+ val script = new File(config.getString("script"))
+ val serviceName = config.getString("serviceName")
+ val appMaster = context.resolveAppID(appid)
+ (appMaster ? GetFileContainer).asInstanceOf[Future[FileContainer]].map { container =>
+ val bytes = FileUtils.readFileToByteArray(zipFile)
+ val result = FileServer.newClient.save(container.url, bytes)
+ result match {
+ case Success(_) =>
+ appMaster ! InstallService(container.url, zipFile.getName, config.getString("target"),
+ FileUtils.readFileToByteArray(script), serviceName, parseServiceConfig(args))
+ context.close()
+ case Failure(ex) => throw ex
+ }
+ }
+ }
+
+ private def filterCustomOptions(args: Array[String]): Array[String] = {
+ args.filter(!_.startsWith("-D"))
+ }
+
+ private def parseServiceConfig(args: Array[String]): Map[String, Any] = {
+ val result = Map.empty[String, Any]
+ args.foldLeft(result) { (result, argument) =>
+ if (argument.startsWith("-D") && argument.contains("=")) {
+ val fixedKV = argument.substring(2).split("=")
+ result + (fixedKV(0) -> fixedKV(1))
+ } else {
+ result
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/distributeservice/src/main/scala/org/apache/gearpump/experiments/distributeservice/FileServer.scala
----------------------------------------------------------------------
diff --git a/examples/distributeservice/src/main/scala/org/apache/gearpump/experiments/distributeservice/FileServer.scala b/examples/distributeservice/src/main/scala/org/apache/gearpump/experiments/distributeservice/FileServer.scala
new file mode 100644
index 0000000..4cd71de
--- /dev/null
+++ b/examples/distributeservice/src/main/scala/org/apache/gearpump/experiments/distributeservice/FileServer.scala
@@ -0,0 +1,138 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.distributeservice
+
+import java.io.File
+import scala.util.{Failure, Success, Try}
+
+import akka.actor.{Actor, Stash}
+import akka.io.IO
+import org.apache.commons.httpclient.HttpClient
+import org.apache.commons.httpclient.methods.{ByteArrayRequestEntity, GetMethod, PostMethod}
+import spray.can.Http
+import spray.http.HttpMethods._
+import spray.http._
+
+import org.apache.gearpump.util.{FileUtils, LogUtil}
+
+/**
+ *
+ * Should not use this to server too big files(more than 100MB), otherwise OOM may happen.
+ *
+ * port: set port to 0 if you want to bind to random port
+ */
+class FileServer(rootDir: File, host: String, port: Int) extends Actor with Stash {
+ private val LOG = LogUtil.getLogger(getClass)
+
+ implicit val system = context.system
+
+ override def preStart(): Unit = {
+ // Creates http server
+ IO(Http) ! Http.Bind(self, host, port)
+ }
+
+ override def postStop(): Unit = {
+ // Stop the server
+ IO(Http) ! Http.Unbind
+ }
+
+ override def receive: Receive = {
+ case Http.Bound(address) =>
+ LOG.info(s"FileServer bound on port: ${address.getPort}")
+ context.become(listen(address.getPort))
+ unstashAll()
+ case _ =>
+ stash()
+ }
+
+ def listen(port: Int): Receive = {
+ case FileServer.GetPort => {
+ sender ! FileServer.Port(port)
+ }
+ case Http.Connected(remote, _) =>
+ sender ! Http.Register(self)
+
+ // Fetches files from remote uri
+ case HttpRequest(GET, uri, _, _, _) =>
+ val child = uri.path.toString()
+ val payload = Try {
+ val source = new File(rootDir, child)
+ FileUtils.readFileToByteArray(source)
+ }
+ payload match {
+ case Success(data) =>
+ sender ! HttpResponse(entity = HttpEntity(data))
+ case Failure(ex) =>
+ LOG.error("failed to get file " + ex.getMessage)
+ sender ! HttpResponse(status = StatusCodes.InternalServerError, entity = ex.getMessage)
+ }
+ // Save file to remote uri
+ case post@HttpRequest(POST, uri, _, _, _) =>
+ val child = uri.path.toString()
+
+ val status = Try {
+ val target = new File(rootDir, child)
+ val payload = post.entity.data.toByteArray
+ FileUtils.writeByteArrayToFile(target, payload)
+ "OK"
+ }
+ status match {
+ case Success(message) => sender ! HttpResponse(entity = message)
+ case Failure(ex) =>
+ LOG.error("save file failed " + ex.getMessage)
+ sender ! HttpResponse(status = StatusCodes.InternalServerError, entity = ex.getMessage)
+ }
+ }
+}
+
+object FileServer {
+ object GetPort
+ case class Port(port: Int)
+
+ def newClient: Client = new Client
+
+ class Client {
+ val client = new HttpClient()
+
+ def save(uri: String, data: Array[Byte]): Try[Int] = {
+ Try {
+ val post = new PostMethod(uri)
+ val entity = new ByteArrayRequestEntity(data)
+ post.setRequestEntity(entity)
+ client.executeMethod(post)
+ }
+ }
+
+ def get(uri: String): Try[Array[Byte]] = {
+ val get = new GetMethod(uri)
+ val status = Try {
+ client.executeMethod(get)
+ }
+
+ val data = status.flatMap { code =>
+ if (code == 200) {
+ Success(get.getResponseBody())
+ } else {
+ Failure(new Exception(s"We cannot get the data, the status code is $code"))
+ }
+ }
+ data
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/distributeservice/src/test/scala/io/gearpump/experiments/distributeservice/DistServiceAppMasterSpec.scala
----------------------------------------------------------------------
diff --git a/examples/distributeservice/src/test/scala/io/gearpump/experiments/distributeservice/DistServiceAppMasterSpec.scala b/examples/distributeservice/src/test/scala/io/gearpump/experiments/distributeservice/DistServiceAppMasterSpec.scala
deleted file mode 100644
index 5bafef1..0000000
--- a/examples/distributeservice/src/test/scala/io/gearpump/experiments/distributeservice/DistServiceAppMasterSpec.scala
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.experiments.distributeservice
-
-import scala.concurrent.Await
-import scala.concurrent.duration._
-
-import akka.actor.ActorSystem
-import akka.testkit.{TestActorRef, TestProbe}
-import org.scalatest.{BeforeAndAfter, Matchers, WordSpec}
-
-import io.gearpump.cluster.AppMasterToMaster.{GetAllWorkers, RegisterAppMaster, RequestResource}
-import io.gearpump.cluster.AppMasterToWorker.LaunchExecutor
-import io.gearpump.cluster.MasterToAppMaster.{AppMasterRegistered, ResourceAllocated, WorkerList}
-import io.gearpump.cluster.appmaster.{AppMasterRuntimeEnvironment, AppMasterRuntimeInfo}
-import io.gearpump.cluster.scheduler.{Relaxation, Resource, ResourceAllocation, ResourceRequest}
-import io.gearpump.cluster.worker.WorkerId
-import io.gearpump.cluster.{AppDescription, AppMasterContext, TestUtil, UserConfig}
-import io.gearpump.experiments.distributeservice.DistServiceAppMaster.{FileContainer, GetFileContainer}
-import io.gearpump.util.ActorSystemBooter.RegisterActorSystem
-import io.gearpump.util.ActorUtil
-
-class DistServiceAppMasterSpec extends WordSpec with Matchers with BeforeAndAfter {
- implicit val system = ActorSystem("AppMasterSpec", TestUtil.DEFAULT_CONFIG)
- val mockMaster = TestProbe()(system)
- val mockWorker1 = TestProbe()(system)
- val client = TestProbe()(system)
- val masterProxy = mockMaster.ref
- val appId = 0
- val userName = "test"
- val masterExecutorId = 0
- val workerList = List(WorkerId(1, 0L), WorkerId(2, 0L), WorkerId(3, 0L))
- val resource = Resource(1)
- val appJar = None
- val appDescription = AppDescription("app0", classOf[DistServiceAppMaster].getName,
- UserConfig.empty)
-
- "DistService AppMaster" should {
- "responsable for service distributing" in {
- val appMasterInfo = AppMasterRuntimeInfo(appId, "appName", mockWorker1.ref)
- val appMasterContext = AppMasterContext(appId, userName, resource, null, appJar, masterProxy,
- appMasterInfo)
- TestActorRef[DistServiceAppMaster](
- AppMasterRuntimeEnvironment.props(List(masterProxy.path), appDescription, appMasterContext))
- val registerAppMaster = mockMaster.receiveOne(15.seconds)
- assert(registerAppMaster.isInstanceOf[RegisterAppMaster])
-
- val appMaster = registerAppMaster.asInstanceOf[RegisterAppMaster].appMaster
- mockMaster.reply(AppMasterRegistered(appId))
- // The DistributedShell AppMaster will ask for worker list
- mockMaster.expectMsg(GetAllWorkers)
- mockMaster.reply(WorkerList(workerList))
- // After worker list is ready, DistributedShell AppMaster will request resouce on each worker
- workerList.foreach { workerId =>
- mockMaster.expectMsg(RequestResource(appId, ResourceRequest(Resource(1), workerId,
- relaxation = Relaxation.SPECIFICWORKER)))
- }
- mockMaster.reply(ResourceAllocated(Array(ResourceAllocation(resource, mockWorker1.ref,
- WorkerId(1, 0L)))))
- mockWorker1.expectMsgClass(classOf[LaunchExecutor])
- mockWorker1.reply(RegisterActorSystem(ActorUtil.getSystemAddress(system).toString))
-
- appMaster.tell(GetFileContainer, client.ref)
- client.expectMsgClass(15.seconds, classOf[FileContainer])
- }
- }
-
- after {
- system.terminate()
- Await.result(system.whenTerminated, Duration.Inf)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/distributeservice/src/test/scala/org/apache/gearpump/experiments/distributeservice/DistServiceAppMasterSpec.scala
----------------------------------------------------------------------
diff --git a/examples/distributeservice/src/test/scala/org/apache/gearpump/experiments/distributeservice/DistServiceAppMasterSpec.scala b/examples/distributeservice/src/test/scala/org/apache/gearpump/experiments/distributeservice/DistServiceAppMasterSpec.scala
new file mode 100644
index 0000000..7516138
--- /dev/null
+++ b/examples/distributeservice/src/test/scala/org/apache/gearpump/experiments/distributeservice/DistServiceAppMasterSpec.scala
@@ -0,0 +1,87 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.experiments.distributeservice
+
+import scala.concurrent.Await
+import scala.concurrent.duration._
+
+import akka.actor.ActorSystem
+import akka.testkit.{TestActorRef, TestProbe}
+import org.scalatest.{BeforeAndAfter, Matchers, WordSpec}
+
+import org.apache.gearpump.cluster.AppMasterToMaster.{GetAllWorkers, RegisterAppMaster, RequestResource}
+import org.apache.gearpump.cluster.AppMasterToWorker.LaunchExecutor
+import org.apache.gearpump.cluster.MasterToAppMaster.{AppMasterRegistered, ResourceAllocated, WorkerList}
+import org.apache.gearpump.cluster.appmaster.{AppMasterRuntimeEnvironment, AppMasterRuntimeInfo}
+import org.apache.gearpump.cluster.scheduler.{Relaxation, Resource, ResourceAllocation, ResourceRequest}
+import org.apache.gearpump.cluster.worker.WorkerId
+import org.apache.gearpump.cluster.{AppDescription, AppMasterContext, TestUtil, UserConfig}
+import org.apache.gearpump.experiments.distributeservice.DistServiceAppMaster.{FileContainer, GetFileContainer}
+import org.apache.gearpump.util.ActorSystemBooter.RegisterActorSystem
+import org.apache.gearpump.util.ActorUtil
+
+class DistServiceAppMasterSpec extends WordSpec with Matchers with BeforeAndAfter {
+ implicit val system = ActorSystem("AppMasterSpec", TestUtil.DEFAULT_CONFIG)
+ val mockMaster = TestProbe()(system)
+ val mockWorker1 = TestProbe()(system)
+ val client = TestProbe()(system)
+ val masterProxy = mockMaster.ref
+ val appId = 0
+ val userName = "test"
+ val masterExecutorId = 0
+ val workerList = List(WorkerId(1, 0L), WorkerId(2, 0L), WorkerId(3, 0L))
+ val resource = Resource(1)
+ val appJar = None
+ val appDescription = AppDescription("app0", classOf[DistServiceAppMaster].getName,
+ UserConfig.empty)
+
+ "DistService AppMaster" should {
+ "responsable for service distributing" in {
+ val appMasterInfo = AppMasterRuntimeInfo(appId, "appName", mockWorker1.ref)
+ val appMasterContext = AppMasterContext(appId, userName, resource, null, appJar, masterProxy,
+ appMasterInfo)
+ TestActorRef[DistServiceAppMaster](
+ AppMasterRuntimeEnvironment.props(List(masterProxy.path), appDescription, appMasterContext))
+ val registerAppMaster = mockMaster.receiveOne(15.seconds)
+ assert(registerAppMaster.isInstanceOf[RegisterAppMaster])
+
+ val appMaster = registerAppMaster.asInstanceOf[RegisterAppMaster].appMaster
+ mockMaster.reply(AppMasterRegistered(appId))
+ // The DistributedShell AppMaster will ask for worker list
+ mockMaster.expectMsg(GetAllWorkers)
+ mockMaster.reply(WorkerList(workerList))
+ // After worker list is ready, DistributedShell AppMaster will request resouce on each worker
+ workerList.foreach { workerId =>
+ mockMaster.expectMsg(RequestResource(appId, ResourceRequest(Resource(1), workerId,
+ relaxation = Relaxation.SPECIFICWORKER)))
+ }
+ mockMaster.reply(ResourceAllocated(Array(ResourceAllocation(resource, mockWorker1.ref,
+ WorkerId(1, 0L)))))
+ mockWorker1.expectMsgClass(classOf[LaunchExecutor])
+ mockWorker1.reply(RegisterActorSystem(ActorUtil.getSystemAddress(system).toString))
+
+ appMaster.tell(GetFileContainer, client.ref)
+ client.expectMsgClass(15.seconds, classOf[FileContainer])
+ }
+ }
+
+ after {
+ system.terminate()
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/pagerank/README.md
----------------------------------------------------------------------
diff --git a/examples/pagerank/README.md b/examples/pagerank/README.md
index 20d9032..7fe9220 100644
--- a/examples/pagerank/README.md
+++ b/examples/pagerank/README.md
@@ -2,7 +2,7 @@
After compile,
```scala
-bin\gear io.gearpump.experiments.pagerank.example.PageRankExample
+bin\gear org.apache.gearpump.experiments.pagerank.example.PageRankExample
```
### Syntax
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/pagerank/src/main/resources/geardefault.conf
----------------------------------------------------------------------
diff --git a/examples/pagerank/src/main/resources/geardefault.conf b/examples/pagerank/src/main/resources/geardefault.conf
index d2a4e16..67275f9 100644
--- a/examples/pagerank/src/main/resources/geardefault.conf
+++ b/examples/pagerank/src/main/resources/geardefault.conf
@@ -1,7 +1,7 @@
gearpump {
serializers {
- "io.gearpump.experiments.pagerank.PageRankController$Tick" = ""
- "io.gearpump.experiments.pagerank.PageRankWorker$UpdateWeight" = ""
- "io.gearpump.experiments.pagerank.PageRankWorker$LatestWeight" = ""
+ "org.apache.gearpump.experiments.pagerank.PageRankController$Tick" = ""
+ "org.apache.gearpump.experiments.pagerank.PageRankWorker$UpdateWeight" = ""
+ "org.apache.gearpump.experiments.pagerank.PageRankWorker$LatestWeight" = ""
}
}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/pagerank/src/main/scala/io/gearpump/experiments/pagerank/PageRankApplication.scala
----------------------------------------------------------------------
diff --git a/examples/pagerank/src/main/scala/io/gearpump/experiments/pagerank/PageRankApplication.scala b/examples/pagerank/src/main/scala/io/gearpump/experiments/pagerank/PageRankApplication.scala
deleted file mode 100644
index 2e37091..0000000
--- a/examples/pagerank/src/main/scala/io/gearpump/experiments/pagerank/PageRankApplication.scala
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.experiments.pagerank
-
-import akka.actor.ActorSystem
-
-import io.gearpump.cluster.{Application, ApplicationMaster, UserConfig}
-import io.gearpump.experiments.pagerank.PageRankApplication.NodeWithTaskId
-import io.gearpump.partitioner.HashPartitioner
-import io.gearpump.streaming.appmaster.AppMaster
-import io.gearpump.streaming.{Processor, StreamApplication}
-import io.gearpump.util.Graph
-import io.gearpump.util.Graph.Node
-
-/**
- *
- * A simple and naive pagerank implementation.
- *
- * @param name name of the application
- * @param iteration max iteration count
- * @param delta decide the accuracy when the page rank example stops.
- * @param dag the page rank graph
- */
-class PageRankApplication[T](
- override val name: String, iteration: Int, delta: Double, dag: Graph[T, _])
- extends Application {
-
- override def appMaster: Class[_ <: ApplicationMaster] = classOf[AppMaster]
- override def userConfig(implicit system: ActorSystem): UserConfig = {
-
- // Map node with taskId
- var taskId = 0
- val pageRankDag = dag.mapVertex { node =>
- val updatedNode = NodeWithTaskId(taskId, node)
- taskId += 1
- updatedNode
- }
-
- val taskCount = taskId
-
- val userConfig = UserConfig.empty.withValue(PageRankApplication.DAG, pageRankDag).
- withInt(PageRankApplication.ITERATION, iteration).
- withInt(PageRankApplication.COUNT, taskCount).
- withDouble(PageRankApplication.DELTA, delta)
-
- val controller = Processor[PageRankController](1)
- val pageRankWorker = Processor[PageRankWorker](taskCount)
- val partitioner = new HashPartitioner
-
- val app = StreamApplication(name, Graph(controller ~ partitioner ~> pageRankWorker), userConfig)
- app.userConfig
- }
-}
-
-object PageRankApplication {
- val DAG = "PageRank.DAG"
- val ITERATION = "PageRank.Iteration"
- val COUNT = "PageRank.COUNT"
- val DELTA = "PageRank.DELTA"
- val REPORTER = "PageRank.Reporter"
- case class NodeWithTaskId[T](taskId: Int, node: T)
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/pagerank/src/main/scala/io/gearpump/experiments/pagerank/PageRankController.scala
----------------------------------------------------------------------
diff --git a/examples/pagerank/src/main/scala/io/gearpump/experiments/pagerank/PageRankController.scala b/examples/pagerank/src/main/scala/io/gearpump/experiments/pagerank/PageRankController.scala
deleted file mode 100644
index 0fb689d..0000000
--- a/examples/pagerank/src/main/scala/io/gearpump/experiments/pagerank/PageRankController.scala
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.experiments.pagerank
-
-import akka.actor.Actor.Receive
-
-import io.gearpump.cluster.UserConfig
-import io.gearpump.experiments.pagerank.PageRankController.Tick
-import io.gearpump.experiments.pagerank.PageRankWorker.LatestWeight
-import io.gearpump.streaming.task._
-
-class PageRankController(taskContext: TaskContext, conf: UserConfig)
- extends Task(taskContext, conf) {
-
- val taskCount = conf.getInt(PageRankApplication.COUNT).get
- val iterationMax = conf.getInt(PageRankApplication.ITERATION).get
- val delta = conf.getDouble(PageRankApplication.DELTA).get
-
- val tasks = (0 until taskCount).toList.map(TaskId(1, _))
-
- var tick: Int = 0
- var receivedWeightForCurrentTick = 0
-
- var weights = Map.empty[TaskId, Double]
- var deltas = Map.empty[TaskId, Double]
-
- override def onStart(startTime: StartTime): Unit = {
- output(Tick(tick), tasks: _*)
- }
-
- private def output(msg: AnyRef, tasks: TaskId*): Unit = {
- taskContext.asInstanceOf[TaskWrapper].outputUnManaged(msg, tasks: _*)
- }
-
- override def receiveUnManagedMessage: Receive = {
- case LatestWeight(taskId, weight, replyTick) =>
- if (this.tick == replyTick) {
-
- deltas += taskId -> Math.abs(weight - weights.getOrElse(taskId, 0.0))
- weights += taskId -> weight
- receivedWeightForCurrentTick += 1
- if (receivedWeightForCurrentTick == taskCount) {
- this.tick += 1
- receivedWeightForCurrentTick = 0
- if (continueIteration) {
- LOG.debug(s"next iteration: $tick, weight: $weights, delta: $deltas")
- output(Tick(tick), tasks: _*)
- } else {
- LOG.info(s"iterations: $tick, weight: $weights, delta: $deltas")
- }
- }
- }
- }
-
- private def continueIteration: Boolean = {
- (tick < iterationMax) && deltas.values.foldLeft(false) { (deltaExceed, value) =>
- deltaExceed || value > delta
- }
- }
-}
-
-object PageRankController {
- case class Tick(iteration: Int)
-}
[02/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/io/gearpump/streaming/task/TaskActorSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/io/gearpump/streaming/task/TaskActorSpec.scala b/streaming/src/test/scala/io/gearpump/streaming/task/TaskActorSpec.scala
deleted file mode 100644
index a48f887..0000000
--- a/streaming/src/test/scala/io/gearpump/streaming/task/TaskActorSpec.scala
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.task
-
-import akka.actor.{ExtendedActorSystem, Props}
-import akka.testkit._
-import com.typesafe.config.{Config, ConfigFactory}
-import org.mockito.Mockito.{mock, times, verify, when}
-import org.scalatest.{BeforeAndAfterEach, Matchers, WordSpec}
-
-import io.gearpump.Message
-import io.gearpump.cluster.{MasterHarness, TestUtil, UserConfig}
-import io.gearpump.partitioner.{HashPartitioner, Partitioner}
-import io.gearpump.serializer.{FastKryoSerializer, SerializationFramework}
-import io.gearpump.streaming.AppMasterToExecutor.{ChangeTask, MsgLostException, StartTask, TaskChanged, TaskRegistered}
-import io.gearpump.streaming.task.TaskActorSpec.TestTask
-import io.gearpump.streaming.{DAG, LifeTime, ProcessorDescription}
-import io.gearpump.util.Graph._
-import io.gearpump.util.{Graph, Util}
-
-class TaskActorSpec extends WordSpec with Matchers with BeforeAndAfterEach with MasterHarness {
- protected override def config: Config = {
- ConfigFactory.parseString(
- """ akka.loggers = ["akka.testkit.TestEventListener"]
- | akka.test.filter-leeway = 20000
- """.stripMargin).
- withFallback(TestUtil.DEFAULT_CONFIG)
- }
-
- val appId = 0
- val task1 = ProcessorDescription(id = 0, taskClass = classOf[TestTask].getName, parallelism = 1)
- val task2 = ProcessorDescription(id = 1, taskClass = classOf[TestTask].getName, parallelism = 1)
- val dag: DAG = DAG(Graph(task1 ~ Partitioner[HashPartitioner] ~> task2))
- val taskId1 = TaskId(0, 0)
- val taskId2 = TaskId(1, 0)
- val executorId1 = 1
- val executorId2 = 2
-
- var mockMaster: TestProbe = null
- var taskContext1: TaskContextData = null
-
- var mockSerializerPool: SerializationFramework = null
-
- override def beforeEach(): Unit = {
- startActorSystem()
- mockMaster = TestProbe()(getActorSystem)
-
- mockSerializerPool = mock(classOf[SerializationFramework])
- val serializer = new FastKryoSerializer(getActorSystem.asInstanceOf[ExtendedActorSystem])
- when(mockSerializerPool.get()).thenReturn(serializer)
-
- taskContext1 = TaskContextData(executorId1, appId,
- "appName", mockMaster.ref, 1,
- LifeTime.Immortal,
- Subscriber.of(processorId = 0, dag))
- }
-
- "TaskActor" should {
- "register itself to AppMaster when started" in {
- val mockTask = mock(classOf[TaskWrapper])
- val testActor = TestActorRef[TaskActor](Props(
- new TaskActor(taskId1, taskContext1, UserConfig.empty,
- mockTask, mockSerializerPool)))(getActorSystem)
- testActor ! TaskRegistered(taskId1, 0, Util.randInt())
- testActor ! StartTask(taskId1)
-
- implicit val system = getActorSystem
- val ack = Ack(taskId2, 100, 99, testActor.underlyingActor.sessionId)
- EventFilter[MsgLostException](occurrences = 1) intercept {
- testActor ! ack
- }
- }
-
- "respond to ChangeTask" in {
- val mockTask = mock(classOf[TaskWrapper])
- val testActor = TestActorRef[TaskActor](Props(new TaskActor(taskId1, taskContext1,
- UserConfig.empty, mockTask, mockSerializerPool)))(getActorSystem)
- testActor ! TaskRegistered(taskId1, 0, Util.randInt())
- testActor ! StartTask(taskId1)
- mockMaster.expectMsgType[GetUpstreamMinClock]
-
- mockMaster.send(testActor, ChangeTask(taskId1, 1, LifeTime.Immortal, List.empty[Subscriber]))
- mockMaster.expectMsgType[TaskChanged]
- }
-
- "handle received message correctly" in {
- val mockTask = mock(classOf[TaskWrapper])
- val msg = Message("test")
-
- val testActor = TestActorRef[TaskActor](Props(new TaskActor(taskId1, taskContext1,
- UserConfig.empty, mockTask, mockSerializerPool)))(getActorSystem)
- testActor.tell(TaskRegistered(taskId1, 0, Util.randInt()), mockMaster.ref)
- testActor.tell(StartTask(taskId1), mockMaster.ref)
-
- testActor.tell(msg, testActor)
-
- verify(mockTask, times(1)).onNext(msg)
- }
- }
-
- override def afterEach(): Unit = {
- shutdownActorSystem()
- }
-}
-
-object TaskActorSpec {
- class TestTask
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/org/apache/gearpump/streaming/DAGSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/org/apache/gearpump/streaming/DAGSpec.scala b/streaming/src/test/scala/org/apache/gearpump/streaming/DAGSpec.scala
new file mode 100644
index 0000000..5f4faee
--- /dev/null
+++ b/streaming/src/test/scala/org/apache/gearpump/streaming/DAGSpec.scala
@@ -0,0 +1,44 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming
+
+import org.apache.gearpump.partitioner.PartitionerDescription
+import org.apache.gearpump.streaming.task.TaskId
+import org.apache.gearpump.util.Graph
+import org.apache.gearpump.util.Graph.Node
+import org.scalacheck.Gen
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{Matchers, PropSpec}
+
+class DAGSpec extends PropSpec with PropertyChecks with Matchers {
+
+ val parallelismGen = Gen.chooseNum[Int](1, 100)
+
+ property("DAG should be built correctly for a single task") {
+ forAll(parallelismGen) { (parallelism: Int) =>
+ val task = ProcessorDescription(id = 0, taskClass = "task", parallelism = parallelism)
+ val graph = Graph[ProcessorDescription, PartitionerDescription](task)
+ val dag = DAG(graph)
+ dag.processors.size shouldBe 1
+ assert(dag.taskCount == parallelism)
+ dag.tasks.sortBy(_.index) shouldBe (0 until parallelism).map(index => TaskId(0, index))
+ dag.graph.edges shouldBe empty
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/org/apache/gearpump/streaming/MessageSerializerSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/org/apache/gearpump/streaming/MessageSerializerSpec.scala b/streaming/src/test/scala/org/apache/gearpump/streaming/MessageSerializerSpec.scala
new file mode 100644
index 0000000..f6f6af2
--- /dev/null
+++ b/streaming/src/test/scala/org/apache/gearpump/streaming/MessageSerializerSpec.scala
@@ -0,0 +1,78 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming
+
+import org.jboss.netty.buffer.{ChannelBufferOutputStream, ChannelBuffers}
+import org.scalatest.{Matchers, WordSpec}
+
+import org.apache.gearpump.streaming.task._
+import org.apache.gearpump.transport.netty.WrappedChannelBuffer
+
+class MessageSerializerSpec extends WordSpec with Matchers {
+
+ def testSerializer[T](obj: T, taskMessageSerializer: TaskMessageSerializer[T]): T = {
+ val length = taskMessageSerializer.getLength(obj)
+ val bout = new ChannelBufferOutputStream(ChannelBuffers.buffer(length))
+ taskMessageSerializer.write(bout, obj)
+ val input = new WrappedChannelBuffer(ChannelBuffers.wrappedBuffer(bout.buffer().array()))
+ taskMessageSerializer.read(input)
+ }
+
+ "SerializedMessageSerializer" should {
+ "serialize and deserialize SerializedMessage properly" in {
+ val serializer = new SerializedMessageSerializer
+ val data = new Array[Byte](256)
+ new java.util.Random().nextBytes(data)
+ val msg = SerializedMessage(1024, data)
+ val result = testSerializer(msg, serializer)
+ assert(result.timeStamp == msg.timeStamp && result.bytes.sameElements(msg.bytes))
+ }
+ }
+
+ "TaskIdSerializer" should {
+ "serialize and deserialize TaskId properly" in {
+ val taskIdSerializer = new TaskIdSerializer
+ val taskId = TaskId(1, 3)
+ assert(testSerializer(taskId, taskIdSerializer).equals(taskId))
+ }
+ }
+
+ "AckRequestSerializer" should {
+ "serialize and deserialize AckRequest properly" in {
+ val serializer = new AckRequestSerializer
+ val ackRequest = AckRequest(TaskId(1, 2), 1000, 1024)
+ assert(testSerializer(ackRequest, serializer).equals(ackRequest))
+ }
+ }
+
+ "InitialAckRequestSerializer" should {
+ "serialize and deserialize AckRequest properly" in {
+ val serializer = new InitialAckRequestSerializer
+ val ackRequest = InitialAckRequest(TaskId(1, 2), 1024)
+ assert(testSerializer(ackRequest, serializer).equals(ackRequest))
+ }
+ }
+
+ "AckSerializer" should {
+ "serialize and deserialize Ack properly" in {
+ val serializer = new AckSerializer
+ val ack = Ack(TaskId(1, 2), 1024, 1023, 1799)
+ assert(testSerializer(ack, serializer).equals(ack))
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/org/apache/gearpump/streaming/MockUtil.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/org/apache/gearpump/streaming/MockUtil.scala b/streaming/src/test/scala/org/apache/gearpump/streaming/MockUtil.scala
new file mode 100644
index 0000000..f24c024
--- /dev/null
+++ b/streaming/src/test/scala/org/apache/gearpump/streaming/MockUtil.scala
@@ -0,0 +1,47 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming
+
+import akka.actor.{Actor, ActorSystem}
+import akka.testkit.TestActorRef
+import org.apache.gearpump.cluster.TestUtil
+import org.apache.gearpump.streaming.task.{TaskContext, TaskId}
+import org.mockito.{ArgumentMatcher, Matchers, Mockito}
+
+object MockUtil {
+
+ lazy val system: ActorSystem = ActorSystem("mockUtil", TestUtil.DEFAULT_CONFIG)
+
+ def mockTaskContext: TaskContext = {
+ val context = Mockito.mock(classOf[TaskContext])
+ Mockito.when(context.self).thenReturn(Mockito.mock(classOf[TestActorRef[Actor]]))
+ Mockito.when(context.system).thenReturn(system)
+ Mockito.when(context.parallelism).thenReturn(1)
+ Mockito.when(context.taskId).thenReturn(TaskId(0, 0))
+ context
+ }
+
+ def argMatch[T](func: T => Boolean): T = {
+ Matchers.argThat(new ArgumentMatcher[T] {
+ override def matches(param: Any): Boolean = {
+ val mesage = param.asInstanceOf[T]
+ func(mesage)
+ }
+ })
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/org/apache/gearpump/streaming/StreamingTestUtil.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/org/apache/gearpump/streaming/StreamingTestUtil.scala b/streaming/src/test/scala/org/apache/gearpump/streaming/StreamingTestUtil.scala
new file mode 100644
index 0000000..f4fffb5
--- /dev/null
+++ b/streaming/src/test/scala/org/apache/gearpump/streaming/StreamingTestUtil.scala
@@ -0,0 +1,48 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming
+
+import akka.actor._
+import akka.testkit.TestActorRef
+import org.apache.gearpump.cluster.AppMasterToMaster.RegisterAppMaster
+import org.apache.gearpump.cluster.appmaster.AppMasterRuntimeInfo
+import org.apache.gearpump.cluster.scheduler.Resource
+import org.apache.gearpump.cluster.{AppDescription, AppMasterContext, MiniCluster, UserConfig}
+import org.apache.gearpump.streaming.appmaster.AppMaster
+import org.apache.gearpump.util.Graph
+
+object StreamingTestUtil {
+ private var executorId = 0
+ val testUserName = "testuser"
+
+ def startAppMaster(miniCluster: MiniCluster, appId: Int): TestActorRef[AppMaster] = {
+
+ implicit val actorSystem = miniCluster.system
+ val masterConf = AppMasterContext(appId, testUserName, Resource(1), null,
+ None, miniCluster.mockMaster, AppMasterRuntimeInfo(appId, appName = appId.toString))
+
+ val app = StreamApplication("test", Graph.empty, UserConfig.empty)
+ val appDescription = AppDescription(app.name, app.appMaster.getName, app.userConfig)
+ val props = Props(new AppMaster(masterConf, appDescription))
+ val appMaster = miniCluster.launchActor(props).asInstanceOf[TestActorRef[AppMaster]]
+ val registerAppMaster = RegisterAppMaster(appMaster, masterConf.registerData)
+ miniCluster.mockMaster.tell(registerAppMaster, appMaster)
+
+ appMaster
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/AppMasterSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/AppMasterSpec.scala b/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/AppMasterSpec.scala
new file mode 100644
index 0000000..38a5cf1
--- /dev/null
+++ b/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/AppMasterSpec.scala
@@ -0,0 +1,237 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.appmaster
+
+import akka.actor.{ActorRef, Props}
+import akka.testkit.{TestActorRef, TestProbe}
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.AppMasterToMaster._
+import org.apache.gearpump.cluster.AppMasterToWorker.LaunchExecutor
+import org.apache.gearpump.cluster.ClientToMaster.ShutdownApplication
+import org.apache.gearpump.cluster.MasterToAppMaster.{AppMasterRegistered, ResourceAllocated}
+import org.apache.gearpump.cluster.WorkerToAppMaster.ExecutorLaunchRejected
+import org.apache.gearpump.cluster._
+import org.apache.gearpump.cluster.appmaster.{AppMasterRuntimeEnvironment, AppMasterRuntimeInfo}
+import org.apache.gearpump.cluster.master.MasterProxy
+import org.apache.gearpump.cluster.scheduler.{Resource, ResourceAllocation, ResourceRequest}
+import org.apache.gearpump.cluster.worker.WorkerId
+import org.apache.gearpump.jarstore.FilePath
+import org.apache.gearpump.partitioner.HashPartitioner
+import org.apache.gearpump.streaming.task.{StartTime, TaskContext, _}
+import org.apache.gearpump.streaming.{Processor, StreamApplication}
+import org.apache.gearpump.util.Graph
+import org.apache.gearpump.util.Graph._
+import org.scalatest._
+
+import scala.concurrent.duration._
+
+class AppMasterSpec extends WordSpec with Matchers with BeforeAndAfterEach with MasterHarness {
+ protected override def config = TestUtil.DEFAULT_CONFIG
+
+ var appMaster: ActorRef = null
+
+ val appId = 0
+ val workerId = WorkerId(1, 0L)
+ val resource = Resource(1)
+ val taskDescription1 = Processor[TaskA](2)
+ val taskDescription2 = Processor[TaskB](2)
+ val partitioner = new HashPartitioner
+ var conf: UserConfig = null
+
+ var mockTask: TestProbe = null
+
+ var mockMaster: TestProbe = null
+ var mockMasterProxy: ActorRef = null
+
+ var mockWorker: TestProbe = null
+ var appDescription: AppDescription = null
+ var appMasterContext: AppMasterContext = null
+ var appMasterRuntimeInfo: AppMasterRuntimeInfo = null
+
+ override def beforeEach(): Unit = {
+ startActorSystem()
+
+ mockTask = TestProbe()(getActorSystem)
+
+ mockMaster = TestProbe()(getActorSystem)
+ mockWorker = TestProbe()(getActorSystem)
+ mockMaster.ignoreMsg(ignoreSaveAppData)
+ appMasterRuntimeInfo = AppMasterRuntimeInfo(appId, appName = appId.toString)
+
+ implicit val system = getActorSystem
+ conf = UserConfig.empty.withValue(AppMasterSpec.MASTER, mockMaster.ref)
+ val mockJar = AppJar("for_test", FilePath("path"))
+ appMasterContext = AppMasterContext(appId, "test", resource, null, Some(mockJar),
+ mockMaster.ref, appMasterRuntimeInfo)
+ val graph = Graph(taskDescription1 ~ partitioner ~> taskDescription2)
+ val streamApp = StreamApplication("test", graph, conf)
+ appDescription = Application.ApplicationToAppDescription(streamApp)
+ import scala.concurrent.duration._
+ mockMasterProxy = getActorSystem.actorOf(Props(new MasterProxy(List(mockMaster.ref.path),
+ 30.seconds)), AppMasterSpec.MOCK_MASTER_PROXY)
+ TestActorRef[AppMaster](
+ AppMasterRuntimeEnvironment.props(List(mockMasterProxy.path), appDescription,
+ appMasterContext))(getActorSystem)
+
+ val registerAppMaster = mockMaster.receiveOne(15.seconds)
+ assert(registerAppMaster.isInstanceOf[RegisterAppMaster])
+ appMaster = registerAppMaster.asInstanceOf[RegisterAppMaster].appMaster
+
+ mockMaster.reply(AppMasterRegistered(appId))
+ mockMaster.expectMsg(15.seconds, GetAppData(appId, "DAG"))
+ mockMaster.reply(GetAppDataResult("DAG", null))
+ mockMaster.expectMsg(15.seconds, GetAppData(appId, "startClock"))
+
+ mockMaster.reply(GetAppDataResult("startClock", 0L))
+
+ mockMaster.expectMsg(15.seconds, RequestResource(appId, ResourceRequest(Resource(4),
+ workerId = WorkerId.unspecified)))
+ }
+
+ override def afterEach(): Unit = {
+ shutdownActorSystem()
+ }
+
+ "AppMaster" should {
+ "kill it self when allocate resource time out" in {
+ mockMaster.reply(ResourceAllocated(Array(ResourceAllocation(Resource(2),
+ mockWorker.ref, workerId))))
+ mockMaster.expectMsg(60.seconds, ShutdownApplication(appId))
+ }
+
+ "reschedule the resource when the worker reject to start executor" in {
+ val resource = Resource(4)
+ mockMaster.reply(ResourceAllocated(Array(ResourceAllocation(resource,
+ mockWorker.ref, workerId))))
+ mockWorker.expectMsgClass(classOf[LaunchExecutor])
+ mockWorker.reply(ExecutorLaunchRejected(""))
+ mockMaster.expectMsg(RequestResource(appId, ResourceRequest(resource, WorkerId.unspecified)))
+ }
+
+ "find a new master when lost connection with master" in {
+
+ val watcher = TestProbe()(getActorSystem)
+ watcher.watch(mockMasterProxy)
+ getActorSystem.stop(mockMasterProxy)
+ watcher.expectTerminated(mockMasterProxy)
+ // Make sure the parent of mockMasterProxy has received the Terminated message.
+ // Issus address: https://github.com/gearpump/gearpump/issues/1919
+ Thread.sleep(2000)
+
+ import scala.concurrent.duration._
+ mockMasterProxy = getActorSystem.actorOf(Props(new MasterProxy(List(mockMaster.ref.path),
+ 30.seconds)), AppMasterSpec.MOCK_MASTER_PROXY)
+ mockMaster.expectMsgClass(15.seconds, classOf[RegisterAppMaster])
+ }
+
+ // // TODO: This test is failing on Travis randomly
+ // // We have not identifed the root cause.
+ // // Check: https://travis-ci.org/intel-hadoop/gearpump/builds/56826843
+ // // Issue tracker: https://github.com/intel-hadoop/gearpump/issues/733
+ //
+ // "launch executor and task properly" in {
+ // mockMaster.reply(ResourceAllocated(Array(ResourceAllocation(Resource(4), mockWorker.ref,
+ // workerId))))
+ // mockWorker.expectMsgClass(classOf[LaunchExecutor])
+ //
+ // val workerSystem = ActorSystem("worker", TestUtil.DEFAULT_CONFIG)
+ // mockWorker.reply(RegisterActorSystem(ActorUtil.getSystemAddress(workerSystem).toString))
+ // for (i <- 1 to 4) {
+ // mockMaster.expectMsg(10 seconds, AppMasterSpec.TaskStarted)
+ // }
+ //
+ // // clock status: task(0,0) -> 1, task(0,1)->0, task(1, 0)->0, task(1,1)->0
+ // appMaster.tell(UpdateClock(TaskId(0, 0), 1), mockTask.ref)
+ //
+ // // there is no further upstream, so the upstreamMinClock is Long.MaxValue
+ // mockTask.expectMsg(UpstreamMinClock(Long.MaxValue))
+ //
+ // // check min clock
+ // appMaster.tell(GetLatestMinClock, mockTask.ref)
+ // mockTask.expectMsg(LatestMinClock(0))
+ //
+ //
+ // // clock status: task(0,0) -> 1, task(0,1)->1, task(1, 0)->0, task(1,1)->0
+ // appMaster.tell(UpdateClock(TaskId(0, 1), 1), mockTask.ref)
+ //
+ // // there is no further upstream, so the upstreamMinClock is Long.MaxValue
+ // mockTask.expectMsg(UpstreamMinClock(Long.MaxValue))
+ //
+ // // check min clock
+ // appMaster.tell(GetLatestMinClock, mockTask.ref)
+ // mockTask.expectMsg(LatestMinClock(0))
+ //
+ // // Clock status: task(0,0) -> 1, task(0,1)->1, task(1, 1)->0, task(1,1)->0
+ // appMaster.tell(UpdateClock(TaskId(1, 0), 1), mockTask.ref)
+ //
+ // // Min clock of processor 0 (Task(0, 0) and Task(0, 1))
+ // mockTask.expectMsg(UpstreamMinClock(1))
+ //
+ // // check min clock
+ // appMaster.tell(GetLatestMinClock, mockTask.ref)
+ // mockTask.expectMsg(LatestMinClock(0))
+ //
+ // // clock status: task(0,0) -> 1, task(0,1)->1, task(1, 1)->0, task(1,1)->1
+ // appMaster.tell(UpdateClock(TaskId(1, 1), 1), mockTask.ref)
+ //
+ // // min clock of processor 0 (Task(0, 0) and Task(0, 1))
+ // mockTask.expectMsg(UpstreamMinClock(1))
+ //
+ // // check min clock
+ // appMaster.tell(GetLatestMinClock, mockTask.ref)
+ // mockTask.expectMsg(LatestMinClock(1))
+ //
+ // // shutdown worker and all executor on this work, expect appmaster to ask
+ // // for new resources
+ // workerSystem.shutdown()
+ // mockMaster.expectMsg(RequestResource(appId, ResourceRequest(Resource(4), relaxation =
+ // Relaxation.ONEWORKER)))
+ // }
+ }
+
+ def ignoreSaveAppData: PartialFunction[Any, Boolean] = {
+ case msg: SaveAppData => true
+ }
+}
+
+object AppMasterSpec {
+ val MASTER = "master"
+ case object TaskStarted
+
+ val MOCK_MASTER_PROXY = "mockMasterProxy"
+}
+
+class TaskA(taskContext: TaskContext, userConf: UserConfig) extends Task(taskContext, userConf) {
+
+ val master = userConf.getValue[ActorRef](AppMasterSpec.MASTER).get
+ override def onStart(startTime: StartTime): Unit = {
+ master ! AppMasterSpec.TaskStarted
+ }
+
+ override def onNext(msg: Message): Unit = {}
+}
+
+class TaskB(taskContext: TaskContext, userConf: UserConfig) extends Task(taskContext, userConf) {
+
+ val master = userConf.getValue[ActorRef](AppMasterSpec.MASTER).get
+ override def onStart(startTime: StartTime): Unit = {
+ master ! AppMasterSpec.TaskStarted
+ }
+
+ override def onNext(msg: Message): Unit = {}
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/ClockServiceSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/ClockServiceSpec.scala b/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/ClockServiceSpec.scala
new file mode 100644
index 0000000..2bb33b7
--- /dev/null
+++ b/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/ClockServiceSpec.scala
@@ -0,0 +1,240 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.appmaster
+
+import akka.actor.{ActorSystem, Props}
+import akka.testkit.{ImplicitSender, TestKit, TestProbe}
+import org.apache.gearpump.cluster.{TestUtil, UserConfig}
+import org.apache.gearpump.partitioner.{HashPartitioner, Partitioner, PartitionerDescription}
+import org.apache.gearpump.streaming.appmaster.ClockService.{ChangeToNewDAG, ChangeToNewDAGSuccess, HealthChecker, ProcessorClock}
+import org.apache.gearpump.streaming.appmaster.ClockServiceSpec.Store
+import org.apache.gearpump.streaming.storage.AppDataStore
+import org.apache.gearpump.streaming.task.{GetLatestMinClock, GetStartClock, UpstreamMinClock, _}
+import org.apache.gearpump.streaming.{DAG, LifeTime, ProcessorDescription}
+import org.apache.gearpump.util.Graph
+import org.apache.gearpump.util.Graph._
+import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}
+
+import scala.concurrent.{Future, Promise}
+
+class ClockServiceSpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender
+ with WordSpecLike with Matchers with BeforeAndAfterAll {
+
+ def this() = this(ActorSystem("ClockServiceSpec", TestUtil.DEFAULT_CONFIG))
+
+ val hash = Partitioner[HashPartitioner]
+ val task1 = ProcessorDescription(id = 0, taskClass = classOf[TaskActor].getName, parallelism = 1)
+ val task2 = ProcessorDescription(id = 1, taskClass = classOf[TaskActor].getName, parallelism = 1)
+ val dag = DAG(Graph(task1 ~ hash ~> task2))
+
+ override def afterAll {
+ TestKit.shutdownActorSystem(system)
+ }
+
+ "The ClockService" should {
+ "maintain a global view of message timestamp in the application" in {
+ val store = new Store()
+ val startClock = 100L
+ store.put(ClockService.START_CLOCK, startClock)
+ val clockService = system.actorOf(Props(new ClockService(dag, store)))
+ clockService ! GetLatestMinClock
+ expectMsg(LatestMinClock(startClock))
+
+ // task(0,0): clock(101); task(1,0): clock(100)
+ clockService ! UpdateClock(TaskId(0, 0), 101)
+
+ // There is no upstream, so pick Long.MaxValue
+ expectMsg(UpstreamMinClock(Long.MaxValue))
+
+ // Min clock is updated
+ clockService ! GetLatestMinClock
+ expectMsg(LatestMinClock(100))
+
+ // task(0,0): clock(101); task(1,0): clock(101)
+ clockService ! UpdateClock(TaskId(1, 0), 101)
+
+ // Upstream is Task(0, 0), 101
+ expectMsg(UpstreamMinClock(101))
+
+ // Min clock is updated
+ clockService ! GetLatestMinClock
+ expectMsg(LatestMinClock(101))
+ }
+
+ "act on ChangeToNewDAG and make sure downstream clock smaller than upstreams" in {
+ val store = new Store()
+ val startClock = 100L
+ store.put(ClockService.START_CLOCK, startClock)
+ val clockService = system.actorOf(Props(new ClockService(dag, store)))
+ val task = TestProbe()
+ clockService.tell(UpdateClock(TaskId(0, 0), 200), task.ref)
+ task.expectMsgType[UpstreamMinClock]
+
+ val task3 = ProcessorDescription(id = 3, taskClass = classOf[TaskActor].getName,
+ parallelism = 1)
+ val task4 = ProcessorDescription(id = 4, taskClass = classOf[TaskActor].getName,
+ parallelism = 1)
+ val task5 = ProcessorDescription(id = 5, taskClass = classOf[TaskActor].getName,
+ parallelism = 1)
+ val dagAddMiddleNode = DAG(Graph(
+ task1 ~ hash ~> task2,
+ task1 ~ hash ~> task3,
+ task3 ~ hash ~> task2,
+ task2 ~ hash ~> task4,
+ task5 ~ hash ~> task1
+ ))
+ val user = TestProbe()
+ clockService.tell(ChangeToNewDAG(dagAddMiddleNode), user.ref)
+
+ val clocks = user.expectMsgPF() {
+ case ChangeToNewDAGSuccess(clocks) =>
+ clocks
+ }
+
+ // For intermediate task, pick its upstream as initial clock
+ assert(clocks(task3.id) == clocks(task1.id))
+
+ // For sink task, pick its upstream as initial clock
+ assert(clocks(task4.id) == clocks(task2.id))
+
+ // For source task, set the initial clock as startClock
+ assert(clocks(task5.id) == startClock)
+ }
+
+ "maintain global checkpoint time" in {
+ val store = new Store()
+ val startClock = 100L
+ store.put(ClockService.START_CLOCK, startClock)
+ val clockService = system.actorOf(Props(new ClockService(dag, store)))
+ clockService ! UpdateClock(TaskId(0, 0), 200L)
+ expectMsgType[UpstreamMinClock]
+ clockService ! UpdateClock(TaskId(1, 0), 200L)
+ expectMsgType[UpstreamMinClock]
+
+ clockService ! GetStartClock
+ expectMsg(StartClock(200L))
+
+ val conf = UserConfig.empty.withBoolean("state.checkpoint.enable", true)
+ val task3 = ProcessorDescription(id = 3, taskClass = classOf[TaskActor].getName,
+ parallelism = 1, taskConf = conf)
+ val task4 = ProcessorDescription(id = 4, taskClass = classOf[TaskActor].getName,
+ parallelism = 1, taskConf = conf)
+ val dagWithStateTasks = DAG(Graph(
+ task1 ~ hash ~> task2,
+ task1 ~ hash ~> task3,
+ task3 ~ hash ~> task2,
+ task2 ~ hash ~> task4
+ ), version = 1)
+
+ val taskId3 = TaskId(3, 0)
+ val taskId4 = TaskId(4, 0)
+
+ clockService ! ChangeToNewDAG(dagWithStateTasks)
+ expectMsgType[ChangeToNewDAGSuccess]
+
+ clockService ! ReportCheckpointClock(taskId3, startClock)
+ clockService ! ReportCheckpointClock(taskId4, startClock)
+ clockService ! GetStartClock
+ expectMsg(StartClock(startClock))
+
+ clockService ! ReportCheckpointClock(taskId3, 200L)
+ clockService ! ReportCheckpointClock(taskId4, 300L)
+ clockService ! GetStartClock
+ expectMsg(StartClock(startClock))
+
+ clockService ! ReportCheckpointClock(taskId3, 300L)
+ clockService ! GetStartClock
+ expectMsg(StartClock(300L))
+ }
+ }
+
+ "ProcessorClock" should {
+ "maintain the min clock of current processor" in {
+ val processorId = 0
+ val parallism = 3
+ val clock = new ProcessorClock(processorId, LifeTime.Immortal, parallism)
+ clock.init(100L)
+ clock.updateMinClock(0, 101)
+ assert(clock.min == 100L)
+
+ clock.updateMinClock(1, 102)
+ assert(clock.min == 100L)
+
+ clock.updateMinClock(2, 103)
+ assert(clock.min == 101L)
+ }
+ }
+
+ "HealthChecker" should {
+ "report stalling if the clock is not advancing" in {
+ val healthChecker = new HealthChecker(stallingThresholdSeconds = 1)
+ val source = ProcessorDescription(id = 0, taskClass = null, parallelism = 1)
+ val sourceClock = new ProcessorClock(0, LifeTime.Immortal, 1)
+ sourceClock.init(0L)
+ val sink = ProcessorDescription(id = 1, taskClass = null, parallelism = 1)
+ val sinkClock = new ProcessorClock(1, LifeTime.Immortal, 1)
+ sinkClock.init(0L)
+ val graph = Graph.empty[ProcessorDescription, PartitionerDescription]
+ graph.addVertex(source)
+ graph.addVertex(sink)
+ graph.addEdge(source, PartitionerDescription(null), sink)
+ val dag = DAG(graph)
+ val clocks = Map(
+ 0 -> sourceClock,
+ 1 -> sinkClock
+ )
+
+ sourceClock.updateMinClock(0, 100L)
+ sinkClock.updateMinClock(0, 100L)
+
+ // Clock advances from 0 to 100, there is no stalling.
+ healthChecker.check(currentMinClock = 100, clocks, dag, 200)
+ healthChecker.getReport.stallingTasks shouldBe List.empty[TaskId]
+
+ // Clock not advancing.
+ // Pasted time exceed the stalling threshold, report stalling
+ healthChecker.check(currentMinClock = 100, clocks, dag, 1300)
+
+ // The source task is stalling the clock
+ healthChecker.getReport.stallingTasks shouldBe List(TaskId(0, 0))
+
+ // Advance the source clock
+ sourceClock.updateMinClock(0, 101L)
+ healthChecker.check(currentMinClock = 100, clocks, dag, 1300)
+ // The sink task is stalling the clock
+ healthChecker.getReport.stallingTasks shouldBe List(TaskId(1, 0))
+ }
+ }
+}
+
+object ClockServiceSpec {
+
+ class Store extends AppDataStore {
+
+ private var map = Map.empty[String, Any]
+
+ def put(key: String, value: Any): Future[Any] = {
+ map = map + (key -> value)
+ Promise.successful(value).future
+ }
+
+ def get(key: String): Future[Any] = {
+ Promise.successful(map.get(key).getOrElse(null)).future
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/DagManagerSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/DagManagerSpec.scala b/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/DagManagerSpec.scala
new file mode 100644
index 0000000..258c7ff
--- /dev/null
+++ b/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/DagManagerSpec.scala
@@ -0,0 +1,107 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.appmaster
+
+import akka.actor.{ActorSystem, Props}
+import akka.testkit.TestProbe
+import org.apache.gearpump.cluster.{TestUtil, UserConfig}
+import org.apache.gearpump.partitioner.{HashPartitioner, Partitioner}
+import org.apache.gearpump.streaming.appmaster.DagManager.{DAGOperationFailed, DAGOperationSuccess, GetLatestDAG, GetTaskLaunchData, LatestDAG, NewDAGDeployed, ReplaceProcessor, TaskLaunchData, WatchChange}
+import org.apache.gearpump.streaming.task.{Subscriber, TaskActor}
+import org.apache.gearpump.streaming.{DAG, LifeTime, ProcessorDescription, StreamApplication}
+import org.apache.gearpump.util.Graph
+import org.apache.gearpump.util.Graph._
+import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}
+
+import scala.concurrent.Await
+import scala.concurrent.duration.Duration
+
+class DagManagerSpec extends WordSpecLike with Matchers with BeforeAndAfterAll {
+
+ val hash = Partitioner[HashPartitioner]
+ val task1 = ProcessorDescription(id = 1, taskClass = classOf[TaskActor].getName, parallelism = 1)
+ val task2 = ProcessorDescription(id = 2, taskClass = classOf[TaskActor].getName, parallelism = 1)
+ val graph = Graph(task1 ~ hash ~> task2)
+ val dag = DAG(graph)
+ implicit var system: ActorSystem = null
+ val appId = 0
+ lazy val userConfig = UserConfig.empty.withValue(StreamApplication.DAG, graph)
+
+ "DagManager" should {
+ import org.apache.gearpump.streaming.appmaster.ClockServiceSpec.Store
+ "maintain the dags properly" in {
+ val store = new Store
+
+ val dagManager = system.actorOf(Props(new DagManager(appId, userConfig, store, Some(dag))))
+ val client = TestProbe()
+ client.send(dagManager, GetLatestDAG)
+ client.expectMsg(LatestDAG(dag))
+
+ client.send(dagManager, GetTaskLaunchData(dag.version, task1.id, null))
+ val task1LaunchData = TaskLaunchData(task1, Subscriber.of(task1.id, dag))
+ client.expectMsg(task1LaunchData)
+
+ val task2LaunchData = TaskLaunchData(task2, Subscriber.of(task2.id, dag))
+ client.send(dagManager, GetTaskLaunchData(dag.version, task2.id, null))
+ client.expectMsg(task2LaunchData)
+
+ val watcher = TestProbe()
+ client.send(dagManager, WatchChange(watcher.ref))
+ val task3 = task2.copy(id = 3, life = LifeTime(100, Long.MaxValue))
+
+ client.send(dagManager, ReplaceProcessor(task2.id, task3))
+ client.expectMsg(DAGOperationSuccess)
+
+ client.send(dagManager, GetLatestDAG)
+ val newDag = client.expectMsgPF() {
+ case LatestDAG(dag) => dag
+ }
+ assert(newDag.processors.contains(task3.id))
+ watcher.expectMsgType[LatestDAG]
+
+ val task4 = task3.copy(id = 4)
+ client.send(dagManager, ReplaceProcessor(task3.id, task4))
+ client.expectMsgType[DAGOperationFailed]
+
+ client.send(dagManager, NewDAGDeployed(newDag.version))
+ client.send(dagManager, ReplaceProcessor(task3.id, task4))
+ client.expectMsg(DAGOperationSuccess)
+ }
+
+ "retrieve last stored dag properly" in {
+ val store = new Store
+ val newGraph = Graph(task1 ~ hash ~> task2 ~> task2)
+ val newDag = DAG(newGraph)
+ store.put(StreamApplication.DAG, newDag)
+ val dagManager = system.actorOf(Props(new DagManager(appId, userConfig, store, Some(dag))))
+ val client = TestProbe()
+ client.send(dagManager, GetLatestDAG)
+ client.expectMsg(LatestDAG(newDag))
+ }
+ }
+
+ override def afterAll {
+ system.terminate()
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+
+ override def beforeAll {
+ this.system = ActorSystem("DagManagerSpec", TestUtil.DEFAULT_CONFIG)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/ExecutorManagerSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/ExecutorManagerSpec.scala b/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/ExecutorManagerSpec.scala
new file mode 100644
index 0000000..42b2618
--- /dev/null
+++ b/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/ExecutorManagerSpec.scala
@@ -0,0 +1,150 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.appmaster
+
+import akka.actor._
+import akka.testkit.TestProbe
+import com.typesafe.config.ConfigFactory
+import org.apache.gearpump.TestProbeUtil
+import org.apache.gearpump.cluster.AppMasterToWorker.ChangeExecutorResource
+import org.apache.gearpump.cluster._
+import org.apache.gearpump.cluster.appmaster.ExecutorSystemScheduler.{ExecutorSystemStarted, StartExecutorSystemTimeout, StartExecutorSystems}
+import org.apache.gearpump.cluster.appmaster.{ExecutorSystem, WorkerInfo}
+import org.apache.gearpump.cluster.scheduler.{Resource, ResourceRequest}
+import org.apache.gearpump.cluster.worker.WorkerId
+import org.apache.gearpump.jarstore.FilePath
+import org.apache.gearpump.streaming.ExecutorId
+import org.apache.gearpump.streaming.ExecutorToAppMaster.RegisterExecutor
+import org.apache.gearpump.streaming.appmaster.ExecutorManager.{ExecutorStarted, _}
+import org.apache.gearpump.streaming.appmaster.ExecutorManagerSpec.StartExecutorActorPlease
+import org.apache.gearpump.util.ActorSystemBooter.BindLifeCycle
+import org.apache.gearpump.util.LogUtil
+import org.scalatest._
+
+import scala.concurrent.Await
+import scala.concurrent.duration.Duration
+
+class ExecutorManagerSpec extends FlatSpec with Matchers with BeforeAndAfterAll {
+ implicit var system: ActorSystem = null
+
+ private val LOG = LogUtil.getLogger(getClass)
+ private val appId = 0
+ private val resource = Resource(10)
+
+ override def beforeAll(): Unit = {
+ system = ActorSystem("test", TestUtil.DEFAULT_CONFIG)
+ }
+
+ override def afterAll(): Unit = {
+ system.terminate()
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+
+ private def startExecutorSystems = {
+ val master = TestProbe()
+ val taskManager = TestProbe()
+ val executor = TestProbe()
+ val userConfig = UserConfig.empty
+
+ val username = "user"
+ val appName = "app"
+ val appJar = Some(AppJar("for_test", FilePath("path")))
+
+ val appMasterContext = AppMasterContext(appId, username, null, null, appJar, master.ref, null)
+
+ val executorFactory = (_: ExecutorContext, _: UserConfig, _: Address, _: ExecutorId) => {
+ executor.ref ! StartExecutorActorPlease
+ TestProbeUtil.toProps(executor)
+ }
+ val executorManager = system.actorOf(Props(new ExecutorManager(userConfig, appMasterContext,
+ executorFactory, ConfigFactory.empty, appName)))
+
+ taskManager.send(executorManager, SetTaskManager(taskManager.ref))
+ val resourceRequest = Array(ResourceRequest(resource, WorkerId.unspecified))
+
+ // Starts executors
+ taskManager.send(executorManager, StartExecutors(resourceRequest, appJar.get))
+
+ // Asks master to start executor systems
+ import scala.concurrent.duration._
+ val startExecutorSystem = master.receiveOne(5.seconds).asInstanceOf[StartExecutorSystems]
+ assert(startExecutorSystem.resources == resourceRequest)
+ import startExecutorSystem.executorSystemConfig.{classPath, executorAkkaConfig, jar, jvmArguments, username => returnedUserName}
+ assert(startExecutorSystem.resources == resourceRequest)
+
+ assert(classPath.length == 0)
+ assert(jvmArguments.length == 0)
+ assert(jar == appJar)
+ assert(returnedUserName == username)
+ assert(executorAkkaConfig.isEmpty)
+
+ (master, executor, taskManager, executorManager)
+ }
+
+ it should "report timeout to taskManager" in {
+ import org.apache.gearpump.streaming.appmaster.ExecutorManager._
+ val (master, executor, taskManager, executorManager) = startExecutorSystems
+ master.reply(StartExecutorSystemTimeout)
+ taskManager.expectMsg(StartExecutorsTimeOut)
+ }
+
+ it should "start executor actor correctly" in {
+ val (master, executor, taskManager, executorManager) = startExecutorSystems
+ val executorSystemDaemon = TestProbe()
+ val worker = TestProbe()
+ val workerId = WorkerId(0, 0L)
+ val workerInfo = WorkerInfo(workerId, worker.ref)
+ val executorSystem = ExecutorSystem(0, null, executorSystemDaemon.ref,
+ resource, workerInfo)
+ master.reply(ExecutorSystemStarted(executorSystem, None))
+ import scala.concurrent.duration._
+ val bindLifeWith = executorSystemDaemon.receiveOne(3.seconds).asInstanceOf[BindLifeCycle]
+ val proxyExecutor = bindLifeWith.actor
+ executor.expectMsg(StartExecutorActorPlease)
+
+ val executorId = 0
+
+ // Registers executor
+ executor.send(executorManager, RegisterExecutor(proxyExecutor, executorId,
+ resource, workerInfo))
+ taskManager.expectMsgType[ExecutorStarted]
+
+ // Broadcasts message to childs
+ taskManager.send(executorManager, BroadCast("broadcast"))
+ executor.expectMsg("broadcast")
+
+ // Unicast
+ taskManager.send(executorManager, UniCast(executorId, "unicast"))
+ executor.expectMsg("unicast")
+
+ // Updates executor resource status
+ val usedResource = Resource(5)
+ executorManager ! ExecutorResourceUsageSummary(Map(executorId -> usedResource))
+ worker.expectMsg(ChangeExecutorResource(appId, executorId, resource - usedResource))
+
+ // Watches for executor termination
+ system.stop(executor.ref)
+ LOG.info("Shutting down executor, and wait taskManager to get notified")
+ taskManager.expectMsg(ExecutorStopped(executorId))
+ }
+}
+
+object ExecutorManagerSpec {
+ case object StartExecutorActorPlease
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/ExecutorRestartPolicySpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/ExecutorRestartPolicySpec.scala b/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/ExecutorRestartPolicySpec.scala
new file mode 100644
index 0000000..5f3905f
--- /dev/null
+++ b/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/ExecutorRestartPolicySpec.scala
@@ -0,0 +1,46 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.appmaster
+
+import org.apache.gearpump.streaming.executor.ExecutorRestartPolicy
+import org.apache.gearpump.streaming.task.TaskId
+import org.scalatest.{Matchers, WordSpec}
+
+import scala.concurrent.duration._
+
+class ExecutorRestartPolicySpec extends WordSpec with Matchers {
+
+ "ExecutorRestartPolicy" should {
+ "decide whether to restart the executor" in {
+ val executorId1 = 1
+ val executorId2 = 2
+ val taskId = TaskId(0, 0)
+ val executorSupervisor = new ExecutorRestartPolicy(
+ maxNrOfRetries = 3, withinTimeRange = 1.seconds)
+ executorSupervisor.addTaskToExecutor(executorId1, taskId)
+ assert(executorSupervisor.allowRestartExecutor(executorId1))
+ assert(executorSupervisor.allowRestartExecutor(executorId1))
+ executorSupervisor.addTaskToExecutor(executorId2, taskId)
+ assert(executorSupervisor.allowRestartExecutor(executorId2))
+ assert(!executorSupervisor.allowRestartExecutor(executorId2))
+ Thread.sleep(1000)
+ assert(executorSupervisor.allowRestartExecutor(executorId2))
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/HistoryMetricsServiceSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/HistoryMetricsServiceSpec.scala b/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/HistoryMetricsServiceSpec.scala
new file mode 100644
index 0000000..5157284
--- /dev/null
+++ b/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/HistoryMetricsServiceSpec.scala
@@ -0,0 +1,196 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.appmaster
+
+import akka.actor.{ActorSystem, Props}
+import akka.testkit.TestProbe
+import org.apache.gearpump.cluster.ClientToMaster.QueryHistoryMetrics
+import org.apache.gearpump.cluster.MasterToClient.HistoryMetrics
+import org.apache.gearpump.cluster.TestUtil
+import org.apache.gearpump.metrics.Metrics.{Counter, Histogram, Meter}
+import org.apache.gearpump.util.HistoryMetricsService
+import org.apache.gearpump.util.HistoryMetricsService._
+import org.scalatest.{BeforeAndAfterEach, FlatSpec, Matchers}
+
+import scala.concurrent.Await
+
+class HistoryMetricsServiceSpec extends FlatSpec with Matchers with BeforeAndAfterEach {
+
+ val count = 2
+ val intervalMs = 10
+
+ val config = HistoryMetricsConfig(
+ retainHistoryDataHours = 72,
+ retainHistoryDataIntervalMs = 3600 * 1000,
+ retainRecentDataSeconds = 300,
+ retainRecentDataIntervalMs = 15 * 1000)
+
+ "SingleValueMetricsStore" should "retain metrics and expire old value" in {
+
+ val store = new SingleValueMetricsStore(count, intervalMs)
+
+ var now = 0L
+ // Only 1 data point will be kept in @intervalMs
+ store.add(Counter("count", 1), now)
+ store.add(Counter("count", 2), now)
+
+ now = now + intervalMs + 1
+
+ // Only 1 data point will be kept in @intervalMs
+ store.add(Counter("count", 3), now)
+ store.add(Counter("count", 4), now)
+
+ now = now + intervalMs + 1
+
+ // Only 1 data point will be kept in @intervalMs
+ // expire oldest data point, because we only keep @count records
+ store.add(Counter("count", 5), now)
+ store.add(Counter("count", 6), now)
+
+ val result = store.read
+ assert(result.size == count)
+
+ // The oldest value is expired
+ assert(result.head.value.asInstanceOf[Counter].value == 3L)
+
+ // The newest value is inserted
+ assert(result.last.value.asInstanceOf[Counter].value == 5L)
+ }
+
+ val meterTemplate = Meter("meter", 0, 0, 0, "s")
+
+ "HistogramMetricsStore" should "retain corse-grain history and fine-grain recent data" in {
+ val store = new HistogramMetricsStore(config)
+ val a = Histogram(null, 100, 0, 0, 0, 0, 0)
+ val b = Histogram(null, 200, 0, 0, 0, 0, 0)
+ val c = Histogram(null, 50, 0, 0, 0, 0, 0)
+
+ store.add(a)
+ store.add(b)
+ store.add(c)
+
+ assert(store.readLatest.map(_.value) == List(c))
+ assert(store.readRecent.map(_.value) == List(a))
+ assert(store.readHistory.map(_.value) == List(a))
+ }
+
+ "MeterMetricsStore" should "retain corse-grain history and fine-grain recent data" in {
+ val store = new MeterMetricsStore(config)
+
+ val a = Meter(null, 1, 100, 0, null)
+ val b = Meter(null, 1, 200, 0, null)
+ val c = Meter(null, 1, 50, 0, null)
+
+ store.add(a)
+ store.add(b)
+ store.add(c)
+
+ assert(store.readLatest.map(_.value) == List(c))
+ assert(store.readRecent.map(_.value) == List(a))
+ assert(store.readHistory.map(_.value) == List(a))
+ }
+
+ "CounterMetricsStore" should "retain corse-grain history and fine-grain recent data" in {
+ val store = new CounterMetricsStore(config)
+ val a = Counter(null, 50)
+ val b = Counter(null, 100)
+ val c = Counter(null, 150)
+
+ store.add(a)
+ store.add(b)
+ store.add(c)
+
+ assert(store.readLatest.map(_.value) == List(c))
+ assert(store.readRecent.map(_.value) == List(a))
+ assert(store.readHistory.map(_.value) == List(a))
+ }
+
+ "HistoryMetricsService" should
+ "retain lastest metrics data and allow user to query metrics by path" in {
+ implicit val system = ActorSystem("test", TestUtil.DEFAULT_CONFIG)
+ val appId = 0
+ val service = system.actorOf(Props(new HistoryMetricsService("app0", config)))
+ service ! Counter("metric.counter", 0)
+ service ! Meter("metric.meter", 0, 0, 0, null)
+ service ! Histogram("metric.histogram", 0, 0, 0, 0, 0, 0)
+
+ val client = TestProbe()
+
+ // Filters metrics with path "metric.counter"
+ client.send(service, QueryHistoryMetrics("metric.counter"))
+ import scala.concurrent.duration._
+ client.expectMsgPF(3.seconds) {
+ case history: HistoryMetrics =>
+ assert(history.path == "metric.counter")
+ val metricList = history.metrics
+ metricList.foreach(metricItem =>
+ assert(metricItem.value.isInstanceOf[Counter])
+ )
+ }
+
+ // Filters metrics with path "metric.meter"
+ client.send(service, QueryHistoryMetrics("metric.meter"))
+ client.expectMsgPF(3.seconds) {
+ case history: HistoryMetrics =>
+ assert(history.path == "metric.meter")
+ val metricList = history.metrics
+ metricList.foreach(metricItem =>
+ assert(metricItem.value.isInstanceOf[Meter])
+ )
+ }
+
+ // Filters metrics with path "metric.histogram"
+ client.send(service, QueryHistoryMetrics("metric.histogram"))
+ client.expectMsgPF(3.seconds) {
+ case history: HistoryMetrics =>
+ assert(history.path == "metric.histogram")
+ val metricList = history.metrics
+ metricList.foreach(metricItem =>
+ assert(metricItem.value.isInstanceOf[Histogram])
+ )
+ }
+
+ // Filters metrics with path prefix "metric", all metrics which can
+ // match the path prefix will be retained.
+ client.send(service, QueryHistoryMetrics("metric"))
+ client.expectMsgPF(3.seconds) {
+ case history: HistoryMetrics =>
+ val metricList = history.metrics
+
+ var counterFound = false
+ var meterFound = false
+ var histogramFound = false
+
+ metricList.foreach(metricItem =>
+ metricItem.value match {
+ case v: Counter => counterFound = true
+ case v: Meter => meterFound = true
+ case v: Histogram => histogramFound = true
+ case _ => // Skip
+ }
+ )
+
+ // All kinds of metric type are reserved.
+ assert(counterFound && meterFound && histogramFound)
+ }
+
+ system.terminate()
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/JarSchedulerSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/JarSchedulerSpec.scala b/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/JarSchedulerSpec.scala
new file mode 100644
index 0000000..5f6dd04
--- /dev/null
+++ b/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/JarSchedulerSpec.scala
@@ -0,0 +1,95 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.appmaster
+
+import akka.actor.ActorSystem
+import org.apache.gearpump.cluster.scheduler.{Resource, ResourceRequest}
+import org.apache.gearpump.cluster.worker.WorkerId
+import org.apache.gearpump.cluster.{AppJar, TestUtil}
+import org.apache.gearpump.jarstore.FilePath
+import org.apache.gearpump.partitioner.{HashPartitioner, Partitioner}
+import org.apache.gearpump.streaming.appmaster.TaskSchedulerSpec.{TestTask1, TestTask2}
+import org.apache.gearpump.streaming.task.TaskId
+import org.apache.gearpump.streaming.{DAG, ProcessorDescription, _}
+import org.apache.gearpump.util.Graph
+import org.apache.gearpump.util.Graph._
+import org.scalatest.{Matchers, WordSpec}
+
+import scala.concurrent.{Await, Future}
+
+class JarSchedulerSpec extends WordSpec with Matchers {
+ val mockJar1 = AppJar("jar1", FilePath("path"))
+ val mockJar2 = AppJar("jar2", FilePath("path"))
+ val task1 = ProcessorDescription(id = 0, taskClass = classOf[TestTask1].getName, parallelism = 1,
+ jar = mockJar1)
+ val task2 = ProcessorDescription(id = 1, taskClass = classOf[TestTask2].getName, parallelism = 1,
+ jar = mockJar1)
+ val task3 = ProcessorDescription(id = 2, taskClass = classOf[TestTask2].getName, parallelism = 2,
+ jar = mockJar2)
+ val dag = DAG(Graph(task1 ~ Partitioner[HashPartitioner] ~> task2))
+
+ import scala.concurrent.duration._
+
+ "JarScheduler" should {
+ "schedule tasks depends on app jar" in {
+ val system = ActorSystem("JarSchedulerSpec")
+ implicit val dispatcher = system.dispatcher
+ val manager = new JarScheduler(0, "APP", TestUtil.DEFAULT_CONFIG, system)
+ manager.setDag(dag, Future {
+ 0L
+ })
+ val requests = Array(ResourceRequest(Resource(2), WorkerId.unspecified))
+ val result = Await.result(manager.getResourceRequestDetails(), 15.seconds)
+ assert(result.length == 1)
+ assert(result.head.jar == mockJar1)
+ assert(result.head.requests.deep == requests.deep)
+
+ val tasks = Await.result(manager.scheduleTask(mockJar1, WorkerId(0, 0L), 0,
+ Resource(2)), 15.seconds)
+ assert(tasks.contains(TaskId(0, 0)))
+ assert(tasks.contains(TaskId(1, 0)))
+
+ val newDag = replaceDAG(dag, 1, task3, 1)
+
+ manager.setDag(newDag, Future {
+ 0
+ })
+ val requestDetails = Await.result(manager.getResourceRequestDetails().
+ map(_.sortBy(_.jar.name)), 15.seconds)
+ assert(requestDetails.length == 2)
+ assert(requestDetails.last.jar == mockJar2)
+ assert(requestDetails.last.requests.deep == requests.deep)
+
+ system.terminate()
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+ }
+
+ def replaceDAG(
+ dag: DAG, oldProcessorId: ProcessorId, newProcessor: ProcessorDescription, newVersion: Int)
+ : DAG = {
+ val oldProcessorLife = LifeTime(dag.processors(oldProcessorId).life.birth,
+ newProcessor.life.birth)
+ val newProcessorMap = dag.processors ++
+ Map(oldProcessorId -> dag.processors(oldProcessorId).copy(life = oldProcessorLife),
+ newProcessor.id -> newProcessor)
+ val newGraph = dag.graph.subGraph(oldProcessorId).
+ replaceVertex(oldProcessorId, newProcessor.id).addGraph(dag.graph)
+ new DAG(newVersion, newProcessorMap, newGraph)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/TaskLocatorSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/TaskLocatorSpec.scala b/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/TaskLocatorSpec.scala
new file mode 100644
index 0000000..4341041
--- /dev/null
+++ b/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/TaskLocatorSpec.scala
@@ -0,0 +1,34 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.appmaster
+
+import org.apache.gearpump.cluster.worker.WorkerId
+import org.apache.gearpump.streaming.appmaster.TaskLocator.Localities
+import org.apache.gearpump.streaming.task.TaskId
+import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
+
+class TaskLocatorSpec extends FlatSpec with Matchers with BeforeAndAfterAll {
+ it should "serialize/deserialize correctly" in {
+ val localities = new Localities(Map(WorkerId(0, 0L) -> Array(TaskId(0, 1), TaskId(1, 2))))
+ Localities.toJson(localities)
+
+ localities.localities.mapValues(_.toList) shouldBe
+ Localities.fromJson(Localities.toJson(localities)).localities.mapValues(_.toList)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/TaskManagerSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/TaskManagerSpec.scala b/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/TaskManagerSpec.scala
new file mode 100644
index 0000000..9765278
--- /dev/null
+++ b/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/TaskManagerSpec.scala
@@ -0,0 +1,275 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.appmaster
+
+import akka.actor.{ActorRef, ActorSystem, Props}
+import akka.testkit.TestProbe
+import org.apache.gearpump.cluster.MasterToAppMaster.ReplayFromTimestampWindowTrailingEdge
+import org.apache.gearpump.cluster.scheduler.{Resource, ResourceRequest}
+import org.apache.gearpump.cluster.worker.WorkerId
+import org.apache.gearpump.cluster.{AppJar, TestUtil, UserConfig}
+import org.apache.gearpump.jarstore.FilePath
+import org.apache.gearpump.partitioner.{HashPartitioner, Partitioner, PartitionerDescription}
+import org.apache.gearpump.streaming.AppMasterToExecutor.{LaunchTasks, StartAllTasks, StartDynamicDag, TaskLocationsReady, TaskLocationsReceived, TaskRegistered}
+import org.apache.gearpump.streaming.ExecutorToAppMaster.RegisterTask
+import org.apache.gearpump.streaming.appmaster.AppMaster.AllocateResourceTimeOut
+import org.apache.gearpump.streaming.appmaster.ClockService.{ChangeToNewDAG, ChangeToNewDAGSuccess}
+import org.apache.gearpump.streaming.appmaster.DagManager.{GetLatestDAG, GetTaskLaunchData, LatestDAG, NewDAGDeployed, TaskLaunchData, WatchChange}
+import org.apache.gearpump.streaming.appmaster.ExecutorManager.{ExecutorResourceUsageSummary, SetTaskManager, StartExecutors, _}
+import org.apache.gearpump.streaming.appmaster.JarScheduler.ResourceRequestDetail
+import org.apache.gearpump.streaming.appmaster.TaskManagerSpec.{Env, Task1, Task2}
+import org.apache.gearpump.streaming.executor.Executor.RestartTasks
+import org.apache.gearpump.streaming.task.{StartTime, TaskContext, _}
+import org.apache.gearpump.streaming.{DAG, LifeTime, ProcessorDescription, ProcessorId}
+import org.apache.gearpump.transport.HostPort
+import org.apache.gearpump.util.Graph
+import org.apache.gearpump.util.Graph._
+import org.apache.gearpump.{Message, TimeStamp}
+import org.mockito.Mockito._
+import org.scalatest.{BeforeAndAfterEach, FlatSpec, Matchers}
+
+import scala.concurrent.duration.Duration
+import scala.concurrent.{Await, Future}
+
+class TaskManagerSpec extends FlatSpec with Matchers with BeforeAndAfterEach {
+
+ implicit var system: ActorSystem = null
+
+ val task1Class = classOf[Task1].getName
+ val task2Class = classOf[Task2].getName
+
+ val mockJar = AppJar("jar_for_test", FilePath("path"))
+ val task1 = ProcessorDescription(id = 0, taskClass = task1Class, parallelism = 1, jar = mockJar)
+ val task2 = ProcessorDescription(id = 1, taskClass = task2Class, parallelism = 1, jar = mockJar)
+
+ val dag: DAG = DAG(Graph(task1 ~ Partitioner[HashPartitioner] ~> task2))
+ val dagVersion = 0
+
+ val task1LaunchData = TaskLaunchData(task1, Subscriber.of(processorId = 0, dag))
+ val task2LaunchData = TaskLaunchData(task2, Subscriber.of(processorId = 1, dag))
+
+ val appId = 0
+
+ val resource = Resource(2)
+ val workerId = WorkerId(0, 0L)
+ val executorId = 0
+
+ override def beforeEach(): Unit = {
+ system = ActorSystem("test", TestUtil.DEFAULT_CONFIG)
+ }
+
+ override def afterEach(): Unit = {
+ system.terminate()
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+
+ it should "recover by requesting new executors when executor stopped unexpectedly" in {
+ val env = bootUp
+ import env._
+ implicit val dispatcher = system.dispatcher
+
+ val resourceRequest = Array(ResourceRequest(resource, workerId))
+ when(scheduler.executorFailed(executorId)).thenReturn(Future {
+ Some(ResourceRequestDetail(mockJar,
+ resourceRequest))
+ })
+
+ taskManager ! ExecutorStopped(executorId)
+
+ // When one executor stop, it will also trigger the recovery by restart
+ // existing executors
+ executorManager.expectMsg(BroadCast(RestartTasks(dagVersion)))
+
+ // Asks for new executors
+ val returned = executorManager.receiveN(1).head.asInstanceOf[StartExecutors]
+ assert(returned.resources.deep == resourceRequest.deep)
+ executorManager.reply(StartExecutorsTimeOut)
+
+ // TaskManager cannot handle the TimeOut error itself, escalate to appmaster.
+ appMaster.expectMsg(AllocateResourceTimeOut)
+ }
+
+ it should "recover by restarting existing executors when message loss happen" in {
+ val env = bootUp
+ import env._
+
+ taskManager ! ReplayFromTimestampWindowTrailingEdge(appId)
+
+ // Restart the executors so that we can replay from minClock
+ executorManager.expectMsg(BroadCast(RestartTasks(dagVersion)))
+ }
+
+ import org.apache.gearpump.streaming.appmaster.TaskManager.TaskChangeRegistry
+ "TaskChangeRegistry" should "track all modified task registration" in {
+ val tasks = List(TaskId(0, 0), TaskId(0, 1))
+ val registry = new TaskChangeRegistry(tasks)
+ registry.taskChanged(TaskId(0, 0))
+ registry.taskChanged(TaskId(0, 1))
+ assert(registry.allTaskChanged)
+ }
+
+ "DAGDiff" should "track all the DAG migration impact" in {
+ val defaultEdge = PartitionerDescription(null)
+ val a = ProcessorDescription(id = 1, taskClass = null, parallelism = 1)
+ val b = ProcessorDescription(id = 2, taskClass = null, parallelism = 1)
+ val c = ProcessorDescription(id = 3, taskClass = null, parallelism = 1)
+ val left = Graph(a ~ defaultEdge ~> b, a ~ defaultEdge ~> c)
+
+ val d = ProcessorDescription(id = 4, taskClass = null, parallelism = 1)
+ val right = left.copy
+ right.addVertex(d)
+ right.addEdge(c, defaultEdge, d)
+ val e = a.copy(life = LifeTime(0, 0))
+ right.replaceVertex(a, e)
+
+ val diff = TaskManager.migrate(DAG(left), DAG(right, version = 1))
+ diff.addedProcessors shouldBe List(d.id)
+
+ diff.modifiedProcessors shouldBe List(a.id)
+
+ diff.impactedUpstream shouldBe List(c.id)
+ }
+
+ private def bootUp: Env = {
+
+ implicit val dispatcher = system.dispatcher
+
+ val executorManager = TestProbe()
+ val clockService = TestProbe()
+ val appMaster = TestProbe()
+ val executor = TestProbe()
+
+ val scheduler = mock(classOf[JarScheduler])
+
+ val dagManager = TestProbe()
+
+ val taskManager = system.actorOf(
+ Props(new TaskManager(appId, dagManager.ref, scheduler, executorManager.ref, clockService.ref,
+ appMaster.ref, "appName")))
+
+ dagManager.expectMsgType[WatchChange]
+ executorManager.expectMsgType[SetTaskManager]
+
+ // Step1: first transition from Unitialized to ApplicationReady
+ executorManager.expectMsgType[ExecutorResourceUsageSummary]
+ dagManager.expectMsgType[NewDAGDeployed]
+
+ // Step2: Get Additional Resource Request
+ when(scheduler.getResourceRequestDetails())
+ .thenReturn(Future {
+ Array(ResourceRequestDetail(mockJar, Array(ResourceRequest(resource,
+ WorkerId.unspecified))))
+ })
+
+ // Step3: DAG changed. Start transit from ApplicationReady -> DynamicDAG
+ dagManager.expectMsg(GetLatestDAG)
+ dagManager.reply(LatestDAG(dag))
+
+ // Step4: Start remote Executors.
+ // received Broadcast
+ executorManager.expectMsg(BroadCast(StartDynamicDag(dag.version)))
+ executorManager.expectMsgType[StartExecutors]
+
+ when(scheduler.scheduleTask(mockJar, workerId, executorId, resource))
+ .thenReturn(Future(List(TaskId(0, 0), TaskId(1, 0))))
+
+ // Step5: Executor is started.
+ executorManager.reply(ExecutorStarted(executorId, resource, workerId, Some(mockJar)))
+
+ // Step6: Prepare to start Task. First GetTaskLaunchData.
+ val taskLaunchData: PartialFunction[Any, TaskLaunchData] = {
+ case GetTaskLaunchData(_, 0, executorStarted) =>
+ task1LaunchData.copy(context = executorStarted)
+ case GetTaskLaunchData(_, 1, executorStarted) =>
+ task2LaunchData.copy(context = executorStarted)
+ }
+
+ val launchData1 = dagManager.expectMsgPF()(taskLaunchData)
+ dagManager.reply(launchData1)
+
+ val launchData2 = dagManager.expectMsgPF()(taskLaunchData)
+ dagManager.reply(launchData2)
+
+ // Step7: Launch Task
+ val launchTaskMatch: PartialFunction[Any, RegisterTask] = {
+ case UniCast(executorId, launch: LaunchTasks) =>
+ RegisterTask(launch.taskId.head, executorId, HostPort("127.0.0.1:3000"))
+ }
+
+ // Taskmanager should return the latest start clock to task(0,0)
+ clockService.expectMsg(GetStartClock)
+ clockService.reply(StartClock(0))
+
+ // Step8: Task is started. registerTask.
+ val registerTask1 = executorManager.expectMsgPF()(launchTaskMatch)
+ taskManager.tell(registerTask1, executor.ref)
+ executor.expectMsgType[TaskRegistered]
+
+ val registerTask2 = executorManager.expectMsgPF()(launchTaskMatch)
+ taskManager.tell(registerTask2, executor.ref)
+ executor.expectMsgType[TaskRegistered]
+
+ // Step9: start broadcasting TaskLocations.
+ import scala.concurrent.duration._
+ assert(executorManager.expectMsgPF(5.seconds) {
+ case BroadCast(startAllTasks) => startAllTasks.isInstanceOf[TaskLocationsReady]
+ })
+
+ // Step10: Executor confirm it has received TaskLocationsReceived(version, executorId)
+ taskManager.tell(TaskLocationsReceived(dag.version, executorId), executor.ref)
+
+ // Step11: Tell ClockService to update DAG.
+ clockService.expectMsgType[ChangeToNewDAG]
+ clockService.reply(ChangeToNewDAGSuccess(Map.empty[ProcessorId, TimeStamp]))
+
+ // Step12: start all tasks
+ import scala.concurrent.duration._
+ assert(executorManager.expectMsgPF(5.seconds) {
+ case BroadCast(startAllTasks) => startAllTasks.isInstanceOf[StartAllTasks]
+ })
+
+ // Step13, Tell executor Manager the updated usage status of executors.
+ executorManager.expectMsgType[ExecutorResourceUsageSummary]
+
+ // Step14: transition from DynamicDAG to ApplicationReady
+ Env(executorManager, clockService, appMaster, executor, taskManager, scheduler)
+ }
+}
+
+object TaskManagerSpec {
+ case class Env(
+ executorManager: TestProbe,
+ clockService: TestProbe,
+ appMaster: TestProbe,
+ executor: TestProbe,
+ taskManager: ActorRef,
+ scheduler: JarScheduler)
+
+ class Task1(taskContext: TaskContext, userConf: UserConfig)
+ extends Task(taskContext, userConf) {
+ override def onStart(startTime: StartTime): Unit = {}
+ override def onNext(msg: Message): Unit = {}
+ }
+
+ class Task2(taskContext: TaskContext, userConf: UserConfig)
+ extends Task(taskContext, userConf) {
+ override def onStart(startTime: StartTime): Unit = {}
+ override def onNext(msg: Message): Unit = {}
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/TaskRegistrySpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/TaskRegistrySpec.scala b/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/TaskRegistrySpec.scala
new file mode 100644
index 0000000..6f85834
--- /dev/null
+++ b/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/TaskRegistrySpec.scala
@@ -0,0 +1,63 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.appmaster
+
+import org.apache.gearpump.cluster.scheduler.Resource
+import org.apache.gearpump.streaming.appmaster.TaskRegistry.{Accept, Reject, TaskLocation, TaskLocations}
+import org.apache.gearpump.streaming.task.TaskId
+import org.apache.gearpump.transport.HostPort
+import org.scalatest.{BeforeAndAfterEach, FlatSpec, Matchers}
+class TaskRegistrySpec extends FlatSpec with Matchers with BeforeAndAfterEach {
+
+ it should "maintain registered tasks" in {
+ val task0 = TaskId(0, 0)
+ val task1 = TaskId(0, 1)
+ val task2 = TaskId(0, 2)
+
+ val register = new TaskRegistry(expectedTasks = List(task0, task1, task2))
+ val host1 = HostPort("127.0.0.1:3000")
+ val host2 = HostPort("127.0.0.1:3001")
+
+ val executorId = 0
+ assert(Accept == register.registerTask(task0, TaskLocation(executorId, host1)))
+ assert(Accept == register.registerTask(task1, TaskLocation(executorId, host1)))
+ assert(Accept == register.registerTask(task2, TaskLocation(executorId, host2)))
+
+ assert(Reject == register.registerTask(TaskId(100, 0), TaskLocation(executorId, host2)))
+
+ assert(register.isAllTasksRegistered)
+ val TaskLocations(taskLocations) = register.getTaskLocations
+ val tasksOnHost1 = taskLocations.get(host1).get
+ val tasksOnHost2 = taskLocations.get(host2).get
+ assert(tasksOnHost1.contains(task0))
+ assert(tasksOnHost1.contains(task1))
+ assert(tasksOnHost2.contains(task2))
+
+ assert(register.getExecutorId(task0) == Some(executorId))
+ assert(register.isTaskRegisteredForExecutor(executorId))
+
+ register.processorExecutors(0) shouldBe Map(
+ executorId -> List(task0, task1, task2)
+ )
+
+ register.usedResource.resources shouldBe Map(
+ executorId -> Resource(3)
+ )
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/TaskSchedulerSpec.scala
----------------------------------------------------------------------
diff --git a/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/TaskSchedulerSpec.scala b/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/TaskSchedulerSpec.scala
new file mode 100644
index 0000000..4a532dd
--- /dev/null
+++ b/streaming/src/test/scala/org/apache/gearpump/streaming/appmaster/TaskSchedulerSpec.scala
@@ -0,0 +1,129 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.appmaster
+
+import com.typesafe.config.ConfigFactory
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.scheduler.{Relaxation, Resource, ResourceRequest}
+import org.apache.gearpump.cluster.worker.WorkerId
+import org.apache.gearpump.cluster.{TestUtil, UserConfig}
+import org.apache.gearpump.partitioner.{HashPartitioner, Partitioner}
+import org.apache.gearpump.streaming.appmaster.TaskLocator.Localities
+import org.apache.gearpump.streaming.appmaster.TaskSchedulerSpec.{TestTask1, TestTask2}
+import org.apache.gearpump.streaming.task.{StartTime, Task, TaskContext, TaskId}
+import org.apache.gearpump.streaming.{DAG, ProcessorDescription}
+import org.apache.gearpump.util.Graph
+import org.apache.gearpump.util.Graph._
+import org.scalatest.{Matchers, WordSpec}
+
+import scala.collection.mutable.ArrayBuffer
+
+class TaskSchedulerSpec extends WordSpec with Matchers {
+ val task1 = ProcessorDescription(id = 0, taskClass = classOf[TestTask1].getName, parallelism = 4)
+ val task2 = ProcessorDescription(id = 1, taskClass = classOf[TestTask2].getName, parallelism = 2)
+
+ val dag = DAG(Graph(task1 ~ Partitioner[HashPartitioner] ~> task2))
+
+ val config = TestUtil.DEFAULT_CONFIG
+
+ "TaskScheduler" should {
+ "schedule tasks on different workers properly according user's configuration" in {
+
+ val localities = Localities(
+ Map(WorkerId(1, 0L) -> Array(TaskId(0, 0), TaskId(0, 1), TaskId(1, 0), TaskId(1, 1)),
+ WorkerId(2, 0L) -> Array(TaskId(0, 2), TaskId(0, 3))
+ ))
+
+ val localityConfig = ConfigFactory.parseString(Localities.toJson(localities))
+
+ import org.apache.gearpump.streaming.Constants.GEARPUMP_STREAMING_LOCALITIES
+ val appName = "app"
+ val taskScheduler = new TaskSchedulerImpl(appId = 0, appName,
+ config.withValue(s"$GEARPUMP_STREAMING_LOCALITIES.$appName", localityConfig.root))
+
+ val expectedRequests =
+ Array(ResourceRequest(Resource(4), WorkerId(1, 0L), relaxation = Relaxation.SPECIFICWORKER),
+ ResourceRequest(Resource(2), WorkerId(2, 0L), relaxation = Relaxation.SPECIFICWORKER))
+
+ taskScheduler.setDAG(dag)
+ val resourceRequests = taskScheduler.getResourceRequests()
+
+ val acturalRequests = resourceRequests.sortBy(_.resource.slots)
+ assert(acturalRequests.sameElements(expectedRequests.sortBy(_.resource.slots)))
+
+ val tasksOnWorker1 = ArrayBuffer[Int]()
+ val tasksOnWorker2 = ArrayBuffer[Int]()
+ for (i <- 0 until 4) {
+ tasksOnWorker1.append(taskScheduler.schedule(WorkerId(1, 0L),
+ executorId = 0, Resource(1)).head.processorId)
+ }
+ for (i <- 0 until 2) {
+ tasksOnWorker2.append(taskScheduler.schedule(WorkerId(2, 0L), executorId = 1,
+ Resource(1)).head.processorId)
+ }
+
+ // Allocates more resource, and no tasks to launch
+ assert(taskScheduler.schedule(WorkerId(3, 0L), executorId = 3,
+ Resource(1)) == List.empty[TaskId])
+
+ // On worker1, executor 0
+ assert(tasksOnWorker1.sorted.sameElements(Array(0, 0, 1, 1)))
+
+ // On worker2, executor 1, Task(0, 0), Task(0, 1)
+ assert(tasksOnWorker2.sorted.sameElements(Array(0, 0)))
+
+ val rescheduledResources = taskScheduler.executorFailed(executorId = 1)
+
+ assert(rescheduledResources.sameElements(Array(ResourceRequest(Resource(2),
+ WorkerId.unspecified, relaxation = Relaxation.ONEWORKER))))
+
+ val launchedTask = taskScheduler.schedule(WorkerId(3, 0L), executorId = 3, Resource(2))
+
+ // Starts the failed 2 tasks Task(0, 0) and Task(0, 1)
+ assert(launchedTask.length == 2)
+ }
+
+ "schedule task fairly" in {
+ val appName = "app"
+ val taskScheduler = new TaskSchedulerImpl(appId = 0, appName, config)
+
+ val expectedRequests =
+ Array(ResourceRequest(Resource(4), WorkerId(1, 0L), relaxation = Relaxation.SPECIFICWORKER),
+ ResourceRequest(Resource(2), WorkerId(2, 0L), relaxation = Relaxation.SPECIFICWORKER))
+
+ taskScheduler.setDAG(dag)
+ val tasks = taskScheduler.schedule(WorkerId(1, 0L), executorId = 0, Resource(4))
+ assert(tasks.filter(_.processorId == 0).length == 2)
+ assert(tasks.filter(_.processorId == 1).length == 2)
+ }
+ }
+}
+
+object TaskSchedulerSpec {
+ class TestTask1(taskContext: TaskContext, userConf: UserConfig)
+ extends Task(taskContext, userConf) {
+ override def onStart(startTime: StartTime): Unit = Unit
+ override def onNext(msg: Message): Unit = Unit
+ }
+
+ class TestTask2(taskContext: TaskContext, userConf: UserConfig)
+ extends Task(taskContext, userConf) {
+ override def onStart(startTime: StartTime): Unit = Unit
+ override def onNext(msg: Message): Unit = Unit
+ }
+}
[37/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/org/apache/gearpump/cluster/master/AppManager.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/org/apache/gearpump/cluster/master/AppManager.scala b/daemon/src/main/scala/org/apache/gearpump/cluster/master/AppManager.scala
new file mode 100644
index 0000000..435b83e
--- /dev/null
+++ b/daemon/src/main/scala/org/apache/gearpump/cluster/master/AppManager.scala
@@ -0,0 +1,341 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.master
+
+import scala.concurrent.Future
+import scala.concurrent.duration._
+import scala.util.{Failure, Success}
+
+import akka.actor._
+import akka.pattern.ask
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.AppMasterToMaster.{AppDataSaved, SaveAppDataFailed, _}
+import org.apache.gearpump.cluster.AppMasterToWorker._
+import org.apache.gearpump.cluster.ClientToMaster._
+import org.apache.gearpump.cluster.MasterToAppMaster.{AppMasterData, AppMasterDataRequest, AppMastersDataRequest, _}
+import org.apache.gearpump.cluster.MasterToClient._
+import org.apache.gearpump.cluster.WorkerToAppMaster.{ShutdownExecutorFailed, _}
+import org.apache.gearpump.cluster.appmaster.{AppMasterRuntimeInfo, ApplicationState}
+import org.apache.gearpump.cluster.master.AppManager._
+import org.apache.gearpump.cluster.master.InMemoryKVService.{GetKVResult, PutKVResult, PutKVSuccess, _}
+import org.apache.gearpump.cluster.master.Master._
+import org.apache.gearpump.util.Constants._
+import org.apache.gearpump.util.{ActorUtil, TimeOutScheduler, Util, _}
+
+/**
+ * AppManager is dedicated child of Master to manager all applications.
+ */
+private[cluster] class AppManager(kvService: ActorRef, launcher: AppMasterLauncherFactory)
+ extends Actor with Stash with TimeOutScheduler {
+
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+
+ private val executorId: Int = APPMASTER_DEFAULT_EXECUTOR_ID
+ private val appMasterMaxRetries: Int = 5
+ private val appMasterRetryTimeRange: Duration = 20.seconds
+
+ implicit val timeout = FUTURE_TIMEOUT
+ implicit val executionContext = context.dispatcher
+
+ // Next available appId
+ private var appId: Int = 1
+
+ // From appid to appMaster data
+ private var appMasterRegistry = Map.empty[Int, (ActorRef, AppMasterRuntimeInfo)]
+
+ // Dead appmaster list
+ private var deadAppMasters = Map.empty[Int, (ActorRef, AppMasterRuntimeInfo)]
+
+ private var appMasterRestartPolicies = Map.empty[Int, RestartPolicy]
+
+ def receive: Receive = null
+
+ kvService ! GetKV(MASTER_GROUP, MASTER_STATE)
+ context.become(waitForMasterState)
+
+ def waitForMasterState: Receive = {
+ case GetKVSuccess(_, result) =>
+ val masterState = result.asInstanceOf[MasterState]
+ if (masterState != null) {
+ this.appId = masterState.maxId + 1
+ this.deadAppMasters = masterState.deadAppMasters
+ this.appMasterRegistry = masterState.appMasterRegistry
+ }
+ context.become(receiveHandler)
+ unstashAll()
+ case GetKVFailed(ex) =>
+ LOG.error("Failed to get master state, shutting down master to avoid data corruption...")
+ context.parent ! PoisonPill
+ case msg =>
+ LOG.info(s"Get message ${msg.getClass.getSimpleName}")
+ stash()
+ }
+
+ def receiveHandler: Receive = {
+ val msg = "Application Manager started. Ready for application submission..."
+ LOG.info(msg)
+ clientMsgHandler orElse appMasterMessage orElse selfMsgHandler orElse workerMessage orElse
+ appDataStoreService orElse terminationWatch
+ }
+
+ def clientMsgHandler: Receive = {
+ case SubmitApplication(app, jar, username) =>
+ LOG.info(s"Submit Application ${app.name}($appId) by $username...")
+ val client = sender
+ if (applicationNameExist(app.name)) {
+ client ! SubmitApplicationResult(Failure(
+ new Exception(s"Application name ${app.name} already existed")))
+ } else {
+ context.actorOf(launcher.props(appId, executorId, app, jar, username, context.parent,
+ Some(client)), s"launcher${appId}_${Util.randInt()}")
+
+ val appState = new ApplicationState(appId, app.name, 0, app, jar, username, null)
+ appMasterRestartPolicies += appId ->
+ new RestartPolicy(appMasterMaxRetries, appMasterRetryTimeRange)
+ kvService ! PutKV(appId.toString, APP_STATE, appState)
+ appId += 1
+ }
+
+ case RestartApplication(appId) =>
+ val client = sender()
+ (kvService ? GetKV(appId.toString, APP_STATE)).asInstanceOf[Future[GetKVResult]].map {
+ case GetKVSuccess(_, result) =>
+ val appState = result.asInstanceOf[ApplicationState]
+ if (appState != null) {
+ LOG.info(s"Shutting down the application (restart), $appId")
+ self ! ShutdownApplication(appId)
+ self.tell(SubmitApplication(appState.app, appState.jar, appState.username), client)
+ } else {
+ client ! SubmitApplicationResult(Failure(
+ new Exception(s"Failed to restart, because the application $appId does not exist.")
+ ))
+ }
+ case GetKVFailed(ex) =>
+ client ! SubmitApplicationResult(Failure(
+ new Exception(s"Unable to obtain the Master State. " +
+ s"Application $appId will not be restarted.")
+ ))
+ }
+
+ case ShutdownApplication(appId) =>
+ LOG.info(s"App Manager Shutting down application $appId")
+ val (_, info) = appMasterRegistry.getOrElse(appId, (null, null))
+ Option(info) match {
+ case Some(info) =>
+ val worker = info.worker
+ val workerPath = Option(worker).map(_.path).orNull
+ LOG.info(s"Shutdown AppMaster at ${workerPath}, appId: $appId, executorId: $executorId")
+ cleanApplicationData(appId)
+ val shutdown = ShutdownExecutor(appId, executorId,
+ s"AppMaster $appId shutdown requested by master...")
+ sendMsgWithTimeOutCallBack(worker, shutdown, 30000, shutDownExecutorTimeOut())
+ sender ! ShutdownApplicationResult(Success(appId))
+ case None =>
+ val errorMsg = s"Failed to find regisration information for appId: $appId"
+ LOG.error(errorMsg)
+ sender ! ShutdownApplicationResult(Failure(new Exception(errorMsg)))
+ }
+ case ResolveAppId(appId) =>
+ val (appMaster, _) = appMasterRegistry.getOrElse(appId, (null, null))
+ if (null != appMaster) {
+ sender ! ResolveAppIdResult(Success(appMaster))
+ } else {
+ sender ! ResolveAppIdResult(Failure(new Exception(s"Can not find Application: $appId")))
+ }
+ case AppMastersDataRequest =>
+ var appMastersData = collection.mutable.ListBuffer[AppMasterData]()
+ appMasterRegistry.foreach(pair => {
+ val (id, (appMaster: ActorRef, info: AppMasterRuntimeInfo)) = pair
+ val appMasterPath = ActorUtil.getFullPath(context.system, appMaster.path)
+ val workerPath = Option(info.worker).map(worker =>
+ ActorUtil.getFullPath(context.system, worker.path))
+ appMastersData += AppMasterData(
+ AppMasterActive, id, info.appName, appMasterPath, workerPath.orNull,
+ info.submissionTime, info.startTime, info.finishTime, info.user)
+ })
+
+ deadAppMasters.foreach(pair => {
+ val (id, (appMaster: ActorRef, info: AppMasterRuntimeInfo)) = pair
+ val appMasterPath = ActorUtil.getFullPath(context.system, appMaster.path)
+ val workerPath = Option(info.worker).map(worker =>
+ ActorUtil.getFullPath(context.system, worker.path))
+
+ appMastersData += AppMasterData(
+ AppMasterInActive, id, info.appName, appMasterPath, workerPath.orNull,
+ info.submissionTime, info.startTime, info.finishTime, info.user)
+ })
+
+ sender ! AppMastersData(appMastersData.toList)
+ case QueryAppMasterConfig(appId) =>
+ val config =
+ if (appMasterRegistry.contains(appId)) {
+ val (_, info) = appMasterRegistry(appId)
+ info.config
+ } else if (deadAppMasters.contains(appId)) {
+ val (_, info) = deadAppMasters(appId)
+ info.config
+ } else {
+ null
+ }
+ sender ! AppMasterConfig(config)
+
+ case appMasterDataRequest: AppMasterDataRequest =>
+ val appId = appMasterDataRequest.appId
+ val (appStatus, appMaster, info) =
+ if (appMasterRegistry.contains(appId)) {
+ val (appMaster, info) = appMasterRegistry(appId)
+ (AppMasterActive, appMaster, info)
+ } else if (deadAppMasters.contains(appId)) {
+ val (appMaster, info) = deadAppMasters(appId)
+ (AppMasterInActive, appMaster, info)
+ } else {
+ (AppMasterNonExist, null, null)
+ }
+
+ appStatus match {
+ case AppMasterActive | AppMasterInActive =>
+ val appMasterPath = ActorUtil.getFullPath(context.system, appMaster.path)
+ val workerPath = Option(info.worker).map(
+ worker => ActorUtil.getFullPath(context.system, worker.path)).orNull
+ sender ! AppMasterData(
+ appStatus, appId, info.appName, appMasterPath, workerPath,
+ info.submissionTime, info.startTime, info.finishTime, info.user)
+
+ case AppMasterNonExist =>
+ sender ! AppMasterData(AppMasterNonExist)
+ }
+ }
+
+ def workerMessage: Receive = {
+ case ShutdownExecutorSucceed(appId, executorId) =>
+ LOG.info(s"Shut down executor $executorId for application $appId successfully")
+ case failed: ShutdownExecutorFailed =>
+ LOG.error(failed.reason)
+ }
+
+ private def shutDownExecutorTimeOut(): Unit = {
+ LOG.error(s"Shut down executor time out")
+ }
+
+ def appMasterMessage: Receive = {
+ case RegisterAppMaster(appMaster, registerBack: AppMasterRuntimeInfo) =>
+ val startTime = System.currentTimeMillis()
+ val register = registerBack.copy(startTime = startTime)
+
+ LOG.info(s"Register AppMaster for app: ${register.appId} $register")
+ context.watch(appMaster)
+ appMasterRegistry += register.appId -> (appMaster, register)
+ kvService ! PutKV(MASTER_GROUP, MASTER_STATE,
+ MasterState(appId, appMasterRegistry, deadAppMasters))
+ sender ! AppMasterRegistered(register.appId)
+ }
+
+ def appDataStoreService: Receive = {
+ case SaveAppData(appId, key, value) =>
+ val client = sender
+ (kvService ? PutKV(appId.toString, key, value)).asInstanceOf[Future[PutKVResult]].map {
+ case PutKVSuccess =>
+ client ! AppDataSaved
+ case PutKVFailed(k, ex) =>
+ client ! SaveAppDataFailed
+ }
+ case GetAppData(appId, key) =>
+ val client = sender
+ (kvService ? GetKV(appId.toString, key)).asInstanceOf[Future[GetKVResult]].map {
+ case GetKVSuccess(privateKey, value) =>
+ client ! GetAppDataResult(key, value)
+ case GetKVFailed(ex) =>
+ client ! GetAppDataResult(key, null)
+ }
+ }
+
+ def terminationWatch: Receive = {
+ case terminate: Terminated =>
+ terminate.getAddressTerminated()
+ LOG.info(s"AppMaster(${terminate.actor.path}) is terminiated, " +
+ s"network down: ${terminate.getAddressTerminated()}")
+
+ // Now we assume that the only normal way to stop the application is submitting a
+ // ShutdownApplication request
+ val application = appMasterRegistry.find { appInfo =>
+ val (_, (actorRef, _)) = appInfo
+ actorRef.compareTo(terminate.actor) == 0
+ }
+ if (application.nonEmpty) {
+ val appId = application.get._1
+ (kvService ? GetKV(appId.toString, APP_STATE)).asInstanceOf[Future[GetKVResult]].map {
+ case GetKVSuccess(_, result) =>
+ val appState = result.asInstanceOf[ApplicationState]
+ if (appState != null) {
+ LOG.info(s"Recovering application, $appId")
+ self ! RecoverApplication(appState)
+ } else {
+ LOG.error(s"Cannot find application state for $appId")
+ }
+ case GetKVFailed(ex) =>
+ LOG.error(s"Cannot find master state to recover")
+ }
+ }
+ }
+
+ def selfMsgHandler: Receive = {
+ case RecoverApplication(state) =>
+ val appId = state.appId
+ if (appMasterRestartPolicies.get(appId).get.allowRestart) {
+ LOG.info(s"AppManager Recovering Application $appId...")
+ context.actorOf(launcher.props(appId, executorId, state.app, state.jar, state.username,
+ context.parent, None), s"launcher${appId}_${Util.randInt()}")
+ } else {
+ LOG.error(s"Application $appId failed too many times")
+ }
+ }
+
+ case class RecoverApplication(applicationStatus: ApplicationState)
+
+ private def cleanApplicationData(appId: Int): Unit = {
+ // Add the dead app to dead appMaster
+ appMasterRegistry.get(appId).foreach { pair =>
+ val (appMasterActor, info) = pair
+ deadAppMasters += appId -> (appMasterActor, info.copy(
+ finishTime = System.currentTimeMillis()))
+ }
+
+ appMasterRegistry -= appId
+
+ kvService ! PutKV(MASTER_GROUP, MASTER_STATE,
+ MasterState(this.appId, appMasterRegistry, deadAppMasters))
+ kvService ! DeleteKVGroup(appId.toString)
+ }
+
+ private def applicationNameExist(appName: String): Boolean = {
+ appMasterRegistry.values.exists(_._2.appName == appName)
+ }
+}
+
+object AppManager {
+ final val APP_STATE = "app_state"
+ // The id is used in KVStore
+ final val MASTER_STATE = "master_state"
+
+ case class MasterState(
+ maxId: Int,
+ appMasterRegistry: Map[Int, (ActorRef, AppMasterRuntimeInfo)],
+ deadAppMasters: Map[Int, (ActorRef, AppMasterRuntimeInfo)])
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/org/apache/gearpump/cluster/master/InMemoryKVService.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/org/apache/gearpump/cluster/master/InMemoryKVService.scala b/daemon/src/main/scala/org/apache/gearpump/cluster/master/InMemoryKVService.scala
new file mode 100644
index 0000000..3e54214
--- /dev/null
+++ b/daemon/src/main/scala/org/apache/gearpump/cluster/master/InMemoryKVService.scala
@@ -0,0 +1,122 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.master
+
+import java.util.concurrent.TimeUnit
+import scala.concurrent.TimeoutException
+import scala.concurrent.duration.Duration
+
+import akka.actor._
+import akka.cluster.Cluster
+import akka.cluster.ddata.Replicator._
+import akka.cluster.ddata.{DistributedData, LWWMap, LWWMapKey}
+import org.slf4j.Logger
+
+import org.apache.gearpump.util.LogUtil
+
+/**
+ * A replicated simple in-memory KV service. The replications are stored on all masters.
+ */
+class InMemoryKVService extends Actor with Stash {
+ import org.apache.gearpump.cluster.master.InMemoryKVService._
+
+ private val KV_SERVICE = "gearpump_kvservice"
+
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+ private val replicator = DistributedData(context.system).replicator
+ private implicit val cluster = Cluster(context.system)
+
+ // Optimize write path, we can tolerate one master down for recovery.
+ private val timeout = Duration(15, TimeUnit.SECONDS)
+ private val readMajority = ReadMajority(timeout)
+ private val writeMajority = WriteMajority(timeout)
+
+ private def groupKey(group: String): LWWMapKey[Any] = {
+ LWWMapKey[Any](KV_SERVICE + "_" + group)
+ }
+
+ def receive: Receive = kvService
+
+ def kvService: Receive = {
+
+ case GetKV(group: String, key: String) =>
+ val request = Request(sender(), key)
+ replicator ! Get(groupKey(group), readMajority, Some(request))
+ case success@GetSuccess(group: LWWMapKey[Any @unchecked], Some(request: Request)) =>
+ val appData = success.get(group)
+ LOG.info(s"Successfully retrived group: ${group.id}")
+ request.client ! GetKVSuccess(request.key, appData.get(request.key).orNull)
+ case NotFound(group: LWWMapKey[Any @unchecked], Some(request: Request)) =>
+ LOG.info(s"We cannot find group $group")
+ request.client ! GetKVSuccess(request.key, null)
+ case GetFailure(group: LWWMapKey[Any @unchecked], Some(request: Request)) =>
+ val error = s"Failed to get application data, the request key is ${request.key}"
+ LOG.error(error)
+ request.client ! GetKVFailed(new Exception(error))
+
+ case PutKV(group: String, key: String, value: Any) =>
+ val request = Request(sender(), key)
+ val update = Update(groupKey(group), LWWMap(), writeMajority, Some(request)) { map =>
+ map + (key -> value)
+ }
+ replicator ! update
+ case UpdateSuccess(group: LWWMapKey[Any @unchecked], Some(request: Request)) =>
+ request.client ! PutKVSuccess
+ case ModifyFailure(group: LWWMapKey[Any @unchecked], error, cause, Some(request: Request)) =>
+ request.client ! PutKVFailed(request.key, new Exception(error, cause))
+ case UpdateTimeout(group: LWWMapKey[Any @unchecked], Some(request: Request)) =>
+ request.client ! PutKVFailed(request.key, new TimeoutException())
+
+ case delete@DeleteKVGroup(group: String) =>
+ replicator ! Delete(groupKey(group), writeMajority)
+ case DeleteSuccess(group) =>
+ LOG.info(s"KV Group ${group.id} is deleted")
+ case ReplicationDeleteFailure(group) =>
+ LOG.error(s"Failed to delete KV Group ${group.id}...")
+ case DataDeleted(group) =>
+ LOG.error(s"Group ${group.id} is deleted, you can no longer put/get/delete this group...")
+ }
+}
+
+object InMemoryKVService {
+ /**
+ * KV Service related
+ */
+ case class GetKV(group: String, key: String)
+
+ trait GetKVResult
+
+ case class GetKVSuccess(key: String, value: Any) extends GetKVResult
+
+ case class GetKVFailed(ex: Throwable) extends GetKVResult
+
+ case class PutKV(group: String, key: String, value: Any)
+
+ case class DeleteKVGroup(group: String)
+
+ case class GroupDeleted(group: String) extends GetKVResult with PutKVResult
+
+ trait PutKVResult
+
+ case object PutKVSuccess extends PutKVResult
+
+ case class PutKVFailed(key: String, ex: Throwable) extends PutKVResult
+
+ case class Request(client: ActorRef, key: String)
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/org/apache/gearpump/cluster/master/Master.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/org/apache/gearpump/cluster/master/Master.scala b/daemon/src/main/scala/org/apache/gearpump/cluster/master/Master.scala
new file mode 100644
index 0000000..1536a23
--- /dev/null
+++ b/daemon/src/main/scala/org/apache/gearpump/cluster/master/Master.scala
@@ -0,0 +1,314 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.master
+
+import java.lang.management.ManagementFactory
+import org.apache.gearpump.cluster.worker.WorkerId
+
+import scala.collection.JavaConverters._
+import scala.collection.immutable
+
+import akka.actor._
+import akka.remote.DisassociatedEvent
+import com.typesafe.config.Config
+import org.apache.commons.lang.exception.ExceptionUtils
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.AppMasterToMaster._
+import org.apache.gearpump.cluster.ClientToMaster._
+import org.apache.gearpump.cluster.ClusterConfig
+import org.apache.gearpump.cluster.MasterToAppMaster._
+import org.apache.gearpump.cluster.MasterToClient.{HistoryMetrics, HistoryMetricsItem, MasterConfig, ResolveWorkerIdResult}
+import org.apache.gearpump.cluster.MasterToWorker._
+import org.apache.gearpump.cluster.WorkerToMaster._
+import org.apache.gearpump.cluster.master.InMemoryKVService._
+import org.apache.gearpump.cluster.master.Master.{MasterInfo, WorkerTerminated, _}
+import org.apache.gearpump.cluster.scheduler.Scheduler.ApplicationFinished
+import org.apache.gearpump.jarstore.local.LocalJarStore
+import org.apache.gearpump.metrics.Metrics.ReportMetrics
+import org.apache.gearpump.metrics.{JvmMetricsSet, Metrics, MetricsReporterService}
+import org.apache.gearpump.transport.HostPort
+import org.apache.gearpump.util.Constants._
+import org.apache.gearpump.util.HistoryMetricsService.HistoryMetricsConfig
+import org.apache.gearpump.util._
+
+/**
+ * Master Actor who manages resources of the whole cluster.
+ * It is like the resource manager of YARN.
+ */
+private[cluster] class Master extends Actor with Stash {
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+ private val systemConfig: Config = context.system.settings.config
+ private implicit val timeout = Constants.FUTURE_TIMEOUT
+ private val kvService = context.actorOf(Props(new InMemoryKVService()), "kvService")
+ // Resources and resourceRequests can be dynamically constructed by
+ // heartbeat of worker and appmaster when master singleton is migrated.
+ // We don't need to persist them in cluster
+ private var appManager: ActorRef = null
+
+ private var scheduler: ActorRef = null
+
+ private var workers = new immutable.HashMap[ActorRef, WorkerId]
+
+ private val birth = System.currentTimeMillis()
+
+ private var nextWorkerId = 0
+
+ def receive: Receive = null
+
+ // Register jvm metrics
+ Metrics(context.system).register(new JvmMetricsSet(s"master"))
+
+ LOG.info("master is started at " + ActorUtil.getFullPath(context.system, self.path) + "...")
+
+ val jarStoreRootPath = systemConfig.getString(Constants.GEARPUMP_APP_JAR_STORE_ROOT_PATH)
+
+ private val jarStore = if (Util.isLocalPath(jarStoreRootPath)) {
+ Some(context.actorOf(Props(classOf[LocalJarStore], jarStoreRootPath)))
+ } else {
+ None
+ }
+
+ private val hostPort = HostPort(ActorUtil.getSystemAddress(context.system).hostPort)
+
+ // Maintain the list of active masters.
+ private var masters: List[MasterNode] = {
+ // Add myself into the list of initial masters.
+ List(MasterNode(hostPort.host, hostPort.port))
+ }
+
+ val metricsEnabled = systemConfig.getBoolean(GEARPUMP_METRIC_ENABLED)
+
+ val getHistoryMetricsConfig = HistoryMetricsConfig(systemConfig)
+ val historyMetricsService = if (metricsEnabled) {
+ val historyMetricsService = {
+ context.actorOf(Props(new HistoryMetricsService("master", getHistoryMetricsConfig)))
+ }
+
+ val metricsReportService = context.actorOf(
+ Props(new MetricsReporterService(Metrics(context.system))))
+ historyMetricsService.tell(ReportMetrics, metricsReportService)
+ Some(historyMetricsService)
+ } else {
+ None
+ }
+
+ kvService ! GetKV(MASTER_GROUP, WORKER_ID)
+ context.become(waitForNextWorkerId)
+
+ def waitForNextWorkerId: Receive = {
+ case GetKVSuccess(_, result) =>
+ if (result != null) {
+ this.nextWorkerId = result.asInstanceOf[Int]
+ } else {
+ LOG.warn("Cannot find existing state in the distributed cluster...")
+ }
+ context.become(receiveHandler)
+ unstashAll()
+ case GetKVFailed(ex) =>
+ LOG.error("Failed to get worker id, shutting down master to avoid data corruption...")
+ context.parent ! PoisonPill
+ case msg =>
+ LOG.info(s"Get message ${msg.getClass.getSimpleName}")
+ stash()
+ }
+
+ def receiveHandler: Receive = workerMsgHandler orElse
+ appMasterMsgHandler orElse
+ onMasterListChange orElse
+ clientMsgHandler orElse
+ metricsService orElse
+ jarStoreService orElse
+ terminationWatch orElse
+ disassociated orElse
+ kvServiceMsgHandler orElse
+ ActorUtil.defaultMsgHandler(self)
+
+ def workerMsgHandler: Receive = {
+ case RegisterNewWorker =>
+ val workerId = WorkerId(nextWorkerId, System.currentTimeMillis())
+ nextWorkerId += 1
+ kvService ! PutKV(MASTER_GROUP, WORKER_ID, nextWorkerId)
+ val workerHostname = ActorUtil.getHostname(sender())
+ LOG.info(s"Register new from $workerHostname ....")
+ self forward RegisterWorker(workerId)
+
+ case RegisterWorker(id) =>
+ context.watch(sender())
+ sender ! WorkerRegistered(id, MasterInfo(self, birth))
+ scheduler forward WorkerRegistered(id, MasterInfo(self, birth))
+ workers += (sender() -> id)
+ val workerHostname = ActorUtil.getHostname(sender())
+ LOG.info(s"Register Worker with id $id from $workerHostname ....")
+ case resourceUpdate: ResourceUpdate =>
+ scheduler forward resourceUpdate
+ }
+
+ def jarStoreService: Receive = {
+ case GetJarStoreServer =>
+ jarStore.foreach(_ forward GetJarStoreServer)
+ }
+
+ def kvServiceMsgHandler: Receive = {
+ case PutKVSuccess =>
+ // Skip
+ case PutKVFailed(key, exception) =>
+ LOG.error(s"Put KV of key $key to InMemoryKVService failed.\n" +
+ ExceptionUtils.getStackTrace(exception))
+ }
+
+ def metricsService: Receive = {
+ case query: QueryHistoryMetrics =>
+ if (historyMetricsService.isEmpty) {
+ // Returns empty metrics so that we don't hang the UI
+ sender ! HistoryMetrics(query.path, List.empty[HistoryMetricsItem])
+ } else {
+ historyMetricsService.get forward query
+ }
+ }
+
+ def appMasterMsgHandler: Receive = {
+ case request: RequestResource =>
+ scheduler forward request
+ case registerAppMaster: RegisterAppMaster =>
+ // Forward to appManager
+ appManager forward registerAppMaster
+ case save: SaveAppData =>
+ appManager forward save
+ case get: GetAppData =>
+ appManager forward get
+ case GetAllWorkers =>
+ sender ! WorkerList(workers.values.toList)
+ case GetMasterData =>
+ val aliveFor = System.currentTimeMillis() - birth
+ val logFileDir = LogUtil.daemonLogDir(systemConfig).getAbsolutePath
+ val userDir = System.getProperty("user.dir")
+
+ val masterDescription =
+ MasterSummary(
+ MasterNode(hostPort.host, hostPort.port),
+ masters,
+ aliveFor,
+ logFileDir,
+ jarStoreRootPath,
+ MasterStatus.Synced,
+ userDir,
+ List.empty[MasterActivity],
+ jvmName = ManagementFactory.getRuntimeMXBean().getName(),
+ historyMetricsConfig = getHistoryMetricsConfig
+ )
+
+ sender ! MasterData(masterDescription)
+
+ case invalidAppMaster: InvalidAppMaster =>
+ appManager forward invalidAppMaster
+ }
+
+ import scala.util.{Failure, Success}
+
+ def onMasterListChange: Receive = {
+ case MasterListUpdated(masters: List[MasterNode]) =>
+ this.masters = masters
+ }
+
+ def clientMsgHandler: Receive = {
+ case app: SubmitApplication =>
+ LOG.debug(s"Receive from client, SubmitApplication $app")
+ appManager.forward(app)
+ case app: RestartApplication =>
+ LOG.debug(s"Receive from client, RestartApplication $app")
+ appManager.forward(app)
+ case app: ShutdownApplication =>
+ LOG.debug(s"Receive from client, Shutting down Application ${app.appId}")
+ scheduler ! ApplicationFinished(app.appId)
+ appManager.forward(app)
+ case app: ResolveAppId =>
+ LOG.debug(s"Receive from client, resolving appId ${app.appId} to ActorRef")
+ appManager.forward(app)
+ case resolve: ResolveWorkerId =>
+ LOG.debug(s"Receive from client, resolving workerId ${resolve.workerId}")
+ val worker = workers.find(_._2 == resolve.workerId)
+ worker match {
+ case Some(worker) => sender ! ResolveWorkerIdResult(Success(worker._1))
+ case None => sender ! ResolveWorkerIdResult(Failure(
+ new Exception(s"cannot find worker ${resolve.workerId}")))
+ }
+ case AppMastersDataRequest =>
+ LOG.debug("Master received AppMastersDataRequest")
+ appManager forward AppMastersDataRequest
+ case appMasterDataRequest: AppMasterDataRequest =>
+ LOG.debug("Master received AppMasterDataRequest")
+ appManager forward appMasterDataRequest
+ case query: QueryAppMasterConfig =>
+ LOG.debug("Master received QueryAppMasterConfig")
+ appManager forward query
+ case QueryMasterConfig =>
+ sender ! MasterConfig(ClusterConfig.filterOutDefaultConfig(systemConfig))
+ }
+
+ def disassociated: Receive = {
+ case disassociated: DisassociatedEvent =>
+ LOG.info(s" disassociated ${disassociated.remoteAddress}")
+ }
+
+ def terminationWatch: Receive = {
+ case t: Terminated =>
+ val actor = t.actor
+ LOG.info(s"worker ${actor.path} get terminated, is it due to network reason?" +
+ t.getAddressTerminated())
+
+ LOG.info("Let's filter out dead resources...")
+ // Filters out dead worker resource
+ if (workers.keySet.contains(actor)) {
+ scheduler ! WorkerTerminated(workers.get(actor).get)
+ workers -= actor
+ }
+ }
+
+ override def preStart(): Unit = {
+ val path = ActorUtil.getFullPath(context.system, self.path)
+ LOG.info(s"master path is $path")
+ val schedulerClass = Class.forName(
+ systemConfig.getString(Constants.GEARPUMP_SCHEDULING_SCHEDULER))
+
+ appManager = context.actorOf(Props(new AppManager(kvService, AppMasterLauncher)),
+ classOf[AppManager].getSimpleName)
+ scheduler = context.actorOf(Props(schedulerClass))
+ context.system.eventStream.subscribe(self, classOf[DisassociatedEvent])
+ }
+}
+
+object Master {
+ final val MASTER_GROUP = "master_group"
+
+ final val WORKER_ID = "next_worker_id"
+
+ case class WorkerTerminated(workerId: WorkerId)
+
+ case class MasterInfo(master: ActorRef, startTime: Long = 0L)
+
+ /** Notify the subscriber that master actor list has been updated */
+ case class MasterListUpdated(masters: List[MasterNode])
+
+ object MasterInfo {
+ def empty: MasterInfo = MasterInfo(null)
+ }
+
+ case class SlotStatus(totalSlots: Int, availableSlots: Int)
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/org/apache/gearpump/cluster/scheduler/PriorityScheduler.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/org/apache/gearpump/cluster/scheduler/PriorityScheduler.scala b/daemon/src/main/scala/org/apache/gearpump/cluster/scheduler/PriorityScheduler.scala
new file mode 100644
index 0000000..1429694
--- /dev/null
+++ b/daemon/src/main/scala/org/apache/gearpump/cluster/scheduler/PriorityScheduler.scala
@@ -0,0 +1,156 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.scheduler
+
+import org.apache.gearpump.cluster.worker.WorkerId
+
+import scala.collection.mutable
+
+import akka.actor.ActorRef
+
+import org.apache.gearpump.cluster.AppMasterToMaster.RequestResource
+import org.apache.gearpump.cluster.MasterToAppMaster.ResourceAllocated
+import org.apache.gearpump.cluster.scheduler.Relaxation._
+import org.apache.gearpump.cluster.scheduler.Scheduler.PendingRequest
+
+/** Assign resource to application based on the priority of the application */
+class PriorityScheduler extends Scheduler {
+ private var resourceRequests = new mutable.PriorityQueue[PendingRequest]()(requestOrdering)
+
+ def requestOrdering: Ordering[PendingRequest] = new Ordering[PendingRequest] {
+ override def compare(x: PendingRequest, y: PendingRequest): Int = {
+ var res = x.request.priority.id - y.request.priority.id
+ if (res == 0) {
+ res = y.timeStamp.compareTo(x.timeStamp)
+ }
+ res
+ }
+ }
+
+ override def receive: Receive = super.handleScheduleMessage orElse resourceRequestHandler
+
+ override def allocateResource(): Unit = {
+ var scheduleLater = Array.empty[PendingRequest]
+ val resourcesSnapShot = resources.clone()
+ var allocated = Resource.empty
+ val totalResource = Resource(resourcesSnapShot.values.map(_._2.slots).sum)
+
+ while (resourceRequests.nonEmpty && (allocated < totalResource)) {
+ val PendingRequest(appId, appMaster, request, timeStamp) = resourceRequests.dequeue()
+ request.relaxation match {
+ case ANY =>
+ val allocations = allocateFairly(resourcesSnapShot, request)
+ val newAllocated = Resource(allocations.map(_.resource.slots).sum)
+ if (allocations.nonEmpty) {
+ appMaster ! ResourceAllocated(allocations.toArray)
+ }
+ if (newAllocated < request.resource) {
+ val remainingRequest = request.resource - newAllocated
+ val remainingExecutors = request.executorNum - allocations.length
+ val newResourceRequest = request.copy(resource = remainingRequest,
+ executorNum = remainingExecutors)
+ scheduleLater = scheduleLater :+
+ PendingRequest(appId, appMaster, newResourceRequest, timeStamp)
+ }
+ allocated = allocated + newAllocated
+ case ONEWORKER =>
+ val availableResource = resourcesSnapShot.find { params =>
+ val (_, (_, resource)) = params
+ resource > request.resource
+ }
+ if (availableResource.nonEmpty) {
+ val (workerId, (worker, resource)) = availableResource.get
+ allocated = allocated + request.resource
+ appMaster ! ResourceAllocated(Array(ResourceAllocation(request.resource, worker,
+ workerId)))
+ resourcesSnapShot.update(workerId, (worker, resource - request.resource))
+ } else {
+ scheduleLater = scheduleLater :+ PendingRequest(appId, appMaster, request, timeStamp)
+ }
+ case SPECIFICWORKER =>
+ val workerAndResource = resourcesSnapShot.get(request.workerId)
+ if (workerAndResource.nonEmpty && workerAndResource.get._2 > request.resource) {
+ val (worker, availableResource) = workerAndResource.get
+ appMaster ! ResourceAllocated(Array(ResourceAllocation(request.resource, worker,
+ request.workerId)))
+ allocated = allocated + request.resource
+ resourcesSnapShot.update(request.workerId, (worker,
+ availableResource - request.resource))
+ } else {
+ scheduleLater = scheduleLater :+ PendingRequest(appId, appMaster, request, timeStamp)
+ }
+ }
+ }
+ for (request <- scheduleLater)
+ resourceRequests.enqueue(request)
+ }
+
+ def resourceRequestHandler: Receive = {
+ case RequestResource(appId, request) =>
+ LOG.info(s"Request resource: appId: $appId, slots: ${request.resource.slots}, " +
+ s"relaxation: ${request.relaxation}, executor number: ${request.executorNum}")
+ val appMaster = sender()
+ resourceRequests.enqueue(new PendingRequest(appId, appMaster, request,
+ System.currentTimeMillis()))
+ allocateResource()
+ }
+
+ override def doneApplication(appId: Int): Unit = {
+ resourceRequests = resourceRequests.filter(_.appId != appId)
+ }
+
+ private def allocateFairly(
+ resources: mutable.HashMap[WorkerId, (ActorRef, Resource)], request: ResourceRequest)
+ : List[ResourceAllocation] = {
+ val workerNum = resources.size
+ var allocations = List.empty[ResourceAllocation]
+ var totalAvailable = Resource(resources.values.map(_._2.slots).sum)
+ var remainingRequest = request.resource
+ var remainingExecutors = Math.min(request.executorNum, request.resource.slots)
+
+ while (remainingExecutors > 0 && !totalAvailable.isEmpty) {
+ val exeutorNum = Math.min(workerNum, remainingExecutors)
+ val toRequest = Resource(remainingRequest.slots * exeutorNum / remainingExecutors)
+
+ val sortedResources = resources.toArray.sortBy(_._2._2.slots)(Ordering[Int].reverse)
+ val pickedResources = sortedResources.take(exeutorNum)
+
+ val flattenResource = pickedResources.zipWithIndex.flatMap { workerWithIndex =>
+ val ((workerId, (worker, resource)), index) = workerWithIndex
+ 0.until(resource.slots).map(seq => ((workerId, worker), seq * workerNum + index))
+ }.sortBy(_._2).map(_._1)
+
+ if (flattenResource.length < toRequest.slots) {
+ // Can not safisfy the user's requirements
+ totalAvailable = Resource.empty
+ } else {
+ flattenResource.take(toRequest.slots).groupBy(actor => actor).mapValues(_.length).
+ toArray.foreach { params =>
+ val ((workerId, worker), slots) = params
+ resources.update(workerId, (worker, resources.get(workerId).get._2 - Resource(slots)))
+ allocations :+= ResourceAllocation(Resource(slots), worker, workerId)
+ }
+ totalAvailable -= toRequest
+ remainingRequest -= toRequest
+ remainingExecutors -= exeutorNum
+ }
+ }
+ allocations
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/org/apache/gearpump/cluster/scheduler/Scheduler.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/org/apache/gearpump/cluster/scheduler/Scheduler.scala b/daemon/src/main/scala/org/apache/gearpump/cluster/scheduler/Scheduler.scala
new file mode 100644
index 0000000..7187c1a
--- /dev/null
+++ b/daemon/src/main/scala/org/apache/gearpump/cluster/scheduler/Scheduler.scala
@@ -0,0 +1,79 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.cluster.scheduler
+
+import org.apache.gearpump.cluster.worker.WorkerId
+
+import scala.collection.mutable
+
+import akka.actor.{Actor, ActorRef}
+import org.slf4j.Logger
+
+import org.apache.gearpump.TimeStamp
+import org.apache.gearpump.cluster.MasterToWorker.{UpdateResourceFailed, UpdateResourceSucceed, WorkerRegistered}
+import org.apache.gearpump.cluster.WorkerToMaster.ResourceUpdate
+import org.apache.gearpump.cluster.master.Master.WorkerTerminated
+import org.apache.gearpump.cluster.scheduler.Scheduler.ApplicationFinished
+import org.apache.gearpump.util.LogUtil
+
+/**
+ * Scheduler schedule resource for different applications.
+ */
+abstract class Scheduler extends Actor {
+ val LOG: Logger = LogUtil.getLogger(getClass)
+ protected var resources = new mutable.HashMap[WorkerId, (ActorRef, Resource)]
+
+ def handleScheduleMessage: Receive = {
+ case WorkerRegistered(id, _) =>
+ if (!resources.contains(id)) {
+ LOG.info(s"Worker $id added to the scheduler")
+ resources.put(id, (sender, Resource.empty))
+ }
+ case update@ResourceUpdate(worker, workerId, resource) =>
+ LOG.info(s"$update...")
+ if (resources.contains(workerId)) {
+ val resourceReturned = resource > resources.get(workerId).get._2
+ resources.update(workerId, (worker, resource))
+ if (resourceReturned) {
+ allocateResource()
+ }
+ sender ! UpdateResourceSucceed
+ }
+ else {
+ sender ! UpdateResourceFailed(
+ s"ResourceUpdate failed! The worker $workerId has not been registered into master")
+ }
+ case WorkerTerminated(workerId) =>
+ if (resources.contains(workerId)) {
+ resources -= workerId
+ }
+ case ApplicationFinished(appId) =>
+ doneApplication(appId)
+ }
+
+ def allocateResource(): Unit
+
+ def doneApplication(appId: Int): Unit
+}
+
+object Scheduler {
+ case class PendingRequest(
+ appId: Int, appMaster: ActorRef, request: ResourceRequest, timeStamp: TimeStamp)
+
+ case class ApplicationFinished(appId: Int)
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/org/apache/gearpump/cluster/worker/DefaultExecutorProcessLauncher.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/org/apache/gearpump/cluster/worker/DefaultExecutorProcessLauncher.scala b/daemon/src/main/scala/org/apache/gearpump/cluster/worker/DefaultExecutorProcessLauncher.scala
new file mode 100644
index 0000000..2f1e23d
--- /dev/null
+++ b/daemon/src/main/scala/org/apache/gearpump/cluster/worker/DefaultExecutorProcessLauncher.scala
@@ -0,0 +1,41 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.cluster.worker
+
+import java.io.File
+
+import com.typesafe.config.Config
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.scheduler.Resource
+import org.apache.gearpump.util.{LogUtil, RichProcess, Util}
+
+/** Launcher to start an executor process */
+class DefaultExecutorProcessLauncher(val config: Config) extends ExecutorProcessLauncher {
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+
+ override def createProcess(
+ appId: Int, executorId: Int, resource: Resource, config: Config, options: Array[String],
+ classPath: Array[String], mainClass: String, arguments: Array[String]): RichProcess = {
+
+ LOG.info(s"Launch executor, classpath: ${classPath.mkString(File.pathSeparator)}")
+ Util.startProcess(options, classPath, mainClass, arguments)
+ }
+
+ override def cleanProcess(appId: Int, executorId: Int): Unit = {}
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/org/apache/gearpump/cluster/worker/Worker.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/org/apache/gearpump/cluster/worker/Worker.scala b/daemon/src/main/scala/org/apache/gearpump/cluster/worker/Worker.scala
new file mode 100644
index 0000000..b290938
--- /dev/null
+++ b/daemon/src/main/scala/org/apache/gearpump/cluster/worker/Worker.scala
@@ -0,0 +1,581 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.worker
+
+import java.io.File
+import java.lang.management.ManagementFactory
+import java.net.URL
+import java.util.concurrent.{Executors, TimeUnit}
+import org.apache.gearpump.cluster.worker.Worker.ExecutorWatcher
+
+import scala.concurrent.duration._
+import scala.concurrent.{ExecutionContext, Future, Promise}
+import scala.util.{Failure, Success, Try}
+
+import akka.actor.SupervisorStrategy.Stop
+import akka.actor._
+import com.typesafe.config.{ConfigValueFactory, Config, ConfigFactory}
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.AppMasterToMaster.{GetWorkerData, WorkerData}
+import org.apache.gearpump.cluster.AppMasterToWorker._
+import org.apache.gearpump.cluster.ClientToMaster.{QueryHistoryMetrics, QueryWorkerConfig}
+import org.apache.gearpump.cluster.MasterToClient.{HistoryMetrics, HistoryMetricsItem, WorkerConfig}
+import org.apache.gearpump.cluster.MasterToWorker._
+import org.apache.gearpump.cluster.WorkerToAppMaster._
+import org.apache.gearpump.cluster.WorkerToMaster._
+import org.apache.gearpump.cluster.master.Master.MasterInfo
+import org.apache.gearpump.cluster.scheduler.Resource
+import org.apache.gearpump.cluster.{ClusterConfig, ExecutorJVMConfig}
+import org.apache.gearpump.jarstore.JarStoreService
+import org.apache.gearpump.metrics.Metrics.ReportMetrics
+import org.apache.gearpump.metrics.{JvmMetricsSet, Metrics, MetricsReporterService}
+import org.apache.gearpump.util.ActorSystemBooter.Daemon
+import org.apache.gearpump.util.Constants._
+import org.apache.gearpump.util.HistoryMetricsService.HistoryMetricsConfig
+import org.apache.gearpump.util.{TimeOutScheduler, _}
+
+/**
+ * Worker is used to track the resource on single machine, it is like
+ * the node manager of YARN.
+ *
+ * @param masterProxy masterProxy is used to resolve the master
+ */
+private[cluster] class Worker(masterProxy: ActorRef) extends Actor with TimeOutScheduler {
+ private val systemConfig: Config = context.system.settings.config
+
+ private val address = ActorUtil.getFullPath(context.system, self.path)
+ private var resource = Resource.empty
+ private var allocatedResources = Map[ActorRef, Resource]()
+ private var executorsInfo = Map[ActorRef, ExecutorSlots]()
+ private var id: WorkerId = WorkerId.unspecified
+ private val createdTime = System.currentTimeMillis()
+ private var masterInfo: MasterInfo = null
+ private var executorNameToActor = Map.empty[String, ActorRef]
+ private val executorProcLauncher: ExecutorProcessLauncher = getExecutorProcLauncher()
+ private val jarStoreService = JarStoreService.get(systemConfig)
+ jarStoreService.init(systemConfig, context.system)
+
+ private val ioPool = ExecutionContext.fromExecutorService(Executors.newCachedThreadPool())
+ private val resourceUpdateTimeoutMs = 30000 // Milliseconds
+
+ private var totalSlots: Int = 0
+
+ val metricsEnabled = systemConfig.getBoolean(GEARPUMP_METRIC_ENABLED)
+ var historyMetricsService: Option[ActorRef] = None
+
+ override def receive: Receive = null
+ var LOG: Logger = LogUtil.getLogger(getClass)
+
+ def service: Receive =
+ appMasterMsgHandler orElse
+ clientMessageHandler orElse
+ metricsService orElse
+ terminationWatch(masterInfo.master) orElse
+ ActorUtil.defaultMsgHandler(self)
+
+ def metricsService: Receive = {
+ case query: QueryHistoryMetrics =>
+ if (historyMetricsService.isEmpty) {
+ // Returns empty metrics so that we don't hang the UI
+ sender ! HistoryMetrics(query.path, List.empty[HistoryMetricsItem])
+ } else {
+ historyMetricsService.get forward query
+ }
+ }
+
+ private var metricsInitialized = false
+
+ val getHistoryMetricsConfig = HistoryMetricsConfig(systemConfig)
+
+ private def initializeMetrics(): Unit = {
+ // Registers jvm metrics
+ val metricsSetName = "worker" + WorkerId.render(id)
+ Metrics(context.system).register(new JvmMetricsSet(metricsSetName))
+
+ historyMetricsService = if (metricsEnabled) {
+ val historyMetricsService = {
+ context.actorOf(Props(new HistoryMetricsService(metricsSetName, getHistoryMetricsConfig)))
+ }
+
+ val metricsReportService = context.actorOf(Props(
+ new MetricsReporterService(Metrics(context.system))))
+ historyMetricsService.tell(ReportMetrics, metricsReportService)
+ Some(historyMetricsService)
+ } else {
+ None
+ }
+ }
+
+ def waitForMasterConfirm(timeoutTicker: Cancellable): Receive = {
+
+ // If master get disconnected, the WorkerRegistered may be triggered multiple times.
+ case WorkerRegistered(id, masterInfo) =>
+ this.id = id
+
+ // Adds the flag check, so that we don't re-initialize the metrics when worker re-register
+ // itself.
+ if (!metricsInitialized) {
+ initializeMetrics()
+ metricsInitialized = true
+ }
+
+ this.masterInfo = masterInfo
+ timeoutTicker.cancel()
+ context.watch(masterInfo.master)
+ this.LOG = LogUtil.getLogger(getClass, worker = id)
+ LOG.info(s"Worker is registered. " +
+ s"actor path: ${ActorUtil.getFullPath(context.system, self.path)} ....")
+ sendMsgWithTimeOutCallBack(masterInfo.master, ResourceUpdate(self, id, resource),
+ resourceUpdateTimeoutMs, updateResourceTimeOut())
+ context.become(service)
+ }
+
+ private def updateResourceTimeOut(): Unit = {
+ LOG.error(s"Update worker resource time out")
+ }
+
+ def appMasterMsgHandler: Receive = {
+ case shutdown@ShutdownExecutor(appId, executorId, reason: String) =>
+ val actorName = ActorUtil.actorNameForExecutor(appId, executorId)
+ val executorToStop = executorNameToActor.get(actorName)
+ if (executorToStop.isDefined) {
+ LOG.info(s"Shutdown executor ${actorName}(${executorToStop.get.path.toString}) " +
+ s"due to: $reason")
+ executorToStop.get.forward(shutdown)
+ } else {
+ LOG.error(s"Cannot find executor $actorName, ignore this message")
+ sender ! ShutdownExecutorFailed(s"Can not find executor $executorId for app $appId")
+ }
+ case launch: LaunchExecutor =>
+ LOG.info(s"$launch")
+ if (resource < launch.resource) {
+ sender ! ExecutorLaunchRejected("There is no free resource on this machine")
+ } else {
+ val actorName = ActorUtil.actorNameForExecutor(launch.appId, launch.executorId)
+
+ val executor = context.actorOf(Props(classOf[ExecutorWatcher], launch, masterInfo, ioPool,
+ jarStoreService, executorProcLauncher))
+ executorNameToActor += actorName -> executor
+
+ resource = resource - launch.resource
+ allocatedResources = allocatedResources + (executor -> launch.resource)
+
+ reportResourceToMaster()
+ executorsInfo += executor ->
+ ExecutorSlots(launch.appId, launch.executorId, launch.resource.slots)
+ context.watch(executor)
+ }
+ case UpdateResourceFailed(reason, ex) =>
+ LOG.error(reason)
+ context.stop(self)
+ case UpdateResourceSucceed =>
+ LOG.info(s"Update resource succeed")
+ case GetWorkerData(workerId) =>
+ val aliveFor = System.currentTimeMillis() - createdTime
+ val logDir = LogUtil.daemonLogDir(systemConfig).getAbsolutePath
+ val userDir = System.getProperty("user.dir")
+ sender ! WorkerData(WorkerSummary(
+ id, "active",
+ address,
+ aliveFor,
+ logDir,
+ executorsInfo.values.toArray,
+ totalSlots,
+ resource.slots,
+ userDir,
+ jvmName = ManagementFactory.getRuntimeMXBean().getName(),
+ resourceManagerContainerId = systemConfig.getString(
+ GEARPUMP_WORKER_RESOURCE_MANAGER_CONTAINER_ID),
+ historyMetricsConfig = getHistoryMetricsConfig)
+ )
+ case ChangeExecutorResource(appId, executorId, usedResource) =>
+ for (executor <- executorActorRef(appId, executorId);
+ allocatedResource <- allocatedResources.get(executor)) {
+
+ allocatedResources += executor -> usedResource
+ resource = resource + allocatedResource - usedResource
+ reportResourceToMaster()
+
+ if (usedResource == Resource(0)) {
+ allocatedResources -= executor
+ // stop executor if there is no resource binded to it.
+ LOG.info(s"Shutdown executor $executorId because the resource used is zero")
+ executor ! ShutdownExecutor(appId, executorId,
+ "Shutdown executor because the resource used is zero")
+ }
+ }
+ }
+
+ private def reportResourceToMaster(): Unit = {
+ sendMsgWithTimeOutCallBack(masterInfo.master,
+ ResourceUpdate(self, id, resource), resourceUpdateTimeoutMs, updateResourceTimeOut())
+ }
+
+ private def executorActorRef(appId: Int, executorId: Int): Option[ActorRef] = {
+ val actorName = ActorUtil.actorNameForExecutor(appId, executorId)
+ executorNameToActor.get(actorName)
+ }
+
+ def clientMessageHandler: Receive = {
+ case QueryWorkerConfig(workerId) =>
+ if (this.id == workerId) {
+ sender ! WorkerConfig(ClusterConfig.filterOutDefaultConfig(systemConfig))
+ } else {
+ sender ! WorkerConfig(ConfigFactory.empty)
+ }
+ }
+
+ private def retryRegisterWorker(workerId: WorkerId, timeOutSeconds: Int): Cancellable = {
+ repeatActionUtil(
+ seconds = timeOutSeconds,
+ action = () => {
+ masterProxy ! RegisterWorker(workerId)
+ },
+ onTimeout = () => {
+ LOG.error(s"Failed to register the worker $workerId after retrying for $timeOutSeconds " +
+ s"seconds, abort and kill the worker...")
+ self ! PoisonPill
+ })
+ }
+
+ def terminationWatch(master: ActorRef): Receive = {
+ case Terminated(actor) =>
+ if (actor.compareTo(master) == 0) {
+ // Parent master is down, no point to keep worker anymore. Let's make suicide to free
+ // resources
+ LOG.info(s"Master cannot be contacted, find a new master ...")
+ context.become(waitForMasterConfirm(retryRegisterWorker(id, timeOutSeconds = 30)))
+ } else if (ActorUtil.isChildActorPath(self, actor)) {
+ // One executor is down,
+ LOG.info(s"Executor is down ${getExecutorName(actor)}")
+
+ val allocated = allocatedResources.get(actor)
+ if (allocated.isDefined) {
+ resource = resource + allocated.get
+ executorsInfo -= actor
+ allocatedResources = allocatedResources - actor
+ sendMsgWithTimeOutCallBack(master, ResourceUpdate(self, id, resource),
+ resourceUpdateTimeoutMs, updateResourceTimeOut())
+ }
+ }
+ }
+
+ private def getExecutorName(actorRef: ActorRef): Option[String] = {
+ executorNameToActor.find(_._2 == actorRef).map(_._1)
+ }
+
+ private def getExecutorProcLauncher(): ExecutorProcessLauncher = {
+ val launcherClazz = Class.forName(
+ systemConfig.getString(GEARPUMP_EXECUTOR_PROCESS_LAUNCHER))
+ launcherClazz.getConstructor(classOf[Config]).newInstance(systemConfig)
+ .asInstanceOf[ExecutorProcessLauncher]
+ }
+
+ import context.dispatcher
+ override def preStart(): Unit = {
+ LOG.info(s"RegisterNewWorker")
+ totalSlots = systemConfig.getInt(GEARPUMP_WORKER_SLOTS)
+ this.resource = Resource(totalSlots)
+ masterProxy ! RegisterNewWorker
+ context.become(waitForMasterConfirm(registerTimeoutTicker(seconds = 30)))
+ }
+
+ private def registerTimeoutTicker(seconds: Int): Cancellable = {
+ repeatActionUtil(seconds, () => Unit, () => {
+ LOG.error(s"Failed to register new worker to Master after waiting for $seconds seconds, " +
+ s"abort and kill the worker...")
+ self ! PoisonPill
+ })
+ }
+
+ private def repeatActionUtil(seconds: Int, action: () => Unit, onTimeout: () => Unit)
+ : Cancellable = {
+ val cancelTimeout = context.system.scheduler.schedule(Duration.Zero,
+ Duration(2, TimeUnit.SECONDS))(action())
+ val cancelSuicide = context.system.scheduler.scheduleOnce(seconds.seconds)(onTimeout())
+ new Cancellable {
+ def cancel(): Boolean = {
+ val result1 = cancelTimeout.cancel()
+ val result2 = cancelSuicide.cancel()
+ result1 && result2
+ }
+
+ def isCancelled: Boolean = {
+ cancelTimeout.isCancelled && cancelSuicide.isCancelled
+ }
+ }
+ }
+
+ override def postStop(): Unit = {
+ LOG.info(s"Worker is going down....")
+ ioPool.shutdown()
+ context.system.terminate()
+ }
+}
+
+private[cluster] object Worker {
+
+ case class ExecutorResult(result: Try[Int])
+
+ class ExecutorWatcher(
+ launch: LaunchExecutor,
+ masterInfo: MasterInfo,
+ ioPool: ExecutionContext,
+ jarStoreService: JarStoreService,
+ procLauncher: ExecutorProcessLauncher) extends Actor {
+ import launch.{appId, executorId, resource}
+
+ private val LOG: Logger = LogUtil.getLogger(getClass, app = appId, executor = executorId)
+
+ val executorConfig: Config = {
+ val workerConfig = context.system.settings.config
+
+ val submissionConfig = Option(launch.executorJvmConfig).flatMap { jvmConfig =>
+ Option(jvmConfig.executorAkkaConfig)
+ }.getOrElse(ConfigFactory.empty())
+
+ resolveExecutorConfig(workerConfig, submissionConfig)
+ }
+
+ // For some config, worker has priority, for others, user Application submission config
+ // have priorities.
+ private def resolveExecutorConfig(workerConfig: Config, submissionConfig: Config): Config = {
+ val config = submissionConfig.withoutPath(GEARPUMP_HOSTNAME)
+ .withoutPath(GEARPUMP_CLUSTER_MASTERS)
+ .withoutPath(GEARPUMP_HOME)
+ .withoutPath(GEARPUMP_LOG_DAEMON_DIR)
+ .withoutPath(GEARPUMP_CLUSTER_EXECUTOR_WORKER_SHARE_SAME_PROCESS)
+ // Falls back to workerConfig
+ .withFallback(workerConfig)
+
+ // Minimum supported akka.scheduler.tick-duration on Windows is 10ms
+ val duration = config.getInt(AKKA_SCHEDULER_TICK_DURATION)
+ val updatedConf = if (akka.util.Helpers.isWindows && duration < 10) {
+ LOG.warn(s"$AKKA_SCHEDULER_TICK_DURATION on Windows must be larger than 10ms, set to 10ms")
+ config.withValue(AKKA_SCHEDULER_TICK_DURATION, ConfigValueFactory.fromAnyRef(10))
+ } else {
+ config
+ }
+
+ // Excludes reference.conf, and JVM properties..
+ ClusterConfig.filterOutDefaultConfig(updatedConf)
+ }
+
+ implicit val executorService = ioPool
+
+ private val executorHandler = {
+ val ctx = launch.executorJvmConfig
+
+ if (executorConfig.getBoolean(GEARPUMP_CLUSTER_EXECUTOR_WORKER_SHARE_SAME_PROCESS)) {
+ new ExecutorHandler {
+ val exitPromise = Promise[Int]()
+ val app = context.actorOf(Props(new InJvmExecutor(launch, exitPromise)))
+
+ override def destroy(): Unit = {
+ context.stop(app)
+ }
+ override def exitValue: Future[Int] = {
+ exitPromise.future
+ }
+ }
+ } else {
+ createProcess(ctx)
+ }
+ }
+
+ private def createProcess(ctx: ExecutorJVMConfig): ExecutorHandler = {
+
+ val process = Future {
+ val jarPath = ctx.jar.map { appJar =>
+ val tempFile = File.createTempFile(appJar.name, ".jar")
+ jarStoreService.copyToLocalFile(tempFile, appJar.filePath)
+ val file = new URL("file:" + tempFile)
+ file.getFile
+ }
+
+ val configFile = {
+ val configFile = File.createTempFile("gearpump", ".conf")
+ ClusterConfig.saveConfig(executorConfig, configFile)
+ val file = new URL("file:" + configFile)
+ file.getFile
+ }
+
+ val classPath = filterOutDaemonLib(Util.getCurrentClassPath) ++
+ ctx.classPath.map(path => expandEnviroment(path)) ++
+ jarPath.map(Array(_)).getOrElse(Array.empty[String])
+
+ val appLogDir = executorConfig.getString(GEARPUMP_LOG_APPLICATION_DIR)
+ val logArgs = List(
+ s"-D${GEARPUMP_APPLICATION_ID}=${launch.appId}",
+ s"-D${GEARPUMP_EXECUTOR_ID}=${launch.executorId}",
+ s"-D${GEARPUMP_MASTER_STARTTIME}=${getFormatedTime(masterInfo.startTime)}",
+ s"-D${GEARPUMP_LOG_APPLICATION_DIR}=${appLogDir}")
+ val configArgs = List(s"-D${GEARPUMP_CUSTOM_CONFIG_FILE}=$configFile")
+
+ val username = List(s"-D${GEARPUMP_USERNAME}=${ctx.username}")
+
+ // Remote debug executor process
+ val remoteDebugFlag = executorConfig.getBoolean(GEARPUMP_REMOTE_DEBUG_EXECUTOR_JVM)
+ val remoteDebugConfig = if (remoteDebugFlag) {
+ val availablePort = Util.findFreePort().get
+ List(
+ "-Xdebug",
+ s"-Xrunjdwp:server=y,transport=dt_socket,address=${availablePort},suspend=n",
+ s"-D${GEARPUMP_REMOTE_DEBUG_PORT}=$availablePort"
+ )
+ } else {
+ List.empty[String]
+ }
+
+ val verboseGCFlag = executorConfig.getBoolean(GEARPUMP_VERBOSE_GC)
+ val verboseGCConfig = if (verboseGCFlag) {
+ List(
+ s"-Xloggc:${appLogDir}/gc-app${launch.appId}-executor-${launch.executorId}.log",
+ "-verbose:gc",
+ "-XX:+PrintGCDetails",
+ "-XX:+PrintGCDateStamps",
+ "-XX:+PrintTenuringDistribution",
+ "-XX:+PrintGCApplicationConcurrentTime",
+ "-XX:+PrintGCApplicationStoppedTime"
+ )
+ } else {
+ List.empty[String]
+ }
+
+ val ipv4 = List(s"-D${PREFER_IPV4}=true")
+
+ val options = ctx.jvmArguments ++ username ++
+ logArgs ++ remoteDebugConfig ++ verboseGCConfig ++ ipv4 ++ configArgs
+
+ LOG.info(s"Launch executor, classpath: ${classPath.mkString(File.pathSeparator)}")
+ val process = procLauncher.createProcess(appId, executorId, resource, executorConfig,
+ options, classPath, ctx.mainClass, ctx.arguments)
+
+ ProcessInfo(process, jarPath, configFile)
+ }
+
+ new ExecutorHandler {
+
+ var destroyed = false
+
+ override def destroy(): Unit = {
+ LOG.info(s"Destroy executor process ${ctx.mainClass}")
+ if (!destroyed) {
+ destroyed = true
+ process.foreach { info =>
+ info.process.destroy()
+ info.jarPath.foreach(new File(_).delete())
+ new File(info.configFile).delete()
+ }
+ }
+ }
+
+ override def exitValue: Future[Int] = {
+ process.flatMap { info =>
+ val exit = info.process.exitValue()
+ if (exit == 0) {
+ Future.successful(0)
+ } else {
+ Future.failed[Int](new Exception(s"Executor exit with failure, exit value: $exit, " +
+ s"error summary: ${info.process.logger.error}"))
+ }
+ }
+ }
+ }
+ }
+
+ private def expandEnviroment(path: String): String = {
+ // TODO: extend this to support more environment.
+ path.replace(s"<${GEARPUMP_HOME}>", executorConfig.getString(GEARPUMP_HOME))
+ }
+
+ override def preStart(): Unit = {
+ executorHandler.exitValue.onComplete { value =>
+ procLauncher.cleanProcess(appId, executorId)
+ val result = ExecutorResult(value)
+ self ! result
+ }
+ }
+
+ override def postStop(): Unit = {
+ executorHandler.destroy()
+ }
+
+ // The folders are under ${GEARPUMP_HOME}
+ val daemonPathPattern = List("lib" + File.separator + "daemon", "lib" +
+ File.separator + "yarn")
+
+ override def receive: Receive = {
+ case ShutdownExecutor(appId, executorId, reason: String) =>
+ executorHandler.destroy()
+ sender ! ShutdownExecutorSucceed(appId, executorId)
+ context.stop(self)
+ case ExecutorResult(executorResult) =>
+ executorResult match {
+ case Success(exit) => LOG.info("Executor exit normally with exit value " + exit)
+ case Failure(e) => LOG.error("Executor exit with errors", e)
+ }
+ context.stop(self)
+ }
+
+ private def getFormatedTime(timestamp: Long): String = {
+ val datePattern = "yyyy-MM-dd-HH-mm"
+ val format = new java.text.SimpleDateFormat(datePattern)
+ format.format(timestamp)
+ }
+
+ private def filterOutDaemonLib(classPath: Array[String]): Array[String] = {
+ classPath.filterNot(matchDaemonPattern(_))
+ }
+
+ private def matchDaemonPattern(path: String): Boolean = {
+ daemonPathPattern.exists(path.contains(_))
+ }
+ }
+
+ trait ExecutorHandler {
+ def destroy(): Unit
+ def exitValue: Future[Int]
+ }
+
+ case class ProcessInfo(process: RichProcess, jarPath: Option[String], configFile: String)
+
+ /**
+ * Starts the executor in the same JVM as worker.
+ */
+ class InJvmExecutor(launch: LaunchExecutor, exit: Promise[Int])
+ extends Daemon(launch.executorJvmConfig.arguments(0), launch.executorJvmConfig.arguments(1)) {
+ private val exitCode = 0
+
+ override val supervisorStrategy =
+ OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1.minute) {
+ case ex: Throwable =>
+ LOG.error(s"system $name stopped ", ex)
+ exit.failure(ex)
+ Stop
+ }
+
+ override def postStop(): Unit = {
+ if (!exit.isCompleted) {
+ exit.success(exitCode)
+ }
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/org/apache/gearpump/jarstore/dfs/DFSJarStoreService.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/org/apache/gearpump/jarstore/dfs/DFSJarStoreService.scala b/daemon/src/main/scala/org/apache/gearpump/jarstore/dfs/DFSJarStoreService.scala
new file mode 100644
index 0000000..d34f5c2
--- /dev/null
+++ b/daemon/src/main/scala/org/apache/gearpump/jarstore/dfs/DFSJarStoreService.scala
@@ -0,0 +1,76 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.jarstore.dfs
+
+import java.io.File
+
+import akka.actor.ActorSystem
+import com.typesafe.config.Config
+import org.apache.hadoop.conf.Configuration
+import org.apache.hadoop.fs.Path
+import org.apache.hadoop.fs.permission.{FsAction, FsPermission}
+import org.slf4j.Logger
+
+import org.apache.gearpump.jarstore.{FilePath, JarStoreService}
+import org.apache.gearpump.util.{Constants, LogUtil}
+
+/**
+ * DFSJarStoreService store the uploaded jar on HDFS
+ */
+class DFSJarStoreService extends JarStoreService {
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+ private var rootPath: Path = null
+
+ override val scheme: String = "hdfs"
+
+ override def init(config: Config, actorRefFactory: ActorSystem): Unit = {
+ rootPath = new Path(config.getString(Constants.GEARPUMP_APP_JAR_STORE_ROOT_PATH))
+ val fs = rootPath.getFileSystem(new Configuration())
+ if (!fs.exists(rootPath)) {
+ fs.mkdirs(rootPath, new FsPermission(FsAction.ALL, FsAction.ALL, FsAction.ALL))
+ }
+ }
+
+ /**
+ * This function will copy the remote file to local file system, called from client side.
+ *
+ * @param localFile The destination of file path
+ * @param remotePath The remote file path from JarStore
+ */
+ override def copyToLocalFile(localFile: File, remotePath: FilePath): Unit = {
+ LOG.info(s"Copying to local file: ${localFile.getAbsolutePath} from ${remotePath}")
+ val filePath = new Path(rootPath, remotePath.path)
+ val fs = filePath.getFileSystem(new Configuration())
+ val target = new Path(localFile.toURI().toString)
+ fs.copyToLocalFile(filePath, target)
+ }
+
+ /**
+ * This function will copy the local file to the remote JarStore, called from client side.
+ *
+ * @param localFile The local file
+ */
+ override def copyFromLocal(localFile: File): FilePath = {
+ val remotePath = FilePath(Math.abs(new java.util.Random().nextLong()).toString)
+ LOG.info(s"Copying from local file: ${localFile.getAbsolutePath} to ${remotePath}")
+ val filePath = new Path(rootPath, remotePath.path)
+ val fs = filePath.getFileSystem(new Configuration())
+ fs.copyFromLocalFile(new Path(localFile.toURI.toString), filePath)
+ remotePath
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/org/apache/gearpump/jarstore/local/LocalJarStore.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/org/apache/gearpump/jarstore/local/LocalJarStore.scala b/daemon/src/main/scala/org/apache/gearpump/jarstore/local/LocalJarStore.scala
new file mode 100644
index 0000000..9bd7071
--- /dev/null
+++ b/daemon/src/main/scala/org/apache/gearpump/jarstore/local/LocalJarStore.scala
@@ -0,0 +1,64 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.jarstore.local
+
+import java.io.File
+
+import akka.actor.{Actor, Stash}
+import akka.pattern.pipe
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.ClientToMaster.{GetJarStoreServer, JarStoreServerAddress}
+import org.apache.gearpump.util._
+
+/**
+ * LocalJarStore store the uploaded jar on local disk.
+ */
+class LocalJarStore(rootDirPath: String) extends Actor with Stash {
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+
+ val host = context.system.settings.config.getString(Constants.GEARPUMP_HOSTNAME)
+ val rootDirectory = new File(rootDirPath)
+
+ FileUtils.forceMkdir(rootDirectory)
+
+ val server = new FileServer(context.system, host, 0, rootDirectory)
+
+ implicit val timeout = Constants.FUTURE_TIMEOUT
+ implicit val executionContext = context.dispatcher
+
+ server.start pipeTo self
+
+ def receive: Receive = {
+ case FileServer.Port(port) =>
+ context.become(listen(port))
+ unstashAll()
+ case _ =>
+ stash()
+ }
+
+ def listen(port: Int): Receive = {
+ case GetJarStoreServer =>
+ sender ! JarStoreServerAddress(s"http://$host:$port/")
+ }
+
+ override def postStop(): Unit = {
+ server.stop
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/org/apache/gearpump/jarstore/local/LocalJarStoreService.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/org/apache/gearpump/jarstore/local/LocalJarStoreService.scala b/daemon/src/main/scala/org/apache/gearpump/jarstore/local/LocalJarStoreService.scala
new file mode 100644
index 0000000..1ab103f
--- /dev/null
+++ b/daemon/src/main/scala/org/apache/gearpump/jarstore/local/LocalJarStoreService.scala
@@ -0,0 +1,81 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.jarstore.local
+
+import java.io.File
+import java.util.concurrent.TimeUnit
+import scala.collection.JavaConverters._
+import scala.concurrent.duration.Duration
+import scala.concurrent.{Await, ExecutionContext, Future}
+
+import akka.actor.{ActorRef, ActorSystem}
+import akka.pattern.ask
+import com.typesafe.config.Config
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.ClientToMaster.{GetJarStoreServer, JarStoreServerAddress}
+import org.apache.gearpump.cluster.master.MasterProxy
+import org.apache.gearpump.jarstore.{FilePath, JarStoreService}
+import org.apache.gearpump.util._
+
+/**
+ * LocalJarStoreService store the uploaded jar on local disk.
+ */
+class LocalJarStoreService extends JarStoreService {
+ private def LOG: Logger = LogUtil.getLogger(getClass)
+ private implicit val timeout = Constants.FUTURE_TIMEOUT
+ private var system: akka.actor.ActorSystem = null
+ private var master: ActorRef = null
+ private implicit def dispatcher: ExecutionContext = system.dispatcher
+
+ override val scheme: String = "file"
+
+ override def init(config: Config, system: ActorSystem): Unit = {
+ this.system = system
+ val masters = config.getStringList(Constants.GEARPUMP_CLUSTER_MASTERS)
+ .asScala.flatMap(Util.parseHostList)
+ master = system.actorOf(MasterProxy.props(masters), s"masterproxy${Util.randInt()}")
+ }
+
+ private lazy val client = (master ? GetJarStoreServer).asInstanceOf[Future[JarStoreServerAddress]]
+ .map { address =>
+ val client = new FileServer.Client(system, address.url)
+ client
+ }
+
+ /**
+ * This function will copy the remote file to local file system, called from client side.
+ *
+ * @param localFile The destination of file path
+ * @param remotePath The remote file path from JarStore
+ */
+ override def copyToLocalFile(localFile: File, remotePath: FilePath): Unit = {
+ LOG.info(s"Copying to local file: ${localFile.getAbsolutePath} from $remotePath")
+ val future = client.flatMap(_.download(remotePath, localFile))
+ Await.ready(future, Duration(60, TimeUnit.SECONDS))
+ }
+
+ /**
+ * This function will copy the local file to the remote JarStore, called from client side.
+ * @param localFile The local file
+ */
+ override def copyFromLocal(localFile: File): FilePath = {
+ val future = client.flatMap(_.upload(localFile))
+ Await.result(future, Duration(60, TimeUnit.SECONDS))
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/daemon/src/main/scala/org/apache/gearpump/util/FileDirective.scala
----------------------------------------------------------------------
diff --git a/daemon/src/main/scala/org/apache/gearpump/util/FileDirective.scala b/daemon/src/main/scala/org/apache/gearpump/util/FileDirective.scala
new file mode 100644
index 0000000..66bb9ba
--- /dev/null
+++ b/daemon/src/main/scala/org/apache/gearpump/util/FileDirective.scala
@@ -0,0 +1,140 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.util
+
+import java.io.File
+import scala.concurrent.{ExecutionContext, Future}
+
+import akka.http.scaladsl.model.{HttpEntity, MediaTypes, Multipart}
+import akka.http.scaladsl.server.Directives._
+import akka.http.scaladsl.server._
+import akka.stream.Materializer
+import akka.stream.scaladsl.FileIO
+import akka.util.ByteString
+
+/**
+ * FileDirective is a set of Akka-http directive to upload/download
+ * huge binary files to/from Akka-Http server.
+ */
+object FileDirective {
+
+ // Form field name
+ type Name = String
+
+ val CHUNK_SIZE = 262144
+
+ /**
+ * File information after a file is uploaded to server.
+ *
+ * @param originFileName original file name when user upload it in browser.
+ * @param file file name after the file is saved to server.
+ * @param length the length of the file
+ */
+ case class FileInfo(originFileName: String, file: File, length: Long)
+
+ class Form(val fields: Map[Name, FormField]) {
+ def getFile(fieldName: String): Option[FileInfo] = {
+ fields.get(fieldName).flatMap {
+ case Left(file) => Option(file)
+ case Right(_) => None
+ }
+ }
+
+ def getValue(fieldName: String): Option[String] = {
+ fields.get(fieldName).flatMap {
+ case Left(_) => None
+ case Right(value) => Option(value)
+ }
+ }
+ }
+
+ type FormField = Either[FileInfo, String]
+
+ /**
+ * directive to uploadFile, it store the uploaded files
+ * to temporary directory, and return a Map from form field name
+ * to FileInfo.
+ */
+ def uploadFile: Directive1[Form] = {
+ uploadFileTo(null)
+ }
+
+ /**
+ * Store the uploaded files to specific rootDirectory.
+ *
+ * @param rootDirectory directory to store the files.
+ * @return
+ */
+ def uploadFileTo(rootDirectory: File): Directive1[Form] = {
+ Directive[Tuple1[Form]] { inner =>
+ extractMaterializer {implicit mat =>
+ extractExecutionContext {implicit ec =>
+ uploadFileImpl(rootDirectory)(mat, ec) { filesFuture =>
+ ctx => {
+ filesFuture.map(map => inner(Tuple1(map))).flatMap(route => route(ctx))
+ }
+ }
+ }
+ }
+ }
+ }
+
+ // Downloads file from server
+ def downloadFile(file: File): Route = {
+ val responseEntity = HttpEntity(
+ MediaTypes.`application/octet-stream`,
+ file.length,
+ FileIO.fromFile(file, CHUNK_SIZE))
+ complete(responseEntity)
+ }
+
+ private def uploadFileImpl(rootDirectory: File)(implicit mat: Materializer, ec: ExecutionContext)
+ : Directive1[Future[Form]] = {
+ Directive[Tuple1[Future[Form]]] { inner =>
+ entity(as[Multipart.FormData]) { (formdata: Multipart.FormData) =>
+ val form = formdata.parts.mapAsync(1) { p =>
+ if (p.filename.isDefined) {
+
+ // Reserve the suffix
+ val targetPath = File.createTempFile(s"userfile_${p.name}_",
+ s"${p.filename.getOrElse("")}", rootDirectory)
+ val written = p.entity.dataBytes.runWith(FileIO.toFile(targetPath))
+ written.map(written =>
+ if (written.count > 0) {
+ Map(p.name -> Left(FileInfo(p.filename.get, targetPath, written.count)))
+ } else {
+ Map.empty[Name, FormField]
+ })
+ } else {
+ val valueFuture = p.entity.dataBytes.runFold(ByteString.empty) {(total, input) =>
+ total ++ input
+ }
+ valueFuture.map{value =>
+ Map(p.name -> Right(value.utf8String))
+ }
+ }
+ }.runFold(new Form(Map.empty[Name, FormField])) {(set, value) =>
+ new Form(set.fields ++ value)
+ }
+
+ inner(Tuple1(form))
+ }
+ }
+ }
+}
\ No newline at end of file
[24/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/util/StormOutputCollector.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/util/StormOutputCollector.scala b/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/util/StormOutputCollector.scala
new file mode 100644
index 0000000..f95b840
--- /dev/null
+++ b/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/util/StormOutputCollector.scala
@@ -0,0 +1,221 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.storm.util
+
+import java.util.{ArrayList => JArrayList, Iterator => JIterator, List => JList, Map => JMap}
+import scala.collection.JavaConverters._
+
+import backtype.storm.generated.{GlobalStreamId, Grouping, JavaObject}
+import backtype.storm.grouping.CustomStreamGrouping
+import backtype.storm.task.TopologyContext
+import backtype.storm.tuple.Fields
+import backtype.storm.utils.Utils
+import org.slf4j.Logger
+
+import org.apache.gearpump._
+import org.apache.gearpump.experiments.storm.topology.GearpumpTuple
+import org.apache.gearpump.experiments.storm.util.StormUtil._
+import org.apache.gearpump.streaming.ProcessorId
+import org.apache.gearpump.streaming.task.{TaskContext, TaskId}
+import org.apache.gearpump.util.LogUtil
+
+object StormOutputCollector {
+ private val LOG: Logger = LogUtil.getLogger(classOf[StormOutputCollector])
+ private[storm] val EMPTY_LIST: JList[Integer] = new JArrayList[Integer](0)
+
+ def apply(taskContext: TaskContext, topologyContext: TopologyContext): StormOutputCollector = {
+ val stormTaskId = topologyContext.getThisTaskId
+ val componentId = topologyContext.getThisComponentId
+ val taskToComponent = topologyContext.getTaskToComponent
+ val componentToProcessorId = getComponentToProcessorId(taskToComponent.asScala.toMap)
+ val targets = topologyContext.getTargets(componentId)
+ val streamGroupers: Map[String, Grouper] =
+ targets.asScala.flatMap { case (streamId, targetGrouping) =>
+ targetGrouping.asScala.collect { case (target, grouping) if !grouping.is_set_direct() =>
+ streamId -> getGrouper(topologyContext, grouping, componentId, streamId, target)
+ }
+ }.toMap
+ val getTargetPartitionsFn = (streamId: String, values: JList[AnyRef]) => {
+ getTargetPartitions(stormTaskId, streamId, targets,
+ streamGroupers, componentToProcessorId, values)
+ }
+ new StormOutputCollector(stormTaskId, taskToComponent, targets, getTargetPartitionsFn,
+ taskContext, LatestTime)
+ }
+
+ /**
+ * get target Gearpump partitions and Storm task ids
+ */
+ private def getTargetPartitions(
+ stormTaskId: Int,
+ streamId: String,
+ targets: JMap[String, JMap[String, Grouping]],
+ streamGroupers: Map[String, Grouper],
+ componentToProcessorId: Map[String, ProcessorId],
+ values: JList[AnyRef]): (Map[String, Array[Int]], JList[Integer]) = {
+ val ret: JList[Integer] = new JArrayList[Integer](targets.size)
+
+ @annotation.tailrec
+ def getRecur(iter: JIterator[String],
+ accum: Map[String, Array[Int]]): Map[String, Array[Int]] = {
+ if (iter.hasNext) {
+ val target = iter.next
+ val grouper = streamGroupers(streamId)
+ val partitions = grouper.getPartitions(stormTaskId, values)
+ partitions.foreach { p =>
+ val stormTaskId = gearpumpTaskIdToStorm(TaskId(componentToProcessorId(target), p))
+ ret.add(stormTaskId)
+ }
+ getRecur(iter, accum + (target -> partitions))
+ } else {
+ accum
+ }
+ }
+ val targetPartitions = getRecur(targets.get(streamId).keySet().iterator,
+ Map.empty[String, Array[Int]])
+ (targetPartitions, ret)
+ }
+
+ private def getComponentToProcessorId(taskToComponent: Map[Integer, String])
+ : Map[String, ProcessorId] = {
+ taskToComponent.map { case (id, component) =>
+ component -> stormTaskIdToGearpump(id).processorId
+ }
+ }
+
+ private def getGrouper(topologyContext: TopologyContext, grouping: Grouping,
+ source: String, streamId: String, target: String): Grouper = {
+ val outFields = topologyContext.getComponentOutputFields(source, streamId)
+ val targetTasks = topologyContext.getComponentTasks(target)
+ val targetTaskNum = targetTasks.size
+ val globalStreamId = new GlobalStreamId(source, streamId)
+
+ grouping.getSetField match {
+ case Grouping._Fields.FIELDS =>
+ if (isGlobalGrouping(grouping)) {
+ new GlobalGrouper
+ } else {
+ new FieldsGrouper(outFields, new Fields(grouping.get_fields()), targetTaskNum)
+ }
+ case Grouping._Fields.SHUFFLE =>
+ new ShuffleGrouper(targetTaskNum)
+ case Grouping._Fields.NONE =>
+ new NoneGrouper(targetTaskNum)
+ case Grouping._Fields.ALL =>
+ new AllGrouper(targetTaskNum)
+ case Grouping._Fields.CUSTOM_SERIALIZED =>
+ val customGrouping = Utils.javaDeserialize(grouping.get_custom_serialized,
+ classOf[Serializable]).asInstanceOf[CustomStreamGrouping]
+ val grouper = new CustomGrouper(customGrouping)
+ grouper.prepare(topologyContext, globalStreamId, targetTasks)
+ grouper
+ case Grouping._Fields.CUSTOM_OBJECT =>
+ val customObject = grouping.get_custom_object()
+ val customGrouping = instantiateJavaObject(customObject)
+ val grouper = new CustomGrouper(customGrouping)
+ grouper.prepare(topologyContext, globalStreamId, targetTasks)
+ grouper
+ case Grouping._Fields.LOCAL_OR_SHUFFLE =>
+ // Gearpump has built-in support for sending messages to local actor
+ new ShuffleGrouper(targetTaskNum)
+ case Grouping._Fields.DIRECT =>
+ throw new Exception("direct grouping should not be called here")
+ }
+ }
+
+ private def isGlobalGrouping(grouping: Grouping): Boolean = {
+ grouping.getSetField == Grouping._Fields.FIELDS &&
+ grouping.get_fields.isEmpty
+ }
+
+ private def instantiateJavaObject(javaObject: JavaObject): CustomStreamGrouping = {
+ val className = javaObject.get_full_class_name()
+ val args = javaObject.get_args_list().asScala.map(_.getFieldValue)
+ val customGrouping = Class.forName(className).getConstructor(args.map(_.getClass): _*)
+ .newInstance(args).asInstanceOf[CustomStreamGrouping]
+ customGrouping
+ }
+}
+
+/**
+ * Provides common functionality for
+ * [[org.apache.gearpump.experiments.storm.producer.StormSpoutOutputCollector]]
+ * and [[org.apache.gearpump.experiments.storm.processor.StormBoltOutputCollector]]
+ */
+class StormOutputCollector(
+ stormTaskId: Int,
+ taskToComponent: JMap[Integer, String],
+ targets: JMap[String, JMap[String, Grouping]],
+ getTargetPartitionsFn: (String, JList[AnyRef]) => (Map[String, Array[Int]], JList[Integer]),
+ val taskContext: TaskContext,
+ private var timestamp: TimeStamp) {
+ import org.apache.gearpump.experiments.storm.util.StormOutputCollector._
+
+ /**
+ * Emits tuple values into a stream (invoked by a Storm output collector).
+ *
+ * wrapS the values into a message of [[GearpumpTuple]] along with the target partitions
+ * to tell [[org.apache.gearpump.experiments.storm.partitioner.StormPartitioner]] where to send
+ * the message. We also return the corresponding target Storm task ids back to the collector
+ *
+ * @param streamId Storm stream id
+ * @param values Storm tuple values
+ * @return Target Storm task ids
+ */
+ def emit(streamId: String, values: JList[AnyRef]): JList[Integer] = {
+ if (targets.containsKey(streamId)) {
+ val (targetPartitions, targetStormTaskIds) = getTargetPartitionsFn(streamId, values)
+ val tuple = new GearpumpTuple(values, stormTaskId, streamId, targetPartitions)
+ taskContext.output(Message(tuple, timestamp))
+ targetStormTaskIds
+ } else {
+ EMPTY_LIST
+ }
+ }
+
+ /**
+ * Emit tuple values to a specific Storm task (invoked by Storm output collector).
+ *
+ * We translate the Storm task id into Gearpump TaskId and tell
+ * [[org.apache.gearpump.experiments.storm.partitioner.StormPartitioner]] through the
+ * targetPartitions field of [[org.apache.gearpump.experiments.storm.topology.GearpumpTuple]]
+ *
+ * @param id Storm task id
+ * @param streamId Storm stream id
+ * @param values Storm tuple values
+ */
+ def emitDirect(id: Int, streamId: String, values: JList[AnyRef]): Unit = {
+ if (targets.containsKey(streamId)) {
+ val target = taskToComponent.get(id)
+ val partition = stormTaskIdToGearpump(id).index
+ val targetPartitions = Map(target -> Array(partition))
+ val tuple = new GearpumpTuple(values, stormTaskId, streamId, targetPartitions)
+ taskContext.output(Message(tuple, timestamp))
+ }
+ }
+
+ /**
+ * set timestamp from each incoming Message if not attached.
+ */
+ def setTimestamp(timestamp: TimeStamp): Unit = {
+ this.timestamp = timestamp
+ }
+
+ def getTimestamp: Long = timestamp
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/util/StormSerializationFramework.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/util/StormSerializationFramework.scala b/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/util/StormSerializationFramework.scala
new file mode 100644
index 0000000..8bffc55
--- /dev/null
+++ b/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/util/StormSerializationFramework.scala
@@ -0,0 +1,82 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.experiments.storm.util
+
+import java.lang.{Integer => JInteger}
+import java.util.{Map => JMap}
+
+import akka.actor.ExtendedActorSystem
+import backtype.storm.serialization.SerializationFactory
+import backtype.storm.utils.ListDelegate
+import com.esotericsoftware.kryo.Kryo
+import com.esotericsoftware.kryo.io.{Input, Output}
+
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.experiments.storm.topology.GearpumpTuple
+import org.apache.gearpump.experiments.storm.util.StormConstants._
+import org.apache.gearpump.serializer.{SerializationFramework, Serializer}
+
+class StormSerializationFramework extends SerializationFramework {
+ private var stormConfig: JMap[AnyRef, AnyRef] = null
+ private var pool: ThreadLocal[Serializer] = null
+
+ override def init(system: ExtendedActorSystem, config: UserConfig): Unit = {
+ implicit val actorSystem = system
+ stormConfig = config.getValue[JMap[AnyRef, AnyRef]](STORM_CONFIG).get
+ pool = new ThreadLocal[Serializer]() {
+ override def initialValue(): Serializer = {
+ val kryo = SerializationFactory.getKryo(stormConfig)
+ new StormSerializer(kryo)
+ }
+ }
+ }
+
+ override def get(): Serializer = {
+ pool.get()
+ }
+}
+
+/**
+ * serializes / deserializes [[org.apache.gearpump.experiments.storm.topology.GearpumpTuple]]
+ *
+ * @param kryo created by Storm [[backtype.storm.serialization.SerializationFactory]]
+ */
+class StormSerializer(kryo: Kryo) extends Serializer {
+ // -1 means the max buffer size is 2147483647
+ private val output = new Output(4096, -1)
+ private val input = new Input
+
+ override def serialize(message: Any): Array[Byte] = {
+ val tuple = message.asInstanceOf[GearpumpTuple]
+ output.clear()
+ output.writeInt(tuple.sourceTaskId)
+ output.writeString(tuple.sourceStreamId)
+ val listDelegate = new ListDelegate
+ listDelegate.setDelegate(tuple.values)
+ kryo.writeObject(output, listDelegate)
+ output.toBytes
+ }
+
+ override def deserialize(msg: Array[Byte]): Any = {
+ input.setBuffer(msg)
+ val sourceTaskId: JInteger = input.readInt
+ val sourceStreamId: String = input.readString
+ val listDelegate = kryo.readObject[ListDelegate](input, classOf[ListDelegate])
+ new GearpumpTuple(listDelegate.getDelegate, sourceTaskId, sourceStreamId, null)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/util/StormUtil.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/util/StormUtil.scala b/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/util/StormUtil.scala
new file mode 100644
index 0000000..40e36a6
--- /dev/null
+++ b/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/util/StormUtil.scala
@@ -0,0 +1,136 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.storm.util
+
+import java.lang.{Boolean => JBoolean}
+import java.util.{HashMap => JHashMap, Map => JMap}
+
+import akka.actor.ActorSystem
+import backtype.storm.Config
+import backtype.storm.generated._
+import org.apache.storm.shade.org.json.simple.JSONValue
+
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.experiments.storm.topology.GearpumpStormComponent.{GearpumpBolt, GearpumpSpout}
+import org.apache.gearpump.experiments.storm.topology._
+import org.apache.gearpump.experiments.storm.util.StormConstants._
+import org.apache.gearpump.streaming.task.{TaskContext, TaskId}
+import org.apache.gearpump.util.Util
+
+object StormUtil {
+
+ /**
+ * Convert storm task id to gearpump [[org.apache.gearpump.streaming.task.TaskId]]
+ *
+ * The high 16 bit of an Int is TaskId.processorId
+ * The low 16 bit of an Int is TaskId.index
+ */
+ def stormTaskIdToGearpump(id: Integer): TaskId = {
+ val index = id & 0xFFFF
+ val processorId = id >> 16
+ TaskId(processorId, index)
+ }
+
+ /**
+ * convert gearpump [[TaskId]] to storm task id
+ * TaskId.processorId is the high 16 bit of an Int
+ * TaskId.index is the low 16 bit of an Int
+ */
+ def gearpumpTaskIdToStorm(taskId: TaskId): Integer = {
+ val index = taskId.index
+ val processorId = taskId.processorId
+ (processorId << 16) + (index & 0xFFFF)
+ }
+
+ /**
+ * @return a configured [[GearpumpStormComponent]]
+ */
+ def getGearpumpStormComponent(
+ taskContext: TaskContext, conf: UserConfig)(implicit system: ActorSystem)
+ : GearpumpStormComponent = {
+ val topology = conf.getValue[StormTopology](STORM_TOPOLOGY).get
+ val stormConfig = conf.getValue[JMap[AnyRef, AnyRef]](STORM_CONFIG).get
+ val componentId = conf.getString(STORM_COMPONENT).get
+ val spouts = topology.get_spouts
+ val bolts = topology.get_bolts
+ if (spouts.containsKey(componentId)) {
+ GearpumpSpout(topology, stormConfig, spouts.get(componentId), taskContext)
+ } else if (bolts.containsKey(componentId)) {
+ GearpumpBolt(topology, stormConfig, bolts.get(componentId), taskContext)
+ } else {
+ throw new Exception(s"storm component $componentId not found")
+ }
+ }
+
+ /**
+ * Parses config in json to map, returns empty map for invalid json string
+ *
+ * @param json config in json
+ * @return config in map
+ */
+ def parseJsonStringToMap(json: String): JMap[AnyRef, AnyRef] = {
+ Option(json).flatMap(json => JSONValue.parse(json) match {
+ case m: JMap[_, _] => Option(m.asInstanceOf[JMap[AnyRef, AnyRef]])
+ case _ => None
+ }).getOrElse(new JHashMap[AnyRef, AnyRef])
+ }
+
+ /**
+ * get Int value of the config name
+ */
+ def getInt(conf: JMap[_, _], name: String): Option[Int] = {
+ Option(conf.get(name)).map {
+ case number: Number => number.intValue
+ case invalid => throw new IllegalArgumentException(
+ s"$name must be Java Integer; actual: ${invalid.getClass}")
+ }
+ }
+
+ /**
+ * get Boolean value of the config name
+ */
+ def getBoolean(conf: JMap[_, _], name: AnyRef): Option[Boolean] = {
+ Option(conf.get(name)).map {
+ case b: JBoolean => b.booleanValue()
+ case invalid => throw new IllegalArgumentException(
+ s"$name must be a Java Boolean; acutal: ${invalid.getClass}")
+ }
+ }
+
+ /**
+ * clojure mod ported from Storm
+ * see https://clojuredocs.org/clojure.core/mod
+ */
+ def mod(num: Int, div: Int): Int = {
+ (num % div + div) % div
+ }
+
+ def ackEnabled(config: JMap[AnyRef, AnyRef]): Boolean = {
+ if (config.containsKey(Config.TOPOLOGY_ACKER_EXECUTORS)) {
+ getInt(config, Config.TOPOLOGY_ACKER_EXECUTORS).map(_ != 0).getOrElse(true)
+ } else {
+ false
+ }
+ }
+
+ def getThriftPort(): Int = {
+ Util.findFreePort().getOrElse(
+ throw new Exception("unable to find free port for thrift server"))
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/test/scala/io/gearpump/experiments/storm/partitioner/StormPartitionerSpec.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/test/scala/io/gearpump/experiments/storm/partitioner/StormPartitionerSpec.scala b/experiments/storm/src/test/scala/io/gearpump/experiments/storm/partitioner/StormPartitionerSpec.scala
deleted file mode 100644
index ed4a6bb..0000000
--- a/experiments/storm/src/test/scala/io/gearpump/experiments/storm/partitioner/StormPartitionerSpec.scala
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.storm.partitioner
-
-import java.util.{List => JList}
-import scala.collection.JavaConverters._
-
-import org.scalacheck.Gen
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{Matchers, PropSpec}
-
-import io.gearpump.Message
-import io.gearpump.experiments.storm.topology.GearpumpTuple
-import io.gearpump.partitioner.Partitioner
-
-class StormPartitionerSpec extends PropSpec with PropertyChecks with Matchers {
-
- property("StormPartitioner should get partitions directed by message and target") {
- val idGen = Gen.chooseNum[Int](0, Int.MaxValue)
- val componentsGen = Gen.listOf[String](Gen.alphaStr).map(_.distinct).suchThat(_.size > 1)
- val partitionsGen = Gen.listOf[Int](idGen).suchThat(_.nonEmpty).map(_.distinct.sorted.toArray)
- val tupleFactoryGen = for {
- values <- Gen.listOf[String](Gen.alphaStr).map(_.asJava.asInstanceOf[JList[AnyRef]])
- sourceTaskId <- idGen
- sourceStreamId <- Gen.alphaStr
- } yield (targetPartitions: Map[String, Array[Int]]) => {
- new GearpumpTuple(values, new Integer(sourceTaskId), sourceStreamId, targetPartitions)
- }
-
- forAll(tupleFactoryGen, idGen, componentsGen, partitionsGen) {
- (tupleFactory: Map[String, Array[Int]] => GearpumpTuple, id: Int,
- components: List[String], partitions: Array[Int]) => {
- val currentPartitionId = id
- val targetPartitions = components.init.map(c => (c, partitions)).toMap
- val tuple = tupleFactory(targetPartitions)
- targetPartitions.foreach {
- case (target, ps) => {
- val partitioner = new StormPartitioner(target)
- ps shouldBe partitioner.getPartitions(Message(tuple), ps.last + 1, currentPartitionId)
- }
- }
- val partitionNum = id
- val nonTarget = components.last
- val partitioner = new StormPartitioner(nonTarget)
-
- partitioner.getPartitions(Message(tuple), partitionNum,
- currentPartitionId) shouldBe List(Partitioner.UNKNOWN_PARTITION_ID)
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/test/scala/io/gearpump/experiments/storm/processor/StormBoltOutputCollectorSpec.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/test/scala/io/gearpump/experiments/storm/processor/StormBoltOutputCollectorSpec.scala b/experiments/storm/src/test/scala/io/gearpump/experiments/storm/processor/StormBoltOutputCollectorSpec.scala
deleted file mode 100644
index 64cabd5..0000000
--- a/experiments/storm/src/test/scala/io/gearpump/experiments/storm/processor/StormBoltOutputCollectorSpec.scala
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.storm.processor
-
-import java.util.{List => JList}
-import scala.collection.JavaConverters._
-
-import backtype.storm.tuple.Tuple
-import backtype.storm.utils.Utils
-import org.mockito.Mockito._
-import org.scalacheck.Gen
-import org.scalatest.mock.MockitoSugar
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{Matchers, PropSpec}
-
-import io.gearpump.experiments.storm.util.StormOutputCollector
-
-class StormBoltOutputCollectorSpec
- extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
-
- property("StormBoltOutputCollector should call StormOutputCollector") {
- val valGen = Gen.oneOf(Gen.alphaStr, Gen.alphaChar, Gen.chooseNum[Int](0, 1000))
- val valuesGen = Gen.listOf[AnyRef](valGen)
-
- forAll(valuesGen) { (values: List[AnyRef]) =>
- val collector = mock[StormOutputCollector]
- val boltCollector = new StormBoltOutputCollector(collector)
- val streamId = Utils.DEFAULT_STREAM_ID
- boltCollector.emit(streamId, null, values.asJava)
- verify(collector).emit(streamId, values.asJava)
- }
- }
-
- property("StormBoltOutputCollector should throw on fail") {
- val collector = mock[StormOutputCollector]
- val tuple = mock[Tuple]
- val boltCollector = new StormBoltOutputCollector(collector)
- an[Exception] should be thrownBy boltCollector.fail(tuple)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/test/scala/io/gearpump/experiments/storm/processor/StormProcessorSpec.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/test/scala/io/gearpump/experiments/storm/processor/StormProcessorSpec.scala b/experiments/storm/src/test/scala/io/gearpump/experiments/storm/processor/StormProcessorSpec.scala
deleted file mode 100644
index a3a8196..0000000
--- a/experiments/storm/src/test/scala/io/gearpump/experiments/storm/processor/StormProcessorSpec.scala
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.storm.processor
-
-import org.mockito.Mockito._
-import org.scalatest.mock.MockitoSugar
-import org.scalatest.{Matchers, WordSpec}
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.experiments.storm.topology.GearpumpStormComponent.GearpumpBolt
-import io.gearpump.streaming.MockUtil
-import io.gearpump.streaming.task.StartTime
-
-class StormProcessorSpec extends WordSpec with Matchers with MockitoSugar {
-
- "StormProcessor" should {
- "start GearpumpSpout onStart" in {
- val startTime = mock[StartTime]
- val gearpumpBolt = mock[GearpumpBolt]
- when(gearpumpBolt.getTickFrequency).thenReturn(None)
- val taskContext = MockUtil.mockTaskContext
- val userConfig = UserConfig.empty
- val stormProcessor = new StormProcessor(gearpumpBolt, taskContext, userConfig)
-
- stormProcessor.onStart(startTime)
-
- verify(gearpumpBolt).start(startTime)
- }
-
- "pass message to GearpumpBolt onNext" in {
- val message = mock[Message]
- val gearpumpBolt = mock[GearpumpBolt]
- val freq = 5
- when(gearpumpBolt.getTickFrequency).thenReturn(Some(freq))
- val taskContext = MockUtil.mockTaskContext
- val userConfig = UserConfig.empty
- val stormProcessor = new StormProcessor(gearpumpBolt, taskContext, userConfig)
-
- stormProcessor.onNext(message)
-
- verify(gearpumpBolt).next(message)
-
- stormProcessor.onNext(StormProcessor.TICK)
-
- verify(gearpumpBolt).tick(freq)
- }
- }
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/test/scala/io/gearpump/experiments/storm/producer/StormProducerSpec.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/test/scala/io/gearpump/experiments/storm/producer/StormProducerSpec.scala b/experiments/storm/src/test/scala/io/gearpump/experiments/storm/producer/StormProducerSpec.scala
deleted file mode 100644
index 8c10afc..0000000
--- a/experiments/storm/src/test/scala/io/gearpump/experiments/storm/producer/StormProducerSpec.scala
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.storm.producer
-
-import akka.testkit.TestProbe
-import org.mockito.Mockito._
-import org.scalatest.mock.MockitoSugar
-import org.scalatest.{Matchers, WordSpec}
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.experiments.storm.topology.GearpumpStormComponent.GearpumpSpout
-import io.gearpump.streaming.MockUtil
-import io.gearpump.streaming.task.StartTime
-
-class StormProducerSpec extends WordSpec with Matchers with MockitoSugar {
-
- "StormProducer" should {
- "start GearpumpSpout onStart" in {
- val startTime = mock[StartTime]
- val gearpumpSpout = mock[GearpumpSpout]
- when(gearpumpSpout.getMessageTimeout).thenReturn(None)
- val taskContext = MockUtil.mockTaskContext
- implicit val actorSystem = taskContext.system
- val taskActor = TestProbe()
- when(taskContext.self).thenReturn(taskActor.ref)
- val userConfig = UserConfig.empty
- val stormProducer = new StormProducer(gearpumpSpout, taskContext, userConfig)
-
- stormProducer.onStart(startTime)
-
- verify(gearpumpSpout).start(startTime)
- taskActor.expectMsg(Message("start"))
- }
-
- "pass message to GearpumpBolt onNext" in {
- val message = mock[Message]
- val gearpumpSpout = mock[GearpumpSpout]
- val timeout = 5L
- when(gearpumpSpout.getMessageTimeout).thenReturn(Some(timeout))
- val taskContext = MockUtil.mockTaskContext
- implicit val actorSystem = taskContext.system
- val taskActor = TestProbe()
- when(taskContext.self).thenReturn(taskActor.ref)
- val userConfig = UserConfig.empty
- val stormProducer = new StormProducer(gearpumpSpout, taskContext, userConfig)
-
- stormProducer.onNext(message)
-
- verify(gearpumpSpout).next(message)
- taskActor.expectMsg(Message("continue"))
-
- stormProducer.onNext(StormProducer.TIMEOUT)
- verify(gearpumpSpout).timeout(timeout)
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/test/scala/io/gearpump/experiments/storm/producer/StormSpoutOutputCollectorSpec.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/test/scala/io/gearpump/experiments/storm/producer/StormSpoutOutputCollectorSpec.scala b/experiments/storm/src/test/scala/io/gearpump/experiments/storm/producer/StormSpoutOutputCollectorSpec.scala
deleted file mode 100644
index e638da9..0000000
--- a/experiments/storm/src/test/scala/io/gearpump/experiments/storm/producer/StormSpoutOutputCollectorSpec.scala
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.storm.producer
-
-import java.util.{List => JList}
-import scala.collection.JavaConverters._
-
-import backtype.storm.spout.ISpout
-import backtype.storm.utils.Utils
-import org.mockito.Mockito._
-import org.scalacheck.Gen
-import org.scalatest.mock.MockitoSugar
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{Matchers, PropSpec}
-
-import io.gearpump.experiments.storm.util.StormOutputCollector
-
-class StormSpoutOutputCollectorSpec
- extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
-
- property("StormSpoutOutputCollector should call StormOutputCollector") {
- val valGen = Gen.oneOf(Gen.alphaStr, Gen.alphaChar, Gen.chooseNum[Int](0, 1000))
- val valuesGen = Gen.listOf[AnyRef](valGen)
-
- forAll(valuesGen) { (values: List[AnyRef]) =>
- val collector = mock[StormOutputCollector]
- val spout = mock[ISpout]
- val streamId = Utils.DEFAULT_STREAM_ID
- val spoutCollector = new StormSpoutOutputCollector(collector, spout, false)
- spoutCollector.emit(streamId, values.asJava, null)
- verify(collector).emit(streamId, values.asJava)
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/test/scala/io/gearpump/experiments/storm/topology/GearpumpStormComponentSpec.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/test/scala/io/gearpump/experiments/storm/topology/GearpumpStormComponentSpec.scala b/experiments/storm/src/test/scala/io/gearpump/experiments/storm/topology/GearpumpStormComponentSpec.scala
deleted file mode 100644
index 319ee27..0000000
--- a/experiments/storm/src/test/scala/io/gearpump/experiments/storm/topology/GearpumpStormComponentSpec.scala
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.experiments.storm.topology
-
-import java.util.{Map => JMap}
-
-import akka.actor.ActorRef
-import backtype.storm.spout.{ISpout, SpoutOutputCollector}
-import backtype.storm.task.{GeneralTopologyContext, IBolt, OutputCollector, TopologyContext}
-import backtype.storm.tuple.Tuple
-import org.mockito.Matchers.{anyObject, eq => mockitoEq}
-import org.mockito.Mockito._
-import org.scalacheck.Gen
-import org.scalatest.mock.MockitoSugar
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{Matchers, PropSpec}
-
-import io.gearpump.experiments.storm.producer.StormSpoutOutputCollector
-import io.gearpump.experiments.storm.topology.GearpumpStormComponent.{GearpumpBolt, GearpumpSpout}
-import io.gearpump.experiments.storm.util.StormOutputCollector
-import io.gearpump.streaming.task.{StartTime, TaskContext, TaskId}
-import io.gearpump.streaming.{DAG, MockUtil}
-import io.gearpump.{Message, TimeStamp}
-
-class GearpumpStormComponentSpec
- extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
-
- property("GearpumpSpout lifecycle") {
- val config = mock[JMap[AnyRef, AnyRef]]
- val spout = mock[ISpout]
- val taskContext = MockUtil.mockTaskContext
- val appMaster = mock[ActorRef]
- when(taskContext.appMaster).thenReturn(appMaster)
- val getDAG = mock[ActorRef => DAG]
- val dag = mock[DAG]
- when(getDAG(appMaster)).thenReturn(dag)
- val getTopologyContext = mock[(DAG, TaskId) => TopologyContext]
- val topologyContext = mock[TopologyContext]
- when(getTopologyContext(dag, taskContext.taskId)).thenReturn(topologyContext)
- val getOutputCollector = mock[(TaskContext, TopologyContext) => StormSpoutOutputCollector]
- val outputCollector = mock[StormSpoutOutputCollector]
- when(getOutputCollector(taskContext, topologyContext)).thenReturn(outputCollector)
-
- val gearpumpSpout = GearpumpSpout(config, spout, getDAG, getTopologyContext,
- getOutputCollector, ackEnabled = false, taskContext)
-
- // Start
- val startTime = mock[StartTime]
- gearpumpSpout.start(startTime)
-
- verify(spout).open(mockitoEq(config), mockitoEq(topologyContext),
- anyObject[SpoutOutputCollector])
-
- // Next
- val message = mock[Message]
- gearpumpSpout.next(message)
-
- verify(spout).nextTuple()
- }
-
- property("GearpumpBolt lifecycle") {
- val timestampGen = Gen.chooseNum[Long](0L, 1000L)
- val freqGen = Gen.chooseNum[Int](1, 100)
- forAll(timestampGen, freqGen) { (timestamp: TimeStamp, freq: Int) =>
- val config = mock[JMap[AnyRef, AnyRef]]
- val bolt = mock[IBolt]
- val taskContext = MockUtil.mockTaskContext
- val appMaster = mock[ActorRef]
- when(taskContext.appMaster).thenReturn(appMaster)
- val getDAG = mock[ActorRef => DAG]
- val dag = mock[DAG]
- when(getDAG(appMaster)).thenReturn(dag)
- val getTopologyContext = mock[(DAG, TaskId) => TopologyContext]
- val topologyContext = mock[TopologyContext]
- when(getTopologyContext(dag, taskContext.taskId)).thenReturn(topologyContext)
- val getGeneralTopologyContext = mock[DAG => GeneralTopologyContext]
- val generalTopologyContext = mock[GeneralTopologyContext]
- when(getGeneralTopologyContext(dag)).thenReturn(generalTopologyContext)
- val getOutputCollector = mock[(TaskContext, TopologyContext) => StormOutputCollector]
- val stormOutputCollector = mock[StormOutputCollector]
- when(getOutputCollector(taskContext, topologyContext)).thenReturn(stormOutputCollector)
- val getTickTuple = mock[(GeneralTopologyContext, Int) => Tuple]
- val tickTuple = mock[Tuple]
- when(getTickTuple(mockitoEq(generalTopologyContext), anyObject[Int]())).thenReturn(tickTuple)
- val gearpumpBolt = GearpumpBolt(config, bolt, getDAG, getTopologyContext,
- getGeneralTopologyContext, getOutputCollector, getTickTuple, taskContext)
-
- // Start
- val startTime = mock[StartTime]
- gearpumpBolt.start(startTime)
-
- verify(bolt).prepare(mockitoEq(config), mockitoEq(topologyContext),
- anyObject[OutputCollector])
-
- // Next
- val gearpumpTuple = mock[GearpumpTuple]
- val tuple = mock[Tuple]
- when(gearpumpTuple.toTuple(generalTopologyContext, timestamp)).thenReturn(tuple)
- val message = Message(gearpumpTuple, timestamp)
- gearpumpBolt.next(message)
-
- verify(stormOutputCollector).setTimestamp(timestamp)
- verify(bolt).execute(tuple)
-
- // Tick
- gearpumpBolt.tick(freq)
- verify(bolt).execute(tickTuple)
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/test/scala/io/gearpump/experiments/storm/topology/GearpumpStormTopologySpec.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/test/scala/io/gearpump/experiments/storm/topology/GearpumpStormTopologySpec.scala b/experiments/storm/src/test/scala/io/gearpump/experiments/storm/topology/GearpumpStormTopologySpec.scala
deleted file mode 100644
index f9ffc5f..0000000
--- a/experiments/storm/src/test/scala/io/gearpump/experiments/storm/topology/GearpumpStormTopologySpec.scala
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.storm.topology
-
-import java.util.{HashMap => JHashMap, Map => JMap}
-import scala.collection.JavaConverters._
-
-import backtype.storm.Config
-import org.scalatest.mock.MockitoSugar
-import org.scalatest.{Matchers, WordSpec}
-
-import io.gearpump.experiments.storm.processor.StormProcessor
-import io.gearpump.experiments.storm.producer.StormProducer
-import io.gearpump.experiments.storm.util.TopologyUtil
-import io.gearpump.streaming.MockUtil
-
-class GearpumpStormTopologySpec extends WordSpec with Matchers with MockitoSugar {
- import io.gearpump.experiments.storm.topology.GearpumpStormTopologySpec._
-
- "GearpumpStormTopology" should {
- "merge configs with defined priority" in {
- val stormTopology = TopologyUtil.getTestTopology
- val name = "name"
- val sysVal = "sys"
- val sysConfig = newJavaConfig(name, sysVal)
- val appVal = "app"
- val appConfig = newJavaConfig(name, appVal)
-
- implicit val system = MockUtil.system
- val topology1 = new GearpumpStormTopology("topology1", stormTopology, newEmptyConfig,
- newEmptyConfig)
- topology1.getStormConfig.get(Config.TOPOLOGY_NAME) shouldBe "topology1"
- topology1.getStormConfig should not contain name
-
- val topology2 = new GearpumpStormTopology("topology2", stormTopology, sysConfig,
- newEmptyConfig)
- topology2.getStormConfig.get(Config.TOPOLOGY_NAME) shouldBe "topology2"
- topology2.getStormConfig.get(name) shouldBe sysVal
-
- val topology3 = new GearpumpStormTopology("topology3", stormTopology, sysConfig, appConfig)
- topology3.getStormConfig.get(Config.TOPOLOGY_NAME) shouldBe "topology3"
- topology3.getStormConfig.get(name) shouldBe appVal
- }
-
- "create Gearpump processors from Storm topology" in {
- val stormTopology = TopologyUtil.getTestTopology
- implicit val system = MockUtil.system
- val gearpumpStormTopology =
- GearpumpStormTopology("app", stormTopology, null)
- val processors = gearpumpStormTopology.getProcessors
- stormTopology.get_spouts().asScala.foreach { case (spoutId, _) =>
- val processor = processors(spoutId)
- processor.taskClass shouldBe classOf[StormProducer]
- processor.description shouldBe spoutId
- }
- stormTopology.get_bolts().asScala.foreach { case (boltId, _) =>
- val processor = processors(boltId)
- processor.taskClass shouldBe classOf[StormProcessor]
- processor.description shouldBe boltId
- }
- }
-
- "get target processors from source id" in {
- val stormTopology = TopologyUtil.getTestTopology
- implicit val system = MockUtil.system
- val sysConfig = new JHashMap[AnyRef, AnyRef]
- val gearpumpStormTopology =
- GearpumpStormTopology("app", stormTopology, null)
- val targets0 = gearpumpStormTopology.getTargets("1")
- targets0 should contain key "3"
- targets0 should contain key "4"
- val targets1 = gearpumpStormTopology.getTargets("2")
- targets1 should contain key "3"
- }
- }
-}
-
-object GearpumpStormTopologySpec {
- def newEmptyConfig: JMap[AnyRef, AnyRef] = {
- new JHashMap[AnyRef, AnyRef]
- }
-
- def newJavaConfig(key: AnyRef, value: AnyRef): JMap[AnyRef, AnyRef] = {
- val config = new JHashMap[AnyRef, AnyRef]
- config.put(key, value)
- config
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/test/scala/io/gearpump/experiments/storm/topology/GearpumpTupleSpec.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/test/scala/io/gearpump/experiments/storm/topology/GearpumpTupleSpec.scala b/experiments/storm/src/test/scala/io/gearpump/experiments/storm/topology/GearpumpTupleSpec.scala
deleted file mode 100644
index f454145..0000000
--- a/experiments/storm/src/test/scala/io/gearpump/experiments/storm/topology/GearpumpTupleSpec.scala
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.experiments.storm.topology
-
-import java.util.{List => JList}
-import scala.collection.JavaConverters._
-
-import backtype.storm.task.GeneralTopologyContext
-import backtype.storm.tuple.Fields
-import org.mockito.Mockito._
-import org.scalacheck.Gen
-import org.scalatest.mock.MockitoSugar
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{Matchers, PropSpec}
-
-import io.gearpump.TimeStamp
-
-class GearpumpTupleSpec extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
-
- property("GearpumpTuple should create Storm Tuple") {
- val tupleGen = for {
- values <- Gen.listOf[String](Gen.alphaStr).map(_.distinct.asJava.asInstanceOf[JList[AnyRef]])
- sourceTaskId <- Gen.chooseNum[Int](0, Int.MaxValue)
- sourceStreamId <- Gen.alphaStr
- } yield new GearpumpTuple(values, new Integer(sourceTaskId), sourceStreamId, null)
-
- forAll(tupleGen, Gen.alphaStr, Gen.chooseNum[Long](0, Long.MaxValue)) {
- (gearpumpTuple: GearpumpTuple, componentId: String, timestamp: TimeStamp) =>
- val topologyContext = mock[GeneralTopologyContext]
- val fields = new Fields(gearpumpTuple.values.asScala.map(_.asInstanceOf[String]): _*)
- when(topologyContext.getComponentId(gearpumpTuple.sourceTaskId)).thenReturn(componentId)
- when(topologyContext.getComponentOutputFields(
- componentId, gearpumpTuple.sourceStreamId)).thenReturn(fields)
-
- val tuple = gearpumpTuple.toTuple(topologyContext, timestamp)
-
- tuple shouldBe a[TimedTuple]
- val timedTuple = tuple.asInstanceOf[TimedTuple]
- timedTuple.getValues shouldBe gearpumpTuple.values
- timedTuple.getSourceTask shouldBe gearpumpTuple.sourceTaskId
- timedTuple.getSourceComponent shouldBe componentId
- timedTuple.getSourceStreamId shouldBe gearpumpTuple.sourceStreamId
- timedTuple.getMessageId shouldBe null
- timedTuple.getFields shouldBe fields
- timedTuple.timestamp shouldBe timestamp
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/test/scala/io/gearpump/experiments/storm/util/GraphBuilderSpec.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/test/scala/io/gearpump/experiments/storm/util/GraphBuilderSpec.scala b/experiments/storm/src/test/scala/io/gearpump/experiments/storm/util/GraphBuilderSpec.scala
deleted file mode 100644
index 27c02fe..0000000
--- a/experiments/storm/src/test/scala/io/gearpump/experiments/storm/util/GraphBuilderSpec.scala
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.storm.util
-
-import org.mockito.Mockito._
-import org.scalatest.mock.MockitoSugar
-import org.scalatest.{Matchers, WordSpec}
-
-import io.gearpump.experiments.storm.partitioner.StormPartitioner
-import io.gearpump.experiments.storm.topology.GearpumpStormTopology
-import io.gearpump.streaming.Processor
-import io.gearpump.streaming.task.Task
-
-class GraphBuilderSpec extends WordSpec with Matchers with MockitoSugar {
-
- "GraphBuilder" should {
- "build Graph from Storm topology" in {
- val topology = mock[GearpumpStormTopology]
-
- val sourceId = "source"
- val sourceProcessor = mock[Processor[Task]]
- val targetId = "target"
- val targetProcessor = mock[Processor[Task]]
-
- when(topology.getProcessors).thenReturn(
- Map(sourceId -> sourceProcessor, targetId -> targetProcessor))
- when(topology.getTargets(sourceId)).thenReturn(Map(targetId -> targetProcessor))
- when(topology.getTargets(targetId)).thenReturn(Map.empty[String, Processor[Task]])
-
- val graph = GraphBuilder.build(topology)
-
- graph.edges.size shouldBe 1
- val (from, edge, to) = graph.edges.head
- from shouldBe sourceProcessor
- edge shouldBe a[StormPartitioner]
- to shouldBe targetProcessor
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/test/scala/io/gearpump/experiments/storm/util/GrouperSpec.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/test/scala/io/gearpump/experiments/storm/util/GrouperSpec.scala b/experiments/storm/src/test/scala/io/gearpump/experiments/storm/util/GrouperSpec.scala
deleted file mode 100644
index 599ea8d..0000000
--- a/experiments/storm/src/test/scala/io/gearpump/experiments/storm/util/GrouperSpec.scala
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.storm.util
-
-import java.util.{List => JList}
-import scala.collection.JavaConverters._
-
-import backtype.storm.generated.GlobalStreamId
-import backtype.storm.grouping.CustomStreamGrouping
-import backtype.storm.task.TopologyContext
-import backtype.storm.tuple.Fields
-import org.mockito.Mockito._
-import org.scalacheck.Gen
-import org.scalatest.mock.MockitoSugar
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{Matchers, PropSpec}
-
-import io.gearpump.experiments.storm.util.GrouperSpec.Value
-
-class GrouperSpec extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
-
- val taskIdGen = Gen.chooseNum[Int](0, 1000)
- val valuesGen = Gen.listOf[String](Gen.alphaStr)
- .map(_.asJava.asInstanceOf[JList[AnyRef]])
- val numTasksGen = Gen.chooseNum[Int](1, 1000)
-
- property("GlobalGrouper should always return partition 0") {
- forAll(taskIdGen, valuesGen) { (taskId: Int, values: JList[AnyRef]) =>
- val grouper = new GlobalGrouper
- grouper.getPartitions(taskId, values) shouldBe List(0)
- }
- }
-
- property("NoneGrouper should returns partition in the range [0, numTasks)") {
- forAll(taskIdGen, valuesGen, numTasksGen) {
- (taskId: Int, values: JList[AnyRef], numTasks: Int) =>
- val grouper = new NoneGrouper(numTasks)
- val partitions = grouper.getPartitions(taskId, values)
- partitions.size shouldBe 1
- partitions.head should (be >= 0 and be < numTasks)
- }
- }
-
- property("ShuffleGrouper should return partition in the range [0, numTasks)") {
- forAll(taskIdGen, valuesGen, numTasksGen) {
- (taskId: Int, values: JList[AnyRef], numTasks: Int) =>
- val grouper = new ShuffleGrouper(numTasks)
- val partitions = grouper.getPartitions(taskId, values)
- partitions.size shouldBe 1
- partitions.head should (be >= 0 and be < numTasks)
- }
- }
-
- property("FieldsGrouper should return partition according to fields") {
- forAll(taskIdGen, numTasksGen) {
- (taskId: Int, numTasks: Int) =>
- val values = 0.until(numTasks).map(i => new Value(i))
- val fields = values.map(_.toString)
- val outFields = new Fields(fields: _*)
- values.flatMap { v =>
- val groupFields = new Fields(v.toString)
- val grouper = new FieldsGrouper(outFields, groupFields, numTasks)
- grouper.getPartitions(taskId,
- values.toList.asJava.asInstanceOf[JList[AnyRef]])
- }.distinct.size shouldBe numTasks
- }
- }
-
- property("AllGrouper should return all partitions") {
- forAll(taskIdGen, numTasksGen, valuesGen) {
- (taskId: Int, numTasks: Int, values: JList[AnyRef]) =>
- val grouper = new AllGrouper(numTasks)
- val partitions = grouper.getPartitions(taskId, values)
- partitions.distinct.size shouldBe numTasks
- partitions.min shouldBe 0
- partitions.max shouldBe (numTasks - 1)
- }
- }
-
- property("CustomGrouper should return partitions specified by user") {
- val grouping = mock[CustomStreamGrouping]
- val grouper = new CustomGrouper(grouping)
- val topologyContext = mock[TopologyContext]
- val globalStreamId = mock[GlobalStreamId]
- val sourceTasks = mock[JList[Integer]]
-
- grouper.prepare(topologyContext, globalStreamId, sourceTasks)
-
- verify(grouping).prepare(topologyContext, globalStreamId, sourceTasks)
-
- forAll(taskIdGen, valuesGen, numTasksGen) {(taskId: Int, values: JList[AnyRef], taskNum: Int) =>
- 0.until(taskNum).foreach { i =>
- when(grouping.chooseTasks(taskId, values)).thenReturn(List(new Integer(i)).asJava)
- grouper.getPartitions(taskId, values) shouldBe List(i)
- }
- }
- }
-}
-
-object GrouperSpec {
- class Value(val i: Int) extends AnyRef {
-
- override def toString: String = s"$i"
-
- override def hashCode(): Int = i
-
- override def equals(other: Any): Boolean = {
- if (other.isInstanceOf[Value]) {
- this.i == other.asInstanceOf[Value].i
- } else {
- false
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/test/scala/io/gearpump/experiments/storm/util/StormOutputCollectorSpec.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/test/scala/io/gearpump/experiments/storm/util/StormOutputCollectorSpec.scala b/experiments/storm/src/test/scala/io/gearpump/experiments/storm/util/StormOutputCollectorSpec.scala
deleted file mode 100644
index 1a28694..0000000
--- a/experiments/storm/src/test/scala/io/gearpump/experiments/storm/util/StormOutputCollectorSpec.scala
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.experiments.storm.util
-
-import java.util.{List => JList, Map => JMap}
-import scala.collection.JavaConverters._
-
-import backtype.storm.generated.Grouping
-import org.mockito.Matchers._
-import org.mockito.Mockito._
-import org.scalacheck.Gen
-import org.scalatest.mock.MockitoSugar
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{Matchers, PropSpec}
-
-import io.gearpump._
-import io.gearpump.experiments.storm.topology.GearpumpTuple
-import io.gearpump.streaming.MockUtil
-
-class StormOutputCollectorSpec
- extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
-
- val stormTaskId = 0
- val streamIdGen = Gen.alphaStr
- val valuesGen = Gen.listOf[String](Gen.alphaStr).map(_.asJava.asInstanceOf[JList[AnyRef]])
- val timestampGen = Gen.chooseNum[Long](0L, 1000L)
-
- property("StormOutputCollector emits tuple values into a stream") {
- forAll(timestampGen, streamIdGen, valuesGen) {
- (timestamp: TimeStamp, streamId: String, values: JList[AnyRef]) =>
- val targets = mock[JMap[String, JMap[String, Grouping]]]
- val taskToComponent = mock[JMap[Integer, String]]
- val getTargetPartitionsFn = mock[(String, JList[AnyRef]) =>
- (Map[String, Array[Int]], JList[Integer])]
- val targetPartitions = mock[Map[String, Array[Int]]]
- val targetStormTaskIds = mock[JList[Integer]]
- when(getTargetPartitionsFn(streamId, values)).thenReturn((targetPartitions,
- targetStormTaskIds))
- val taskContext = MockUtil.mockTaskContext
- val stormOutputCollector = new StormOutputCollector(stormTaskId, taskToComponent,
- targets, getTargetPartitionsFn, taskContext, LatestTime)
-
- when(targets.containsKey(streamId)).thenReturn(false)
- stormOutputCollector.emit(streamId, values) shouldBe StormOutputCollector.EMPTY_LIST
- verify(taskContext, times(0)).output(anyObject[Message])
-
- when(targets.containsKey(streamId)).thenReturn(true)
- stormOutputCollector.setTimestamp(timestamp)
- stormOutputCollector.emit(streamId, values) shouldBe targetStormTaskIds
- verify(taskContext, times(1)).output(MockUtil.argMatch[Message]({
- case Message(tuple: GearpumpTuple, t) =>
- val expected = new GearpumpTuple(values, stormTaskId, streamId, targetPartitions)
- tuple == expected && t == timestamp
- }))
- }
- }
-
- property("StormOutputCollector emit direct to a task") {
- val idGen = Gen.chooseNum[Int](0, 1000)
- val targetGen = Gen.alphaStr
- forAll(idGen, targetGen, timestampGen, streamIdGen, valuesGen) {
- (id: Int, target: String, timestamp: Long, streamId: String, values: JList[AnyRef]) =>
- val targets = mock[JMap[String, JMap[String, Grouping]]]
- val taskToComponent = mock[JMap[Integer, String]]
- when(taskToComponent.get(id)).thenReturn(target)
- val getTargetPartitionsFn = mock[(String, JList[AnyRef]) =>
- (Map[String, Array[Int]], JList[Integer])]
- val targetPartitions = mock[Map[String, Array[Int]]]
- val targetStormTaskIds = mock[JList[Integer]]
- when(getTargetPartitionsFn(streamId, values)).thenReturn((targetPartitions,
- targetStormTaskIds))
- val taskContext = MockUtil.mockTaskContext
- val stormOutputCollector = new StormOutputCollector(stormTaskId, taskToComponent,
- targets, getTargetPartitionsFn, taskContext, LatestTime)
-
- when(targets.containsKey(streamId)).thenReturn(false)
- verify(taskContext, times(0)).output(anyObject[Message])
-
- when(targets.containsKey(streamId)).thenReturn(true)
- stormOutputCollector.setTimestamp(timestamp)
- stormOutputCollector.emitDirect(id, streamId, values)
- val partitions = Array(StormUtil.stormTaskIdToGearpump(id).index)
- verify(taskContext, times(1)).output(MockUtil.argMatch[Message]({
- case Message(tuple: GearpumpTuple, t) => {
- val expected = new GearpumpTuple(values, stormTaskId, streamId,
- Map(target -> partitions))
-
- val result = tuple == expected && t == timestamp
- result
- }
- }))
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/test/scala/io/gearpump/experiments/storm/util/StormSerializerPoolSpec.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/test/scala/io/gearpump/experiments/storm/util/StormSerializerPoolSpec.scala b/experiments/storm/src/test/scala/io/gearpump/experiments/storm/util/StormSerializerPoolSpec.scala
deleted file mode 100644
index d8a29e8..0000000
--- a/experiments/storm/src/test/scala/io/gearpump/experiments/storm/util/StormSerializerPoolSpec.scala
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.storm.util
-
-import java.util.{HashMap => JHashMap, List => JList, Map => JMap}
-import scala.collection.JavaConverters._
-
-import akka.actor.ExtendedActorSystem
-import backtype.storm.utils.Utils
-import com.esotericsoftware.kryo.Kryo
-import org.scalacheck.Gen
-import org.scalatest.mock.MockitoSugar
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{Matchers, PropSpec}
-
-import io.gearpump.cluster.UserConfig
-import io.gearpump.experiments.storm.topology.GearpumpTuple
-import io.gearpump.experiments.storm.util.StormConstants._
-import io.gearpump.streaming.MockUtil
-
-class StormSerializerPoolSpec extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
-
- property("StormSerializerPool should create and manage StormSerializer") {
- val taskContext = MockUtil.mockTaskContext
- val serializerPool = new StormSerializationFramework
- val system = taskContext.system.asInstanceOf[ExtendedActorSystem]
- implicit val actorSystem = system
- val stormConfig = Utils.readDefaultConfig.asInstanceOf[JMap[AnyRef, AnyRef]]
- val config = UserConfig.empty.withValue[JMap[AnyRef, AnyRef]](STORM_CONFIG, stormConfig)
- serializerPool.init(system, config)
- serializerPool.get shouldBe a[StormSerializer]
- }
-
- property("StormSerializer should serialize and deserialize GearpumpTuple") {
- val tupleGen = for {
- values <- Gen.listOf[String](Gen.alphaStr).map(_.asJava.asInstanceOf[JList[AnyRef]])
- sourceTaskId <- Gen.chooseNum[Int](0, Int.MaxValue)
- sourceStreamId <- Gen.alphaStr
- } yield new GearpumpTuple(values, new Integer(sourceTaskId), sourceStreamId, null)
-
- val kryo = new Kryo
- forAll(tupleGen) { (tuple: GearpumpTuple) =>
- val serializer = new StormSerializer(kryo)
- serializer.deserialize(serializer.serialize(tuple)) shouldBe tuple
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/test/scala/io/gearpump/experiments/storm/util/StormUtilSpec.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/test/scala/io/gearpump/experiments/storm/util/StormUtilSpec.scala b/experiments/storm/src/test/scala/io/gearpump/experiments/storm/util/StormUtilSpec.scala
deleted file mode 100644
index a9b93c9..0000000
--- a/experiments/storm/src/test/scala/io/gearpump/experiments/storm/util/StormUtilSpec.scala
+++ /dev/null
@@ -1,157 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.storm.util
-
-import java.lang.{Boolean => JBoolean, Long => JLong}
-import java.util.{HashMap => JHashMap, Map => JMap}
-import scala.collection.JavaConverters._
-
-import backtype.storm.Config
-import backtype.storm.generated.StormTopology
-import org.apache.storm.shade.org.json.simple.JSONValue
-import org.scalacheck.Gen
-import org.scalatest.mock.MockitoSugar
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{Matchers, PropSpec}
-
-import io.gearpump.cluster.UserConfig
-import io.gearpump.experiments.storm.topology.GearpumpStormComponent.{GearpumpBolt, GearpumpSpout}
-import io.gearpump.experiments.storm.util.StormConstants._
-import io.gearpump.experiments.storm.util.StormUtil._
-import io.gearpump.streaming.MockUtil
-import io.gearpump.streaming.task.TaskId
-
-class StormUtilSpec extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
-
- property("convert Storm task ids to gearpump TaskIds and back") {
- val idGen = Gen.chooseNum[Int](0, Int.MaxValue)
- forAll(idGen) { (stormTaskId: Int) =>
- gearpumpTaskIdToStorm(stormTaskIdToGearpump(stormTaskId)) shouldBe stormTaskId
- }
-
- val processorIdGen = Gen.chooseNum[Int](0, Int.MaxValue >> 16)
- val indexGen = Gen.chooseNum[Int](0, Int.MaxValue >> 16)
- forAll(processorIdGen, indexGen) { (processorId: Int, index: Int) =>
- val taskId = TaskId(processorId, index)
- stormTaskIdToGearpump(gearpumpTaskIdToStorm(taskId)) shouldBe taskId
- }
- }
-
- property("get GearpumpStormComponent from user config") {
- val taskContext = MockUtil.mockTaskContext
- val topology = TopologyUtil.getTestTopology
- implicit val actorSystem = taskContext.system
- val userConfig = UserConfig.empty
- .withValue[StormTopology](STORM_TOPOLOGY, topology)
- .withValue[JMap[AnyRef, AnyRef]](STORM_CONFIG, new JHashMap[AnyRef, AnyRef])
- topology.get_spouts.asScala.foreach { case (spoutId, _) =>
- val config = userConfig.withString(STORM_COMPONENT, spoutId)
- val component = getGearpumpStormComponent(taskContext, config)(taskContext.system)
- component shouldBe a[GearpumpSpout]
- }
- topology.get_bolts.asScala.foreach { case (boltId, _) =>
- val config = userConfig.withString(STORM_COMPONENT, boltId)
- val component = getGearpumpStormComponent(taskContext, config)(taskContext.system)
- component shouldBe a[GearpumpBolt]
- }
- }
-
- property("parse json to map") {
- val mapGen = Gen.listOf[String](Gen.alphaStr)
- .map(_.map(s => (s, s)).toMap.asJava.asInstanceOf[JMap[AnyRef, AnyRef]])
-
- forAll(mapGen) { (map: JMap[AnyRef, AnyRef]) =>
- parseJsonStringToMap(JSONValue.toJSONString(map)) shouldBe map
- }
-
- val invalidJsonGen: Gen[String] = Gen.oneOf(null, "", "1")
- forAll(invalidJsonGen) { (invalidJson: String) =>
- val map = parseJsonStringToMap(invalidJson)
- map shouldBe empty
- map shouldBe a[JMap[_, _]]
- }
- }
-
- property("get int from config") {
- val name = "int"
- val conf: JMap[AnyRef, AnyRef] = new JHashMap[AnyRef, AnyRef]
- getInt(conf, name) shouldBe None
- conf.put(name, null)
- getInt(conf, name) shouldBe None
-
- forAll(Gen.chooseNum[Int](Int.MinValue, Int.MaxValue)) { (int: Int) =>
- conf.put(name, new Integer(int))
- getInt(conf, name) shouldBe Some(int)
- }
-
- forAll(Gen.chooseNum[Long](Int.MinValue, Int.MaxValue)) { (long: Long) =>
- conf.put(name, new JLong(long))
- getInt(conf, name) shouldBe Some(long)
- }
-
- forAll(Gen.alphaStr) { (s: String) =>
- conf.put(name, s)
- an[IllegalArgumentException] should be thrownBy getInt(conf, name)
- }
- }
-
- property("get boolean from config") {
- val name = "boolean"
- val conf: JMap[AnyRef, AnyRef] = new JHashMap[AnyRef, AnyRef]
- getBoolean(conf, name) shouldBe None
- conf.put(name, null)
- getBoolean(conf, name) shouldBe None
-
- forAll(Gen.oneOf(true, false)) { (boolean: Boolean) =>
- conf.put(name, new JBoolean(boolean))
- getBoolean(conf, name) shouldBe Some(boolean)
- }
-
- forAll(Gen.alphaStr) { (s: String) =>
- conf.put(name, s)
- an[IllegalArgumentException] should be thrownBy getBoolean(conf, name)
- }
- }
-
- property("mod should be correct") {
- mod(10, 5) shouldBe 0
- mod(10, 6) shouldBe 4
- mod(10, -3) shouldBe -2
- mod(-2, 5) shouldBe 3
- mod(-1, -2) shouldBe -1
- }
-
- property("get whether ack enabled") {
- val conf: JMap[AnyRef, AnyRef] = new JHashMap[AnyRef, AnyRef]
- ackEnabled(conf) shouldBe false
- conf.put(Config.TOPOLOGY_ACKER_EXECUTORS, new Integer(0))
- ackEnabled(conf) shouldBe false
- conf.put(Config.TOPOLOGY_ACKER_EXECUTORS, null)
- ackEnabled(conf) shouldBe true
- forAll(Gen.chooseNum[Int](Int.MinValue, Int.MaxValue)) {
- (ackers: Int) =>
- conf.put(Config.TOPOLOGY_ACKER_EXECUTORS, new Integer(ackers))
- if (ackers == 0) {
- ackEnabled(conf) shouldBe false
- } else {
- ackEnabled(conf) shouldBe true
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/test/scala/io/gearpump/experiments/storm/util/TopologyUtil.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/test/scala/io/gearpump/experiments/storm/util/TopologyUtil.scala b/experiments/storm/src/test/scala/io/gearpump/experiments/storm/util/TopologyUtil.scala
deleted file mode 100644
index 8491786..0000000
--- a/experiments/storm/src/test/scala/io/gearpump/experiments/storm/util/TopologyUtil.scala
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.storm.util
-
-import backtype.storm.generated.StormTopology
-import backtype.storm.testing.{TestGlobalCount, TestWordCounter, TestWordSpout}
-import backtype.storm.topology.TopologyBuilder
-import backtype.storm.tuple.Fields
-import backtype.storm.utils.Utils
-
-object TopologyUtil {
- val DEFAULT_STREAM_ID = Utils.DEFAULT_STREAM_ID
- val DEFAULT_COMPONENT_ID = "component"
-
- def getTestTopology: StormTopology = {
- val topologyBuilder = new TopologyBuilder
- topologyBuilder.setSpout("1", new TestWordSpout(true), 5)
- topologyBuilder.setSpout("2", new TestWordSpout(true), 3)
- topologyBuilder.setBolt("3", new TestWordCounter(), 3)
- .fieldsGrouping("1", new Fields("word"))
- .fieldsGrouping("2", new Fields("word"))
- topologyBuilder.setBolt("4", new TestGlobalCount()).globalGrouping("1")
- topologyBuilder.createTopology()
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/partitioner/StormPartitionerSpec.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/partitioner/StormPartitionerSpec.scala b/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/partitioner/StormPartitionerSpec.scala
new file mode 100644
index 0000000..5513423
--- /dev/null
+++ b/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/partitioner/StormPartitionerSpec.scala
@@ -0,0 +1,67 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.storm.partitioner
+
+import java.util.{List => JList}
+import scala.collection.JavaConverters._
+
+import org.scalacheck.Gen
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{Matchers, PropSpec}
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.experiments.storm.topology.GearpumpTuple
+import org.apache.gearpump.partitioner.Partitioner
+
+class StormPartitionerSpec extends PropSpec with PropertyChecks with Matchers {
+
+ property("StormPartitioner should get partitions directed by message and target") {
+ val idGen = Gen.chooseNum[Int](0, Int.MaxValue)
+ val componentsGen = Gen.listOf[String](Gen.alphaStr).map(_.distinct).suchThat(_.size > 1)
+ val partitionsGen = Gen.listOf[Int](idGen).suchThat(_.nonEmpty).map(_.distinct.sorted.toArray)
+ val tupleFactoryGen = for {
+ values <- Gen.listOf[String](Gen.alphaStr).map(_.asJava.asInstanceOf[JList[AnyRef]])
+ sourceTaskId <- idGen
+ sourceStreamId <- Gen.alphaStr
+ } yield (targetPartitions: Map[String, Array[Int]]) => {
+ new GearpumpTuple(values, new Integer(sourceTaskId), sourceStreamId, targetPartitions)
+ }
+
+ forAll(tupleFactoryGen, idGen, componentsGen, partitionsGen) {
+ (tupleFactory: Map[String, Array[Int]] => GearpumpTuple, id: Int,
+ components: List[String], partitions: Array[Int]) => {
+ val currentPartitionId = id
+ val targetPartitions = components.init.map(c => (c, partitions)).toMap
+ val tuple = tupleFactory(targetPartitions)
+ targetPartitions.foreach {
+ case (target, ps) => {
+ val partitioner = new StormPartitioner(target)
+ ps shouldBe partitioner.getPartitions(Message(tuple), ps.last + 1, currentPartitionId)
+ }
+ }
+ val partitionNum = id
+ val nonTarget = components.last
+ val partitioner = new StormPartitioner(nonTarget)
+
+ partitioner.getPartitions(Message(tuple), partitionNum,
+ currentPartitionId) shouldBe List(Partitioner.UNKNOWN_PARTITION_ID)
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/processor/StormBoltOutputCollectorSpec.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/processor/StormBoltOutputCollectorSpec.scala b/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/processor/StormBoltOutputCollectorSpec.scala
new file mode 100644
index 0000000..430b1c0
--- /dev/null
+++ b/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/processor/StormBoltOutputCollectorSpec.scala
@@ -0,0 +1,56 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.storm.processor
+
+import java.util.{List => JList}
+
+import backtype.storm.tuple.Tuple
+import backtype.storm.utils.Utils
+import org.apache.gearpump.experiments.storm.util.StormOutputCollector
+import org.mockito.Mockito._
+import org.scalacheck.Gen
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{Matchers, PropSpec}
+
+import scala.collection.JavaConverters._
+
+class StormBoltOutputCollectorSpec
+ extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
+
+ property("StormBoltOutputCollector should call StormOutputCollector") {
+ val valGen = Gen.oneOf(Gen.alphaStr, Gen.alphaChar, Gen.chooseNum[Int](0, 1000))
+ val valuesGen = Gen.listOf[AnyRef](valGen)
+
+ forAll(valuesGen) { (values: List[AnyRef]) =>
+ val collector = mock[StormOutputCollector]
+ val boltCollector = new StormBoltOutputCollector(collector)
+ val streamId = Utils.DEFAULT_STREAM_ID
+ boltCollector.emit(streamId, null, values.asJava)
+ verify(collector).emit(streamId, values.asJava)
+ }
+ }
+
+ property("StormBoltOutputCollector should throw on fail") {
+ val collector = mock[StormOutputCollector]
+ val tuple = mock[Tuple]
+ val boltCollector = new StormBoltOutputCollector(collector)
+ an[Exception] should be thrownBy boltCollector.fail(tuple)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/processor/StormProcessorSpec.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/processor/StormProcessorSpec.scala b/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/processor/StormProcessorSpec.scala
new file mode 100644
index 0000000..2111df6
--- /dev/null
+++ b/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/processor/StormProcessorSpec.scala
@@ -0,0 +1,65 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.storm.processor
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.experiments.storm.topology.GearpumpStormComponent.GearpumpBolt
+import org.apache.gearpump.streaming.MockUtil
+import org.apache.gearpump.streaming.task.StartTime
+import org.mockito.Mockito._
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.{Matchers, WordSpec}
+
+class StormProcessorSpec extends WordSpec with Matchers with MockitoSugar {
+
+ "StormProcessor" should {
+ "start GearpumpSpout onStart" in {
+ val startTime = mock[StartTime]
+ val gearpumpBolt = mock[GearpumpBolt]
+ when(gearpumpBolt.getTickFrequency).thenReturn(None)
+ val taskContext = MockUtil.mockTaskContext
+ val userConfig = UserConfig.empty
+ val stormProcessor = new StormProcessor(gearpumpBolt, taskContext, userConfig)
+
+ stormProcessor.onStart(startTime)
+
+ verify(gearpumpBolt).start(startTime)
+ }
+
+ "pass message to GearpumpBolt onNext" in {
+ val message = mock[Message]
+ val gearpumpBolt = mock[GearpumpBolt]
+ val freq = 5
+ when(gearpumpBolt.getTickFrequency).thenReturn(Some(freq))
+ val taskContext = MockUtil.mockTaskContext
+ val userConfig = UserConfig.empty
+ val stormProcessor = new StormProcessor(gearpumpBolt, taskContext, userConfig)
+
+ stormProcessor.onNext(message)
+
+ verify(gearpumpBolt).next(message)
+
+ stormProcessor.onNext(StormProcessor.TICK)
+
+ verify(gearpumpBolt).tick(freq)
+ }
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/producer/StormProducerSpec.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/producer/StormProducerSpec.scala b/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/producer/StormProducerSpec.scala
new file mode 100644
index 0000000..39a008f
--- /dev/null
+++ b/experiments/storm/src/test/scala/org/apache/gearpump/experiments/storm/producer/StormProducerSpec.scala
@@ -0,0 +1,72 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.storm.producer
+
+import akka.testkit.TestProbe
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.experiments.storm.topology.GearpumpStormComponent.GearpumpSpout
+import org.apache.gearpump.streaming.MockUtil
+import org.apache.gearpump.streaming.task.StartTime
+import org.mockito.Mockito._
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.{Matchers, WordSpec}
+
+class StormProducerSpec extends WordSpec with Matchers with MockitoSugar {
+
+ "StormProducer" should {
+ "start GearpumpSpout onStart" in {
+ val startTime = mock[StartTime]
+ val gearpumpSpout = mock[GearpumpSpout]
+ when(gearpumpSpout.getMessageTimeout).thenReturn(None)
+ val taskContext = MockUtil.mockTaskContext
+ implicit val actorSystem = taskContext.system
+ val taskActor = TestProbe()
+ when(taskContext.self).thenReturn(taskActor.ref)
+ val userConfig = UserConfig.empty
+ val stormProducer = new StormProducer(gearpumpSpout, taskContext, userConfig)
+
+ stormProducer.onStart(startTime)
+
+ verify(gearpumpSpout).start(startTime)
+ taskActor.expectMsg(Message("start"))
+ }
+
+ "pass message to GearpumpBolt onNext" in {
+ val message = mock[Message]
+ val gearpumpSpout = mock[GearpumpSpout]
+ val timeout = 5L
+ when(gearpumpSpout.getMessageTimeout).thenReturn(Some(timeout))
+ val taskContext = MockUtil.mockTaskContext
+ implicit val actorSystem = taskContext.system
+ val taskActor = TestProbe()
+ when(taskContext.self).thenReturn(taskActor.ref)
+ val userConfig = UserConfig.empty
+ val stormProducer = new StormProducer(gearpumpSpout, taskContext, userConfig)
+
+ stormProducer.onNext(message)
+
+ verify(gearpumpSpout).next(message)
+ taskActor.expectMsg(Message("continue"))
+
+ stormProducer.onNext(StormProducer.TIMEOUT)
+ verify(gearpumpSpout).timeout(timeout)
+ }
+ }
+}
[10/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/dsl/StreamApp.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/dsl/StreamApp.scala b/streaming/src/main/scala/io/gearpump/streaming/dsl/StreamApp.scala
deleted file mode 100644
index a2ac70f..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/dsl/StreamApp.scala
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.dsl
-
-import scala.language.implicitConversions
-
-import akka.actor.ActorSystem
-
-import io.gearpump.cluster.UserConfig
-import io.gearpump.cluster.client.ClientContext
-import io.gearpump.streaming.StreamApplication
-import io.gearpump.streaming.dsl.op.{DataSourceOp, Op, OpEdge, ProcessorOp}
-import io.gearpump.streaming.dsl.plan.Planner
-import io.gearpump.streaming.source.DataSource
-import io.gearpump.streaming.task.{Task, TaskContext}
-import io.gearpump.util.Graph
-import io.gearpump.{Message, TimeStamp}
-
-/**
- * Example:
- * {{{
- * val data = "This is a good start, bingo!! bingo!!"
- * app.fromCollection(data.lines.toList).
- * // word => (word, count)
- * flatMap(line => line.split("[\\s]+")).map((_, 1)).
- * // (word, count1), (word, count2) => (word, count1 + count2)
- * groupBy(kv => kv._1).reduce(sum(_, _))
- *
- * val appId = context.submit(app)
- * context.close()
- * }}}
- *
- * @param name name of app
- */
-class StreamApp(
- val name: String, system: ActorSystem, userConfig: UserConfig, val graph: Graph[Op, OpEdge]) {
-
- def this(name: String, system: ActorSystem, userConfig: UserConfig) = {
- this(name, system, userConfig, Graph.empty[Op, OpEdge])
- }
-
- def plan(): StreamApplication = {
- implicit val actorSystem = system
- val planner = new Planner
- val dag = planner.plan(graph)
- StreamApplication(name, dag, userConfig)
- }
-}
-
-object StreamApp {
- def apply(name: String, context: ClientContext, userConfig: UserConfig = UserConfig.empty)
- : StreamApp = {
- new StreamApp(name, context.system, userConfig)
- }
-
- implicit def streamAppToApplication(streamApp: StreamApp): StreamApplication = {
- streamApp.plan
- }
-
- implicit class Source(app: StreamApp) extends java.io.Serializable {
-
- def source[T](dataSource: DataSource, parallism: Int): Stream[T] = {
- source(dataSource, parallism, UserConfig.empty)
- }
-
- def source[T](dataSource: DataSource, parallism: Int, description: String): Stream[T] = {
- source(dataSource, parallism, UserConfig.empty, description)
- }
-
- def source[T](dataSource: DataSource, parallism: Int, conf: UserConfig): Stream[T] = {
- source(dataSource, parallism, conf, description = null)
- }
-
- def source[T](dataSource: DataSource, parallism: Int, conf: UserConfig, description: String)
- : Stream[T] = {
- implicit val sourceOp = DataSourceOp(dataSource, parallism, conf, description)
- app.graph.addVertex(sourceOp)
- new Stream[T](app.graph, sourceOp)
- }
- def source[T](seq: Seq[T], parallism: Int, description: String): Stream[T] = {
- this.source(new CollectionDataSource[T](seq), parallism, UserConfig.empty, description)
- }
-
- def source[T](source: Class[_ <: Task], parallism: Int, conf: UserConfig, description: String)
- : Stream[T] = {
- val sourceOp = ProcessorOp(source, parallism, conf, Option(description).getOrElse("source"))
- app.graph.addVertex(sourceOp)
- new Stream[T](app.graph, sourceOp)
- }
- }
-}
-
-/** A test message source which generated message sequence repeatedly. */
-class CollectionDataSource[T](seq: Seq[T]) extends DataSource {
- private val iterator: Iterator[T] = seq.iterator
-
- override def read(): Message = {
- if (iterator.hasNext) {
- Message(iterator.next())
- } else {
- null
- }
- }
-
- override def close(): Unit = {}
-
- override def open(context: TaskContext, startTime: TimeStamp): Unit = {}
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/dsl/javaapi/JavaStream.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/dsl/javaapi/JavaStream.scala b/streaming/src/main/scala/io/gearpump/streaming/dsl/javaapi/JavaStream.scala
deleted file mode 100644
index 549cc6e..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/dsl/javaapi/JavaStream.scala
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.dsl.javaapi
-
-import scala.collection.JavaConverters._
-
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.dsl.Stream
-import io.gearpump.streaming.javaapi.dsl.functions._
-import io.gearpump.streaming.task.Task
-
-/**
- * Java DSL
- */
-class JavaStream[T](val stream: Stream[T]) {
-
- /** FlatMap on stream */
- def flatMap[R](fn: FlatMapFunction[T, R], description: String): JavaStream[R] = {
- new JavaStream[R](stream.flatMap({ t: T => fn(t).asScala }, description))
- }
-
- /** Map on stream */
- def map[R](fn: MapFunction[T, R], description: String): JavaStream[R] = {
- new JavaStream[R](stream.map({ t: T => fn(t) }, description))
- }
-
- /** Only keep the messages that FilterFunction returns true. */
- def filter(fn: FilterFunction[T], description: String): JavaStream[T] = {
- new JavaStream[T](stream.filter({ t: T => fn(t) }, description))
- }
-
- /** Does aggregation on the stream */
- def reduce(fn: ReduceFunction[T], description: String): JavaStream[T] = {
- new JavaStream[T](stream.reduce({ (t1: T, t2: T) => fn(t1, t2) }, description))
- }
-
- def log(): Unit = {
- stream.log()
- }
-
- /** Merges streams of same type together */
- def merge(other: JavaStream[T], description: String): JavaStream[T] = {
- new JavaStream[T](stream.merge(other.stream, description))
- }
-
- /**
- * Group by a stream and turns it to a list of sub-streams. Operations chained after
- * groupBy applies to sub-streams.
- */
- def groupBy[Group](fn: GroupByFunction[T, Group], parallelism: Int, description: String)
- : JavaStream[T] = {
- new JavaStream[T](stream.groupBy({t: T => fn(t)}, parallelism, description))
- }
-
- /** Add a low level Processor to process messages */
- def process[R](
- processor: Class[_ <: Task], parallelism: Int, conf: UserConfig, description: String)
- : JavaStream[R] = {
- new JavaStream[R](stream.process(processor, parallelism, conf, description))
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/dsl/javaapi/JavaStreamApp.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/dsl/javaapi/JavaStreamApp.scala b/streaming/src/main/scala/io/gearpump/streaming/dsl/javaapi/JavaStreamApp.scala
deleted file mode 100644
index e39e054..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/dsl/javaapi/JavaStreamApp.scala
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.dsl.javaapi
-
-import java.util.Collection
-import scala.collection.JavaConverters._
-
-import io.gearpump.cluster.UserConfig
-import io.gearpump.cluster.client.ClientContext
-import io.gearpump.streaming.dsl.{CollectionDataSource, StreamApp}
-import io.gearpump.streaming.source.DataSource
-
-class JavaStreamApp(name: String, context: ClientContext, userConfig: UserConfig) {
-
- private val streamApp = StreamApp(name, context, userConfig)
-
- def source[T](collection: Collection[T], parallelism: Int,
- conf: UserConfig, description: String): JavaStream[T] = {
- val dataSource = new CollectionDataSource(collection.asScala.toSeq)
- source(dataSource, parallelism, conf, description)
- }
-
- def source[T](dataSource: DataSource, parallelism: Int,
- conf: UserConfig, description: String): JavaStream[T] = {
- new JavaStream[T](streamApp.source(dataSource, parallelism, conf, description))
- }
-
- def run(): Unit = {
- context.submit(streamApp)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/dsl/op/OP.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/dsl/op/OP.scala b/streaming/src/main/scala/io/gearpump/streaming/dsl/op/OP.scala
deleted file mode 100644
index f0a86fa..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/dsl/op/OP.scala
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.dsl.op
-
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.sink.DataSink
-import io.gearpump.streaming.source.DataSource
-import io.gearpump.streaming.task.Task
-
-/**
- * Operators for the DSL
- */
-sealed trait Op {
- def description: String
- def conf: UserConfig
-}
-
-/**
- * When translated to running DAG, SlaveOP can be attach to MasterOP or other SlaveOP
- * "Attach" means running in same Actor.
- */
-trait SlaveOp[T] extends Op
-
-case class FlatMapOp[T, R](
- fun: (T) => TraversableOnce[R], description: String, conf: UserConfig = UserConfig.empty)
- extends SlaveOp[T]
-
-case class ReduceOp[T](fun: (T, T) => T, description: String, conf: UserConfig = UserConfig.empty)
- extends SlaveOp[T]
-
-trait MasterOp extends Op
-
-trait ParameterizedOp[T] extends MasterOp
-
-case class MergeOp(description: String, override val conf: UserConfig = UserConfig.empty)
- extends MasterOp
-
-case class GroupByOp[T, R](
- fun: T => R, parallelism: Int, description: String,
- override val conf: UserConfig = UserConfig.empty)
- extends ParameterizedOp[T]
-
-case class ProcessorOp[T <: Task](
- processor: Class[T], parallelism: Int, conf: UserConfig, description: String)
- extends ParameterizedOp[T]
-
-case class DataSourceOp[T](
- dataSource: DataSource, parallelism: Int, conf: UserConfig, description: String)
- extends ParameterizedOp[T]
-
-case class DataSinkOp[T](
- dataSink: DataSink, parallelism: Int, conf: UserConfig, description: String)
- extends ParameterizedOp[T]
-
-/**
- * Contains operators which can be chained to single one.
- *
- * For example, flatmap().map().reduce() can be chained to single operator as
- * no data shuffling is required.
- * @param ops list of operations
- */
-case class OpChain(ops: List[Op]) extends Op {
- def head: Op = ops.head
- def last: Op = ops.last
-
- def description: String = null
-
- override def conf: UserConfig = {
- // The head's conf has priority
- ops.reverse.foldLeft(UserConfig.empty) { (conf, op) =>
- conf.withConfig(op.conf)
- }
- }
-}
-
-trait OpEdge
-
-/**
- * The upstream OP and downstream OP doesn't require network data shuffle.
- *
- * For example, map, flatmap operation doesn't require network shuffle, we can use Direct
- * to represent the relation with upstream operators.
- */
-case object Direct extends OpEdge
-
-/**
- * The upstream OP and downstream OP DOES require network data shuffle.
- *
- * For example, map, flatmap operation doesn't require network shuffle, we can use Direct
- * to represent the relation with upstream operators.
- */
-case object Shuffle extends OpEdge
-
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/dsl/partitioner/GroupbyPartitioner.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/dsl/partitioner/GroupbyPartitioner.scala b/streaming/src/main/scala/io/gearpump/streaming/dsl/partitioner/GroupbyPartitioner.scala
deleted file mode 100644
index b842c7b..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/dsl/partitioner/GroupbyPartitioner.scala
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.dsl.partitioner
-
-import io.gearpump.Message
-import io.gearpump.partitioner.UnicastPartitioner
-
-/**
- * Partition messages by applying group by function first.
- *
- * For example:
- * {{{
- * case class People(name: String, gender: String)
- *
- * object Test{
- *
- * val groupBy: (People => String) = people => people.gender
- * val partitioner = GroupByPartitioner(groupBy)
- * }
- * }}}
- *
- * @param groupBy First apply message with groupBy function, then pick the hashCode of the output
- * to do the partitioning. You must define hashCode() for output type of groupBy function.
- */
-class GroupByPartitioner[T, GROUP](groupBy: T => GROUP = null) extends UnicastPartitioner {
- override def getPartition(msg: Message, partitionNum: Int, currentPartitionId: Int): Int = {
- val hashCode = groupBy(msg.msg.asInstanceOf[T]).hashCode()
- (hashCode & Integer.MAX_VALUE) % partitionNum
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/dsl/plan/OpTranslator.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/dsl/plan/OpTranslator.scala b/streaming/src/main/scala/io/gearpump/streaming/dsl/plan/OpTranslator.scala
deleted file mode 100644
index 11b4c34..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/dsl/plan/OpTranslator.scala
+++ /dev/null
@@ -1,296 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.dsl.plan
-
-import scala.collection.TraversableOnce
-
-import akka.actor.ActorSystem
-import org.slf4j.Logger
-
-import io.gearpump._
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.Constants._
-import io.gearpump.streaming.Processor
-import io.gearpump.streaming.Processor.DefaultProcessor
-import io.gearpump.streaming.dsl.op._
-import io.gearpump.streaming.dsl.plan.OpTranslator._
-import io.gearpump.streaming.sink.DataSink
-import io.gearpump.streaming.source.DataSource
-import io.gearpump.streaming.task.{StartTime, Task, TaskContext}
-import io.gearpump.util.LogUtil
-
-/**
- * Translates a OP to a TaskDescription
- */
-class OpTranslator extends java.io.Serializable {
- val LOG: Logger = LogUtil.getLogger(getClass)
-
- def translate(ops: OpChain)(implicit system: ActorSystem): Processor[_ <: Task] = {
-
- val baseConfig = ops.conf
-
- ops.ops.head match {
- case op: MasterOp =>
- val tail = ops.ops.tail
- val func = toFunction(tail)
- val userConfig = baseConfig.withValue(GEARPUMP_STREAMING_OPERATOR, func)
-
- op match {
- case DataSourceOp(dataSource, parallism, conf, description) =>
- Processor[SourceTask[Object, Object]](parallism,
- description = description + "." + func.description,
- userConfig.withValue(GEARPUMP_STREAMING_SOURCE, dataSource))
- case groupby@GroupByOp(_, parallism, description, _) =>
- Processor[GroupByTask[Object, Object, Object]](parallism,
- description = description + "." + func.description,
- userConfig.withValue(GEARPUMP_STREAMING_GROUPBY_FUNCTION, groupby))
- case merge: MergeOp =>
- Processor[TransformTask[Object, Object]](1,
- description = op.description + "." + func.description,
- userConfig)
- case ProcessorOp(processor, parallism, conf, description) =>
- DefaultProcessor(parallism,
- description = description + "." + func.description,
- userConfig, processor)
- case DataSinkOp(dataSink, parallelism, conf, description) =>
- Processor[SinkTask[Object]](parallelism,
- description = description + func.description,
- userConfig.withValue(GEARPUMP_STREAMING_SINK, dataSink))
- }
- case op: SlaveOp[_] =>
- val func = toFunction(ops.ops)
- val userConfig = baseConfig.withValue(GEARPUMP_STREAMING_OPERATOR, func)
-
- Processor[TransformTask[Object, Object]](1,
- description = func.description,
- taskConf = userConfig)
- case chain: OpChain =>
- throw new RuntimeException("Not supposed to be called!")
- }
- }
-
- private def toFunction(ops: List[Op]): SingleInputFunction[Object, Object] = {
- val func: SingleInputFunction[Object, Object] = new DummyInputFunction[Object]()
- val totalFunction = ops.foldLeft(func) { (fun, op) =>
-
- val opFunction = op match {
- case flatmap: FlatMapOp[Object @unchecked, Object @unchecked] =>
- new FlatMapFunction(flatmap.fun, flatmap.description)
- case reduce: ReduceOp[Object @unchecked] =>
- new ReduceFunction(reduce.fun, reduce.description)
- case _ =>
- throw new RuntimeException("Not supposed to be called!")
- }
- fun.andThen(opFunction.asInstanceOf[SingleInputFunction[Object, Object]])
- }
- totalFunction.asInstanceOf[SingleInputFunction[Object, Object]]
- }
-}
-
-object OpTranslator {
-
- trait SingleInputFunction[IN, OUT] extends Serializable {
- def process(value: IN): TraversableOnce[OUT]
- def andThen[OUTER](other: SingleInputFunction[OUT, OUTER]): SingleInputFunction[IN, OUTER] = {
- new AndThen(this, other)
- }
-
- def description: String
- }
-
- class DummyInputFunction[T] extends SingleInputFunction[T, T] {
- override def andThen[OUTER](other: SingleInputFunction[T, OUTER])
- : SingleInputFunction[T, OUTER] = {
- other
- }
-
- // Should never be called
- override def process(value: T): TraversableOnce[T] = None
-
- override def description: String = ""
- }
-
- class AndThen[IN, MIDDLE, OUT](
- first: SingleInputFunction[IN, MIDDLE], second: SingleInputFunction[MIDDLE, OUT])
- extends SingleInputFunction[IN, OUT] {
-
- override def process(value: IN): TraversableOnce[OUT] = {
- first.process(value).flatMap(second.process(_))
- }
-
- override def description: String = {
- Option(first.description).flatMap { description =>
- Option(second.description).map(description + "." + _)
- }.getOrElse(null)
- }
- }
-
- class FlatMapFunction[IN, OUT](fun: IN => TraversableOnce[OUT], descriptionMessage: String)
- extends SingleInputFunction[IN, OUT] {
-
- override def process(value: IN): TraversableOnce[OUT] = {
- fun(value)
- }
-
- override def description: String = {
- this.descriptionMessage
- }
- }
-
- class ReduceFunction[T](fun: (T, T) => T, descriptionMessage: String)
- extends SingleInputFunction[T, T] {
-
- private var state: Any = null
-
- override def process(value: T): TraversableOnce[T] = {
- if (state == null) {
- state = value
- } else {
- state = fun(state.asInstanceOf[T], value)
- }
- Some(state.asInstanceOf[T])
- }
-
- override def description: String = descriptionMessage
- }
-
- class GroupByTask[IN, GROUP, OUT](
- groupBy: IN => GROUP, taskContext: TaskContext, userConf: UserConfig)
- extends Task(taskContext, userConf) {
-
- def this(taskContext: TaskContext, userConf: UserConfig) = {
- this(userConf.getValue[GroupByOp[IN, GROUP]](
- GEARPUMP_STREAMING_GROUPBY_FUNCTION )(taskContext.system).get.fun,
- taskContext, userConf)
- }
-
- private var groups = Map.empty[GROUP, SingleInputFunction[IN, OUT]]
-
- override def onStart(startTime: StartTime): Unit = {
- }
-
- override def onNext(msg: Message): Unit = {
- val time = msg.timestamp
-
- val group = groupBy(msg.msg.asInstanceOf[IN])
- if (!groups.contains(group)) {
- val operator =
- userConf.getValue[SingleInputFunction[IN, OUT]](GEARPUMP_STREAMING_OPERATOR).get
- groups += group -> operator
- }
-
- val operator = groups(group)
-
- operator.process(msg.msg.asInstanceOf[IN]).foreach { msg =>
- taskContext.output(new Message(msg.asInstanceOf[AnyRef], time))
- }
- }
- }
-
- class SourceTask[T, OUT](
- source: DataSource, operator: Option[SingleInputFunction[T, OUT]], taskContext: TaskContext,
- userConf: UserConfig)
- extends Task(taskContext, userConf) {
-
- def this(taskContext: TaskContext, userConf: UserConfig) = {
- this(
- userConf.getValue[DataSource](GEARPUMP_STREAMING_SOURCE)(taskContext.system).get,
- userConf.getValue[SingleInputFunction[T, OUT]](GEARPUMP_STREAMING_OPERATOR)(
- taskContext.system),
- taskContext, userConf)
- }
-
- override def onStart(startTime: StartTime): Unit = {
- source.open(taskContext, startTime.startTime)
- self ! Message("start", System.currentTimeMillis())
- }
-
- override def onNext(msg: Message): Unit = {
- val time = System.currentTimeMillis()
- Option(source.read()).foreach { msg =>
- operator match {
- case Some(operator) =>
- operator match {
- case bad: DummyInputFunction[T] =>
- taskContext.output(msg)
- case _ =>
- operator.process(msg.msg.asInstanceOf[T]).foreach(msg => {
- taskContext.output(new Message(msg.asInstanceOf[AnyRef], time))
- })
- }
- case None =>
- taskContext.output(msg)
- }
- }
-
- self ! Message("next", System.currentTimeMillis())
- }
-
- override def onStop(): Unit = {
- source.close()
- }
- }
-
- class TransformTask[IN, OUT](
- operator: Option[SingleInputFunction[IN, OUT]], taskContext: TaskContext,
- userConf: UserConfig) extends Task(taskContext, userConf) {
-
- def this(taskContext: TaskContext, userConf: UserConfig) = {
- this(userConf.getValue[SingleInputFunction[IN, OUT]](
- GEARPUMP_STREAMING_OPERATOR)(taskContext.system), taskContext, userConf)
- }
-
- override def onStart(startTime: StartTime): Unit = {
- }
-
- override def onNext(msg: Message): Unit = {
- val time = msg.timestamp
-
- operator match {
- case Some(operator) =>
- operator.process(msg.msg.asInstanceOf[IN]).foreach { msg =>
- taskContext.output(new Message(msg.asInstanceOf[AnyRef], time))
- }
- case None =>
- taskContext.output(new Message(msg.msg, time))
- }
- }
- }
-
- class SinkTask[T](dataSink: DataSink, taskContext: TaskContext, userConf: UserConfig)
- extends Task(taskContext, userConf) {
-
- def this(taskContext: TaskContext, userConf: UserConfig) = {
- this(userConf.getValue[DataSink](GEARPUMP_STREAMING_SINK)(taskContext.system).get,
- taskContext, userConf)
- }
-
- override def onStart(startTime: StartTime): Unit = {
- dataSink.open(taskContext)
- }
-
- override def onNext(msg: Message): Unit = {
- dataSink.write(msg)
- }
-
- override def onStop(): Unit = {
- dataSink.close()
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/dsl/plan/Planner.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/dsl/plan/Planner.scala b/streaming/src/main/scala/io/gearpump/streaming/dsl/plan/Planner.scala
deleted file mode 100644
index aafd8d3..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/dsl/plan/Planner.scala
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.dsl.plan
-
-import akka.actor.ActorSystem
-
-import io.gearpump.partitioner.{CoLocationPartitioner, HashPartitioner, Partitioner}
-import io.gearpump.streaming.Processor
-import io.gearpump.streaming.dsl.op._
-import io.gearpump.streaming.dsl.partitioner.GroupByPartitioner
-import io.gearpump.streaming.task.Task
-import io.gearpump.util.Graph
-
-class Planner {
-
- /*
- * Converts Dag of Op to Dag of TaskDescription. TaskDescription is part of the low
- * level Graph API.
- */
- def plan(dag: Graph[Op, OpEdge])(implicit system: ActorSystem)
- : Graph[Processor[_ <: Task], _ <: Partitioner] = {
-
- val opTranslator = new OpTranslator()
-
- val newDag = optimize(dag)
- newDag.mapEdge { (node1, edge, node2) =>
- edge match {
- case Shuffle =>
- node2.head match {
- case groupBy: GroupByOp[Any @unchecked, Any @unchecked] =>
- new GroupByPartitioner(groupBy.fun)
- case _ => new HashPartitioner
- }
- case Direct =>
- new CoLocationPartitioner
- }
- }.mapVertex { opChain =>
- opTranslator.translate(opChain)
- }
- }
-
- private def optimize(dag: Graph[Op, OpEdge]): Graph[OpChain, OpEdge] = {
- val newGraph = dag.mapVertex(op => OpChain(List(op)))
-
- val nodes = newGraph.topologicalOrderWithCirclesIterator.toList.reverse
- for (node <- nodes) {
- val outGoingEdges = newGraph.outgoingEdgesOf(node)
- for (edge <- outGoingEdges) {
- merge(newGraph, edge._1, edge._3)
- }
- }
- newGraph
- }
-
- private def merge(dag: Graph[OpChain, OpEdge], node1: OpChain, node2: OpChain)
- : Graph[OpChain, OpEdge] = {
- if (dag.outDegreeOf(node1) == 1 &&
- dag.inDegreeOf(node2) == 1 &&
- // For processor node, we don't allow it to merge with downstream operators
- !node1.head.isInstanceOf[ProcessorOp[_ <: Task]]) {
- val (_, edge, _) = dag.outgoingEdgesOf(node1)(0)
- if (edge == Direct) {
- val opList = OpChain(node1.ops ++ node2.ops)
- dag.addVertex(opList)
- for (incomingEdge <- dag.incomingEdgesOf(node1)) {
- dag.addEdge(incomingEdge._1, incomingEdge._2, opList)
- }
-
- for (outgoingEdge <- dag.outgoingEdgesOf(node2)) {
- dag.addEdge(opList, outgoingEdge._2, outgoingEdge._3)
- }
-
- // Remove the old vertex
- dag.removeVertex(node1)
- dag.removeVertex(node2)
- }
- }
- dag
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/executor/Executor.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/executor/Executor.scala b/streaming/src/main/scala/io/gearpump/streaming/executor/Executor.scala
deleted file mode 100644
index 48007d5..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/executor/Executor.scala
+++ /dev/null
@@ -1,476 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.executor
-
-import java.lang.management.ManagementFactory
-import scala.concurrent.duration._
-
-import akka.actor.SupervisorStrategy.Resume
-import akka.actor._
-import com.typesafe.config.Config
-import org.apache.commons.lang.exception.ExceptionUtils
-import org.slf4j.Logger
-
-import io.gearpump.cluster.worker.WorkerId
-import io.gearpump.cluster.{ClusterConfig, ExecutorContext, UserConfig}
-import io.gearpump.metrics.Metrics.ReportMetrics
-import io.gearpump.metrics.{JvmMetricsSet, Metrics, MetricsReporterService}
-import io.gearpump.serializer.SerializationFramework
-import io.gearpump.streaming.AppMasterToExecutor.{MsgLostException, TasksChanged, TasksLaunched, _}
-import io.gearpump.streaming.ExecutorToAppMaster.{MessageLoss, RegisterExecutor, RegisterTask, UnRegisterTask}
-import io.gearpump.streaming.ProcessorId
-import io.gearpump.streaming.executor.Executor._
-import io.gearpump.streaming.executor.TaskLauncher.TaskArgument
-import io.gearpump.streaming.task.{Subscriber, TaskId}
-import io.gearpump.transport.{Express, HostPort}
-import io.gearpump.util.Constants._
-import io.gearpump.util.{ActorUtil, Constants, LogUtil, TimeOutScheduler}
-
-/**
- * Executor is child of AppMaster.
- * It usually represents a JVM process. It is a container for all tasks.
- */
-
-// TODO: What if Executor stuck in state DynamicDag and cannot get out???
-// For example, due to some message loss when there is network glitch.
-// Executor will hang there for ever???
-//
-class Executor(executorContext: ExecutorContext, userConf : UserConfig, launcher: ITaskLauncher)
- extends Actor with TimeOutScheduler{
-
- def this(executorContext: ExecutorContext, userConf: UserConfig) = {
- this(executorContext, userConf, TaskLauncher(executorContext, userConf))
- }
-
- import context.dispatcher
- import executorContext.{appId, appMaster, executorId, resource, worker}
-
- private val LOG: Logger = LogUtil.getLogger(getClass, executor = executorId, app = appId)
-
- private implicit val timeOut = FUTURE_TIMEOUT
- private val address = ActorUtil.getFullPath(context.system, self.path)
- private val systemConfig = context.system.settings.config
- private val serializerPool = getSerializerPool()
- private val taskDispatcher = systemConfig.getString(Constants.GEARPUMP_TASK_DISPATCHER)
-
- private var state = State.ACTIVE
- private var transitionStart = 0L
- // States transition start, in unix time
- private var transitionEnd = 0L
- // States transition end, in unix time
- private val transitWarningThreshold = 5000 // ms,
-
- // Starts health check Ticks
- self ! HealthCheck
-
- LOG.info(s"Executor $executorId has been started, start to register itself...")
- LOG.info(s"Executor actor path: ${ActorUtil.getFullPath(context.system, self.path)}")
-
- appMaster ! RegisterExecutor(self, executorId, resource, worker)
- context.watch(appMaster)
-
- private var tasks = Map.empty[TaskId, ActorRef]
- private val taskArgumentStore = new TaskArgumentStore()
-
- val express = Express(context.system)
-
- val metricsEnabled = systemConfig.getBoolean(GEARPUMP_METRIC_ENABLED)
-
- if (metricsEnabled) {
- // Registers jvm metrics
- Metrics(context.system).register(new JvmMetricsSet(s"app$appId.executor$executorId"))
-
- val metricsReportService = context.actorOf(Props(new MetricsReporterService(
- Metrics(context.system))))
- appMaster.tell(ReportMetrics, metricsReportService)
- }
-
- private val NOT_INITIALIZED = -1
- def receive: Receive = applicationReady(dagVersion = NOT_INITIALIZED)
-
- private def getTaskId(actorRef: ActorRef): Option[TaskId] = {
- tasks.find(_._2 == actorRef).map(_._1)
- }
-
- override val supervisorStrategy =
- OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1.minute) {
- case _: MsgLostException =>
- val taskId = getTaskId(sender)
- val cause = s"We got MessageLossException from task ${getTaskId(sender)}, " +
- s"replaying application..."
- LOG.error(cause)
- taskId.foreach(appMaster ! MessageLoss(executorId, _, cause))
- Resume
- case ex: Throwable =>
- val taskId = getTaskId(sender)
- val errorMsg = s"We got ${ex.getClass.getName} from $taskId, we will treat it as" +
- s" MessageLoss, so that the system will replay all lost message"
- LOG.error(errorMsg, ex)
- val detailErrorMsg = errorMsg + "\n" + ExceptionUtils.getStackTrace(ex)
- taskId.foreach(appMaster ! MessageLoss(executorId, _, detailErrorMsg))
- Resume
- }
-
- private def launchTask(taskId: TaskId, argument: TaskArgument): ActorRef = {
- launcher.launch(List(taskId), argument, context, serializerPool, taskDispatcher).values.head
- }
-
- private def assertVersion(expectVersion: Int, version: Int, clue: Any): Unit = {
- if (expectVersion != version) {
- val errorMessage = s"Version mismatch: we expect dag version $expectVersion, " +
- s"but get $version; clue: $clue"
- LOG.error(errorMessage)
- throw new DagVersionMismatchException(errorMessage)
- }
- }
-
- def dynamicDagPhase1(
- dagVersion: Int, launched: List[TaskId], changed: List[ChangeTask], registered: List[TaskId])
- : Receive = {
- state = State.DYNAMIC_DAG_PHASE1
- box({
- case launch@LaunchTasks(taskIds, version, processorDescription,
- subscribers: List[Subscriber]) => {
- assertVersion(dagVersion, version, clue = launch)
-
- LOG.info(s"Launching Task $taskIds for app: $appId")
- val taskArgument = TaskArgument(version, processorDescription, subscribers)
- taskIds.foreach(taskArgumentStore.add(_, taskArgument))
- val newAdded = launcher.launch(taskIds, taskArgument, context, serializerPool,
- taskDispatcher)
- newAdded.foreach { newAddedTask =>
- context.watch(newAddedTask._2)
- }
- tasks ++= newAdded
- sender ! TasksLaunched
- context.become(dynamicDagPhase1(version, launched ++ taskIds, changed, registered))
- }
- case change@ChangeTasks(taskIds, version, life, subscribers) =>
- assertVersion(dagVersion, version, clue = change)
-
- LOG.info(s"Change Tasks $taskIds for app: $appId, verion: $life, $dagVersion, $subscribers")
-
- val newChangedTasks = taskIds.map { taskId =>
- for (taskArgument <- taskArgumentStore.get(dagVersion, taskId)) {
- val processorDescription = taskArgument.processorDescription.copy(life = life)
- taskArgumentStore.add(taskId, TaskArgument(dagVersion, processorDescription,
- subscribers))
- }
- ChangeTask(taskId, dagVersion, life, subscribers)
- }
- sender ! TasksChanged(taskIds)
- context.become(dynamicDagPhase1(dagVersion, launched, changed ++ newChangedTasks,
- registered))
-
- case locations@TaskLocationsReady(taskLocations, version) =>
- LOG.info(s"TaskLocations Ready...")
- assertVersion(dagVersion, version, clue = locations)
-
- // Check whether all tasks has been registered.
- if ((launched.toSet -- registered.toSet).isEmpty) {
- // Confirm all tasks has been registered.
- val result = taskLocations.locations.filter {
- location => !location._1.equals(express.localHost)
- }.flatMap { kv =>
- val (host, taskIdList) = kv
- taskIdList.map(taskId => (TaskId.toLong(taskId), host))
- }
-
- val replyTo = sender
- express.startClients(taskLocations.locations.keySet).foreach { _ =>
- express.remoteAddressMap.send(result)
- express.remoteAddressMap.future().foreach { _ =>
- LOG.info(s"sending TaskLocationsReceived back to appmaster")
- replyTo ! TaskLocationsReceived(version, executorId)
- }
- }
- context.become(dynamicDagPhase2(dagVersion, launched, changed))
- } else {
- LOG.error("Inconsistency between AppMaser and Executor! AppMaster thinks DynamicDag " +
- "transition is ready, while Executor have not get all tasks registered, " +
- "that task will not be functional...")
-
- // Reject TaskLocations...
- val missedTasks = (launched.toSet -- registered.toSet).toList
- val errorMsg = "We have not received TaskRegistered for following tasks: " +
- missedTasks.mkString(", ")
- LOG.error(errorMsg)
- sender ! TaskLocationsRejected(dagVersion, executorId, errorMsg, null)
- // Stays with current status...
- }
-
- case confirm: TaskRegistered =>
- tasks.get(confirm.taskId).foreach {
- case actorRef: ActorRef =>
- tasks += confirm.taskId -> actorRef
- actorRef forward confirm
- }
- context.become(dynamicDagPhase1(dagVersion, launched, changed,
- registered :+ confirm.taskId))
-
- case rejected: TaskRejected =>
- // Means this task shoud not exists...
- tasks.get(rejected.taskId).foreach(_ ! PoisonPill)
- tasks -= rejected.taskId
- LOG.error(s"Task ${rejected.taskId} is rejected by AppMaster, shutting down it...")
-
- case register: RegisterTask =>
- appMaster ! register
- })
- }
-
- def dynamicDagPhase2(dagVersion: Int, launched: List[TaskId], changed: List[ChangeTask])
- : Receive = {
- LOG.info("Transit to dynamic Dag Phase2")
- state = State.DYNAMIC_DAG_PHASE2
- box {
- case startAll@StartAllTasks(version) =>
- LOG.info(s"Start All Tasks...")
- assertVersion(dagVersion, version, clue = startAll)
-
- launched.foreach(taskId => tasks.get(taskId).foreach(_ ! StartTask(taskId)))
- changed.foreach(changeTask => tasks.get(changeTask.taskId).foreach(_ ! changeTask))
-
- taskArgumentStore.removeNewerVersion(dagVersion)
- taskArgumentStore.removeObsoleteVersion
- context.become(applicationReady(dagVersion))
- }
- }
-
- def applicationReady(dagVersion: Int): Receive = {
- state = State.ACTIVE
- transitionEnd = System.currentTimeMillis()
-
- if (dagVersion != NOT_INITIALIZED) {
- LOG.info("Transit to state Application Ready. This transition takes " +
- (transitionEnd - transitionStart) + " milliseconds")
- }
- box {
- case start: StartDynamicDag =>
- LOG.info("received StartDynamicDag")
- if (start.dagVersion > dagVersion) {
- transitionStart = System.currentTimeMillis()
- LOG.info(s"received $start, Executor transit to dag version: ${start.dagVersion} from " +
- s"current version $dagVersion")
- context.become(dynamicDagPhase1(start.dagVersion, List.empty[TaskId],
- List.empty[ChangeTask], List.empty[TaskId]))
- }
- case launch: LaunchTasks =>
- if (launch.dagVersion > dagVersion) {
- transitionStart = System.currentTimeMillis()
- LOG.info(s"received $launch, Executor transit to dag " +
- s"version: ${launch.dagVersion} from current version $dagVersion")
- context.become(dynamicDagPhase1(launch.dagVersion, List.empty[TaskId],
- List.empty[ChangeTask], List.empty[TaskId]))
- self forward launch
- }
-
- case change: ChangeTasks =>
- if (change.dagVersion > dagVersion) {
- transitionStart = System.currentTimeMillis()
- LOG.info(s"received $change, Executor transit to dag version: ${change.dagVersion} from" +
- s" current version $dagVersion")
- context.become(dynamicDagPhase1(change.dagVersion, List.empty[TaskId],
- List.empty[ChangeTask], List.empty[TaskId]))
- self forward change
- }
-
- case StopTask(taskId) =>
- // Old soldiers never die, they just fade away ;)
- val fadeAwayTask = tasks.get(taskId)
- if (fadeAwayTask.isDefined) {
- context.stop(fadeAwayTask.get)
- }
- tasks -= taskId
-
- case unRegister@UnRegisterTask(taskId, _) =>
- // Sends UnRegisterTask to AppMaster
- appMaster ! unRegister
- }
- }
-
- def restartingTasks(dagVersion: Int, remain: Int, needRestart: List[TaskId]): Receive = {
- state = State.RECOVERY
- box {
- case TaskStopped(actor) =>
- for (taskId <- getTaskId(actor)) {
- if (taskArgumentStore.get(dagVersion, taskId).nonEmpty) {
- val newNeedRestart = needRestart :+ taskId
- val newRemain = remain - 1
- if (newRemain == 0) {
- val newRestarted = newNeedRestart.map { taskId_ =>
- val taskActor = launchTask(taskId_, taskArgumentStore.get(dagVersion, taskId_).get)
- context.watch(taskActor)
- taskId_ -> taskActor
- }.toMap
-
- tasks = newRestarted
- context.become(dynamicDagPhase1(dagVersion, newNeedRestart, List.empty[ChangeTask],
- List.empty[TaskId]))
- } else {
- context.become(restartingTasks(dagVersion, newRemain, newNeedRestart))
- }
- }
- }
- }
- }
-
- val terminationWatch: Receive = {
- case Terminated(actor) =>
- if (actor.compareTo(appMaster) == 0) {
- LOG.info(s"AppMaster ${appMaster.path.toString} is terminated, shutting down current " +
- s"executor $appId, $executorId")
- context.stop(self)
- } else {
- self ! TaskStopped(actor)
- }
- }
-
- def onRestartTasks: Receive = {
- case RestartTasks(dagVersion) =>
- LOG.info(s"Executor received restart tasks")
- val tasksToRestart = tasks.keys.count(taskArgumentStore.get(dagVersion, _).nonEmpty)
- express.remoteAddressMap.send(Map.empty[Long, HostPort])
- context.become(restartingTasks(dagVersion, remain = tasksToRestart,
- needRestart = List.empty[TaskId]))
-
- tasks.values.foreach {
- case task: ActorRef => task ! PoisonPill
- }
- }
-
- def executorService: Receive = terminationWatch orElse onRestartTasks orElse {
- case taskChanged: TaskChanged =>
- // Skip
- case get: GetExecutorSummary =>
- val logFile = LogUtil.applicationLogDir(systemConfig)
- val processorTasks = tasks.keySet.groupBy(_.processorId).mapValues(_.toList).view.force
- sender ! ExecutorSummary(
- executorId,
- worker.workerId,
- address,
- logFile.getAbsolutePath,
- state,
- tasks.size,
- processorTasks,
- jvmName = ManagementFactory.getRuntimeMXBean().getName())
-
- case query: QueryExecutorConfig =>
- sender ! ExecutorConfig(ClusterConfig.filterOutDefaultConfig(systemConfig))
- case HealthCheck =>
- context.system.scheduler.scheduleOnce(3.second)(HealthCheck)
- if (state != State.ACTIVE && (transitionEnd - transitionStart) > transitWarningThreshold) {
- LOG.error(s"Executor status: " + state +
- s", it takes too long(${transitionEnd - transitionStart}) to do transition")
- }
- }
-
- private def getSerializerPool(): SerializationFramework = {
- val system = context.system.asInstanceOf[ExtendedActorSystem]
- val clazz = Class.forName(systemConfig.getString(Constants.GEARPUMP_SERIALIZER_POOL))
- val pool = clazz.newInstance().asInstanceOf[SerializationFramework]
- pool.init(system, userConf)
- pool.asInstanceOf[SerializationFramework]
- }
-
- private def unHandled(state: String): Receive = {
- case other =>
- LOG.info(s"Received unknown message $other in state: $state")
- }
-
- private def box(receive: Receive): Receive = {
- executorService orElse receive orElse unHandled(state)
- }
-}
-
-object Executor {
- case class RestartTasks(dagVersion: Int)
-
- class TaskArgumentStore {
-
- private var store = Map.empty[TaskId, List[TaskArgument]]
-
- def add(taskId: TaskId, task: TaskArgument): Unit = {
- val list = store.getOrElse(taskId, List.empty[TaskArgument])
- store += taskId -> (task :: list)
- }
-
- def get(dagVersion: Int, taskId: TaskId): Option[TaskArgument] = {
- store.get(taskId).flatMap { list =>
- list.find { arg =>
- arg.dagVersion <= dagVersion
- }
- }
- }
-
- /**
- * When the new DAG is successfully deployed, then we should remove obsolete
- * TaskArgument of old DAG.
- */
- def removeObsoleteVersion(): Unit = {
- store = store.map { kv =>
- val (k, list) = kv
- (k, list.take(1))
- }
- }
-
- def removeNewerVersion(currentVersion: Int): Unit = {
- store = store.map { kv =>
- val (k, list) = kv
- (k, list.filter(_.dagVersion <= currentVersion))
- }
- }
- }
-
- case class TaskStopped(task: ActorRef)
-
- case class ExecutorSummary(
- id: Int,
- workerId: WorkerId,
- actorPath: String,
- logFile: String,
- status: String,
- taskCount: Int,
- tasks: Map[ProcessorId, List[TaskId]],
- jvmName: String
- )
-
- object ExecutorSummary {
- def empty: ExecutorSummary = {
- ExecutorSummary(0, WorkerId.unspecified, "", "", "", 1, null, jvmName = "")
- }
- }
-
- case class GetExecutorSummary(executorId: Int)
-
- case class QueryExecutorConfig(executorId: Int)
-
- case class ExecutorConfig(config: Config)
-
- class DagVersionMismatchException(msg: String) extends Exception(msg)
-
- object State {
- val ACTIVE = "active"
- val DYNAMIC_DAG_PHASE1 = "dynamic_dag_phase1"
- val DYNAMIC_DAG_PHASE2 = "dynamic_dag_phase2"
- val RECOVERY = "dag_recovery"
- }
-
- object HealthCheck
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/executor/ExecutorRestartPolicy.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/executor/ExecutorRestartPolicy.scala b/streaming/src/main/scala/io/gearpump/streaming/executor/ExecutorRestartPolicy.scala
deleted file mode 100644
index c40aa5f..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/executor/ExecutorRestartPolicy.scala
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.executor
-
-import scala.collection.immutable
-import scala.concurrent.duration.Duration
-
-import io.gearpump.streaming.task.TaskId
-import io.gearpump.util.RestartPolicy
-
-/**
- *
- * Controls how many retries to recover failed executors.
- *
- * @param maxNrOfRetries the number of times a executor is allowed to be restarted,
- * negative value means no limit, if the limit is exceeded the policy
- * will not allow to restart the executor
- * @param withinTimeRange duration of the time window for maxNrOfRetries, Duration.Inf
- * means no window
- */
-class ExecutorRestartPolicy(maxNrOfRetries: Int, withinTimeRange: Duration) {
- private var executorToTaskIds = Map.empty[Int, Set[TaskId]]
- private var taskRestartPolocies = new immutable.HashMap[TaskId, RestartPolicy]
-
- def addTaskToExecutor(executorId: Int, taskId: TaskId): Unit = {
- var taskSetForExecutorId = executorToTaskIds.getOrElse(executorId, Set.empty[TaskId])
- taskSetForExecutorId += taskId
- executorToTaskIds += executorId -> taskSetForExecutorId
- if (!taskRestartPolocies.contains(taskId)) {
- taskRestartPolocies += taskId -> new RestartPolicy(maxNrOfRetries, withinTimeRange)
- }
- }
-
- def allowRestartExecutor(executorId: Int): Boolean = {
- executorToTaskIds.get(executorId).map { taskIds =>
- taskIds.foreach { taskId =>
- taskRestartPolocies.get(taskId).map { policy =>
- if (!policy.allowRestart) {
- // scalastyle:off return
- return false
- // scalastyle:on return
- }
- }
- }
- }
- true
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/executor/TaskLauncher.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/executor/TaskLauncher.scala b/streaming/src/main/scala/io/gearpump/streaming/executor/TaskLauncher.scala
deleted file mode 100644
index d377ea4..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/executor/TaskLauncher.scala
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.executor
-
-import akka.actor.{Actor, ActorRef, ActorRefFactory, Props}
-
-import io.gearpump.cluster.{ExecutorContext, UserConfig}
-import io.gearpump.serializer.SerializationFramework
-import io.gearpump.streaming.ProcessorDescription
-import io.gearpump.streaming.executor.TaskLauncher.TaskArgument
-import io.gearpump.streaming.task._
-import io.gearpump.streaming.util.ActorPathUtil
-
-trait ITaskLauncher {
-
- /** Launch a list of task actors */
- def launch(taskIds: List[TaskId], argument: TaskArgument,
- context: ActorRefFactory, serializer: SerializationFramework, dispatcher: String)
- : Map[TaskId, ActorRef]
-}
-
-class TaskLauncher(
- appId: Int,
- appName: String,
- executorId: Int,
- appMaster: ActorRef,
- userConf: UserConfig,
- taskActorClass: Class[_ <: Actor])
- extends ITaskLauncher{
-
- override def launch(
- taskIds: List[TaskId], argument: TaskArgument,
- context: ActorRefFactory, serializer: SerializationFramework, dispatcher: String)
- : Map[TaskId, ActorRef] = {
- import argument.{processorDescription, subscribers}
-
- val taskConf = userConf.withConfig(processorDescription.taskConf)
-
- val taskContext = TaskContextData(executorId,
- appId, appName, appMaster,
- processorDescription.parallelism,
- processorDescription.life, subscribers)
-
- val taskClass = TaskUtil.loadClass(processorDescription.taskClass)
-
- var tasks = Map.empty[TaskId, ActorRef]
- taskIds.foreach { taskId =>
- val task = new TaskWrapper(taskId, taskClass, taskContext, taskConf)
- val taskActor = context.actorOf(Props(taskActorClass, taskId, taskContext, userConf, task,
- serializer).withDispatcher(dispatcher), ActorPathUtil.taskActorName(taskId))
- tasks += taskId -> taskActor
- }
- tasks
- }
-}
-
-object TaskLauncher {
-
- case class TaskArgument(
- dagVersion: Int, processorDescription: ProcessorDescription,
- subscribers: List[Subscriber])
-
- def apply(executorContext: ExecutorContext, userConf: UserConfig): TaskLauncher = {
- import executorContext.{appId, appMaster, appName, executorId}
- new TaskLauncher(appId, appName, executorId, appMaster, userConf, classOf[TaskActor])
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/metrics/ProcessorAggregator.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/metrics/ProcessorAggregator.scala b/streaming/src/main/scala/io/gearpump/streaming/metrics/ProcessorAggregator.scala
deleted file mode 100644
index 8be2e72..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/metrics/ProcessorAggregator.scala
+++ /dev/null
@@ -1,301 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.metrics
-
-import java.util
-
-import com.typesafe.config.Config
-
-import io.gearpump.TimeStamp
-import io.gearpump.cluster.ClientToMaster.ReadOption
-import io.gearpump.cluster.MasterToClient.HistoryMetricsItem
-import io.gearpump.google.common.collect.Iterators
-import io.gearpump.metrics.Metrics.{Histogram, Meter}
-import io.gearpump.metrics.MetricsAggregator
-import io.gearpump.streaming.metrics.ProcessorAggregator._
-import io.gearpump.util.HistoryMetricsService.HistoryMetricsConfig
-
-/**
- *
- * Does aggregation on metrics after grouping by these three attributes:
- * 1. processorId
- * 2. time section(represented as a index integer)
- * 3. metricName(like sendThroughput)
- *
- * It assumes that for each [[io.gearpump.cluster.MasterToClient.HistoryMetricsItem]], the name
- * follow the format app(appId).processor(processorId).task(taskId).(metricName)
- *
- * It parses the name to get processorId and metricName. If the parsing fails, then current
- * [[io.gearpump.cluster.MasterToClient.HistoryMetricsItem]] will be skipped.
- *
- * NOTE: this class is optimized for performance.
- */
-class ProcessorAggregator(historyMetricConfig: HistoryMetricsConfig) extends MetricsAggregator {
-
- def this(config: Config) = {
- this(HistoryMetricsConfig(config))
- }
-
- private val aggregatorFactory: AggregatorFactory = new AggregatorFactory()
-
- /**
- * Accepts options:
- * key: "readOption", value: one of "readLatest", "readRecent", "readHistory"
- */
- override def aggregate(options: Map[String, String],
- inputs: Iterator[HistoryMetricsItem]): List[HistoryMetricsItem] = {
- val readOption = options.get(ReadOption.Key).getOrElse(ReadOption.ReadLatest)
- aggregate(readOption, inputs, System.currentTimeMillis())
- }
-
- def aggregate(
- readOption: ReadOption.ReadOption, inputs: Iterator[HistoryMetricsItem], now: TimeStamp)
- : List[HistoryMetricsItem] = {
- val (start, end, interval) = getTimeRange(readOption, now)
- val timeSlotsCount = ((end - start - 1) / interval + 1).toInt
- val map = new MultiLayerMap[Aggregator](timeSlotsCount)
-
- val taskIdentity = new TaskIdentity(0, null)
- while (inputs.hasNext) {
- val item = inputs.next()
-
- if (item.value.isInstanceOf[Meter] || item.value.isInstanceOf[Histogram]) {
- if (item.time >= start && item.time < end) {
- val timeIndex = ((item.time - start) / interval).toInt
-
- if (parseName(item.value.name, taskIdentity)) {
- var op = map.get(timeIndex, taskIdentity.group)
- if (op == null) {
- op = aggregatorFactory.create(item, taskIdentity.group)
- map.put(timeIndex, taskIdentity.group, op)
- }
- op.aggregate(item)
- }
- }
- }
- }
-
- val result = new Array[HistoryMetricsItem](map.size)
- val iterator = map.valueIterator
- var index = 0
- while (iterator.hasNext()) {
- val op = iterator.next()
- result(index) = op.result
- index += 1
- }
-
- result.toList
- }
-
- // Returns (start, end, interval)
- private def getTimeRange(readOption: ReadOption.ReadOption, now: TimeStamp)
- : (TimeStamp, TimeStamp, TimeStamp) = {
- readOption match {
- case ReadOption.ReadRecent =>
- val end = now
- val start = end - (historyMetricConfig.retainRecentDataSeconds) * 1000
- val interval = historyMetricConfig.retainRecentDataIntervalMs
- (floor(start, interval), floor(end, interval), interval)
- case ReadOption.ReadHistory =>
- val end = now
- val start = end - (historyMetricConfig.retainHistoryDataHours) * 3600 * 1000
- val interval = historyMetricConfig.retainHistoryDataIntervalMs
- (floor(start, interval), floor(end, interval), interval)
- case _ =>
- // All data points are aggregated together.
- (0L, Long.MaxValue, Long.MaxValue)
- }
- }
-
- // The original metrics data is divided by interval points:
- // time series (0, interval, 2*interval, 3*interval....)
- // floor(..) make sure the Aggregator use the same set of interval points.
- private def floor(value: Long, interval: Long): Long = {
- (value / interval) * interval
- }
-
- // Returns "app0.processor0:sendThroughput" as the group Id.
- private def parseName(name: String, result: TaskIdentity): Boolean = {
- val taskIndex = name.indexOf(TASK_TAG)
- if (taskIndex > 0) {
- val processor = name.substring(0, taskIndex)
- val typeIndex = name.indexOf(":", taskIndex + 1)
- if (typeIndex > 0) {
- result.task = (name.substring(taskIndex + TASK_TAG.length, typeIndex)).toShort
- val metricName = name.substring(typeIndex)
- result.group = processor + metricName
- true
- } else {
- false
- }
- } else {
- false
- }
- }
-}
-
-object ProcessorAggregator {
- val readOption = ReadOption.Key
-
- private val TASK_TAG = ".task"
-
- private class TaskIdentity(var task: Short, var group: String)
-
- /**
- *
- * MultiLayerMap has multiple layers. For each layer, there
- * is a hashMap.
- *
- * To access a value with get, user need to specify first layer Id, then key.
- *
- * This class is optimized for performance.
- */
- class MultiLayerMap[Value](layers: Int) {
-
- private var _size: Int = 0
- private val map: Array[java.util.HashMap[String, Value]] = createMap(layers)
-
- /**
- * @param key key in current layer
- * @return return null if key is not found
- */
- def get(layer: Int, key: String): Value = {
- if (layer < layers) {
- map(layer).get(key)
- } else {
- null.asInstanceOf[Value]
- }
- }
-
- def put(layer: Int, key: String, value: Value): Unit = {
- if (layer < layers) {
- map(layer).put(key, value)
- _size += 1
- }
- }
-
- def size: Int = _size
-
- def valueIterator: util.Iterator[Value] = {
- val iterators = new Array[util.Iterator[Value]](layers)
- var layer = 0
- while (layer < layers) {
- iterators(layer) = map(layer).values().iterator()
- layer += 1
- }
-
- Iterators.concat(iterators: _*)
- }
-
- private def createMap(layers: Int) = {
- val map = new Array[java.util.HashMap[String, Value]](layers)
- var index = 0
- val length = map.length
- while (index < length) {
- map(index) = new java.util.HashMap[String, Value]()
- index += 1
- }
- map
- }
- }
-
- trait Aggregator {
- def aggregate(item: HistoryMetricsItem): Unit
- def result: HistoryMetricsItem
- }
-
- class HistogramAggregator(name: String) extends Aggregator {
-
- var count: Long = 0
- var mean: Double = 0
- var stddev: Double = 0
- var median: Double = 0
- var p95: Double = 0
- var p99: Double = 0
- var p999: Double = 0
-
- var startTime: TimeStamp = Long.MaxValue
-
- override def aggregate(item: HistoryMetricsItem): Unit = {
- val input = item.value.asInstanceOf[Histogram]
- count += 1
- mean += input.mean
- stddev += input.stddev
- median += input.median
- p95 += input.p95
- p99 += input.p99
- p999 += input.p999
-
- if (item.time < startTime) {
- startTime = item.time
- }
- }
-
- override def result: HistoryMetricsItem = {
- if (count > 0) {
- HistoryMetricsItem(startTime, Histogram(name, mean / count, stddev / count,
- median / count, p95 / count, p99 / count, p999 / count))
- } else {
- HistoryMetricsItem(0, Histogram(name, 0, 0, 0, 0, 0, 0))
- }
- }
- }
-
- class MeterAggregator(name: String) extends Aggregator {
-
- var count: Long = 0
- var meanRate: Double = 0
- var m1: Double = 0
- var rateUnit: String = null
-
- var startTime: TimeStamp = Long.MaxValue
-
- override def aggregate(item: HistoryMetricsItem): Unit = {
-
- val input = item.value.asInstanceOf[Meter]
- count += input.count
-
- meanRate += input.meanRate
- m1 += input.m1
-
- if (null == rateUnit) {
- rateUnit = input.rateUnit
- }
-
- if (item.time < startTime) {
- startTime = item.time
- }
- }
-
- override def result: HistoryMetricsItem = {
- HistoryMetricsItem(startTime, Meter(name, count, meanRate,
- m1, rateUnit))
- }
- }
-
- class AggregatorFactory {
- def create(item: HistoryMetricsItem, name: String): Aggregator = {
- item.value match {
- case meter: Meter => new MeterAggregator(name)
- case histogram: Histogram => new HistogramAggregator(name)
- case _ => null // not supported
- }
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/metrics/TaskFilterAggregator.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/metrics/TaskFilterAggregator.scala b/streaming/src/main/scala/io/gearpump/streaming/metrics/TaskFilterAggregator.scala
deleted file mode 100644
index dbf79ec..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/metrics/TaskFilterAggregator.scala
+++ /dev/null
@@ -1,157 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.metrics
-
-import scala.collection.mutable.ListBuffer
-import scala.util.{Failure, Success, Try}
-
-import com.typesafe.config.Config
-
-import io.gearpump.cluster.ClientToMaster.ReadOption
-import io.gearpump.cluster.MasterToClient.HistoryMetricsItem
-import io.gearpump.metrics.MetricsAggregator
-import io.gearpump.util.{Constants, LogUtil}
-
-/**
- * Filters the latest metrics data by specifying a
- * processor Id range, and taskId range.
- */
-class TaskFilterAggregator(maxLimit: Int) extends MetricsAggregator {
-
- import io.gearpump.streaming.metrics.TaskFilterAggregator._
-
- def this(config: Config) = {
- this(config.getInt(Constants.GEARPUMP_METRICS_MAX_LIMIT))
- }
- override def aggregate(options: Map[String, String], inputs: Iterator[HistoryMetricsItem])
- : List[HistoryMetricsItem] = {
-
- if (options.get(ReadOption.Key) != Some(ReadOption.ReadLatest)) {
- // Returns empty set
- List.empty[HistoryMetricsItem]
- } else {
- val parsed = Options.parse(options)
- if (parsed != null) {
- aggregate(parsed, inputs)
- } else {
- List.empty[HistoryMetricsItem]
- }
- }
- }
-
- def aggregate(options: Options, inputs: Iterator[HistoryMetricsItem])
- : List[HistoryMetricsItem] = {
-
- val result = new ListBuffer[HistoryMetricsItem]
- val effectiveLimit = Math.min(options.limit, maxLimit)
- var count = 0
-
- val taskIdentity = new TaskIdentity(0, 0)
-
- while (inputs.hasNext && count < effectiveLimit) {
- val item = inputs.next()
- if (parseName(item.value.name, taskIdentity)) {
- if (taskIdentity.processor >= options.startProcessor &&
- taskIdentity.processor < options.endProcessor &&
- taskIdentity.task >= options.startTask &&
- taskIdentity.task < options.endTask) {
- result.prepend(item)
- count += 1
- }
- }
- }
- result.toList
- }
-
- // Assume the name format is: "app0.processor0.task0:sendThroughput", returns
- // (processorId, taskId)
- //
- // returns true if success
- private def parseName(name: String, result: TaskIdentity): Boolean = {
- val processorStart = name.indexOf(PROCESSOR_TAG)
- if (processorStart != -1) {
- val taskStart = name.indexOf(TASK_TAG, processorStart + 1)
- if (taskStart != -1) {
- val processorId = name.substring(processorStart, taskStart).substring(PROCESSOR_TAG.length)
- .toInt
- result.processor = processorId
- val taskEnd = name.indexOf(":", taskStart + 1)
- if (taskEnd != -1) {
- val taskId = name.substring(taskStart, taskEnd).substring(TASK_TAG.length).toInt
- result.task = taskId
- true
- } else {
- false
- }
- } else {
- false
- }
- } else {
- false
- }
- }
-}
-
-object TaskFilterAggregator {
- val StartTask = "startTask"
- val EndTask = "endTask"
- val StartProcessor = "startProcessor"
- val EndProcessor = "endProcessor"
- val Limit = "limit"
-
- val TASK_TAG = ".task"
- val PROCESSOR_TAG = ".processor"
-
- private class TaskIdentity(var processor: Int, var task: Int)
-
- case class Options(
- limit: Int, startTask: Int, endTask: Int, startProcessor: Int, endProcessor: Int)
-
- private val LOG = LogUtil.getLogger(getClass)
-
- object Options {
-
- def acceptAll: Options = {
- new Options(Int.MaxValue, 0, Int.MaxValue, 0, Int.MaxValue)
- }
-
- def parse(options: Map[String, String]): Options = {
- // Do sanity check
- val optionTry = Try {
- val startTask = options.get(StartTask).map(_.toInt).getOrElse(0)
- val endTask = options.get(EndTask).map(_.toInt).getOrElse(Integer.MAX_VALUE)
- val startProcessor = options.get(StartProcessor).map(_.toInt).getOrElse(0)
- val endProcessor = options.get(EndProcessor).map(_.toInt).getOrElse(Integer.MAX_VALUE)
- val limit = options.get(Limit).map(_.toInt).getOrElse(DEFAULT_LIMIT)
- new Options(limit, startTask, endTask, startProcessor, endProcessor)
- }
-
- optionTry match {
- case Success(options) => options
- case Failure(ex) =>
- LOG.error("Failed to parse the options in TaskFilterAggregator. Error msg: " +
- ex.getMessage)
- null
- }
- }
- }
-
- val DEFAULT_LIMIT = 1000
- val MAX_LIMIT = 1000
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/package.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/package.scala b/streaming/src/main/scala/io/gearpump/streaming/package.scala
deleted file mode 100644
index 95d51f0..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/package.scala
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump
-
-package object streaming {
- type ProcessorId = Int
- type TaskIndex = Int
- type ExecutorId = Int
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/sink/DataSink.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/sink/DataSink.scala b/streaming/src/main/scala/io/gearpump/streaming/sink/DataSink.scala
deleted file mode 100644
index b036619..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/sink/DataSink.scala
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.sink
-
-import io.gearpump.Message
-import io.gearpump.streaming.task.TaskContext
-
-/**
- * Interface to implement custom data sink where result of a DAG is typically written
- * a DataSink could be a data store like HBase or simply a console
- *
- * An example would be like:
- * {{{
- * class ConsoleSink extends DataSink[String] {
- *
- * def open(context: TaskContext): Unit = {}
- *
- * def write(s: String): Unit = {
- * Console.println(s)
- * }
- *
- * def close(): Unit = {}
- * }
- * }}}
- *
- * Subclass is required to be serializable
- */
-trait DataSink extends java.io.Serializable {
-
- /**
- * Opens connection to data sink
- * invoked at onStart() method of [[io.gearpump.streaming.task.Task]]
- * @param context is the task context at runtime
- */
- def open(context: TaskContext): Unit
-
- /**
- * Writes message into data sink
- * invoked at onNext() method of [[io.gearpump.streaming.task.Task]]
- * @param message wraps data to be written out
- */
- def write(message: Message): Unit
-
- /**
- * Closes connection to data sink
- * invoked at onClose() method of [[io.gearpump.streaming.task.Task]]
- */
- def close(): Unit
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/sink/DataSinkProcessor.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/sink/DataSinkProcessor.scala b/streaming/src/main/scala/io/gearpump/streaming/sink/DataSinkProcessor.scala
deleted file mode 100644
index d753cc2..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/sink/DataSinkProcessor.scala
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.sink
-
-import akka.actor.ActorSystem
-
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.Processor
-
-/**
- * Utility that helps user to create a DAG ending in [[DataSink]]
- * user should pass in a [[DataSink]].
- *
- * here is an example to build a DAG that does word count and write to KafkaSink
- * {{{
- * val split = Processor[Split](1)
- * val sum = Processor[Sum](1)
- * val sink = new KafkaSink()
- * val sinkProcessor = DataSinkProcessor(sink, 1)
- * val dag = split ~> sum ~> sink
- * }}}
- */
-object DataSinkProcessor {
- def apply(
- dataSink: DataSink,
- parallelism: Int,
- description: String = "",
- taskConf: UserConfig = UserConfig.empty)(implicit system: ActorSystem)
- : Processor[DataSinkTask] = {
- Processor[DataSinkTask](parallelism, description = description,
- taskConf.withValue[DataSink](DataSinkTask.DATA_SINK, dataSink))
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/sink/DataSinkTask.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/sink/DataSinkTask.scala b/streaming/src/main/scala/io/gearpump/streaming/sink/DataSinkTask.scala
deleted file mode 100644
index 7436617..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/sink/DataSinkTask.scala
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.sink
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.task.{StartTime, Task, TaskContext}
-
-object DataSinkTask {
- val DATA_SINK = "data_sink"
-}
-
-/**
- * General task that runs any [[DataSink]]
- */
-class DataSinkTask(context: TaskContext, conf: UserConfig) extends Task(context, conf) {
- import io.gearpump.streaming.sink.DataSinkTask._
-
- private val sink = conf.getValue[DataSink](DATA_SINK).get
-
- override def onStart(startTime: StartTime): Unit = {
- LOG.info("opening data sink...")
- sink.open(context)
- }
-
- override def onNext(message: Message): Unit = {
- sink.write(message)
- }
-
- override def onStop(): Unit = {
- LOG.info("closing data sink...")
- sink.close()
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/source/DataSource.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/source/DataSource.scala b/streaming/src/main/scala/io/gearpump/streaming/source/DataSource.scala
deleted file mode 100644
index e145079..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/source/DataSource.scala
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.source
-
-import io.gearpump.streaming.task.TaskContext
-import io.gearpump.Message
-
-import scala.util.Random
-
-/**
- * Interface to implement custom source where data is read into the system.
- * a DataSource could be a message queue like kafka or simply data generation source.
- *
- * An example would be like
- * {{{
- * GenMsgSource extends DataSource {
- *
- * def open(context: TaskContext, startTime: TimeStamp): Unit = {}
- *
- * def read(context: TaskContext): Message = {
- * Message("message")
- * }
- *
- * def close(): Unit = {}
- * }
- * }}}
- *
- * subclass is required to be serializable
- */
-trait DataSource extends java.io.Serializable {
-
- /**
- * Opens connection to data source
- * invoked in onStart() method of [[io.gearpump.streaming.source.DataSourceTask]]
- *
- * @param context is the task context at runtime
- * @param startTime is the start time of system
- */
- def open(context: TaskContext, startTime: Long): Unit
-
- /**
- * Reads next message from data source and
- * returns null if no message is available
- *
- * @return a [[io.gearpump.Message]] or null
- */
- def read(): Message
-
- /**
- * Closes connection to data source.
- * invoked in onStop() method of [[io.gearpump.streaming.source.DataSourceTask]]
- */
- def close(): Unit
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/source/DataSourceConfig.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/source/DataSourceConfig.scala b/streaming/src/main/scala/io/gearpump/streaming/source/DataSourceConfig.scala
deleted file mode 100644
index 6ca939f..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/source/DataSourceConfig.scala
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.source
-
-object DataSourceConfig {
-
- val SOURCE_READ_BATCH_SIZE = "gearpump.source.read.batch.size"
- val SOURCE_TIMESTAMP_FILTER = "gearpump.source.timestamp.filter.class"
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/source/DataSourceProcessor.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/source/DataSourceProcessor.scala b/streaming/src/main/scala/io/gearpump/streaming/source/DataSourceProcessor.scala
deleted file mode 100644
index 384b86a..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/source/DataSourceProcessor.scala
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.source
-
-import akka.actor.ActorSystem
-
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.Processor
-
-/**
- * Utility that helps user to create a DAG starting with [[DataSourceTask]]
- * user should pass in a [[DataSource]]
- *
- * Here is an example to build a DAG that reads from Kafka source followed by word count
- * {{{
- * val source = new KafkaSource()
- * val sourceProcessor = DataSourceProcessor(source, 1)
- * val split = Processor[Split](1)
- * val sum = Processor[Sum](1)
- * val dag = sourceProcessor ~> split ~> sum
- * }}}
- */
-object DataSourceProcessor {
- def apply(
- dataSource: DataSource,
- parallelism: Int,
- description: String = "",
- taskConf: UserConfig = UserConfig.empty)(implicit system: ActorSystem)
- : Processor[DataSourceTask] = {
- Processor[DataSourceTask](parallelism, description = description,
- taskConf.withValue[DataSource](DataSourceTask.DATA_SOURCE, dataSource))
- }
-}
[21/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/glue/ContainerLaunchContext.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/glue/ContainerLaunchContext.scala b/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/glue/ContainerLaunchContext.scala
new file mode 100644
index 0000000..7e5d9ec
--- /dev/null
+++ b/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/glue/ContainerLaunchContext.scala
@@ -0,0 +1,99 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.yarn.glue
+
+import java.io.File
+import java.nio.ByteBuffer
+import scala.collection.JavaConverters._
+
+import org.apache.hadoop.fs.{FileSystem => YarnFileSystem, Path}
+import org.apache.hadoop.io.DataOutputBuffer
+import org.apache.hadoop.mapreduce.security.TokenCache
+import org.apache.hadoop.security.UserGroupInformation
+import org.apache.hadoop.yarn.api.ApplicationConstants.Environment
+import org.apache.hadoop.yarn.api.records._
+import org.apache.hadoop.yarn.conf.YarnConfiguration
+import org.apache.hadoop.yarn.util.ConverterUtils
+import org.slf4j.Logger
+
+import org.apache.gearpump.util.LogUtil
+
+private[glue]
+object ContainerLaunchContext {
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+
+ def apply(yarnConf: YarnConfiguration, command: String, packagePath: String, configPath: String)
+ : ContainerLaunchContext = {
+ val context = Records.newRecord(classOf[ContainerLaunchContext])
+ context.setCommands(Seq(command).asJava)
+ context.setEnvironment(getAppEnv(yarnConf).asJava)
+ context.setTokens(getToken(yarnConf, packagePath, configPath))
+ context.setLocalResources(getAMLocalResourcesMap(yarnConf, packagePath, configPath).asJava)
+ context
+ }
+
+ private def getFs(yarnConf: YarnConfiguration) = YarnFileSystem.get(yarnConf)
+
+ private def getAppEnv(yarnConf: YarnConfiguration): Map[String, String] = {
+ val classPaths = yarnConf.getStrings(
+ YarnConfiguration.YARN_APPLICATION_CLASSPATH,
+ YarnConfiguration.DEFAULT_YARN_APPLICATION_CLASSPATH.mkString(File.pathSeparator))
+ val allPaths = Option(classPaths).getOrElse(Array(""))
+
+ allPaths :+ Environment.PWD.$() + File.separator + "*" + File.pathSeparator
+
+ Map(Environment.CLASSPATH.name -> allPaths.map(_.trim).mkString(File.pathSeparator))
+ }
+
+ private def getAMLocalResourcesMap(
+ yarnConf: YarnConfiguration, packagePath: String, configPath: String)
+ : Map[String, LocalResource] = {
+ val fs = getFs(yarnConf)
+
+ Map(
+ "pack" -> newYarnAppResource(fs, new Path(packagePath),
+ LocalResourceType.ARCHIVE, LocalResourceVisibility.APPLICATION),
+ "conf" -> newYarnAppResource(fs, new Path(configPath),
+ LocalResourceType.FILE, LocalResourceVisibility.APPLICATION))
+ }
+
+ private def newYarnAppResource(
+ fs: YarnFileSystem, path: Path,
+ resourceType: LocalResourceType, vis: LocalResourceVisibility): LocalResource = {
+ val qualified = fs.makeQualified(path)
+ val status = fs.getFileStatus(qualified)
+ val resource = Records.newRecord(classOf[LocalResource])
+ resource.setType(resourceType)
+ resource.setVisibility(vis)
+ resource.setResource(ConverterUtils.getYarnUrlFromPath(qualified))
+ resource.setTimestamp(status.getModificationTime)
+ resource.setSize(status.getLen)
+ resource
+ }
+
+ private def getToken(yc: YarnConfiguration, packagePath: String, configPath: String)
+ : ByteBuffer = {
+ val credentials = UserGroupInformation.getCurrentUser.getCredentials
+ val dob = new DataOutputBuffer
+ val dirs = Array(new Path(packagePath), new Path(configPath))
+ TokenCache.obtainTokensForNamenodes(credentials, dirs, yc)
+ credentials.writeTokenStorageToStream(dob)
+ ByteBuffer.wrap(dob.getData)
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/glue/FileSystem.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/glue/FileSystem.scala b/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/glue/FileSystem.scala
new file mode 100644
index 0000000..dcb53e9
--- /dev/null
+++ b/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/glue/FileSystem.scala
@@ -0,0 +1,73 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.yarn.glue
+
+import java.io.{InputStream, OutputStream}
+import java.net.ConnectException
+
+import org.apache.gearpump.util.LogUtil
+import org.apache.hadoop.fs.Path
+
+import scala.util.{Failure, Success, Try}
+
+class FileSystem(yarnConfig: YarnConfig) {
+
+ private val conf = yarnConfig.conf
+ private val fs = org.apache.hadoop.fs.FileSystem.get(conf)
+
+ private def LOG = LogUtil.getLogger(getClass)
+
+ def open(file: String): InputStream = exceptionHandler {
+ val path = new Path(file)
+ fs.open(path)
+ }
+
+ def create(file: String): OutputStream = exceptionHandler {
+ val path = new Path(file)
+ fs.create(path)
+ }
+
+ def exists(file: String): Boolean = exceptionHandler {
+ val path = new Path(file)
+ fs.exists(path)
+ }
+
+ def name: String = {
+ fs.getUri.toString
+ }
+
+ def getHomeDirectory: String = {
+ fs.getHomeDirectory.toString
+ }
+
+ private def exceptionHandler[T](call: => T): T = {
+ val callTry = Try(call)
+ callTry match {
+ case Success(v) => v
+ case Failure(ex) =>
+ if (ex.isInstanceOf[ConnectException]) {
+ LOG.error("Please check whether we connect to the right HDFS file system, " +
+ "current file system is $name." + "\n. Please copy all configs under " +
+ "$HADOOP_HOME/etc/hadoop into conf/yarnconf directory of Gearpump package, " +
+ "so that we can use the right File system.", ex)
+ }
+ throw ex
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/glue/NMClient.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/glue/NMClient.scala b/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/glue/NMClient.scala
new file mode 100644
index 0000000..59f3832
--- /dev/null
+++ b/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/glue/NMClient.scala
@@ -0,0 +1,99 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.yarn.glue
+
+import java.nio.ByteBuffer
+
+import akka.actor.ActorRef
+import com.typesafe.config.Config
+import org.apache.gearpump.experiments.yarn.appmaster.YarnAppMaster.ContainerStarted
+import org.apache.gearpump.experiments.yarn.glue.Records._
+import org.apache.gearpump.util.LogUtil
+import org.apache.hadoop.yarn.api.records.{ApplicationId => YarnApplicationId, ApplicationReport => YarnApplicationReport, Container => YarnContainer, ContainerId => YarnContainerId, ContainerStatus => YarnContainerStatus, NodeId => YarnNodeId, Resource => YarnResource}
+import org.apache.hadoop.yarn.client.api.async.NMClientAsync
+import org.apache.hadoop.yarn.client.api.async.impl.NMClientAsyncImpl
+/**
+ * Adapter for node manager client
+ */
+class NMClient(yarnConf: YarnConfig, config: Config) extends NMClientAsync.CallbackHandler {
+
+ private val LOG = LogUtil.getLogger(getClass)
+
+ private var reportTo: ActorRef = null
+ private var client: NMClientAsyncImpl = null
+
+ def start(reportTo: ActorRef): Unit = {
+ LOG.info("Starting Node Manager Client NMClient...")
+ this.reportTo = reportTo
+ client = new NMClientAsyncImpl(this)
+ client.init(yarnConf.conf)
+ client.start()
+ }
+
+ private[glue]
+ override def onContainerStarted(
+ containerId: YarnContainerId, allServiceResponse: java.util.Map[String, ByteBuffer]) {
+ LOG.info(s"Container started : $containerId, " + allServiceResponse)
+ reportTo ! ContainerStarted(containerId)
+ }
+
+ private[glue]
+ override def onContainerStatusReceived(
+ containerId: YarnContainerId, containerStatus: YarnContainerStatus) {
+ LOG.info(s"Container status received : $containerId, status $containerStatus")
+ }
+
+ private[glue]
+ override def onContainerStopped(containerId: YarnContainerId) {
+ LOG.error(s"Container stopped : $containerId")
+ }
+
+ private[glue]
+ override def onGetContainerStatusError(containerId: YarnContainerId, throwable: Throwable) {
+ LOG.error(s"Container exception : $containerId", throwable)
+ }
+
+ private[glue]
+ override def onStartContainerError(containerId: YarnContainerId, throwable: Throwable) {
+ LOG.error(s"Container exception : $containerId", throwable)
+ }
+
+ private[glue]
+ override def onStopContainerError(containerId: YarnContainerId, throwable: Throwable) {
+ LOG.error(s"Container exception : $containerId", throwable)
+ }
+
+ def launchCommand(
+ container: Container, command: String, packagePath: String, configPath: String): Unit = {
+ LOG.info(s"Launching command : $command on container" +
+ s": ${container.getId}, host ip : ${container.getNodeId.getHost}")
+ val context = ContainerLaunchContext(yarnConf.conf, command, packagePath, configPath)
+ client.startContainerAsync(container, context)
+ }
+
+ def stopContainer(containerId: ContainerId, nodeId: NodeId): Unit = {
+ LOG.info(s"Stop container ${containerId.toString} on node: ${nodeId.toString} ")
+ client.stopContainerAsync(containerId, nodeId)
+ }
+
+ def stop(): Unit = {
+ LOG.info(s"Shutdown NMClient")
+ client.stop()
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/glue/RMClient.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/glue/RMClient.scala b/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/glue/RMClient.scala
new file mode 100644
index 0000000..629e233
--- /dev/null
+++ b/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/glue/RMClient.scala
@@ -0,0 +1,127 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.yarn.glue
+
+import akka.actor.ActorRef
+import org.apache.gearpump.experiments.yarn.appmaster.YarnAppMaster.{AppMasterRegistered, ContainersAllocated, ContainersCompleted, ResourceManagerException, ShutdownApplication}
+import org.apache.gearpump.experiments.yarn.glue.Records._
+import org.apache.gearpump.util.LogUtil
+import org.apache.hadoop.yarn.api.records.{ApplicationId => YarnApplicationId, ApplicationReport => YarnApplicationReport, Container => YarnContainer, ContainerId => YarnContainerId, ContainerStatus => YarnContainerStatus, FinalApplicationStatus, NodeId => YarnNodeId, NodeReport, Priority, Resource => YarnResource}
+import org.apache.hadoop.yarn.client.api.AMRMClient.ContainerRequest
+import org.apache.hadoop.yarn.client.api.async.AMRMClientAsync
+import org.slf4j.Logger
+
+import scala.collection.JavaConverters._
+
+/**
+ * Adapter for resource manager client
+ */
+class RMClient(yarnConf: YarnConfig) extends AMRMClientAsync.CallbackHandler {
+
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+
+ private var reportTo: ActorRef = null
+ private var client: AMRMClientAsync[ContainerRequest] = null
+
+ def start(reportTo: ActorRef): Unit = {
+ LOG.info("Starting Resource Manager Client RMClient...")
+ this.reportTo = reportTo
+ client = startAMRMClient
+ }
+
+ private def startAMRMClient: AMRMClientAsync[ContainerRequest] = {
+ val timeIntervalMs = 1000 // ms
+ val amrmClient = AMRMClientAsync.createAMRMClientAsync[ContainerRequest](timeIntervalMs, this)
+ amrmClient.init(yarnConf.conf)
+ amrmClient.start()
+ amrmClient
+ }
+
+ override def getProgress: Float = 0.5F
+
+ private var allocatedContainers = Set.empty[YarnContainerId]
+
+ private[glue]
+ override def onContainersAllocated(containers: java.util.List[YarnContainer]) {
+ val newContainers = containers.asScala.toList.filterNot(container =>
+ allocatedContainers.contains(container.getId))
+ allocatedContainers ++= newContainers.map(_.getId)
+ LOG.info(s"New allocated ${newContainers.size} containers")
+ reportTo ! ContainersAllocated(newContainers.map(yarnContainerToContainer(_)))
+ }
+
+ private[glue]
+ override def onContainersCompleted(completedContainers: java.util.List[YarnContainerStatus])
+ : Unit = {
+ LOG.info(s"Got response from RM. Completed containers=${completedContainers.size()}")
+ reportTo ! ContainersCompleted(
+ completedContainers.asScala.toList.map(yarnContainerStatusToContainerStatus(_)))
+ }
+
+ private[glue]
+ override def onError(ex: Throwable) {
+ LOG.info("Error occurred")
+ reportTo ! ResourceManagerException(ex)
+ }
+
+ private[glue]
+ override def onNodesUpdated(updatedNodes: java.util.List[NodeReport]): Unit = {
+ LOG.info("onNodesUpdates")
+ }
+
+ private[glue]
+ override def onShutdownRequest() {
+ LOG.info("Shutdown requested")
+ reportTo ! ShutdownApplication
+ }
+
+ def requestContainers(containers: List[Resource]): Unit = {
+ LOG.info(s"request Resource, slots: ${containers.length}, ${containers.mkString("\n")}")
+ containers.foreach(resource => {
+ client.addContainerRequest(createContainerRequest(resource))
+ })
+ }
+
+ private def createContainerRequest(capability: Resource): ContainerRequest = {
+ LOG.info("creating ContainerRequest")
+ val priorityRecord = org.apache.hadoop.yarn.util.Records.newRecord(classOf[Priority])
+ priorityRecord.setPriority(0)
+ val priority = Priority.newInstance(0)
+ new ContainerRequest(capability, null, null, priority)
+ }
+
+ def registerAppMaster(host: String, port: Int, url: String): Unit = {
+ LOG.info(s"Received RegisterAMMessage! $host:$port $url")
+ val response = client.registerApplicationMaster(host, port, url)
+ LOG.info("Received RegisterAppMasterResponse ")
+ reportTo ! AppMasterRegistered
+ }
+
+ def shutdownApplication(): Unit = {
+ LOG.info(s"Shutdown application")
+ client.unregisterApplicationMaster(FinalApplicationStatus.SUCCEEDED, "success", null)
+ client.stop()
+ }
+
+ def failApplication(ex: Throwable): Unit = {
+ LOG.error(s"Application failed! ", ex)
+ client.unregisterApplicationMaster(FinalApplicationStatus.SUCCEEDED, ex.getMessage, null)
+ client.stop()
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/glue/Records.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/glue/Records.scala b/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/glue/Records.scala
new file mode 100644
index 0000000..ca729ce
--- /dev/null
+++ b/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/glue/Records.scala
@@ -0,0 +1,219 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.yarn.glue
+
+import org.apache.hadoop.yarn.api.records.{ApplicationId => YarnApplicationId, ApplicationReport => YarnApplicationReport, ApplicationSubmissionContext, Container => YarnContainer, ContainerId => YarnContainerId, ContainerStatus => YarnContainerStatus, NodeId => YarnNodeId, Resource => YarnResource, YarnApplicationState}
+import org.apache.hadoop.yarn.util.{Records => YarnRecords}
+
+import scala.language.implicitConversions
+
+object Records {
+ def newRecord[T](clazz: Class[T]): T = YarnRecords.newRecord(clazz)
+
+ def newAppSubmissionContext: ApplicationSubmissionContext = {
+ YarnRecords.newRecord(classOf[ApplicationSubmissionContext])
+ }
+
+ class ApplicationId(private[glue] val impl: YarnApplicationId) {
+ def getId: Int = impl.getId
+
+ override def toString: String = impl.toString
+
+ override def equals(other: Any): Boolean = {
+ if (other.isInstanceOf[ApplicationId]) {
+ impl.equals(other.asInstanceOf[ApplicationId].impl)
+ } else {
+ false
+ }
+ }
+
+ override def hashCode(): Int = {
+ impl.hashCode()
+ }
+ }
+
+ object ApplicationId {
+ def newInstance(timestamp: Long, id: Int): ApplicationId = {
+ YarnApplicationId.newInstance(timestamp, id)
+ }
+ }
+
+ class ApplicationReport(private[glue] val impl: YarnApplicationReport) {
+ def getApplicationId: ApplicationId = impl.getApplicationId
+
+ def getDiagnostics: String = impl.getDiagnostics
+
+ def getFinishTime: Long = impl.getFinishTime
+
+ def getOriginalTrackingUrl: String = impl.getOriginalTrackingUrl
+
+ def getYarnApplicationState: YarnApplicationState = impl.getYarnApplicationState
+
+ override def toString: String = impl.toString
+ }
+ class Resource(private[glue] val impl: YarnResource) {
+ override def toString: String = impl.toString
+
+ override def equals(other: Any): Boolean = {
+ if (other.isInstanceOf[Resource]) {
+ impl.equals(other.asInstanceOf[Resource].impl)
+ } else {
+ false
+ }
+ }
+
+ override def hashCode(): Int = {
+ impl.hashCode()
+ }
+ }
+
+ object Resource {
+ def newInstance(memory: Int, vCores: Int): Resource = {
+ YarnResource.newInstance(memory, vCores)
+ }
+ }
+
+ class Container(private[glue] val impl: YarnContainer) {
+ def getId: ContainerId = impl.getId
+
+ def getNodeHttpAddress: String = impl.getNodeHttpAddress
+
+ def getNodeId: NodeId = impl.getNodeId
+
+ override def toString: String = impl.toString
+
+ override def equals(other: Any): Boolean = {
+ if (other.isInstanceOf[Container]) {
+ impl.equals(other.asInstanceOf[Container].impl)
+ } else {
+ false
+ }
+ }
+
+ override def hashCode(): Int = {
+ impl.hashCode()
+ }
+ }
+
+ class ContainerId(private[glue] val impl: YarnContainerId) {
+ override def toString: String = impl.toString
+
+ override def equals(other: Any): Boolean = {
+ if (other.isInstanceOf[ContainerId]) {
+ impl.equals(other.asInstanceOf[ContainerId].impl)
+ } else {
+ false
+ }
+ }
+
+ override def hashCode(): Int = {
+ impl.hashCode()
+ }
+ }
+
+ object ContainerId {
+ def fromString(worker: String): ContainerId = YarnContainerId.fromString(worker)
+ }
+
+ class NodeId(private[glue] val impl: YarnNodeId) {
+ def getHost: String = impl.getHost
+
+ override def toString: String = impl.toString
+
+ override def equals(other: Any): Boolean = {
+ if (other.isInstanceOf[NodeId]) {
+ impl.equals(other.asInstanceOf[NodeId].impl)
+ } else {
+ false
+ }
+ }
+
+ override def hashCode(): Int = {
+ impl.hashCode()
+ }
+ }
+
+ class ContainerStatus(private[glue] val impl: YarnContainerStatus) {
+ def getDiagnostics: String = impl.getDiagnostics
+
+ def getContainerId: ContainerId = impl.getContainerId
+
+ def getExitStatus: Int = impl.getExitStatus
+
+ override def toString: String = impl.toString
+ }
+
+ private[glue] implicit def yarnResourceToResource(res: YarnResource): Resource = {
+ new Resource(res)
+ }
+
+ private[glue] implicit def resourceToYarnResource(res: Resource): YarnResource = {
+ res.impl
+ }
+
+ private[glue] implicit def yarnAppIdToAppId(yarn: YarnApplicationId): ApplicationId = {
+ new ApplicationId(yarn)
+ }
+
+ private[glue] implicit def appIdToYarnAppId(app: ApplicationId): YarnApplicationId = {
+ app.impl
+ }
+
+ private[glue] implicit def yarnReportToReport(yarn: YarnApplicationReport): ApplicationReport = {
+ new ApplicationReport(yarn)
+ }
+
+ private[glue] implicit def reportToYarnReport(app: ApplicationReport): YarnApplicationReport = {
+ app.impl
+ }
+
+ private[glue] implicit def yarnContainerToContainer(yarn: YarnContainer): Container = {
+ new Container(yarn)
+ }
+
+ private[glue] implicit def containerToYarnContainer(app: Container): YarnContainer = {
+ app.impl
+ }
+
+ private[glue] implicit def yarnContainerStatusToContainerStatus(yarn: YarnContainerStatus)
+ : ContainerStatus = {
+ new ContainerStatus(yarn)
+ }
+
+ private[glue] implicit def containerStatusToYarnContainerStatus(app: ContainerStatus)
+ : YarnContainerStatus = {
+ app.impl
+ }
+
+ private[glue] implicit def containerIdToYarnContainerId(app: ContainerId): YarnContainerId = {
+ app.impl
+ }
+
+ private[glue] implicit def yarnContainerIdToContainerId(yarn: YarnContainerId): ContainerId = {
+ new ContainerId(yarn)
+ }
+
+ private[glue] implicit def nodeIdToYarnNodeId(app: NodeId): YarnNodeId = {
+ app.impl
+ }
+
+ private[glue] implicit def yarnNodeIdToNodeId(yarn: YarnNodeId): NodeId = {
+ new NodeId(yarn)
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/glue/YarnClient.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/glue/YarnClient.scala b/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/glue/YarnClient.scala
new file mode 100644
index 0000000..634dd0e
--- /dev/null
+++ b/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/glue/YarnClient.scala
@@ -0,0 +1,103 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.yarn.glue
+
+import org.apache.gearpump.experiments.yarn.glue.Records._
+import org.apache.gearpump.util.LogUtil
+import org.apache.hadoop.yarn.client.api
+
+/**
+ * Adapter for api.YarnClient
+ */
+class YarnClient(yarn: YarnConfig) {
+
+ val LOG = LogUtil.getLogger(getClass)
+
+ private val client: api.YarnClient = api.YarnClient.createYarnClient
+ client.init(yarn.conf)
+ client.start()
+ LOG.info("Starting YarnClient...")
+
+ def createApplication: ApplicationId = {
+ val app = client.createApplication()
+ val response = app.getNewApplicationResponse()
+ LOG.info("Create application, appId: " + response.getApplicationId())
+ response.getApplicationId()
+ }
+
+ def getApplicationReport(appId: ApplicationId): ApplicationReport = {
+ client.getApplicationReport(appId)
+ }
+
+ def submit(
+ name: String, appId: ApplicationId, command: String, resource: Resource, queue: String,
+ packagePath: String, configPath: String): ApplicationId = {
+
+ val appContext = Records.newAppSubmissionContext
+ appContext.setApplicationName(name)
+ appContext.setApplicationId(appId)
+
+ val containerContext = ContainerLaunchContext(yarn.conf, command, packagePath, configPath)
+ appContext.setAMContainerSpec(containerContext)
+ appContext.setResource(resource)
+ appContext.setQueue(queue)
+
+ LOG.info(s"Submit Application $appId to YARN...")
+ client.submitApplication(appContext)
+ }
+
+ def awaitApplication(appId: ApplicationId, timeoutMilliseconds: Long = Long.MaxValue)
+ : ApplicationReport = {
+ import org.apache.hadoop.yarn.api.records.YarnApplicationState._
+ val terminated = Set(FINISHED, KILLED, FAILED, RUNNING)
+ var result: ApplicationReport = null
+ var done = false
+
+ val start = System.currentTimeMillis()
+ def timeout: Boolean = {
+ val now = System.currentTimeMillis()
+ if (now - start > timeoutMilliseconds) {
+ true
+ } else {
+ false
+ }
+ }
+
+ while (!done && !timeout) {
+ val report = client.getApplicationReport(appId)
+ val status = report.getYarnApplicationState
+ if (terminated.contains(status)) {
+ done = true
+ result = report
+ } else {
+ Console.print(".")
+ Thread.sleep(1000)
+ }
+ }
+
+ if (timeout) {
+ throw new Exception(s"Launch Application $appId timeout...")
+ }
+ result
+ }
+
+ def stop(): Unit = {
+ client.stop()
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/glue/YarnConfig.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/glue/YarnConfig.scala b/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/glue/YarnConfig.scala
new file mode 100644
index 0000000..4b927de
--- /dev/null
+++ b/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/glue/YarnConfig.scala
@@ -0,0 +1,33 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.yarn.glue
+
+import org.apache.hadoop.conf.Configuration
+import org.apache.hadoop.yarn.conf.YarnConfiguration
+
+/**
+ * wrapper for yarn configuration
+ */
+case class YarnConfig(conf: YarnConfiguration = new YarnConfiguration(new Configuration(true))) {
+ def writeXml(out: java.io.Writer): Unit = conf.writeXml(out)
+
+ def resourceManager: String = {
+ conf.get("yarn.resourcemanager.hostname")
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/glue/package.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/glue/package.scala b/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/glue/package.scala
new file mode 100644
index 0000000..33e5778
--- /dev/null
+++ b/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/glue/package.scala
@@ -0,0 +1,25 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.yarn
+
+/**
+ * YARN facade to decouple Gearpump with YARN.
+ */
+package object glue {
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/test/scala/io/gearpump/experiments/yarn/appmaster/CommandSpec.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/test/scala/io/gearpump/experiments/yarn/appmaster/CommandSpec.scala b/experiments/yarn/src/test/scala/io/gearpump/experiments/yarn/appmaster/CommandSpec.scala
deleted file mode 100644
index 2a6bf38..0000000
--- a/experiments/yarn/src/test/scala/io/gearpump/experiments/yarn/appmaster/CommandSpec.scala
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.yarn.appmaster
-
-import com.typesafe.config.ConfigFactory
-import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
-
-import io.gearpump.cluster.TestUtil
-import io.gearpump.transport.HostPort
-
-class CommandSpec extends FlatSpec with Matchers with BeforeAndAfterAll {
- val config = ConfigFactory.parseString(
-
- """
- |
- |gearpump {
- | yarn {
- | client {
- | package -path = "/user/gearpump/gearpump.zip"
- | }
- |
- | applicationmaster {
- | ## Memory of YarnAppMaster
- | command = "$JAVA_HOME/bin/java -Xmx512m"
- | memory = "512"
- | vcores = "1"
- | queue = "default"
- | }
- |
- | master {
- | ## Memory of master daemon
- | command = "$JAVA_HOME/bin/java -Xmx512m"
- | memory = "512"
- | vcores = "1"
- | }
- |
- | worker {
- | ## memory of worker daemon
- | command = "$JAVA_HOME/bin/java -Xmx512m"
- | containers = "4"
- | ## This also contains all memory for child executors.
- | memory = "4096"
- | vcores = "1"
- | }
- | services {
- | enabled = true
- | }
- | }
- |}
- """.stripMargin).withFallback(TestUtil.DEFAULT_CONFIG)
-
- "MasterCommand" should "create correct command line" in {
- val version = "gearpump-0.1"
- val master = MasterCommand(config, version, HostPort("127.0.0.1", 8080))
-
- // scalastyle:off line.size.limit
- val expected = "$JAVA_HOME/bin/java -Xmx512m -cp conf:pack/gearpump-0.1/conf:pack/gearpump-0.1/lib/daemon/*:pack/gearpump-0.1/lib/*:$CLASSPATH -Dgearpump.cluster.masters.0=127.0.0.1:8080 -Dgearpump.hostname=127.0.0.1 -Dgearpump.master-resource-manager-container-id={{CONTAINER_ID}} -Dgearpump.home={{LOCAL_DIRS}}/{{CONTAINER_ID}}/pack/gearpump-0.1 -Dgearpump.log.daemon.dir=<LOG_DIR> -Dgearpump.log.application.dir=<LOG_DIR> io.gearpump.cluster.main.Master -ip 127.0.0.1 -port 8080 2>&1 | /usr/bin/tee -a <LOG_DIR>/stderr"
- // scalastyle:on line.size.limit
- assert(master.get == expected)
- }
-
- "WorkerCommand" should "create correct command line" in {
- val version = "gearpump-0.1"
- val worker = WorkerCommand(config, version, HostPort("127.0.0.1", 8080), "worker-machine")
- // scalastyle:off line.size.limit
- val expected = "$JAVA_HOME/bin/java -Xmx512m -cp conf:pack/gearpump-0.1/conf:pack/gearpump-0.1/lib/daemon/*:pack/gearpump-0.1/lib/*:$CLASSPATH -Dgearpump.cluster.masters.0=127.0.0.1:8080 -Dgearpump.log.daemon.dir=<LOG_DIR> -Dgearpump.worker-resource-manager-container-id={{CONTAINER_ID}} -Dgearpump.home={{LOCAL_DIRS}}/{{CONTAINER_ID}}/pack/gearpump-0.1 -Dgearpump.log.application.dir=<LOG_DIR> -Dgearpump.hostname=worker-machine io.gearpump.cluster.main.Worker 2>&1 | /usr/bin/tee -a <LOG_DIR>/stderr"
- // scalastyle:on line.size.limit
- assert(worker.get == expected)
- }
-
- "AppMasterCommand" should "create correct command line" in {
- val version = "gearpump-0.1"
- val appmaster = AppMasterCommand(config, version, Array("arg1", "arg2", "arg3"))
- // scalastyle:off line.size.limit
- val expected = "$JAVA_HOME/bin/java -Xmx512m -cp conf:pack/gearpump-0.1/conf:pack/gearpump-0.1/dashboard:pack/gearpump-0.1/lib/*:pack/gearpump-0.1/lib/daemon/*:pack/gearpump-0.1/lib/services/*:pack/gearpump-0.1/lib/yarn/*:$CLASSPATH -Dgearpump.home={{LOCAL_DIRS}}/{{CONTAINER_ID}}/pack/gearpump-0.1 -Dgearpump.binary-version-with-scala-version=gearpump-0.1 -Dgearpump.log.daemon.dir=<LOG_DIR> -Dgearpump.log.application.dir=<LOG_DIR> -Dgearpump.hostname={{NM_HOST}} io.gearpump.experiments.yarn.appmaster.YarnAppMaster arg1 arg2 arg3 2>&1 | /usr/bin/tee -a <LOG_DIR>/stderr"
- // scalastyle:on line.size.limit
- assert(appmaster.get == expected)
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/test/scala/io/gearpump/experiments/yarn/appmaster/UIServiceSpec.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/test/scala/io/gearpump/experiments/yarn/appmaster/UIServiceSpec.scala b/experiments/yarn/src/test/scala/io/gearpump/experiments/yarn/appmaster/UIServiceSpec.scala
deleted file mode 100644
index f8f9fe8..0000000
--- a/experiments/yarn/src/test/scala/io/gearpump/experiments/yarn/appmaster/UIServiceSpec.scala
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.yarn.appmaster
-
-import scala.concurrent.Await
-import scala.concurrent.duration.Duration
-
-import akka.actor.{ActorRef, ActorSystem, Props}
-import akka.testkit.TestProbe
-import com.typesafe.config.ConfigFactory
-import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
-
-import io.gearpump.cluster.TestUtil
-import io.gearpump.experiments.yarn.appmaster.UIServiceSpec.{Info, MockUI}
-import io.gearpump.transport.HostPort
-import io.gearpump.util.Constants
-
-class UIServiceSpec extends FlatSpec with Matchers with BeforeAndAfterAll {
- implicit var system: ActorSystem = null
-
- override def beforeAll(): Unit = {
- system = ActorSystem(getClass.getSimpleName, TestUtil.DEFAULT_CONFIG)
- }
-
- override def afterAll(): Unit = {
- system.terminate()
- Await.result(system.whenTerminated, Duration.Inf)
- }
-
- it should "start UI server correctly" in {
- val probe = TestProbe()
- val masters = List(
- HostPort("127.0.0.1", 3000),
- HostPort("127.0.0.1", 3001),
- HostPort("127.0.0.1", 3002)
- )
- val host = "local"
- val port = 8091
-
- val ui = system.actorOf(Props(new MockUI(masters, host, port, probe.ref)))
-
- probe.expectMsgPF() {
- case info: Info => {
- assert(info.masterHost == "127.0.0.1")
- assert(info.masterPort == 3000)
- val conf = ConfigFactory.parseFile(new java.io.File(info.configFile))
- assert(conf.getString(Constants.GEARPUMP_SERVICE_HOST) == host)
- assert(conf.getString(Constants.GEARPUMP_SERVICE_HTTP) == "8091")
- assert(conf.getString(Constants.NETTY_TCP_HOSTNAME) == host)
- }
- }
-
- system.stop(ui)
- }
-}
-
-object UIServiceSpec {
-
- case class Info(supervisor: String, masterHost: String, masterPort: Int, configFile: String)
-
- class MockUI(masters: List[HostPort], host: String, port: Int, probe: ActorRef)
- extends UIService(masters, host, port) {
-
- override def launch(
- supervisor: String, masterHost: String, masterPort: Int, configFile: String): Unit = {
- probe ! Info(supervisor, masterHost, masterPort, configFile)
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/test/scala/io/gearpump/experiments/yarn/appmaster/YarnAppMasterSpec.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/test/scala/io/gearpump/experiments/yarn/appmaster/YarnAppMasterSpec.scala b/experiments/yarn/src/test/scala/io/gearpump/experiments/yarn/appmaster/YarnAppMasterSpec.scala
deleted file mode 100644
index 84d6d37..0000000
--- a/experiments/yarn/src/test/scala/io/gearpump/experiments/yarn/appmaster/YarnAppMasterSpec.scala
+++ /dev/null
@@ -1,221 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.yarn.appmaster
-
-import scala.concurrent.Await
-import scala.concurrent.duration.Duration
-
-import akka.actor.{Actor, ActorSystem, Props}
-import akka.testkit.{TestActorRef, TestProbe}
-import com.typesafe.config.ConfigFactory
-import org.mockito.ArgumentCaptor
-import org.mockito.Matchers._
-import org.mockito.Mockito._
-import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
-
-import io.gearpump.cluster.ClientToMaster.{AddWorker, CommandResult, RemoveWorker}
-import io.gearpump.cluster.TestUtil
-import io.gearpump.experiments.yarn.Constants
-import io.gearpump.experiments.yarn.appmaster.YarnAppMaster.{ActiveConfig, AppMasterRegistered, ClusterInfo, ContainerStarted, ContainersAllocated, GetActiveConfig, Kill, QueryClusterInfo, QueryVersion, ResourceManagerException, Version}
-import io.gearpump.experiments.yarn.appmaster.YarnAppMasterSpec.UI
-import io.gearpump.experiments.yarn.glue.Records.{Container, Resource, _}
-import io.gearpump.experiments.yarn.glue.{NMClient, RMClient}
-import io.gearpump.transport.HostPort
-
-class YarnAppMasterSpec extends FlatSpec with Matchers with BeforeAndAfterAll {
-
- val config = ConfigFactory.parseString(
-
- """
- |gearpump {
- | yarn {
- | client {
- | package -path = "/user/gearpump/gearpump.zip"
- | }
- |
- | applicationmaster {
- | ## Memory of YarnAppMaster
- | command = "$JAVA_HOME/bin/java -Xmx512m"
- | memory = "512"
- | vcores = "1"
- | queue = "default"
- | }
- |
- | master {
- | ## Memory of master daemon
- | command = "$JAVA_HOME/bin/java -Xmx512m"
- | memory = "512"
- | vcores = "1"
- | }
- |
- | worker {
- | ## memory of worker daemon
- | command = "$JAVA_HOME/bin/java -Xmx512m"
- | containers = "4"
- | ## This also contains all memory for child executors.
- | memory = "4096"
- | vcores = "1"
- | }
- | services {
- | enabled = true
- | }
- | }
- |}
- """.stripMargin).withFallback(TestUtil.DEFAULT_CONFIG)
-
- val masterCount = 1
- val workerCount = config.getString(Constants.WORKER_CONTAINERS).toInt
-
- implicit var system: ActorSystem = null
- val packagePath = "/user/gearpump/gearpump.zip"
- val configPath = "/user/my/conf"
-
- override def beforeAll(): Unit = {
- system = ActorSystem("test", config)
- }
-
- override def afterAll(): Unit = {
- system.terminate()
- Await.result(system.whenTerminated, Duration.Inf)
- }
-
- private def startAppMaster(): (TestActorRef[YarnAppMaster], TestProbe, NMClient, RMClient) = {
- val rmClient = mock(classOf[RMClient])
- val nmClient = mock(classOf[NMClient])
- val ui = mock(classOf[UIFactory])
- when(ui.props(any[List[HostPort]], anyString, anyInt)).thenReturn(Props(new UI))
-
- val appMaster = TestActorRef[YarnAppMaster](Props(
- new YarnAppMaster(rmClient, nmClient, packagePath, configPath, ui)))
-
- verify(rmClient).start(appMaster)
- verify(nmClient).start(appMaster)
- verify(rmClient).registerAppMaster(anyString, anyInt, anyString)
-
- appMaster ! AppMasterRegistered
-
- val masterResources = ArgumentCaptor.forClass(classOf[List[Resource]])
- verify(rmClient).requestContainers(masterResources.capture())
- assert(masterResources.getValue.size == masterCount)
-
- val masterContainer = mock(classOf[Container])
- val mockNode = mock(classOf[NodeId])
- val mockId = mock(classOf[ContainerId])
- when(masterContainer.getNodeId).thenReturn(mockNode)
- when(masterContainer.getId).thenReturn(mockId)
-
- // Launchs master
- appMaster ! ContainersAllocated(List.fill(masterCount)(masterContainer))
- verify(nmClient,
- times(masterCount)).launchCommand(any[Container], anyString, anyString, anyString)
-
- // Master containers started
- (0 until masterCount).foreach(_ => appMaster ! ContainerStarted(mockId))
-
- // Transition to start workers
- val workerResources = ArgumentCaptor.forClass(classOf[List[Resource]])
- verify(rmClient, times(2)).requestContainers(workerResources.capture())
- assert(workerResources.getValue.size == workerCount)
-
- // Launchs workers
- val workerContainer = mock(classOf[Container])
- when(workerContainer.getNodeId).thenReturn(mockNode)
- val workerContainerId = ContainerId.fromString("container_1449802454214_0034_01_000006")
- when(workerContainer.getId).thenReturn(workerContainerId)
- appMaster ! ContainersAllocated(List.fill(workerCount)(workerContainer))
- verify(nmClient, times(workerCount + masterCount))
- .launchCommand(any[Container], anyString, anyString, anyString)
-
- // Worker containers started
- (0 until workerCount).foreach(_ => appMaster ! ContainerStarted(mockId))
-
- // Starts UI server
- verify(ui, times(1)).props(any[List[HostPort]], anyString, anyInt)
-
- // Application Ready...
- val client = TestProbe()
-
- // Gets active config
- appMaster.tell(GetActiveConfig("client"), client.ref)
- client.expectMsgType[ActiveConfig]
-
- // Queries version
- appMaster.tell(QueryVersion, client.ref)
- client.expectMsgType[Version]
-
- // Queries version
- appMaster.tell(QueryClusterInfo, client.ref)
- client.expectMsgType[ClusterInfo]
-
- // Adds worker
- val newWorkerCount = 2
- appMaster.tell(AddWorker(newWorkerCount), client.ref)
- client.expectMsgType[CommandResult]
- val newWorkerResources = ArgumentCaptor.forClass(classOf[List[Resource]])
- verify(rmClient, times(3)).requestContainers(newWorkerResources.capture())
- assert(newWorkerResources.getValue.size == newWorkerCount)
-
- // New container allocated
- appMaster ! ContainersAllocated(List.fill(newWorkerCount)(workerContainer))
- verify(nmClient, times(workerCount + masterCount + newWorkerCount)).
- launchCommand(any[Container], anyString, anyString, anyString)
-
- // New worker containers started
- (0 until newWorkerCount).foreach(_ => appMaster ! ContainerStarted(mockId))
-
- // Same UI server
- verify(ui, times(1)).props(any[List[HostPort]], anyString, anyInt)
-
- // Removes worker
- appMaster.tell(RemoveWorker(workerContainerId.toString), client.ref)
- client.expectMsgType[CommandResult]
- verify(nmClient).stopContainer(any[ContainerId], any[NodeId])
-
- (appMaster, client: TestProbe, nmClient, rmClient)
- }
-
- it should "start master, worker and UI on YARN" in {
- val env = startAppMaster()
- val (appMaster, client, nmClient, rmClient) = env
-
- // Kills the app
- appMaster.tell(Kill, client.ref)
- client.expectMsgType[CommandResult]
- verify(nmClient, times(1)).stop()
- verify(rmClient, times(1)).shutdownApplication()
- }
-
- it should "handle resource manager errors" in {
- val env = startAppMaster()
- val (appMaster, client, nmClient, rmClient) = env
-
- // on error
- val ex = new Exception("expected resource manager exception")
- appMaster.tell(ResourceManagerException(ex), client.ref)
- verify(nmClient, times(1)).stop()
- verify(rmClient, times(1)).failApplication(ex)
- }
-}
-
-object YarnAppMasterSpec {
-
- class UI extends Actor {
- def receive: Receive = null
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/test/scala/io/gearpump/experiments/yarn/client/LaunchClusterSpec.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/test/scala/io/gearpump/experiments/yarn/client/LaunchClusterSpec.scala b/experiments/yarn/src/test/scala/io/gearpump/experiments/yarn/client/LaunchClusterSpec.scala
deleted file mode 100644
index 3bd7f4f..0000000
--- a/experiments/yarn/src/test/scala/io/gearpump/experiments/yarn/client/LaunchClusterSpec.scala
+++ /dev/null
@@ -1,232 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.yarn.client
-
-import java.io.{ByteArrayInputStream, ByteArrayOutputStream, InputStream, OutputStream}
-import java.util.Random
-import java.util.zip.{ZipEntry, ZipOutputStream}
-import scala.concurrent.Await
-import scala.concurrent.duration.Duration
-import scala.util.Try
-
-import akka.actor.ActorSystem
-import akka.testkit.TestProbe
-import com.typesafe.config.ConfigFactory
-import org.mockito.Matchers._
-import org.mockito.Mockito._
-import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
-
-import io.gearpump.cluster.TestUtil
-import io.gearpump.experiments.yarn.appmaster.YarnAppMaster.{ActiveConfig, GetActiveConfig}
-import io.gearpump.experiments.yarn.glue.Records._
-import io.gearpump.experiments.yarn.glue.{FileSystem, YarnClient, YarnConfig}
-import io.gearpump.util.FileUtils
-class LaunchClusterSpec extends FlatSpec with Matchers with BeforeAndAfterAll {
- implicit var system: ActorSystem = null
-
- val rand = new Random()
-
- private def randomArray(size: Int): Array[Byte] = {
- val array = new Array[Byte](size)
- rand.nextBytes(array)
- array
- }
- val appId = ApplicationId.newInstance(0L, 0)
-
- val akka = ConfigFactory.parseString(
-
- """
- |gearpump {
- | yarn {
- | client {
- | package -path = "/user/gearpump/gearpump.zip"
- | }
- |
- | applicationmaster {
- | ## Memory of YarnAppMaster
- | command = "$JAVA_HOME/bin/java -Xmx512m"
- | memory = "512"
- | vcores = "1"
- | queue = "default"
- | }
- |
- | master {
- | ## Memory of master daemon
- | command = "$JAVA_HOME/bin/java -Xmx512m"
- | containers = "2"
- | memory = "512"
- | vcores = "1"
- | }
- |
- | worker {
- | ## memory of worker daemon
- | command = "$JAVA_HOME/bin/java -Xmx512m"
- | containers = "4"
- | ## This also contains all memory for child executors.
- | memory = "4096"
- | vcores = "1"
- | }
- | services {
- | enabled = true
- | }
- | }
- |}
- """.stripMargin).withFallback(TestUtil.DEFAULT_CONFIG)
-
- override def beforeAll(): Unit = {
- system = ActorSystem(getClass.getSimpleName, akka)
- }
-
- override def afterAll(): Unit = {
- system.terminate()
- Await.result(system.whenTerminated, Duration.Inf)
- }
-
- it should "reject non-zip files" in {
- val yarnConfig = mock(classOf[YarnConfig])
- val yarnClient = mock(classOf[YarnClient])
- val fs = mock(classOf[FileSystem])
- val appMasterResolver = mock(classOf[AppMasterResolver])
-
- val launcher = new LaunchCluster(akka, yarnConfig, yarnClient, fs, system, appMasterResolver)
- val packagePath = "gearpump.zip2"
- assert(Try(launcher.submit("gearpump", packagePath)).isFailure)
- }
-
- it should "reject if we cannot find the package file on HDFS" in {
- val yarnConfig = mock(classOf[YarnConfig])
- val yarnClient = mock(classOf[YarnClient])
- val fs = mock(classOf[FileSystem])
- val appMasterResolver = mock(classOf[AppMasterResolver])
-
- val launcher = new LaunchCluster(akka, yarnConfig, yarnClient, fs, system, appMasterResolver)
- val packagePath = "gearpump.zip"
- when(fs.exists(anyString)).thenReturn(false)
- assert(Try(launcher.submit("gearpump", packagePath)).isFailure)
- }
-
- it should "throw when package exists on HDFS, but the file is corrupted" in {
- val yarnConfig = mock(classOf[YarnConfig])
- val yarnClient = mock(classOf[YarnClient])
- val fs = mock(classOf[FileSystem])
- val appMasterResolver = mock(classOf[AppMasterResolver])
-
- val launcher = new LaunchCluster(akka, yarnConfig, yarnClient, fs, system, appMasterResolver)
- val packagePath = "gearpump.zip"
- when(fs.exists(anyString)).thenReturn(true)
-
- val content = new ByteArrayInputStream(randomArray(10))
- when(fs.open(anyString)).thenReturn(content)
- assert(Try(launcher.submit("gearpump", packagePath)).isFailure)
- content.close()
- }
-
- it should "throw when the HDFS package version is not consistent with local version" in {
- val yarnConfig = mock(classOf[YarnConfig])
- val yarnClient = mock(classOf[YarnClient])
- val fs = mock(classOf[FileSystem])
- val appMasterResolver = mock(classOf[AppMasterResolver])
-
- val version = "gearpump-0.2"
- val launcher = new LaunchCluster(akka, yarnConfig, yarnClient, fs, system,
- appMasterResolver, version)
- val packagePath = "gearpump.zip"
- when(fs.exists(anyString)).thenReturn(true)
-
- val oldVesion = "gearpump-0.1"
- when(fs.open(anyString)).thenReturn(zipInputStream(oldVesion))
- assert(Try(launcher.submit("gearpump", packagePath)).isFailure)
- }
-
- it should "upload config file to HDFS when submitting" in {
- val yarnConfig = mock(classOf[YarnConfig])
- val yarnClient = mock(classOf[YarnClient])
- val fs = mock(classOf[FileSystem])
- val appMasterResolver = mock(classOf[AppMasterResolver])
-
- val version = "gearpump-0.2"
- val launcher = new LaunchCluster(akka, yarnConfig, yarnClient,
- fs, system, appMasterResolver, version)
- val packagePath = "gearpump.zip"
-
- val out = mock(classOf[OutputStream])
- when(fs.exists(anyString)).thenReturn(true)
- when(fs.create(anyString)).thenReturn(out)
- when(fs.getHomeDirectory).thenReturn("/root")
-
- when(fs.open(anyString)).thenReturn(zipInputStream(version))
-
- val report = mock(classOf[ApplicationReport])
- when(yarnClient.awaitApplication(any[ApplicationId], anyLong())).thenReturn(report)
-
- when(report.getApplicationId).thenReturn(appId)
- when(yarnClient.createApplication).thenReturn(appId)
- assert(appId == launcher.submit("gearpump", packagePath))
-
- // 3 Config files are uploaded to HDFS, one is akka.conf,
- // one is yarn-site.xml, one is log4j.properties.
- verify(fs, times(3)).create(anyString)
- verify(out, times(3)).close()
-
- // val workerResources = ArgumentCaptor.forClass(classOf[List[Resource]])
- // scalastyle:off line.size.limit
- val expectedCommand = "$JAVA_HOME/bin/java -Xmx512m -cp conf:pack/gearpump-0.2/conf:pack/gearpump-0.2/dashboard:pack/gearpump-0.2/lib/*:pack/gearpump-0.2/lib/daemon/*:pack/gearpump-0.2/lib/services/*:pack/gearpump-0.2/lib/yarn/*:$CLASSPATH -Dgearpump.home={{LOCAL_DIRS}}/{{CONTAINER_ID}}/pack/gearpump-0.2 -Dgearpump.binary-version-with-scala-version=gearpump-0.2 -Dgearpump.log.daemon.dir=<LOG_DIR> -Dgearpump.log.application.dir=<LOG_DIR> -Dgearpump.hostname={{NM_HOST}} io.gearpump.experiments.yarn.appmaster.YarnAppMaster -conf /root/.gearpump_application_0_0000/conf/ -package gearpump.zip 2>&1 | /usr/bin/tee -a <LOG_DIR>/stderr"
- // scalastyle:on line.size.limit
- verify(yarnClient).submit("gearpump", appId, expectedCommand,
- Resource.newInstance(512, 1), "default",
- "gearpump.zip", "/root/.gearpump_application_0_0000/conf/")
- }
-
- it should "save active config from Gearpump cluster" in {
- val yarnConfig = mock(classOf[YarnConfig])
- val yarnClient = mock(classOf[YarnClient])
- val fs = mock(classOf[FileSystem])
- val appMasterResolver = mock(classOf[AppMasterResolver])
- val appMaster = TestProbe()
-
- val version = "gearpump-0.2"
- val launcher = new LaunchCluster(akka, yarnConfig, yarnClient, fs, system,
- appMasterResolver, version)
- val outputPath = java.io.File.createTempFile("LaunchClusterSpec", ".conf")
-
- when(appMasterResolver.resolve(any[ApplicationId], anyInt)).thenReturn(appMaster.ref)
- val fileFuture = launcher.saveConfig(appId, outputPath.getPath)
- appMaster.expectMsgType[GetActiveConfig]
- appMaster.reply(ActiveConfig(ConfigFactory.empty()))
-
- import scala.concurrent.duration._
- val file = Await.result(fileFuture, 30.seconds).asInstanceOf[java.io.File]
-
- assert(!FileUtils.read(file).isEmpty)
- file.delete()
- }
-
- private def zipInputStream(version: String): InputStream = {
- val bytes = new ByteArrayOutputStream(1000)
- val zipOut = new ZipOutputStream(bytes)
-
- // Not available on BufferedOutputStream
- zipOut.putNextEntry(new ZipEntry(s"$version/README.md"))
- zipOut.write("README".getBytes())
- // Not available on BufferedOutputStream
- zipOut.closeEntry()
- zipOut.close()
- new ByteArrayInputStream(bytes.toByteArray)
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/test/scala/io/gearpump/experiments/yarn/client/ManageClusterSpec.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/test/scala/io/gearpump/experiments/yarn/client/ManageClusterSpec.scala b/experiments/yarn/src/test/scala/io/gearpump/experiments/yarn/client/ManageClusterSpec.scala
deleted file mode 100644
index b324ece..0000000
--- a/experiments/yarn/src/test/scala/io/gearpump/experiments/yarn/client/ManageClusterSpec.scala
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.yarn.client
-
-import scala.concurrent.Await
-import scala.concurrent.duration.Duration
-
-import akka.actor.ActorSystem
-import akka.testkit.TestProbe
-import com.typesafe.config.ConfigFactory
-import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
-
-import io.gearpump.cluster.ClientToMaster.{AddWorker, CommandResult, RemoveWorker}
-import io.gearpump.cluster.TestUtil
-import io.gearpump.cluster.main.ParseResult
-import io.gearpump.experiments.yarn.appmaster.YarnAppMaster.{ActiveConfig, ClusterInfo, GetActiveConfig, Kill, QueryClusterInfo, QueryVersion, Version}
-import io.gearpump.experiments.yarn.client.ManageCluster._
-import io.gearpump.experiments.yarn.glue.Records.ApplicationId
-import io.gearpump.util.FileUtils
-
-class ManageClusterSpec extends FlatSpec with Matchers with BeforeAndAfterAll {
-
- implicit var system: ActorSystem = null
-
- override def beforeAll(): Unit = {
- system = ActorSystem("test", TestUtil.DEFAULT_CONFIG)
- }
-
- override def afterAll(): Unit = {
- system.terminate()
- Await.result(system.whenTerminated, Duration.Inf)
- }
-
- it should "getConfig from remote Gearpump" in {
- val appId = ApplicationId.newInstance(0L, 0)
- val appMaster = TestProbe()
- val manager = new ManageCluster(appId, appMaster.ref, system)
-
- val output = java.io.File.createTempFile("managerClusterSpec", ".conf")
-
- val future = manager.command(GET_CONFIG, new ParseResult(Map("output" -> output.toString),
- Array.empty[String]))
- appMaster.expectMsgType[GetActiveConfig]
- appMaster.reply(ActiveConfig(ConfigFactory.empty()))
- import scala.concurrent.duration._
- Await.result(future, 30.seconds)
-
- val content = FileUtils.read(output)
- assert(content.length > 0)
- output.delete()
- }
-
- it should "addworker" in {
- val appId = ApplicationId.newInstance(0L, 0)
- val appMaster = TestProbe()
- val manager = new ManageCluster(appId, appMaster.ref, system)
-
- val future = manager.command(ADD_WORKER, new ParseResult(Map("count" -> 1.toString),
- Array.empty[String]))
- appMaster.expectMsg(AddWorker(1))
- appMaster.reply(CommandResult(true))
- import scala.concurrent.duration._
- val result = Await.result(future, 30.seconds).asInstanceOf[CommandResult]
- assert(result.success)
- }
-
- it should "removeworker" in {
- val appId = ApplicationId.newInstance(0L, 0)
- val appMaster = TestProbe()
- val manager = new ManageCluster(appId, appMaster.ref, system)
-
- val future = manager.command(REMOVE_WORKER, new ParseResult(Map("container" -> "1"),
- Array.empty[String]))
- appMaster.expectMsg(RemoveWorker("1"))
- appMaster.reply(CommandResult(true))
- import scala.concurrent.duration._
- val result = Await.result(future, 30.seconds).asInstanceOf[CommandResult]
- assert(result.success)
- }
-
- it should "get version" in {
- val appId = ApplicationId.newInstance(0L, 0)
- val appMaster = TestProbe()
- val manager = new ManageCluster(appId, appMaster.ref, system)
- val future = manager.command(VERSION, new ParseResult(Map("container" -> "1"),
- Array.empty[String]))
- appMaster.expectMsg(QueryVersion)
- appMaster.reply(Version("version 0.1"))
- import scala.concurrent.duration._
- val result = Await.result(future, 30.seconds).asInstanceOf[Version]
- assert(result.version == "version 0.1")
- }
-
- it should "get cluster info" in {
- val appId = ApplicationId.newInstance(0L, 0)
- val appMaster = TestProbe()
- val manager = new ManageCluster(appId, appMaster.ref, system)
-
- val output = java.io.File.createTempFile("managerClusterSpec", ".conf")
-
- val future = manager.command(QUERY, new ParseResult(Map.empty[String, String],
- Array.empty[String]))
- appMaster.expectMsg(QueryClusterInfo)
- appMaster.reply(ClusterInfo(List("master"), List("worker")))
- import scala.concurrent.duration._
- val result = Await.result(future, 30.seconds).asInstanceOf[ClusterInfo]
- assert(result.masters.sameElements(List("master")))
- assert(result.workers.sameElements(List("worker")))
- }
-
- it should "kill the cluster" in {
- val appId = ApplicationId.newInstance(0L, 0)
- val appMaster = TestProbe()
- val manager = new ManageCluster(appId, appMaster.ref, system)
-
- val output = java.io.File.createTempFile("managerClusterSpec", ".conf")
-
- val future = manager.command(KILL, new ParseResult(Map("container" -> "1"),
- Array.empty[String]))
- appMaster.expectMsg(Kill)
- appMaster.reply(CommandResult(true))
- import scala.concurrent.duration._
- val result = Await.result(future, 30.seconds).asInstanceOf[CommandResult]
- assert(result.success)
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/test/scala/org/apache/gearpump/experiments/yarn/appmaster/CommandSpec.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/test/scala/org/apache/gearpump/experiments/yarn/appmaster/CommandSpec.scala b/experiments/yarn/src/test/scala/org/apache/gearpump/experiments/yarn/appmaster/CommandSpec.scala
new file mode 100644
index 0000000..c4c5a65
--- /dev/null
+++ b/experiments/yarn/src/test/scala/org/apache/gearpump/experiments/yarn/appmaster/CommandSpec.scala
@@ -0,0 +1,95 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.yarn.appmaster
+
+import com.typesafe.config.ConfigFactory
+import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
+
+import org.apache.gearpump.cluster.TestUtil
+import org.apache.gearpump.transport.HostPort
+
+class CommandSpec extends FlatSpec with Matchers with BeforeAndAfterAll {
+ val config = ConfigFactory.parseString(
+
+ """
+ |
+ |gearpump {
+ | yarn {
+ | client {
+ | package -path = "/user/gearpump/gearpump.zip"
+ | }
+ |
+ | applicationmaster {
+ | ## Memory of YarnAppMaster
+ | command = "$JAVA_HOME/bin/java -Xmx512m"
+ | memory = "512"
+ | vcores = "1"
+ | queue = "default"
+ | }
+ |
+ | master {
+ | ## Memory of master daemon
+ | command = "$JAVA_HOME/bin/java -Xmx512m"
+ | memory = "512"
+ | vcores = "1"
+ | }
+ |
+ | worker {
+ | ## memory of worker daemon
+ | command = "$JAVA_HOME/bin/java -Xmx512m"
+ | containers = "4"
+ | ## This also contains all memory for child executors.
+ | memory = "4096"
+ | vcores = "1"
+ | }
+ | services {
+ | enabled = true
+ | }
+ | }
+ |}
+ """.stripMargin).withFallback(TestUtil.DEFAULT_CONFIG)
+
+ "MasterCommand" should "create correct command line" in {
+ val version = "gearpump-0.1"
+ val master = MasterCommand(config, version, HostPort("127.0.0.1", 8080))
+
+ // scalastyle:off line.size.limit
+ val expected = "$JAVA_HOME/bin/java -Xmx512m -cp conf:pack/gearpump-0.1/conf:pack/gearpump-0.1/lib/daemon/*:pack/gearpump-0.1/lib/*:$CLASSPATH -Dgearpump.cluster.masters.0=127.0.0.1:8080 -Dgearpump.hostname=127.0.0.1 -Dgearpump.master-resource-manager-container-id={{CONTAINER_ID}} -Dgearpump.home={{LOCAL_DIRS}}/{{CONTAINER_ID}}/pack/gearpump-0.1 -Dgearpump.log.daemon.dir=<LOG_DIR> -Dgearpump.log.application.dir=<LOG_DIR> org.apache.gearpump.cluster.main.Master -ip 127.0.0.1 -port 8080 2>&1 | /usr/bin/tee -a <LOG_DIR>/stderr"
+ // scalastyle:on line.size.limit
+ assert(master.get == expected)
+ }
+
+ "WorkerCommand" should "create correct command line" in {
+ val version = "gearpump-0.1"
+ val worker = WorkerCommand(config, version, HostPort("127.0.0.1", 8080), "worker-machine")
+ // scalastyle:off line.size.limit
+ val expected = "$JAVA_HOME/bin/java -Xmx512m -cp conf:pack/gearpump-0.1/conf:pack/gearpump-0.1/lib/daemon/*:pack/gearpump-0.1/lib/*:$CLASSPATH -Dgearpump.cluster.masters.0=127.0.0.1:8080 -Dgearpump.log.daemon.dir=<LOG_DIR> -Dgearpump.worker-resource-manager-container-id={{CONTAINER_ID}} -Dgearpump.home={{LOCAL_DIRS}}/{{CONTAINER_ID}}/pack/gearpump-0.1 -Dgearpump.log.application.dir=<LOG_DIR> -Dgearpump.hostname=worker-machine org.apache.gearpump.cluster.main.Worker 2>&1 | /usr/bin/tee -a <LOG_DIR>/stderr"
+ // scalastyle:on line.size.limit
+ assert(worker.get == expected)
+ }
+
+ "AppMasterCommand" should "create correct command line" in {
+ val version = "gearpump-0.1"
+ val appmaster = AppMasterCommand(config, version, Array("arg1", "arg2", "arg3"))
+ // scalastyle:off line.size.limit
+ val expected = "$JAVA_HOME/bin/java -Xmx512m -cp conf:pack/gearpump-0.1/conf:pack/gearpump-0.1/dashboard:pack/gearpump-0.1/lib/*:pack/gearpump-0.1/lib/daemon/*:pack/gearpump-0.1/lib/services/*:pack/gearpump-0.1/lib/yarn/*:$CLASSPATH -Dgearpump.home={{LOCAL_DIRS}}/{{CONTAINER_ID}}/pack/gearpump-0.1 -Dgearpump.binary-version-with-scala-version=gearpump-0.1 -Dgearpump.log.daemon.dir=<LOG_DIR> -Dgearpump.log.application.dir=<LOG_DIR> -Dgearpump.hostname={{NM_HOST}} org.apache.gearpump.experiments.yarn.appmaster.YarnAppMaster arg1 arg2 arg3 2>&1 | /usr/bin/tee -a <LOG_DIR>/stderr"
+ // scalastyle:on line.size.limit
+ assert(appmaster.get == expected)
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/test/scala/org/apache/gearpump/experiments/yarn/appmaster/UIServiceSpec.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/test/scala/org/apache/gearpump/experiments/yarn/appmaster/UIServiceSpec.scala b/experiments/yarn/src/test/scala/org/apache/gearpump/experiments/yarn/appmaster/UIServiceSpec.scala
new file mode 100644
index 0000000..34af145
--- /dev/null
+++ b/experiments/yarn/src/test/scala/org/apache/gearpump/experiments/yarn/appmaster/UIServiceSpec.scala
@@ -0,0 +1,84 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.yarn.appmaster
+
+import akka.actor.{ActorRef, ActorSystem, Props}
+import akka.testkit.TestProbe
+import com.typesafe.config.ConfigFactory
+import org.apache.gearpump.cluster.TestUtil
+import org.apache.gearpump.experiments.yarn.appmaster.UIServiceSpec.{Info, MockUI}
+import org.apache.gearpump.transport.HostPort
+import org.apache.gearpump.util.Constants
+import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
+
+import scala.concurrent.Await
+import scala.concurrent.duration.Duration
+
+class UIServiceSpec extends FlatSpec with Matchers with BeforeAndAfterAll {
+ implicit var system: ActorSystem = null
+
+ override def beforeAll(): Unit = {
+ system = ActorSystem(getClass.getSimpleName, TestUtil.DEFAULT_CONFIG)
+ }
+
+ override def afterAll(): Unit = {
+ system.terminate()
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+
+ it should "start UI server correctly" in {
+ val probe = TestProbe()
+ val masters = List(
+ HostPort("127.0.0.1", 3000),
+ HostPort("127.0.0.1", 3001),
+ HostPort("127.0.0.1", 3002)
+ )
+ val host = "local"
+ val port = 8091
+
+ val ui = system.actorOf(Props(new MockUI(masters, host, port, probe.ref)))
+
+ probe.expectMsgPF() {
+ case info: Info => {
+ assert(info.masterHost == "127.0.0.1")
+ assert(info.masterPort == 3000)
+ val conf = ConfigFactory.parseFile(new java.io.File(info.configFile))
+ assert(conf.getString(Constants.GEARPUMP_SERVICE_HOST) == host)
+ assert(conf.getString(Constants.GEARPUMP_SERVICE_HTTP) == "8091")
+ assert(conf.getString(Constants.NETTY_TCP_HOSTNAME) == host)
+ }
+ }
+
+ system.stop(ui)
+ }
+}
+
+object UIServiceSpec {
+
+ case class Info(supervisor: String, masterHost: String, masterPort: Int, configFile: String)
+
+ class MockUI(masters: List[HostPort], host: String, port: Int, probe: ActorRef)
+ extends UIService(masters, host, port) {
+
+ override def launch(
+ supervisor: String, masterHost: String, masterPort: Int, configFile: String): Unit = {
+ probe ! Info(supervisor, masterHost, masterPort, configFile)
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/test/scala/org/apache/gearpump/experiments/yarn/appmaster/YarnAppMasterSpec.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/test/scala/org/apache/gearpump/experiments/yarn/appmaster/YarnAppMasterSpec.scala b/experiments/yarn/src/test/scala/org/apache/gearpump/experiments/yarn/appmaster/YarnAppMasterSpec.scala
new file mode 100644
index 0000000..055e822
--- /dev/null
+++ b/experiments/yarn/src/test/scala/org/apache/gearpump/experiments/yarn/appmaster/YarnAppMasterSpec.scala
@@ -0,0 +1,220 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.yarn.appmaster
+
+import akka.actor.{Actor, ActorSystem, Props}
+import akka.testkit.{TestActorRef, TestProbe}
+import com.typesafe.config.ConfigFactory
+import org.apache.gearpump.cluster.ClientToMaster.{AddWorker, CommandResult, RemoveWorker}
+import org.apache.gearpump.cluster.TestUtil
+import org.apache.gearpump.experiments.yarn.Constants
+import org.apache.gearpump.experiments.yarn.appmaster.YarnAppMaster.{ActiveConfig, AppMasterRegistered, ClusterInfo, ContainerStarted, ContainersAllocated, GetActiveConfig, Kill, QueryClusterInfo, QueryVersion, ResourceManagerException, Version}
+import org.apache.gearpump.experiments.yarn.appmaster.YarnAppMasterSpec.UI
+import org.apache.gearpump.experiments.yarn.glue.Records.{Container, Resource, _}
+import org.apache.gearpump.experiments.yarn.glue.{NMClient, RMClient}
+import org.apache.gearpump.transport.HostPort
+import org.mockito.ArgumentCaptor
+import org.mockito.Matchers._
+import org.mockito.Mockito._
+import org.scalatest.{BeforeAndAfterAll, FlatSpec, Matchers}
+
+import scala.concurrent.Await
+import scala.concurrent.duration.Duration
+
+class YarnAppMasterSpec extends FlatSpec with Matchers with BeforeAndAfterAll {
+
+ val config = ConfigFactory.parseString(
+
+ """
+ |gearpump {
+ | yarn {
+ | client {
+ | package -path = "/user/gearpump/gearpump.zip"
+ | }
+ |
+ | applicationmaster {
+ | ## Memory of YarnAppMaster
+ | command = "$JAVA_HOME/bin/java -Xmx512m"
+ | memory = "512"
+ | vcores = "1"
+ | queue = "default"
+ | }
+ |
+ | master {
+ | ## Memory of master daemon
+ | command = "$JAVA_HOME/bin/java -Xmx512m"
+ | memory = "512"
+ | vcores = "1"
+ | }
+ |
+ | worker {
+ | ## memory of worker daemon
+ | command = "$JAVA_HOME/bin/java -Xmx512m"
+ | containers = "4"
+ | ## This also contains all memory for child executors.
+ | memory = "4096"
+ | vcores = "1"
+ | }
+ | services {
+ | enabled = true
+ | }
+ | }
+ |}
+ """.stripMargin).withFallback(TestUtil.DEFAULT_CONFIG)
+
+ val masterCount = 1
+ val workerCount = config.getString(Constants.WORKER_CONTAINERS).toInt
+
+ implicit var system: ActorSystem = null
+ val packagePath = "/user/gearpump/gearpump.zip"
+ val configPath = "/user/my/conf"
+
+ override def beforeAll(): Unit = {
+ system = ActorSystem("test", config)
+ }
+
+ override def afterAll(): Unit = {
+ system.terminate()
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+
+ private def startAppMaster(): (TestActorRef[YarnAppMaster], TestProbe, NMClient, RMClient) = {
+ val rmClient = mock(classOf[RMClient])
+ val nmClient = mock(classOf[NMClient])
+ val ui = mock(classOf[UIFactory])
+ when(ui.props(any[List[HostPort]], anyString, anyInt)).thenReturn(Props(new UI))
+
+ val appMaster = TestActorRef[YarnAppMaster](Props(
+ new YarnAppMaster(rmClient, nmClient, packagePath, configPath, ui)))
+
+ verify(rmClient).start(appMaster)
+ verify(nmClient).start(appMaster)
+ verify(rmClient).registerAppMaster(anyString, anyInt, anyString)
+
+ appMaster ! AppMasterRegistered
+
+ val masterResources = ArgumentCaptor.forClass(classOf[List[Resource]])
+ verify(rmClient).requestContainers(masterResources.capture())
+ assert(masterResources.getValue.size == masterCount)
+
+ val masterContainer = mock(classOf[Container])
+ val mockNode = mock(classOf[NodeId])
+ val mockId = mock(classOf[ContainerId])
+ when(masterContainer.getNodeId).thenReturn(mockNode)
+ when(masterContainer.getId).thenReturn(mockId)
+
+ // Launchs master
+ appMaster ! ContainersAllocated(List.fill(masterCount)(masterContainer))
+ verify(nmClient,
+ times(masterCount)).launchCommand(any[Container], anyString, anyString, anyString)
+
+ // Master containers started
+ (0 until masterCount).foreach(_ => appMaster ! ContainerStarted(mockId))
+
+ // Transition to start workers
+ val workerResources = ArgumentCaptor.forClass(classOf[List[Resource]])
+ verify(rmClient, times(2)).requestContainers(workerResources.capture())
+ assert(workerResources.getValue.size == workerCount)
+
+ // Launchs workers
+ val workerContainer = mock(classOf[Container])
+ when(workerContainer.getNodeId).thenReturn(mockNode)
+ val workerContainerId = ContainerId.fromString("container_1449802454214_0034_01_000006")
+ when(workerContainer.getId).thenReturn(workerContainerId)
+ appMaster ! ContainersAllocated(List.fill(workerCount)(workerContainer))
+ verify(nmClient, times(workerCount + masterCount))
+ .launchCommand(any[Container], anyString, anyString, anyString)
+
+ // Worker containers started
+ (0 until workerCount).foreach(_ => appMaster ! ContainerStarted(mockId))
+
+ // Starts UI server
+ verify(ui, times(1)).props(any[List[HostPort]], anyString, anyInt)
+
+ // Application Ready...
+ val client = TestProbe()
+
+ // Gets active config
+ appMaster.tell(GetActiveConfig("client"), client.ref)
+ client.expectMsgType[ActiveConfig]
+
+ // Queries version
+ appMaster.tell(QueryVersion, client.ref)
+ client.expectMsgType[Version]
+
+ // Queries version
+ appMaster.tell(QueryClusterInfo, client.ref)
+ client.expectMsgType[ClusterInfo]
+
+ // Adds worker
+ val newWorkerCount = 2
+ appMaster.tell(AddWorker(newWorkerCount), client.ref)
+ client.expectMsgType[CommandResult]
+ val newWorkerResources = ArgumentCaptor.forClass(classOf[List[Resource]])
+ verify(rmClient, times(3)).requestContainers(newWorkerResources.capture())
+ assert(newWorkerResources.getValue.size == newWorkerCount)
+
+ // New container allocated
+ appMaster ! ContainersAllocated(List.fill(newWorkerCount)(workerContainer))
+ verify(nmClient, times(workerCount + masterCount + newWorkerCount)).
+ launchCommand(any[Container], anyString, anyString, anyString)
+
+ // New worker containers started
+ (0 until newWorkerCount).foreach(_ => appMaster ! ContainerStarted(mockId))
+
+ // Same UI server
+ verify(ui, times(1)).props(any[List[HostPort]], anyString, anyInt)
+
+ // Removes worker
+ appMaster.tell(RemoveWorker(workerContainerId.toString), client.ref)
+ client.expectMsgType[CommandResult]
+ verify(nmClient).stopContainer(any[ContainerId], any[NodeId])
+
+ (appMaster, client: TestProbe, nmClient, rmClient)
+ }
+
+ it should "start master, worker and UI on YARN" in {
+ val env = startAppMaster()
+ val (appMaster, client, nmClient, rmClient) = env
+
+ // Kills the app
+ appMaster.tell(Kill, client.ref)
+ client.expectMsgType[CommandResult]
+ verify(nmClient, times(1)).stop()
+ verify(rmClient, times(1)).shutdownApplication()
+ }
+
+ it should "handle resource manager errors" in {
+ val env = startAppMaster()
+ val (appMaster, client, nmClient, rmClient) = env
+
+ // on error
+ val ex = new Exception("expected resource manager exception")
+ appMaster.tell(ResourceManagerException(ex), client.ref)
+ verify(nmClient, times(1)).stop()
+ verify(rmClient, times(1)).failApplication(ex)
+ }
+}
+
+object YarnAppMasterSpec {
+
+ class UI extends Actor {
+ def receive: Receive = null
+ }
+}
\ No newline at end of file
[27/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/Hierarchy.java
----------------------------------------------------------------------
diff --git a/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/Hierarchy.java b/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/Hierarchy.java
deleted file mode 100644
index 69ec1ed..0000000
--- a/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/Hierarchy.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.cluster.cgroup;
-
-import java.util.Set;
-
-public class Hierarchy {
-
- private final String name;
-
- private final Set<ResourceType> resourceTypes;
-
- private final String type;
-
- private final String dir;
-
- private final CgroupCommon rootCgroups;
-
- public Hierarchy(String name, Set<ResourceType> resourceTypes, String dir) {
- this.name = name;
- this.resourceTypes = resourceTypes;
- this.dir = dir;
- this.rootCgroups = new CgroupCommon(this, dir);
- this.type = CgroupUtils.reAnalyse(resourceTypes);
- }
-
- public Set<ResourceType> getResourceTypes() {
- return resourceTypes;
- }
-
- public String getType() {
- return type;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((dir == null) ? 0 : dir.hashCode());
- result = prime * result + ((name == null) ? 0 : name.hashCode());
- result = prime * result + ((type == null) ? 0 : type.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- Hierarchy other = (Hierarchy) obj;
- if (dir == null) {
- if (other.dir != null)
- return false;
- } else if (!dir.equals(other.dir))
- return false;
- if (name == null) {
- if (other.name != null)
- return false;
- } else if (!name.equals(other.name))
- return false;
- if (type == null) {
- if (other.type != null)
- return false;
- } else if (!type.equals(other.type))
- return false;
- return true;
- }
-
- public String getDir() {
- return dir;
- }
-
- public CgroupCommon getRootCgroups() {
- return rootCgroups;
- }
-
- public String getName() {
- return name;
- }
-
- public boolean subSystemMounted(ResourceType subsystem) {
- for (ResourceType type : this.resourceTypes) {
- if (type == subsystem)
- return true;
- }
- return false;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/ResourceType.java
----------------------------------------------------------------------
diff --git a/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/ResourceType.java b/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/ResourceType.java
deleted file mode 100644
index c2a1d42..0000000
--- a/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/ResourceType.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.cluster.cgroup;
-
-public enum ResourceType {
-
- // net_cls,ns is not supposted in ubuntu
- blkio, cpu, cpuacct, cpuset, devices, freezer, memory, perf_event, net_cls, net_prio;
-
- public static ResourceType getResourceType(String str) {
- if (str.equals("cpu"))
- return cpu;
- return null;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/core/CgroupCore.java
----------------------------------------------------------------------
diff --git a/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/core/CgroupCore.java b/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/core/CgroupCore.java
deleted file mode 100644
index 23e630c..0000000
--- a/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/core/CgroupCore.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.cluster.cgroup.core;
-
-import io.gearpump.cluster.cgroup.ResourceType;
-
-public interface CgroupCore {
-
- public ResourceType getType();
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/core/CpuCore.java
----------------------------------------------------------------------
diff --git a/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/core/CpuCore.java b/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/core/CpuCore.java
deleted file mode 100644
index 3402d5a..0000000
--- a/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/core/CpuCore.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.cluster.cgroup.core;
-
-import io.gearpump.cluster.cgroup.CgroupUtils;
-import io.gearpump.cluster.cgroup.Constants;
-import io.gearpump.cluster.cgroup.ResourceType;
-
-import java.io.IOException;
-
-public class CpuCore implements CgroupCore {
-
- public static final String CPU_SHARES = "/cpu.shares";
- public static final String CPU_CFS_PERIOD_US = "/cpu.cfs_period_us";
- public static final String CPU_CFS_QUOTA_US = "/cpu.cfs_quota_us";
-
- private final String dir;
-
- public CpuCore(String dir) {
- this.dir = dir;
- }
-
- @Override
- public ResourceType getType() {
- // TODO Auto-generated method stub
- return ResourceType.cpu;
- }
-
- public void setCpuShares(int weight) throws IOException {
- CgroupUtils.writeFileByLine(Constants.getDir(this.dir, CPU_SHARES), String.valueOf(weight));
- }
-
- public int getCpuShares() throws IOException {
- return Integer.parseInt(CgroupUtils.readFileByLine(Constants.getDir(this.dir, CPU_SHARES)).get(0));
- }
-
- public void setCpuCfsPeriodUs(long us) throws IOException {
- CgroupUtils.writeFileByLine(Constants.getDir(this.dir, CPU_CFS_PERIOD_US), String.valueOf(us));
- }
-
- public void setCpuCfsQuotaUs(long us) throws IOException {
- CgroupUtils.writeFileByLine(Constants.getDir(this.dir, CPU_CFS_QUOTA_US), String.valueOf(us));
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/cgroup/src/main/java/io/gearpump/cluster/utils/SystemOperation.java
----------------------------------------------------------------------
diff --git a/experiments/cgroup/src/main/java/io/gearpump/cluster/utils/SystemOperation.java b/experiments/cgroup/src/main/java/io/gearpump/cluster/utils/SystemOperation.java
deleted file mode 100644
index 0772133..0000000
--- a/experiments/cgroup/src/main/java/io/gearpump/cluster/utils/SystemOperation.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.cluster.utils;
-
-import org.apache.commons.io.IOUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.IOException;
-
-public class SystemOperation {
-
- public static final Logger LOG = LoggerFactory.getLogger(SystemOperation.class);
-
- public static void mount(String name, String target, String type, String data) throws IOException {
- StringBuilder sb = new StringBuilder();
- sb.append("mount -t ").append(type).append(" -o ").append(data).append(" ").append(name).append(" ").append(target);
- SystemOperation.exec(sb.toString());
- }
-
- public static void umount(String name) throws IOException {
- StringBuilder sb = new StringBuilder();
- sb.append("umount ").append(name);
- SystemOperation.exec(sb.toString());
- }
-
- public static String exec(String cmd) throws IOException {
- LOG.debug("Shell cmd: " + cmd);
- Process process = new ProcessBuilder(new String[]{"/bin/bash", "-c", cmd}).start();
- try {
- process.waitFor();
- String output = IOUtils.toString(process.getInputStream());
- String errorOutput = IOUtils.toString(process.getErrorStream());
- LOG.debug("Shell Output: " + output);
- if (errorOutput.length() != 0) {
- LOG.error("Shell Error Output: " + errorOutput);
- throw new IOException(errorOutput);
- }
- return output;
- } catch (InterruptedException ie) {
- throw new IOException(ie.toString());
- }
- }
-
- public static void main(String[] args) throws IOException {
- SystemOperation.mount("test", "/cgroup/cpu", "cgroup", "cpu");
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/CGroupResource.java
----------------------------------------------------------------------
diff --git a/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/CGroupResource.java b/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/CGroupResource.java
new file mode 100644
index 0000000..a616593
--- /dev/null
+++ b/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/CGroupResource.java
@@ -0,0 +1,68 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.cluster.cgroup;
+
+public class CGroupResource {
+
+ private ResourceType type;
+
+ private int hierarchyID;
+
+ private int cgroupsNum;
+
+ private boolean enable;
+
+ public CGroupResource(ResourceType type, int hierarchyID, int cgroupNum, boolean enable) {
+ this.type = type;
+ this.hierarchyID = hierarchyID;
+ this.cgroupsNum = cgroupNum;
+ this.enable = enable;
+ }
+
+ public ResourceType getType() {
+ return type;
+ }
+
+ public void setType(ResourceType type) {
+ this.type = type;
+ }
+
+ public int getHierarchyID() {
+ return hierarchyID;
+ }
+
+ public void setHierarchyID(int hierarchyID) {
+ this.hierarchyID = hierarchyID;
+ }
+
+ public int getCgroupsNum() {
+ return cgroupsNum;
+ }
+
+ public void setCgroupsNum(int cgroupsNum) {
+ this.cgroupsNum = cgroupsNum;
+ }
+
+ public boolean isEnable() {
+ return enable;
+ }
+
+ public void setEnable(boolean enable) {
+ this.enable = enable;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/CgroupCenter.java
----------------------------------------------------------------------
diff --git a/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/CgroupCenter.java b/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/CgroupCenter.java
new file mode 100644
index 0000000..fb2ba65
--- /dev/null
+++ b/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/CgroupCenter.java
@@ -0,0 +1,212 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.cluster.cgroup;
+
+import org.apache.gearpump.cluster.utils.SystemOperation;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.*;
+
+public class CgroupCenter implements CgroupOperation {
+
+ public static Logger LOG = LoggerFactory.getLogger(CgroupCenter.class);
+
+ private static CgroupCenter instance;
+
+ private CgroupCenter() {
+
+ }
+
+ /**
+ * Thread unsafe
+ *
+ * @return
+ */
+ public synchronized static CgroupCenter getInstance() {
+ if (instance == null)
+ instance = new CgroupCenter();
+ return CgroupUtils.enabled() ? instance : null;
+ }
+
+ @Override
+ public List<Hierarchy> getHierarchies() {
+ // TODO Auto-generated method stub
+ Map<String, Hierarchy> hierarchies = new HashMap<String, Hierarchy>();
+ FileReader reader = null;
+ BufferedReader br = null;
+ try {
+ reader = new FileReader(Constants.MOUNT_STATUS_FILE);
+ br = new BufferedReader(reader);
+ String str = null;
+ while ((str = br.readLine()) != null) {
+ String[] strSplit = str.split(" ");
+ if (!strSplit[2].equals("cgroup"))
+ continue;
+ String name = strSplit[0];
+ String type = strSplit[3];
+ String dir = strSplit[1];
+ Hierarchy h = hierarchies.get(type);
+ h = new Hierarchy(name, CgroupUtils.analyse(type), dir);
+ hierarchies.put(type, h);
+ }
+ return new ArrayList<Hierarchy>(hierarchies.values());
+ } catch (Exception e) {
+ LOG.error("Get hierarchies error", e);
+ } finally {
+ CgroupUtils.close(reader, br);
+ }
+ return null;
+ }
+
+ @Override
+ public Set<CGroupResource> getCGroupResources() {
+ // TODO Auto-generated method stub
+ Set<CGroupResource> resources = new HashSet<CGroupResource>();
+ FileReader reader = null;
+ BufferedReader br = null;
+ try {
+ reader = new FileReader(Constants.CGROUP_STATUS_FILE);
+ br = new BufferedReader(reader);
+ String str = null;
+ while ((str = br.readLine()) != null) {
+ String[] split = str.split("\t");
+ ResourceType type = ResourceType.getResourceType(split[0]);
+ if (type == null)
+ continue;
+ resources.add(new CGroupResource(type, Integer.valueOf(split[1]), Integer.valueOf(split[2]), Integer.valueOf(split[3]).intValue() == 1 ? true
+ : false));
+ }
+ return resources;
+ } catch (Exception e) {
+ LOG.error("Get subSystems error ", e);
+ } finally {
+ CgroupUtils.close(reader, br);
+ }
+ return null;
+ }
+
+ @Override
+ public boolean enabled(ResourceType resourceType) {
+ // TODO Auto-generated method stub
+ Set<CGroupResource> resources = this.getCGroupResources();
+ for (CGroupResource resource : resources) {
+ if (resource.getType() == resourceType)
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public Hierarchy busy(ResourceType resourceType) {
+ List<Hierarchy> hierarchies = this.getHierarchies();
+ for (Hierarchy hierarchy : hierarchies) {
+ for (ResourceType type : hierarchy.getResourceTypes()) {
+ if (type == resourceType)
+ return hierarchy;
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public Hierarchy mounted(Hierarchy hierarchy) {
+ // TODO Auto-generated method stub
+ List<Hierarchy> hierarchies = this.getHierarchies();
+ if (CgroupUtils.dirExists(hierarchy.getDir())) {
+ for (Hierarchy h : hierarchies) {
+ if (h.equals(hierarchy))
+ return h;
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public void mount(Hierarchy hierarchy) throws IOException {
+ // TODO Auto-generated method stub
+ if (this.mounted(hierarchy) != null) {
+ LOG.error(hierarchy.getDir() + " is mounted");
+ return;
+ }
+ Set<ResourceType> resourceTypes = hierarchy.getResourceTypes();
+ for (ResourceType type : resourceTypes) {
+ if (this.busy(type) != null) {
+ LOG.error("subsystem: " + type.name() + " is busy");
+ resourceTypes.remove(type);
+ }
+ }
+ if (resourceTypes.size() == 0)
+ return;
+ if (!CgroupUtils.dirExists(hierarchy.getDir()))
+ new File(hierarchy.getDir()).mkdirs();
+ String subSystems = CgroupUtils.reAnalyse(resourceTypes);
+ SystemOperation.mount(subSystems, hierarchy.getDir(), "cgroup", subSystems);
+ }
+
+ @Override
+ public void umount(Hierarchy hierarchy) throws IOException {
+ // TODO Auto-generated method stub
+ if (this.mounted(hierarchy) != null) {
+ hierarchy.getRootCgroups().delete();
+ SystemOperation.umount(hierarchy.getDir());
+ CgroupUtils.deleteDir(hierarchy.getDir());
+ }
+ }
+
+ @Override
+ public void create(CgroupCommon cgroup) throws SecurityException {
+ // TODO Auto-generated method stub
+ if (cgroup.isRoot()) {
+ LOG.error("You can't create rootCgroup in this function");
+ return;
+ }
+ CgroupCommon parent = cgroup.getParent();
+ while (parent != null) {
+ if (!CgroupUtils.dirExists(parent.getDir())) {
+ LOG.error(parent.getDir() + "is not existed");
+ return;
+ }
+ parent = parent.getParent();
+ }
+ Hierarchy h = cgroup.getHierarchy();
+ if (mounted(h) == null) {
+ LOG.error(h.getDir() + " is not mounted");
+ return;
+ }
+ if (CgroupUtils.dirExists(cgroup.getDir())) {
+ LOG.error(cgroup.getDir() + " is existed");
+ return;
+ }
+ (new File(cgroup.getDir())).mkdir();
+ }
+
+ @Override
+ public void delete(CgroupCommon cgroup) throws IOException {
+ // TODO Auto-generated method stub
+ cgroup.delete();
+ }
+
+ public static void main(String args[]) {
+ System.out.println(CgroupCenter.getInstance().getHierarchies().get(0).getRootCgroups().getChildren().size());
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/CgroupCommon.java
----------------------------------------------------------------------
diff --git a/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/CgroupCommon.java b/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/CgroupCommon.java
new file mode 100644
index 0000000..2bccfec
--- /dev/null
+++ b/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/CgroupCommon.java
@@ -0,0 +1,220 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.cluster.cgroup;
+
+import org.apache.gearpump.cluster.cgroup.core.CgroupCore;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+public class CgroupCommon implements CgroupCommonOperation {
+
+ public static final String TASKS = "/tasks";
+ public static final String NOTIFY_ON_RELEASE = "/notify_on_release";
+ public static final String RELEASE_AGENT = "/release_agent";
+ public static final String CGROUP_CLONE_CHILDREN = "/cgroup.clone_children";
+ public static final String CGROUP_EVENT_CONTROL = "/cgroup.event_control";
+ public static final String CGROUP_PROCS = "/cgroup.procs";
+
+ private final Hierarchy hierarchy;
+
+ private final String name;
+
+ private final String dir;
+
+ private final CgroupCommon parent;
+
+ private final Map<ResourceType, CgroupCore> cores;
+
+ private final boolean isRoot;
+
+ private final Set<CgroupCommon> children = new HashSet<CgroupCommon>();
+
+ public CgroupCommon(String name, Hierarchy hierarchy, CgroupCommon parent) {
+ this.name = parent.getName() + "/" + name;
+ this.hierarchy = hierarchy;
+ this.parent = parent;
+ this.dir = parent.getDir() + "/" + name;
+ this.init();
+ cores = CgroupCoreFactory.getInstance(this.hierarchy.getResourceTypes(), this.dir);
+ this.isRoot = false;
+ }
+
+ /**
+ * rootCgroup
+ */
+ public CgroupCommon(Hierarchy hierarchy, String dir) {
+ this.name = "";
+ this.hierarchy = hierarchy;
+ this.parent = null;
+ this.dir = dir;
+ this.init();
+ cores = CgroupCoreFactory.getInstance(this.hierarchy.getResourceTypes(), this.dir);
+ this.isRoot = true;
+ }
+
+ @Override
+ public void addTask(int taskId) throws IOException {
+ // TODO Auto-generated method stub
+ CgroupUtils.writeFileByLine(Constants.getDir(this.dir, TASKS), String.valueOf(taskId));
+ }
+
+ @Override
+ public Set<Integer> getTasks() throws IOException {
+ List<String> stringTasks = CgroupUtils.readFileByLine(Constants.getDir(this.dir, TASKS));
+ Set<Integer> tasks = new HashSet<Integer>();
+ for (String task : stringTasks) {
+ tasks.add(Integer.valueOf(task));
+ }
+ return tasks;
+ }
+
+ @Override
+ public void addProcs(int pid) throws IOException {
+ // TODO Auto-generated method stub
+ CgroupUtils.writeFileByLine(Constants.getDir(this.dir, CGROUP_PROCS), String.valueOf(pid));
+ }
+
+ @Override
+ public Set<Integer> getPids() throws IOException {
+ // TODO Auto-generated method stub
+ List<String> stringPids = CgroupUtils.readFileByLine(Constants.getDir(this.dir, CGROUP_PROCS));
+ Set<Integer> pids = new HashSet<Integer>();
+ for (String task : stringPids) {
+ pids.add(Integer.valueOf(task));
+ }
+ return pids;
+ }
+
+ @Override
+ public void setNotifyOnRelease(boolean flag) throws IOException {
+ // TODO Auto-generated method stub
+ CgroupUtils.writeFileByLine(Constants.getDir(this.dir, NOTIFY_ON_RELEASE), flag ? "1" : "0");
+ }
+
+ @Override
+ public boolean getNotifyOnRelease() throws IOException {
+ return CgroupUtils.readFileByLine(Constants.getDir(this.dir, NOTIFY_ON_RELEASE)).get(0).equals("1") ? true : false;
+ }
+
+ @Override
+ public void setReleaseAgent(String command) throws IOException {
+ // TODO Auto-generated method stub
+ if (!this.isRoot)
+ return;
+ CgroupUtils.writeFileByLine(Constants.getDir(this.dir, RELEASE_AGENT), command);
+ }
+
+ @Override
+ public String getReleaseAgent() throws IOException {
+ if (!this.isRoot)
+ return null;
+ return CgroupUtils.readFileByLine(Constants.getDir(this.dir, RELEASE_AGENT)).get(0);
+ }
+
+ @Override
+ public void setCgroupCloneChildren(boolean flag) throws IOException {
+ // TODO Auto-generated method stub
+ if (!this.cores.keySet().contains(ResourceType.cpuset))
+ return;
+ CgroupUtils.writeFileByLine(Constants.getDir(this.dir, CGROUP_CLONE_CHILDREN), flag ? "1" : "0");
+ }
+
+ @Override
+ public boolean getCgroupCloneChildren() throws IOException {
+ return CgroupUtils.readFileByLine(Constants.getDir(this.dir, CGROUP_CLONE_CHILDREN)).get(0).equals("1") ? true : false;
+ }
+
+ @Override
+ public void setEventControl(String eventFd, String controlFd, String... args) throws IOException {
+ // TODO Auto-generated method stub
+ StringBuilder sb = new StringBuilder();
+ sb.append(eventFd);
+ sb.append(' ');
+ sb.append(controlFd);
+ for (String arg : args) {
+ sb.append(' ');
+ sb.append(arg);
+ }
+ CgroupUtils.writeFileByLine(Constants.getDir(this.dir, CGROUP_EVENT_CONTROL), sb.toString());
+ }
+
+ public Hierarchy getHierarchy() {
+ return hierarchy;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getDir() {
+ return dir;
+ }
+
+ public CgroupCommon getParent() {
+ return parent;
+ }
+
+ public Set<CgroupCommon> getChildren() {
+ return children;
+ }
+
+ public boolean isRoot() {
+ return isRoot;
+ }
+
+ public Map<ResourceType, CgroupCore> getCores() {
+ return cores;
+ }
+
+ public void delete() throws IOException {
+ this.free();
+ if (!this.isRoot)
+ this.parent.getChildren().remove(this);
+ }
+
+ private void free() throws IOException {
+ for (CgroupCommon child : this.children)
+ child.free();
+ if (this.isRoot)
+ return;
+ Set<Integer> tasks = this.getTasks();
+ if (tasks != null) {
+ for (Integer task : tasks) {
+ this.parent.addTask(task);
+ }
+ }
+ CgroupUtils.deleteDir(this.dir);
+ }
+
+ private void init() {
+ File file = new File(this.dir);
+ File[] files = file.listFiles();
+ if (files == null)
+ return;
+ for (File child : files) {
+ if (child.isDirectory()) {
+ this.children.add(new CgroupCommon(child.getName(), this.hierarchy, this));
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/CgroupCommonOperation.java
----------------------------------------------------------------------
diff --git a/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/CgroupCommonOperation.java b/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/CgroupCommonOperation.java
new file mode 100644
index 0000000..9ae923b
--- /dev/null
+++ b/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/CgroupCommonOperation.java
@@ -0,0 +1,46 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.cluster.cgroup;
+
+import java.io.IOException;
+import java.util.Set;
+
+public interface CgroupCommonOperation {
+
+ public void addTask(int taskid) throws IOException;
+
+ public Set<Integer> getTasks() throws IOException;
+
+ public void addProcs(int pid) throws IOException;
+
+ public Set<Integer> getPids() throws IOException;
+
+ public void setNotifyOnRelease(boolean flag) throws IOException;
+
+ public boolean getNotifyOnRelease() throws IOException;
+
+ public void setReleaseAgent(String command) throws IOException;
+
+ public String getReleaseAgent() throws IOException;
+
+ public void setCgroupCloneChildren(boolean flag) throws IOException;
+
+ public boolean getCgroupCloneChildren() throws IOException;
+
+ public void setEventControl(String eventFd, String controlFd, String... args) throws IOException;
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/CgroupCoreFactory.java
----------------------------------------------------------------------
diff --git a/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/CgroupCoreFactory.java b/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/CgroupCoreFactory.java
new file mode 100644
index 0000000..15ebcbc
--- /dev/null
+++ b/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/CgroupCoreFactory.java
@@ -0,0 +1,42 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.cluster.cgroup;
+
+import org.apache.gearpump.cluster.cgroup.core.CgroupCore;
+import org.apache.gearpump.cluster.cgroup.core.CpuCore;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+
+public class CgroupCoreFactory {
+
+ public static Map<ResourceType, CgroupCore> getInstance(Set<ResourceType> types, String dir) {
+ Map<ResourceType, CgroupCore> result = new HashMap<ResourceType, CgroupCore>();
+ for (ResourceType type : types) {
+ switch (type) {
+ case cpu:
+ result.put(ResourceType.cpu, new CpuCore(dir));
+ break;
+ default:
+ break;
+ }
+ }
+ return result;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/CgroupOperation.java
----------------------------------------------------------------------
diff --git a/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/CgroupOperation.java b/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/CgroupOperation.java
new file mode 100644
index 0000000..399f3bd
--- /dev/null
+++ b/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/CgroupOperation.java
@@ -0,0 +1,43 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.cluster.cgroup;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Set;
+
+public interface CgroupOperation {
+
+ public List<Hierarchy> getHierarchies();
+
+ public Set<CGroupResource> getCGroupResources();
+
+ public boolean enabled(ResourceType subsystem);
+
+ public Hierarchy busy(ResourceType subsystem);
+
+ public Hierarchy mounted(Hierarchy hierarchy);
+
+ public void mount(Hierarchy hierarchy) throws IOException;
+
+ public void umount(Hierarchy hierarchy) throws IOException;
+
+ public void create(CgroupCommon cgroup) throws SecurityException;
+
+ public void delete(CgroupCommon cgroup) throws IOException;
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/CgroupUtils.java
----------------------------------------------------------------------
diff --git a/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/CgroupUtils.java b/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/CgroupUtils.java
new file mode 100644
index 0000000..8f199d9
--- /dev/null
+++ b/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/CgroupUtils.java
@@ -0,0 +1,160 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.cluster.cgroup;
+
+import org.apache.gearpump.cluster.utils.SystemOperation;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.*;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+public class CgroupUtils {
+
+ public static final Logger LOG = LoggerFactory.getLogger(CgroupUtils.class);
+
+ public static void deleteDir(String dir) {
+ try {
+ String cmd = "rmdir " + dir;
+ SystemOperation.exec(cmd);
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ LOG.error("rm " + dir + " fail!", e);
+ }
+ }
+
+ public static boolean fileExists(String dir) {
+ File file = new File(dir);
+ return file.exists();
+ }
+
+ public static boolean dirExists(String dir) {
+ File file = new File(dir);
+ return file.isDirectory();
+ }
+
+ public static Set<ResourceType> analyse(String str) {
+ Set<ResourceType> result = new HashSet<ResourceType>();
+ String[] subSystems = str.split(",");
+ for (String subSystem : subSystems) {
+ ResourceType type = ResourceType.getResourceType(subSystem);
+ if (type != null)
+ result.add(type);
+ }
+ return result;
+ }
+
+ public static String reAnalyse(Set<ResourceType> subSystems) {
+ StringBuilder sb = new StringBuilder();
+ if (subSystems.size() == 0)
+ return sb.toString();
+ for (ResourceType type : subSystems) {
+ sb.append(type.name()).append(",");
+ }
+ return sb.toString().substring(0, sb.length() - 1);
+ }
+
+ public static boolean enabled() {
+ return CgroupUtils.fileExists(Constants.CGROUP_STATUS_FILE);
+ }
+
+ public static List<String> readFileByLine(String fileDir) throws IOException {
+ List<String> result = new ArrayList<String>();
+ FileReader fileReader = null;
+ BufferedReader reader = null;
+ try {
+ File file = new File(fileDir);
+ fileReader = new FileReader(file);
+ reader = new BufferedReader(fileReader);
+ String tempString = null;
+ while ((tempString = reader.readLine()) != null) {
+ result.add(tempString);
+ }
+ } finally {
+ CgroupUtils.close(fileReader, reader);
+ }
+ return result;
+ }
+
+ public static void writeFileByLine(String fileDir, List<String> strings) throws IOException {
+ FileWriter writer = null;
+ BufferedWriter bw = null;
+ try {
+ File file = new File(fileDir);
+ if (!file.exists()) {
+ LOG.error(fileDir + " is no existed");
+ return;
+ }
+ writer = new FileWriter(file, true);
+ bw = new BufferedWriter(writer);
+ for (String string : strings) {
+ bw.write(string);
+ bw.newLine();
+ bw.flush();
+ }
+ } finally {
+ CgroupUtils.close(writer, bw);
+ }
+ }
+
+ public static void writeFileByLine(String fileDir, String string) throws IOException {
+ FileWriter writer = null;
+ BufferedWriter bw = null;
+ try {
+ File file = new File(fileDir);
+ if (!file.exists()) {
+ LOG.error(fileDir + " is no existed");
+ return;
+ }
+ writer = new FileWriter(file, true);
+ bw = new BufferedWriter(writer);
+ bw.write(string);
+ bw.newLine();
+ bw.flush();
+ } finally {
+ CgroupUtils.close(writer, bw);
+ }
+ }
+
+ public static void close(FileReader reader, BufferedReader br) {
+ try {
+ if (reader != null)
+ reader.close();
+ if (br != null)
+ br.close();
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+
+ }
+ }
+
+ public static void close(FileWriter writer, BufferedWriter bw) {
+ try {
+ if (writer != null)
+ writer.close();
+ if (bw != null)
+ bw.close();
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/Constants.java
----------------------------------------------------------------------
diff --git a/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/Constants.java b/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/Constants.java
new file mode 100644
index 0000000..fb905c7
--- /dev/null
+++ b/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/Constants.java
@@ -0,0 +1,29 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.cluster.cgroup;
+
+public class Constants {
+
+ public static final String CGROUP_STATUS_FILE = "/proc/cgroups";
+
+ public static final String MOUNT_STATUS_FILE = "/proc/mounts";
+
+ public static String getDir(String dir, String constant) {
+ return dir + constant;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/Hierarchy.java
----------------------------------------------------------------------
diff --git a/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/Hierarchy.java b/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/Hierarchy.java
new file mode 100644
index 0000000..446802f
--- /dev/null
+++ b/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/Hierarchy.java
@@ -0,0 +1,106 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.cluster.cgroup;
+
+import java.util.Set;
+
+public class Hierarchy {
+
+ private final String name;
+
+ private final Set<ResourceType> resourceTypes;
+
+ private final String type;
+
+ private final String dir;
+
+ private final CgroupCommon rootCgroups;
+
+ public Hierarchy(String name, Set<ResourceType> resourceTypes, String dir) {
+ this.name = name;
+ this.resourceTypes = resourceTypes;
+ this.dir = dir;
+ this.rootCgroups = new CgroupCommon(this, dir);
+ this.type = CgroupUtils.reAnalyse(resourceTypes);
+ }
+
+ public Set<ResourceType> getResourceTypes() {
+ return resourceTypes;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((dir == null) ? 0 : dir.hashCode());
+ result = prime * result + ((name == null) ? 0 : name.hashCode());
+ result = prime * result + ((type == null) ? 0 : type.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ Hierarchy other = (Hierarchy) obj;
+ if (dir == null) {
+ if (other.dir != null)
+ return false;
+ } else if (!dir.equals(other.dir))
+ return false;
+ if (name == null) {
+ if (other.name != null)
+ return false;
+ } else if (!name.equals(other.name))
+ return false;
+ if (type == null) {
+ if (other.type != null)
+ return false;
+ } else if (!type.equals(other.type))
+ return false;
+ return true;
+ }
+
+ public String getDir() {
+ return dir;
+ }
+
+ public CgroupCommon getRootCgroups() {
+ return rootCgroups;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public boolean subSystemMounted(ResourceType subsystem) {
+ for (ResourceType type : this.resourceTypes) {
+ if (type == subsystem)
+ return true;
+ }
+ return false;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/ResourceType.java
----------------------------------------------------------------------
diff --git a/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/ResourceType.java b/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/ResourceType.java
new file mode 100644
index 0000000..c3360e6
--- /dev/null
+++ b/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/ResourceType.java
@@ -0,0 +1,30 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.cluster.cgroup;
+
+public enum ResourceType {
+
+ // net_cls,ns is not supposted in ubuntu
+ blkio, cpu, cpuacct, cpuset, devices, freezer, memory, perf_event, net_cls, net_prio;
+
+ public static ResourceType getResourceType(String str) {
+ if (str.equals("cpu"))
+ return cpu;
+ return null;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/core/CgroupCore.java
----------------------------------------------------------------------
diff --git a/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/core/CgroupCore.java b/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/core/CgroupCore.java
new file mode 100644
index 0000000..39c0999
--- /dev/null
+++ b/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/core/CgroupCore.java
@@ -0,0 +1,25 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.cluster.cgroup.core;
+
+import org.apache.gearpump.cluster.cgroup.ResourceType;
+
+public interface CgroupCore {
+
+ public ResourceType getType();
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/core/CpuCore.java
----------------------------------------------------------------------
diff --git a/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/core/CpuCore.java b/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/core/CpuCore.java
new file mode 100644
index 0000000..4b35f7f
--- /dev/null
+++ b/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/cgroup/core/CpuCore.java
@@ -0,0 +1,59 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.cluster.cgroup.core;
+
+import org.apache.gearpump.cluster.cgroup.CgroupUtils;
+import org.apache.gearpump.cluster.cgroup.Constants;
+import org.apache.gearpump.cluster.cgroup.ResourceType;
+
+import java.io.IOException;
+
+public class CpuCore implements CgroupCore {
+
+ public static final String CPU_SHARES = "/cpu.shares";
+ public static final String CPU_CFS_PERIOD_US = "/cpu.cfs_period_us";
+ public static final String CPU_CFS_QUOTA_US = "/cpu.cfs_quota_us";
+
+ private final String dir;
+
+ public CpuCore(String dir) {
+ this.dir = dir;
+ }
+
+ @Override
+ public ResourceType getType() {
+ // TODO Auto-generated method stub
+ return ResourceType.cpu;
+ }
+
+ public void setCpuShares(int weight) throws IOException {
+ CgroupUtils.writeFileByLine(Constants.getDir(this.dir, CPU_SHARES), String.valueOf(weight));
+ }
+
+ public int getCpuShares() throws IOException {
+ return Integer.parseInt(CgroupUtils.readFileByLine(Constants.getDir(this.dir, CPU_SHARES)).get(0));
+ }
+
+ public void setCpuCfsPeriodUs(long us) throws IOException {
+ CgroupUtils.writeFileByLine(Constants.getDir(this.dir, CPU_CFS_PERIOD_US), String.valueOf(us));
+ }
+
+ public void setCpuCfsQuotaUs(long us) throws IOException {
+ CgroupUtils.writeFileByLine(Constants.getDir(this.dir, CPU_CFS_QUOTA_US), String.valueOf(us));
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/utils/SystemOperation.java
----------------------------------------------------------------------
diff --git a/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/utils/SystemOperation.java b/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/utils/SystemOperation.java
new file mode 100644
index 0000000..5b2a890
--- /dev/null
+++ b/experiments/cgroup/src/main/java/org/apache/gearpump/cluster/utils/SystemOperation.java
@@ -0,0 +1,63 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.cluster.utils;
+
+import org.apache.commons.io.IOUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+
+public class SystemOperation {
+
+ public static final Logger LOG = LoggerFactory.getLogger(SystemOperation.class);
+
+ public static void mount(String name, String target, String type, String data) throws IOException {
+ StringBuilder sb = new StringBuilder();
+ sb.append("mount -t ").append(type).append(" -o ").append(data).append(" ").append(name).append(" ").append(target);
+ SystemOperation.exec(sb.toString());
+ }
+
+ public static void umount(String name) throws IOException {
+ StringBuilder sb = new StringBuilder();
+ sb.append("umount ").append(name);
+ SystemOperation.exec(sb.toString());
+ }
+
+ public static String exec(String cmd) throws IOException {
+ LOG.debug("Shell cmd: " + cmd);
+ Process process = new ProcessBuilder(new String[]{"/bin/bash", "-c", cmd}).start();
+ try {
+ process.waitFor();
+ String output = IOUtils.toString(process.getInputStream());
+ String errorOutput = IOUtils.toString(process.getErrorStream());
+ LOG.debug("Shell Output: " + output);
+ if (errorOutput.length() != 0) {
+ LOG.error("Shell Error Output: " + errorOutput);
+ throw new IOException(errorOutput);
+ }
+ return output;
+ } catch (InterruptedException ie) {
+ throw new IOException(ie.toString());
+ }
+ }
+
+ public static void main(String[] args) throws IOException {
+ SystemOperation.mount("test", "/cgroup/cpu", "cgroup", "cpu");
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/cgroup/src/main/scala/io/gearpump/cluster/worker/CGroupManager.scala
----------------------------------------------------------------------
diff --git a/experiments/cgroup/src/main/scala/io/gearpump/cluster/worker/CGroupManager.scala b/experiments/cgroup/src/main/scala/io/gearpump/cluster/worker/CGroupManager.scala
deleted file mode 100644
index ae7fb42..0000000
--- a/experiments/cgroup/src/main/scala/io/gearpump/cluster/worker/CGroupManager.scala
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.cluster.worker
-
-import com.typesafe.config.Config
-import org.apache.commons.lang.SystemUtils
-import org.slf4j.{Logger, LoggerFactory}
-
-import io.gearpump.cluster.cgroup.core.{CgroupCore, CpuCore}
-import io.gearpump.cluster.cgroup.{CgroupCenter, CgroupCommon, Hierarchy, ResourceType}
-import io.gearpump.cluster.worker.CGroupManager._
-
-class CGroupManager(config: Config) {
- private val center = CgroupCenter.getInstance()
- private val rootDir = CGroupManager.getCgroupRootDir(config)
- private var hierarchy: Hierarchy = null
- private var rootCgroup: CgroupCommon = null
-
- prepareSubSystem()
-
- private def prepareSubSystem(): Unit = {
- if (rootDir == null) {
- throw new RuntimeException(s"Check configuration file. The $CGROUP_ROOT is missing.")
- }
- if (center == null) {
- throw new RuntimeException("Cgroup error, please check /proc/cgroups")
- }
- hierarchy = center.busy(ResourceType.cpu)
- if (hierarchy == null) {
- val types = new java.util.HashSet[ResourceType]
- types.add(ResourceType.cpu)
- hierarchy = new Hierarchy(GEARPUMP_HIERARCHY_NAME, types, GEARPUMP_CPU_HIERARCHY_DIR)
- }
- rootCgroup = new CgroupCommon(rootDir, hierarchy, hierarchy.getRootCgroups)
- }
-
- private def validateCpuUpperLimitValue(value: Int): Int = {
- if (value > 10) {
- 10
- } else if (value < 1 && value != -1) {
- 1
- } else {
- value
- }
- }
-
- private def setCpuUsageUpperLimit(cpuCore: CpuCore, cpuCoreUpperLimit: Int): Unit = {
- val _cpuCoreUpperLimit = validateCpuUpperLimitValue(cpuCoreUpperLimit)
- if (_cpuCoreUpperLimit == -1) {
- cpuCore.setCpuCfsQuotaUs(_cpuCoreUpperLimit)
- }
- else {
- cpuCore.setCpuCfsPeriodUs(100000)
- cpuCore.setCpuCfsQuotaUs(_cpuCoreUpperLimit * 100000)
- }
- }
-
- def startNewExecutor(config: Config, cpuNum: Int, appId: Int, executorId: Int): List[String] = {
- val groupName = getGroupName(appId, executorId)
- val workerGroup: CgroupCommon = new CgroupCommon(groupName, hierarchy, this.rootCgroup)
- this.center.create(workerGroup)
- val cpu: CgroupCore = workerGroup.getCores.get(ResourceType.cpu)
- val cpuCore: CpuCore = cpu.asInstanceOf[CpuCore]
- cpuCore.setCpuShares(cpuNum * CGroupManager.ONE_CPU_SLOT)
- setCpuUsageUpperLimit(cpuCore, CGroupManager.getWorkerCpuCoreUpperLimit(config))
-
- val sb: StringBuilder = new StringBuilder
- sb.append("cgexec -g cpu:").append(workerGroup.getName).toString().split(" ").toList
- }
-
- def shutDownExecutor(appId: Int, executorId: Int): Unit = {
- val groupName = getGroupName(appId, executorId)
- val workerGroup = new CgroupCommon(groupName, hierarchy, this.rootCgroup)
- center.delete(workerGroup)
- }
-
- def close(): Unit = {
- center.delete(rootCgroup)
- }
-
- private def getGroupName(appId: Int, executorId: Int): String = {
- "app" + appId + "executor" + executorId
- }
-}
-
-object CGroupManager {
- private val LOG: Logger = LoggerFactory.getLogger(getClass)
- private val CGROUP_ROOT = "gearpump.cgroup.root"
- private val Executor_CPU_CORE_UPPER_LIMIT = "gearpump.cgroup.cpu-core-limit-per-executor"
- private val GEARPUMP_HIERARCHY_NAME = "gearpump_cpu"
- private val GEARPUMP_CPU_HIERARCHY_DIR = "/cgroup/cpu"
- private val ONE_CPU_SLOT = 1024
-
- def getCgroupRootDir(config: Config): String = {
- config.getString(CGROUP_ROOT)
- }
-
- def getWorkerCpuCoreUpperLimit(config: Config): Int = {
- config.getInt(Executor_CPU_CORE_UPPER_LIMIT)
- }
-
- def getInstance(config: Config): Option[CGroupManager] = {
- if (SystemUtils.IS_OS_WINDOWS || SystemUtils.IS_OS_MAC_OSX) {
- LOG.error(s"CGroup is not supported on Windows OS, Mac OS X")
- None
- } else {
- Some(new CGroupManager(config))
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/cgroup/src/main/scala/io/gearpump/cluster/worker/CGroupProcessLauncher.scala
----------------------------------------------------------------------
diff --git a/experiments/cgroup/src/main/scala/io/gearpump/cluster/worker/CGroupProcessLauncher.scala b/experiments/cgroup/src/main/scala/io/gearpump/cluster/worker/CGroupProcessLauncher.scala
deleted file mode 100644
index eb57a18..0000000
--- a/experiments/cgroup/src/main/scala/io/gearpump/cluster/worker/CGroupProcessLauncher.scala
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.cluster.worker
-
-import java.io.File
-import scala.sys.process.Process
-
-import com.typesafe.config.Config
-import org.slf4j.{Logger, LoggerFactory}
-
-import io.gearpump.cluster.scheduler.Resource
-import io.gearpump.util.{ProcessLogRedirector, RichProcess}
-
-/**
- * CGroupProcessLauncher is used to launch a process for Executor with CGroup.
- * For more details, please refer http://gearpump.io
- */
-class CGroupProcessLauncher(val config: Config) extends ExecutorProcessLauncher {
- private val APP_MASTER = -1
- private val cgroupManager: Option[CGroupManager] = CGroupManager.getInstance(config)
- private val LOG: Logger = LoggerFactory.getLogger(getClass)
-
- override def cleanProcess(appId: Int, executorId: Int): Unit = {
- if (executorId != APP_MASTER) {
- cgroupManager.foreach(_.shutDownExecutor(appId, executorId))
- }
- }
-
- override def createProcess(
- appId: Int, executorId: Int, resource: Resource, appConfig: Config, options: Array[String],
- classPath: Array[String], mainClass: String, arguments: Array[String]): RichProcess = {
- val cgroupCommand = if (executorId != APP_MASTER) {
- cgroupManager.map(_.startNewExecutor(appConfig, resource.slots, appId,
- executorId)).getOrElse(List.empty)
- } else List.empty
- LOG.info(s"Launch executor with CGroup ${cgroupCommand.mkString(" ")}, " +
- s"classpath: ${classPath.mkString(File.pathSeparator)}")
-
- val java = System.getProperty("java.home") + "/bin/java"
- val command = cgroupCommand ++ List(java) ++ options ++ List("-cp", classPath
- .mkString(File.pathSeparator), mainClass) ++ arguments
- LOG.info(s"Starting executor process java $mainClass ${arguments.mkString(" ")}; " +
- s"options: ${options.mkString(" ")}")
- val logger = new ProcessLogRedirector()
- val process = Process(command).run(logger)
- new RichProcess(process, logger)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/cgroup/src/main/scala/org/apache/gearpump/cluster/worker/CGroupManager.scala
----------------------------------------------------------------------
diff --git a/experiments/cgroup/src/main/scala/org/apache/gearpump/cluster/worker/CGroupManager.scala b/experiments/cgroup/src/main/scala/org/apache/gearpump/cluster/worker/CGroupManager.scala
new file mode 100644
index 0000000..24c169c
--- /dev/null
+++ b/experiments/cgroup/src/main/scala/org/apache/gearpump/cluster/worker/CGroupManager.scala
@@ -0,0 +1,125 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.cluster.worker
+
+import com.typesafe.config.Config
+import org.apache.commons.lang.SystemUtils
+import org.slf4j.{Logger, LoggerFactory}
+
+import org.apache.gearpump.cluster.cgroup.core.{CgroupCore, CpuCore}
+import org.apache.gearpump.cluster.cgroup.{CgroupCenter, CgroupCommon, Hierarchy, ResourceType}
+import org.apache.gearpump.cluster.worker.CGroupManager._
+
+class CGroupManager(config: Config) {
+ private val center = CgroupCenter.getInstance()
+ private val rootDir = CGroupManager.getCgroupRootDir(config)
+ private var hierarchy: Hierarchy = null
+ private var rootCgroup: CgroupCommon = null
+
+ prepareSubSystem()
+
+ private def prepareSubSystem(): Unit = {
+ if (rootDir == null) {
+ throw new RuntimeException(s"Check configuration file. The $CGROUP_ROOT is missing.")
+ }
+ if (center == null) {
+ throw new RuntimeException("Cgroup error, please check /proc/cgroups")
+ }
+ hierarchy = center.busy(ResourceType.cpu)
+ if (hierarchy == null) {
+ val types = new java.util.HashSet[ResourceType]
+ types.add(ResourceType.cpu)
+ hierarchy = new Hierarchy(GEARPUMP_HIERARCHY_NAME, types, GEARPUMP_CPU_HIERARCHY_DIR)
+ }
+ rootCgroup = new CgroupCommon(rootDir, hierarchy, hierarchy.getRootCgroups)
+ }
+
+ private def validateCpuUpperLimitValue(value: Int): Int = {
+ if (value > 10) {
+ 10
+ } else if (value < 1 && value != -1) {
+ 1
+ } else {
+ value
+ }
+ }
+
+ private def setCpuUsageUpperLimit(cpuCore: CpuCore, cpuCoreUpperLimit: Int): Unit = {
+ val _cpuCoreUpperLimit = validateCpuUpperLimitValue(cpuCoreUpperLimit)
+ if (_cpuCoreUpperLimit == -1) {
+ cpuCore.setCpuCfsQuotaUs(_cpuCoreUpperLimit)
+ }
+ else {
+ cpuCore.setCpuCfsPeriodUs(100000)
+ cpuCore.setCpuCfsQuotaUs(_cpuCoreUpperLimit * 100000)
+ }
+ }
+
+ def startNewExecutor(config: Config, cpuNum: Int, appId: Int, executorId: Int): List[String] = {
+ val groupName = getGroupName(appId, executorId)
+ val workerGroup: CgroupCommon = new CgroupCommon(groupName, hierarchy, this.rootCgroup)
+ this.center.create(workerGroup)
+ val cpu: CgroupCore = workerGroup.getCores.get(ResourceType.cpu)
+ val cpuCore: CpuCore = cpu.asInstanceOf[CpuCore]
+ cpuCore.setCpuShares(cpuNum * CGroupManager.ONE_CPU_SLOT)
+ setCpuUsageUpperLimit(cpuCore, CGroupManager.getWorkerCpuCoreUpperLimit(config))
+
+ val sb: StringBuilder = new StringBuilder
+ sb.append("cgexec -g cpu:").append(workerGroup.getName).toString().split(" ").toList
+ }
+
+ def shutDownExecutor(appId: Int, executorId: Int): Unit = {
+ val groupName = getGroupName(appId, executorId)
+ val workerGroup = new CgroupCommon(groupName, hierarchy, this.rootCgroup)
+ center.delete(workerGroup)
+ }
+
+ def close(): Unit = {
+ center.delete(rootCgroup)
+ }
+
+ private def getGroupName(appId: Int, executorId: Int): String = {
+ "app" + appId + "executor" + executorId
+ }
+}
+
+object CGroupManager {
+ private val LOG: Logger = LoggerFactory.getLogger(getClass)
+ private val CGROUP_ROOT = "gearpump.cgroup.root"
+ private val Executor_CPU_CORE_UPPER_LIMIT = "gearpump.cgroup.cpu-core-limit-per-executor"
+ private val GEARPUMP_HIERARCHY_NAME = "gearpump_cpu"
+ private val GEARPUMP_CPU_HIERARCHY_DIR = "/cgroup/cpu"
+ private val ONE_CPU_SLOT = 1024
+
+ def getCgroupRootDir(config: Config): String = {
+ config.getString(CGROUP_ROOT)
+ }
+
+ def getWorkerCpuCoreUpperLimit(config: Config): Int = {
+ config.getInt(Executor_CPU_CORE_UPPER_LIMIT)
+ }
+
+ def getInstance(config: Config): Option[CGroupManager] = {
+ if (SystemUtils.IS_OS_WINDOWS || SystemUtils.IS_OS_MAC_OSX) {
+ LOG.error(s"CGroup is not supported on Windows OS, Mac OS X")
+ None
+ } else {
+ Some(new CGroupManager(config))
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/cgroup/src/main/scala/org/apache/gearpump/cluster/worker/CGroupProcessLauncher.scala
----------------------------------------------------------------------
diff --git a/experiments/cgroup/src/main/scala/org/apache/gearpump/cluster/worker/CGroupProcessLauncher.scala b/experiments/cgroup/src/main/scala/org/apache/gearpump/cluster/worker/CGroupProcessLauncher.scala
new file mode 100644
index 0000000..dc2eabd
--- /dev/null
+++ b/experiments/cgroup/src/main/scala/org/apache/gearpump/cluster/worker/CGroupProcessLauncher.scala
@@ -0,0 +1,63 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.cluster.worker
+
+import java.io.File
+import scala.sys.process.Process
+
+import com.typesafe.config.Config
+import org.slf4j.{Logger, LoggerFactory}
+
+import org.apache.gearpump.cluster.scheduler.Resource
+import org.apache.gearpump.util.{ProcessLogRedirector, RichProcess}
+
+/**
+ * CGroupProcessLauncher is used to launch a process for Executor with CGroup.
+ * For more details, please refer http://gearpump.io
+ */
+class CGroupProcessLauncher(val config: Config) extends ExecutorProcessLauncher {
+ private val APP_MASTER = -1
+ private val cgroupManager: Option[CGroupManager] = CGroupManager.getInstance(config)
+ private val LOG: Logger = LoggerFactory.getLogger(getClass)
+
+ override def cleanProcess(appId: Int, executorId: Int): Unit = {
+ if (executorId != APP_MASTER) {
+ cgroupManager.foreach(_.shutDownExecutor(appId, executorId))
+ }
+ }
+
+ override def createProcess(
+ appId: Int, executorId: Int, resource: Resource, appConfig: Config, options: Array[String],
+ classPath: Array[String], mainClass: String, arguments: Array[String]): RichProcess = {
+ val cgroupCommand = if (executorId != APP_MASTER) {
+ cgroupManager.map(_.startNewExecutor(appConfig, resource.slots, appId,
+ executorId)).getOrElse(List.empty)
+ } else List.empty
+ LOG.info(s"Launch executor with CGroup ${cgroupCommand.mkString(" ")}, " +
+ s"classpath: ${classPath.mkString(File.pathSeparator)}")
+
+ val java = System.getProperty("java.home") + "/bin/java"
+ val command = cgroupCommand ++ List(java) ++ options ++ List("-cp", classPath
+ .mkString(File.pathSeparator), mainClass) ++ arguments
+ LOG.info(s"Starting executor process java $mainClass ${arguments.mkString(" ")}; " +
+ s"options: ${options.mkString(" ")}")
+ val logger = new ProcessLogRedirector()
+ val process = Process(command).run(logger)
+ new RichProcess(process, logger)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/java/io/gearpump/experiments/storm/util/TimeCacheMapWrapper.java
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/java/io/gearpump/experiments/storm/util/TimeCacheMapWrapper.java b/experiments/storm/src/main/java/io/gearpump/experiments/storm/util/TimeCacheMapWrapper.java
deleted file mode 100644
index 510258d..0000000
--- a/experiments/storm/src/main/java/io/gearpump/experiments/storm/util/TimeCacheMapWrapper.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.storm.util;
-
-import backtype.storm.utils.TimeCacheMap;
-
-/**
- * Wrapper class to suppress "deprecation" warning, as scala doesn't support the suppression.
- */
-@SuppressWarnings("deprecation")
-public class TimeCacheMapWrapper<K, V> extends TimeCacheMap<K, V> {
-
- public TimeCacheMapWrapper (int expirationSecs, Callback<K, V> callback) {
- super(expirationSecs, new ExpiredCallback<K, V>() {
-
- @Override
- public void expire(K key, V val) {
- callback.expire(key, val);
- }
- });
- }
-
- public static interface Callback<K, V> {
- public void expire(K key, V val);
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/java/org/apache/gearpump/experiments/storm/util/TimeCacheMapWrapper.java
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/java/org/apache/gearpump/experiments/storm/util/TimeCacheMapWrapper.java b/experiments/storm/src/main/java/org/apache/gearpump/experiments/storm/util/TimeCacheMapWrapper.java
new file mode 100644
index 0000000..923883c
--- /dev/null
+++ b/experiments/storm/src/main/java/org/apache/gearpump/experiments/storm/util/TimeCacheMapWrapper.java
@@ -0,0 +1,42 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.storm.util;
+
+import backtype.storm.utils.TimeCacheMap;
+
+/**
+ * Wrapper class to suppress "deprecation" warning, as scala doesn't support the suppression.
+ */
+@SuppressWarnings("deprecation")
+public class TimeCacheMapWrapper<K, V> extends TimeCacheMap<K, V> {
+
+ public TimeCacheMapWrapper (int expirationSecs, Callback<K, V> callback) {
+ super(expirationSecs, new ExpiredCallback<K, V>() {
+
+ @Override
+ public void expire(K key, V val) {
+ callback.expire(key, val);
+ }
+ });
+ }
+
+ public static interface Callback<K, V> {
+ public void expire(K key, V val);
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/resources/geardefault.conf
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/resources/geardefault.conf b/experiments/storm/src/main/resources/geardefault.conf
index 54c478e..38ac9d3 100644
--- a/experiments/storm/src/main/resources/geardefault.conf
+++ b/experiments/storm/src/main/resources/geardefault.conf
@@ -1,5 +1,5 @@
gearpump {
storm {
- serialization-framework = "io.gearpump.experiments.storm.util.StormSerializationFramework"
+ serialization-framework = "org.apache.gearpump.experiments.storm.util.StormSerializationFramework"
}
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/scala/io/gearpump/experiments/storm/StormRunner.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/scala/io/gearpump/experiments/storm/StormRunner.scala b/experiments/storm/src/main/scala/io/gearpump/experiments/storm/StormRunner.scala
deleted file mode 100644
index 19814e9..0000000
--- a/experiments/storm/src/main/scala/io/gearpump/experiments/storm/StormRunner.scala
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.storm
-
-import org.slf4j.Logger
-
-import io.gearpump.experiments.storm.main.{GearpumpNimbus, GearpumpStormClient}
-import io.gearpump.util.LogUtil
-
-object StormRunner {
- private val LOG: Logger = LogUtil.getLogger(getClass)
-
- private val commands = Map("nimbus" -> GearpumpNimbus, "app" -> GearpumpStormClient)
-
- private def usage(): Unit = {
- val keys = commands.keys.toList.sorted
- // scalastyle:off println
- Console.err.println("Usage: " + "<" + keys.mkString("|") + ">")
- // scalastyle:on println
- }
-
- private def executeCommand(command: String, commandArgs: Array[String]): Unit = {
- if (!commands.contains(command)) {
- usage()
- } else {
- commands(command).main(commandArgs)
- }
- }
-
- def main(args: Array[String]): Unit = {
- if (args.length == 0) {
- usage()
- } else {
- val command = args(0)
- val commandArgs = args.drop(1)
- executeCommand(command, commandArgs)
- }
- }
-}
[22/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/client/ManageCluster.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/client/ManageCluster.scala b/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/client/ManageCluster.scala
deleted file mode 100644
index 3e50abe..0000000
--- a/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/client/ManageCluster.scala
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.yarn.client
-
-import java.io.{File, IOException}
-import java.net.InetAddress
-import scala.concurrent.{Await, Future}
-
-import akka.actor.{ActorRef, ActorSystem}
-
-import io.gearpump.cluster.ClientToMaster.{AddWorker, CommandResult, RemoveWorker}
-import io.gearpump.cluster.ClusterConfig
-import io.gearpump.cluster.main.{ArgumentsParser, CLIOption, ParseResult}
-import io.gearpump.experiments.yarn.appmaster.YarnAppMaster.{ActiveConfig, ClusterInfo, GetActiveConfig, Kill, QueryClusterInfo, QueryVersion, Version}
-import io.gearpump.experiments.yarn.glue.Records.ApplicationId
-import io.gearpump.experiments.yarn.glue.{YarnClient, YarnConfig}
-import io.gearpump.util.ActorUtil.askActor
-import io.gearpump.util.{AkkaApp, LogUtil}
-
-/** Manage current Gearpump cluster on YARN */
-class ManageCluster(appId: ApplicationId, appMaster: ActorRef, system: ActorSystem) {
- import io.gearpump.experiments.yarn.client.ManageCluster._
-
- private val host = InetAddress.getLocalHost.getHostName
- implicit val dispatcher = system.dispatcher
-
- def getConfig: Future[ActiveConfig] = askActor[ActiveConfig](appMaster, GetActiveConfig(host))
- def version: Future[Version] = askActor[Version](appMaster, QueryVersion)
- def addWorker(count: Int): Future[CommandResult] = {
- askActor[CommandResult](appMaster, AddWorker(count))
- }
-
- def removeWorker(worker: String): Future[CommandResult] = {
- askActor[CommandResult](appMaster, RemoveWorker(worker))
- }
-
- def shutdown: Future[CommandResult] = askActor[CommandResult](appMaster, Kill)
- def queryClusterInfo: Future[ClusterInfo] = askActor[ClusterInfo](appMaster, QueryClusterInfo)
-
- def command(command: String, parsed: ParseResult): Future[AnyRef] = {
- command match {
- case GET_CONFIG =>
- if (parsed.exists(OUTPUT)) {
- getConfig.map { conf =>
- ClusterConfig.saveConfig(conf.config, new File(parsed.getString(OUTPUT)))
- conf
- }
- } else {
- throw new IOException(s"Please specify -$OUTPUT option")
- }
- case ADD_WORKER =>
- val count = parsed.getString(COUNT).toInt
- addWorker(count)
- case REMOVE_WORKER =>
- val containerId = parsed.getString(CONTAINER)
- if (containerId == null || containerId.isEmpty) {
- throw new IOException(s"Please specify -$CONTAINER option")
- } else {
- removeWorker(containerId)
- }
- case KILL =>
- shutdown
- case QUERY =>
- queryClusterInfo
- case VERSION =>
- version
- }
- }
-}
-
-object ManageCluster extends AkkaApp with ArgumentsParser {
- val GET_CONFIG = "getconfig"
- val ADD_WORKER = "addworker"
- val REMOVE_WORKER = "removeworker"
- val KILL = "kill"
- val VERSION = "version"
- val QUERY = "query"
- val COMMAND = "command"
- val CONTAINER = "container"
- val OUTPUT = "output"
- val COUNT = "count"
- val APPID = "appid"
- val VERBOSE = "verbose"
-
- val commands = List(GET_CONFIG, ADD_WORKER, REMOVE_WORKER, KILL, VERSION, QUERY)
-
- import scala.concurrent.duration._
- val TIME_OUT_SECONDS = 30.seconds
-
- override val options: Array[(String, CLIOption[Any])] = Array(
- COMMAND -> CLIOption[String](s"<${commands.mkString("|")}>", required = true),
- APPID -> CLIOption[String]("<Application id, format: application_timestamp_id>",
- required = true),
- COUNT -> CLIOption("<how many instance to add or remove>", required = false,
- defaultValue = Some(1)),
- VERBOSE -> CLIOption("<print verbose log on console>", required = false,
- defaultValue = Some(false)),
- OUTPUT -> CLIOption("<output path for configuration file>", required = false,
- defaultValue = Some("")),
- CONTAINER -> CLIOption("<container id for master or worker>", required = false,
- defaultValue = Some(""))
- )
-
- override def main(akkaConf: Config, args: Array[String]): Unit = {
-
- val yarnConfig = new YarnConfig()
- val yarnClient = new YarnClient(yarnConfig)
-
- val parsed = parse(args)
-
- if (parsed.getBoolean(VERBOSE)) {
- LogUtil.verboseLogToConsole()
- }
-
- val appId = parseAppId(parsed.getString(APPID))
- val system = ActorSystem("manageCluster", akkaConf)
-
- val appMasterResolver = new AppMasterResolver(yarnClient, system)
- val appMaster = appMasterResolver.resolve(appId)
-
- implicit val dispatcher = system.dispatcher
- val manager = new ManageCluster(appId, appMaster, system)
-
- val command = parsed.getString(COMMAND)
- val result = manager.command(command, parsed)
-
- // scalastyle:off println
- Console.println(Await.result(result, TIME_OUT_SECONDS))
- // scalastyle:on println
- system.terminate()
- Await.result(system.whenTerminated, Duration.Inf)
- }
-
- def parseAppId(str: String): ApplicationId = {
- val parts = str.split("_")
- val timestamp = parts(1).toLong
- val id = parts(2).toInt
- ApplicationId.newInstance(timestamp, id)
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/glue/ContainerLaunchContext.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/glue/ContainerLaunchContext.scala b/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/glue/ContainerLaunchContext.scala
deleted file mode 100644
index 6b3385f..0000000
--- a/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/glue/ContainerLaunchContext.scala
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.yarn.glue
-
-import java.io.File
-import java.nio.ByteBuffer
-import scala.collection.JavaConverters._
-
-import org.apache.hadoop.fs.{FileSystem => YarnFileSystem, Path}
-import org.apache.hadoop.io.DataOutputBuffer
-import org.apache.hadoop.mapreduce.security.TokenCache
-import org.apache.hadoop.security.UserGroupInformation
-import org.apache.hadoop.yarn.api.ApplicationConstants.Environment
-import org.apache.hadoop.yarn.api.records._
-import org.apache.hadoop.yarn.conf.YarnConfiguration
-import org.apache.hadoop.yarn.util.ConverterUtils
-import org.slf4j.Logger
-
-import io.gearpump.util.LogUtil
-
-private[glue]
-object ContainerLaunchContext {
- private val LOG: Logger = LogUtil.getLogger(getClass)
-
- def apply(yarnConf: YarnConfiguration, command: String, packagePath: String, configPath: String)
- : ContainerLaunchContext = {
- val context = Records.newRecord(classOf[ContainerLaunchContext])
- context.setCommands(Seq(command).asJava)
- context.setEnvironment(getAppEnv(yarnConf).asJava)
- context.setTokens(getToken(yarnConf, packagePath, configPath))
- context.setLocalResources(getAMLocalResourcesMap(yarnConf, packagePath, configPath).asJava)
- context
- }
-
- private def getFs(yarnConf: YarnConfiguration) = YarnFileSystem.get(yarnConf)
-
- private def getAppEnv(yarnConf: YarnConfiguration): Map[String, String] = {
- val classPaths = yarnConf.getStrings(
- YarnConfiguration.YARN_APPLICATION_CLASSPATH,
- YarnConfiguration.DEFAULT_YARN_APPLICATION_CLASSPATH.mkString(File.pathSeparator))
- val allPaths = Option(classPaths).getOrElse(Array(""))
-
- allPaths :+ Environment.PWD.$() + File.separator + "*" + File.pathSeparator
-
- Map(Environment.CLASSPATH.name -> allPaths.map(_.trim).mkString(File.pathSeparator))
- }
-
- private def getAMLocalResourcesMap(
- yarnConf: YarnConfiguration, packagePath: String, configPath: String)
- : Map[String, LocalResource] = {
- val fs = getFs(yarnConf)
-
- Map(
- "pack" -> newYarnAppResource(fs, new Path(packagePath),
- LocalResourceType.ARCHIVE, LocalResourceVisibility.APPLICATION),
- "conf" -> newYarnAppResource(fs, new Path(configPath),
- LocalResourceType.FILE, LocalResourceVisibility.APPLICATION))
- }
-
- private def newYarnAppResource(
- fs: YarnFileSystem, path: Path,
- resourceType: LocalResourceType, vis: LocalResourceVisibility): LocalResource = {
- val qualified = fs.makeQualified(path)
- val status = fs.getFileStatus(qualified)
- val resource = Records.newRecord(classOf[LocalResource])
- resource.setType(resourceType)
- resource.setVisibility(vis)
- resource.setResource(ConverterUtils.getYarnUrlFromPath(qualified))
- resource.setTimestamp(status.getModificationTime)
- resource.setSize(status.getLen)
- resource
- }
-
- private def getToken(yc: YarnConfiguration, packagePath: String, configPath: String)
- : ByteBuffer = {
- val credentials = UserGroupInformation.getCurrentUser.getCredentials
- val dob = new DataOutputBuffer
- val dirs = Array(new Path(packagePath), new Path(configPath))
- TokenCache.obtainTokensForNamenodes(credentials, dirs, yc)
- credentials.writeTokenStorageToStream(dob)
- ByteBuffer.wrap(dob.getData)
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/glue/FileSystem.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/glue/FileSystem.scala b/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/glue/FileSystem.scala
deleted file mode 100644
index acf09ac..0000000
--- a/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/glue/FileSystem.scala
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.yarn.glue
-
-import java.io.{InputStream, OutputStream}
-import java.net.ConnectException
-import scala.util.{Failure, Success, Try}
-
-import org.apache.hadoop.fs.Path
-
-import io.gearpump.util.LogUtil
-
-class FileSystem(yarnConfig: YarnConfig) {
-
- private val conf = yarnConfig.conf
- private val fs = org.apache.hadoop.fs.FileSystem.get(conf)
-
- private def LOG = LogUtil.getLogger(getClass)
-
- def open(file: String): InputStream = exceptionHandler {
- val path = new Path(file)
- fs.open(path)
- }
-
- def create(file: String): OutputStream = exceptionHandler {
- val path = new Path(file)
- fs.create(path)
- }
-
- def exists(file: String): Boolean = exceptionHandler {
- val path = new Path(file)
- fs.exists(path)
- }
-
- def name: String = {
- fs.getUri.toString
- }
-
- def getHomeDirectory: String = {
- fs.getHomeDirectory.toString
- }
-
- private def exceptionHandler[T](call: => T): T = {
- val callTry = Try(call)
- callTry match {
- case Success(v) => v
- case Failure(ex) =>
- if (ex.isInstanceOf[ConnectException]) {
- LOG.error("Please check whether we connect to the right HDFS file system, " +
- "current file system is $name." + "\n. Please copy all configs under " +
- "$HADOOP_HOME/etc/hadoop into conf/yarnconf directory of Gearpump package, " +
- "so that we can use the right File system.", ex)
- }
- throw ex
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/glue/NMClient.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/glue/NMClient.scala b/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/glue/NMClient.scala
deleted file mode 100644
index 3e7e668..0000000
--- a/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/glue/NMClient.scala
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.yarn.glue
-
-import java.nio.ByteBuffer
-
-import akka.actor.ActorRef
-import com.typesafe.config.Config
-import org.apache.hadoop.yarn.api.records.{ApplicationId => YarnApplicationId, ApplicationReport => YarnApplicationReport, Container => YarnContainer, ContainerId => YarnContainerId, ContainerStatus => YarnContainerStatus, NodeId => YarnNodeId, Resource => YarnResource}
-import org.apache.hadoop.yarn.client.api.async.NMClientAsync
-import org.apache.hadoop.yarn.client.api.async.impl.NMClientAsyncImpl
-
-import io.gearpump.experiments.yarn.appmaster.YarnAppMaster.ContainerStarted
-import io.gearpump.experiments.yarn.glue.Records._
-import io.gearpump.util.LogUtil
-/**
- * Adapter for node manager client
- */
-class NMClient(yarnConf: YarnConfig, config: Config) extends NMClientAsync.CallbackHandler {
-
- private val LOG = LogUtil.getLogger(getClass)
-
- private var reportTo: ActorRef = null
- private var client: NMClientAsyncImpl = null
-
- def start(reportTo: ActorRef): Unit = {
- LOG.info("Starting Node Manager Client NMClient...")
- this.reportTo = reportTo
- client = new NMClientAsyncImpl(this)
- client.init(yarnConf.conf)
- client.start()
- }
-
- private[glue]
- override def onContainerStarted(
- containerId: YarnContainerId, allServiceResponse: java.util.Map[String, ByteBuffer]) {
- LOG.info(s"Container started : $containerId, " + allServiceResponse)
- reportTo ! ContainerStarted(containerId)
- }
-
- private[glue]
- override def onContainerStatusReceived(
- containerId: YarnContainerId, containerStatus: YarnContainerStatus) {
- LOG.info(s"Container status received : $containerId, status $containerStatus")
- }
-
- private[glue]
- override def onContainerStopped(containerId: YarnContainerId) {
- LOG.error(s"Container stopped : $containerId")
- }
-
- private[glue]
- override def onGetContainerStatusError(containerId: YarnContainerId, throwable: Throwable) {
- LOG.error(s"Container exception : $containerId", throwable)
- }
-
- private[glue]
- override def onStartContainerError(containerId: YarnContainerId, throwable: Throwable) {
- LOG.error(s"Container exception : $containerId", throwable)
- }
-
- private[glue]
- override def onStopContainerError(containerId: YarnContainerId, throwable: Throwable) {
- LOG.error(s"Container exception : $containerId", throwable)
- }
-
- def launchCommand(
- container: Container, command: String, packagePath: String, configPath: String): Unit = {
- LOG.info(s"Launching command : $command on container" +
- s": ${container.getId}, host ip : ${container.getNodeId.getHost}")
- val context = ContainerLaunchContext(yarnConf.conf, command, packagePath, configPath)
- client.startContainerAsync(container, context)
- }
-
- def stopContainer(containerId: ContainerId, nodeId: NodeId): Unit = {
- LOG.info(s"Stop container ${containerId.toString} on node: ${nodeId.toString} ")
- client.stopContainerAsync(containerId, nodeId)
- }
-
- def stop(): Unit = {
- LOG.info(s"Shutdown NMClient")
- client.stop()
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/glue/RMClient.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/glue/RMClient.scala b/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/glue/RMClient.scala
deleted file mode 100644
index 7b9d83c..0000000
--- a/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/glue/RMClient.scala
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.yarn.glue
-
-import scala.collection.JavaConverters._
-
-import akka.actor.ActorRef
-import org.apache.hadoop.yarn.api.records.{ApplicationId => YarnApplicationId, ApplicationReport => YarnApplicationReport, Container => YarnContainer, ContainerId => YarnContainerId, ContainerStatus => YarnContainerStatus, FinalApplicationStatus, NodeId => YarnNodeId, NodeReport, Priority, Resource => YarnResource}
-import org.apache.hadoop.yarn.client.api.AMRMClient.ContainerRequest
-import org.apache.hadoop.yarn.client.api.async.AMRMClientAsync
-import org.slf4j.Logger
-
-import io.gearpump.experiments.yarn.appmaster.YarnAppMaster.{AppMasterRegistered, ContainersAllocated, ContainersCompleted, ResourceManagerException, ShutdownApplication}
-import io.gearpump.experiments.yarn.glue.Records._
-import io.gearpump.util.LogUtil
-
-/**
- * Adapter for resource manager client
- */
-class RMClient(yarnConf: YarnConfig) extends AMRMClientAsync.CallbackHandler {
-
- private val LOG: Logger = LogUtil.getLogger(getClass)
-
- private var reportTo: ActorRef = null
- private var client: AMRMClientAsync[ContainerRequest] = null
-
- def start(reportTo: ActorRef): Unit = {
- LOG.info("Starting Resource Manager Client RMClient...")
- this.reportTo = reportTo
- client = startAMRMClient
- }
-
- private def startAMRMClient: AMRMClientAsync[ContainerRequest] = {
- val timeIntervalMs = 1000 // ms
- val amrmClient = AMRMClientAsync.createAMRMClientAsync[ContainerRequest](timeIntervalMs, this)
- amrmClient.init(yarnConf.conf)
- amrmClient.start()
- amrmClient
- }
-
- override def getProgress: Float = 0.5F
-
- private var allocatedContainers = Set.empty[YarnContainerId]
-
- private[glue]
- override def onContainersAllocated(containers: java.util.List[YarnContainer]) {
- val newContainers = containers.asScala.toList.filterNot(container =>
- allocatedContainers.contains(container.getId))
- allocatedContainers ++= newContainers.map(_.getId)
- LOG.info(s"New allocated ${newContainers.size} containers")
- reportTo ! ContainersAllocated(newContainers.map(yarnContainerToContainer(_)))
- }
-
- private[glue]
- override def onContainersCompleted(completedContainers: java.util.List[YarnContainerStatus])
- : Unit = {
- LOG.info(s"Got response from RM. Completed containers=${completedContainers.size()}")
- reportTo ! ContainersCompleted(
- completedContainers.asScala.toList.map(yarnContainerStatusToContainerStatus(_)))
- }
-
- private[glue]
- override def onError(ex: Throwable) {
- LOG.info("Error occurred")
- reportTo ! ResourceManagerException(ex)
- }
-
- private[glue]
- override def onNodesUpdated(updatedNodes: java.util.List[NodeReport]): Unit = {
- LOG.info("onNodesUpdates")
- }
-
- private[glue]
- override def onShutdownRequest() {
- LOG.info("Shutdown requested")
- reportTo ! ShutdownApplication
- }
-
- def requestContainers(containers: List[Resource]): Unit = {
- LOG.info(s"request Resource, slots: ${containers.length}, ${containers.mkString("\n")}")
- containers.foreach(resource => {
- client.addContainerRequest(createContainerRequest(resource))
- })
- }
-
- private def createContainerRequest(capability: Resource): ContainerRequest = {
- LOG.info("creating ContainerRequest")
- val priorityRecord = org.apache.hadoop.yarn.util.Records.newRecord(classOf[Priority])
- priorityRecord.setPriority(0)
- val priority = Priority.newInstance(0)
- new ContainerRequest(capability, null, null, priority)
- }
-
- def registerAppMaster(host: String, port: Int, url: String): Unit = {
- LOG.info(s"Received RegisterAMMessage! $host:$port $url")
- val response = client.registerApplicationMaster(host, port, url)
- LOG.info("Received RegisterAppMasterResponse ")
- reportTo ! AppMasterRegistered
- }
-
- def shutdownApplication(): Unit = {
- LOG.info(s"Shutdown application")
- client.unregisterApplicationMaster(FinalApplicationStatus.SUCCEEDED, "success", null)
- client.stop()
- }
-
- def failApplication(ex: Throwable): Unit = {
- LOG.error(s"Application failed! ", ex)
- client.unregisterApplicationMaster(FinalApplicationStatus.SUCCEEDED, ex.getMessage, null)
- client.stop()
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/glue/Records.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/glue/Records.scala b/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/glue/Records.scala
deleted file mode 100644
index 7b863fa..0000000
--- a/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/glue/Records.scala
+++ /dev/null
@@ -1,219 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.yarn.glue
-
-import scala.language.implicitConversions
-
-import org.apache.hadoop.yarn.api.records.{ApplicationId => YarnApplicationId, ApplicationReport => YarnApplicationReport, ApplicationSubmissionContext, Container => YarnContainer, ContainerId => YarnContainerId, ContainerStatus => YarnContainerStatus, NodeId => YarnNodeId, Resource => YarnResource, YarnApplicationState}
-import org.apache.hadoop.yarn.util.{Records => YarnRecords}
-
-object Records {
- def newRecord[T](clazz: Class[T]): T = YarnRecords.newRecord(clazz)
-
- def newAppSubmissionContext: ApplicationSubmissionContext = {
- YarnRecords.newRecord(classOf[ApplicationSubmissionContext])
- }
-
- class ApplicationId(private[glue] val impl: YarnApplicationId) {
- def getId: Int = impl.getId
-
- override def toString: String = impl.toString
-
- override def equals(other: Any): Boolean = {
- if (other.isInstanceOf[ApplicationId]) {
- impl.equals(other.asInstanceOf[ApplicationId].impl)
- } else {
- false
- }
- }
-
- override def hashCode(): Int = {
- impl.hashCode()
- }
- }
-
- object ApplicationId {
- def newInstance(timestamp: Long, id: Int): ApplicationId = {
- YarnApplicationId.newInstance(timestamp, id)
- }
- }
-
- class ApplicationReport(private[glue] val impl: YarnApplicationReport) {
- def getApplicationId: ApplicationId = impl.getApplicationId
-
- def getDiagnostics: String = impl.getDiagnostics
-
- def getFinishTime: Long = impl.getFinishTime
-
- def getOriginalTrackingUrl: String = impl.getOriginalTrackingUrl
-
- def getYarnApplicationState: YarnApplicationState = impl.getYarnApplicationState
-
- override def toString: String = impl.toString
- }
- class Resource(private[glue] val impl: YarnResource) {
- override def toString: String = impl.toString
-
- override def equals(other: Any): Boolean = {
- if (other.isInstanceOf[Resource]) {
- impl.equals(other.asInstanceOf[Resource].impl)
- } else {
- false
- }
- }
-
- override def hashCode(): Int = {
- impl.hashCode()
- }
- }
-
- object Resource {
- def newInstance(memory: Int, vCores: Int): Resource = {
- YarnResource.newInstance(memory, vCores)
- }
- }
-
- class Container(private[glue] val impl: YarnContainer) {
- def getId: ContainerId = impl.getId
-
- def getNodeHttpAddress: String = impl.getNodeHttpAddress
-
- def getNodeId: NodeId = impl.getNodeId
-
- override def toString: String = impl.toString
-
- override def equals(other: Any): Boolean = {
- if (other.isInstanceOf[Container]) {
- impl.equals(other.asInstanceOf[Container].impl)
- } else {
- false
- }
- }
-
- override def hashCode(): Int = {
- impl.hashCode()
- }
- }
-
- class ContainerId(private[glue] val impl: YarnContainerId) {
- override def toString: String = impl.toString
-
- override def equals(other: Any): Boolean = {
- if (other.isInstanceOf[ContainerId]) {
- impl.equals(other.asInstanceOf[ContainerId].impl)
- } else {
- false
- }
- }
-
- override def hashCode(): Int = {
- impl.hashCode()
- }
- }
-
- object ContainerId {
- def fromString(worker: String): ContainerId = YarnContainerId.fromString(worker)
- }
-
- class NodeId(private[glue] val impl: YarnNodeId) {
- def getHost: String = impl.getHost
-
- override def toString: String = impl.toString
-
- override def equals(other: Any): Boolean = {
- if (other.isInstanceOf[NodeId]) {
- impl.equals(other.asInstanceOf[NodeId].impl)
- } else {
- false
- }
- }
-
- override def hashCode(): Int = {
- impl.hashCode()
- }
- }
-
- class ContainerStatus(private[glue] val impl: YarnContainerStatus) {
- def getDiagnostics: String = impl.getDiagnostics
-
- def getContainerId: ContainerId = impl.getContainerId
-
- def getExitStatus: Int = impl.getExitStatus
-
- override def toString: String = impl.toString
- }
-
- private[glue] implicit def yarnResourceToResource(res: YarnResource): Resource = {
- new Resource(res)
- }
-
- private[glue] implicit def resourceToYarnResource(res: Resource): YarnResource = {
- res.impl
- }
-
- private[glue] implicit def yarnAppIdToAppId(yarn: YarnApplicationId): ApplicationId = {
- new ApplicationId(yarn)
- }
-
- private[glue] implicit def appIdToYarnAppId(app: ApplicationId): YarnApplicationId = {
- app.impl
- }
-
- private[glue] implicit def yarnReportToReport(yarn: YarnApplicationReport): ApplicationReport = {
- new ApplicationReport(yarn)
- }
-
- private[glue] implicit def reportToYarnReport(app: ApplicationReport): YarnApplicationReport = {
- app.impl
- }
-
- private[glue] implicit def yarnContainerToContainer(yarn: YarnContainer): Container = {
- new Container(yarn)
- }
-
- private[glue] implicit def containerToYarnContainer(app: Container): YarnContainer = {
- app.impl
- }
-
- private[glue] implicit def yarnContainerStatusToContainerStatus(yarn: YarnContainerStatus)
- : ContainerStatus = {
- new ContainerStatus(yarn)
- }
-
- private[glue] implicit def containerStatusToYarnContainerStatus(app: ContainerStatus)
- : YarnContainerStatus = {
- app.impl
- }
-
- private[glue] implicit def containerIdToYarnContainerId(app: ContainerId): YarnContainerId = {
- app.impl
- }
-
- private[glue] implicit def yarnContainerIdToContainerId(yarn: YarnContainerId): ContainerId = {
- new ContainerId(yarn)
- }
-
- private[glue] implicit def nodeIdToYarnNodeId(app: NodeId): YarnNodeId = {
- app.impl
- }
-
- private[glue] implicit def yarnNodeIdToNodeId(yarn: YarnNodeId): NodeId = {
- new NodeId(yarn)
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/glue/YarnClient.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/glue/YarnClient.scala b/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/glue/YarnClient.scala
deleted file mode 100644
index db7d5d7..0000000
--- a/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/glue/YarnClient.scala
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.yarn.glue
-
-import org.apache.hadoop.yarn.api.records.YarnApplicationState
-import org.apache.hadoop.yarn.client.api
-
-import io.gearpump.experiments.yarn.glue.Records._
-import io.gearpump.util.LogUtil
-
-/**
- * Adapter for api.YarnClient
- */
-class YarnClient(yarn: YarnConfig) {
-
- val LOG = LogUtil.getLogger(getClass)
-
- private val client: api.YarnClient = api.YarnClient.createYarnClient
- client.init(yarn.conf)
- client.start()
- LOG.info("Starting YarnClient...")
-
- def createApplication: ApplicationId = {
- val app = client.createApplication()
- val response = app.getNewApplicationResponse()
- LOG.info("Create application, appId: " + response.getApplicationId())
- response.getApplicationId()
- }
-
- def getApplicationReport(appId: ApplicationId): ApplicationReport = {
- client.getApplicationReport(appId)
- }
-
- def submit(
- name: String, appId: ApplicationId, command: String, resource: Resource, queue: String,
- packagePath: String, configPath: String): ApplicationId = {
-
- val appContext = Records.newAppSubmissionContext
- appContext.setApplicationName(name)
- appContext.setApplicationId(appId)
-
- val containerContext = ContainerLaunchContext(yarn.conf, command, packagePath, configPath)
- appContext.setAMContainerSpec(containerContext)
- appContext.setResource(resource)
- appContext.setQueue(queue)
-
- LOG.info(s"Submit Application $appId to YARN...")
- client.submitApplication(appContext)
- }
-
- def awaitApplication(appId: ApplicationId, timeoutMilliseconds: Long = Long.MaxValue)
- : ApplicationReport = {
- import org.apache.hadoop.yarn.api.records.YarnApplicationState._
- val terminated = Set(FINISHED, KILLED, FAILED, RUNNING)
- var result: ApplicationReport = null
- var done = false
-
- val start = System.currentTimeMillis()
- def timeout: Boolean = {
- val now = System.currentTimeMillis()
- if (now - start > timeoutMilliseconds) {
- true
- } else {
- false
- }
- }
-
- while (!done && !timeout) {
- val report = client.getApplicationReport(appId)
- val status = report.getYarnApplicationState
- if (terminated.contains(status)) {
- done = true
- result = report
- } else {
- Console.print(".")
- Thread.sleep(1000)
- }
- }
-
- if (timeout) {
- throw new Exception(s"Launch Application $appId timeout...")
- }
- result
- }
-
- def stop(): Unit = {
- client.stop()
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/glue/YarnConfig.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/glue/YarnConfig.scala b/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/glue/YarnConfig.scala
deleted file mode 100644
index 87f199a..0000000
--- a/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/glue/YarnConfig.scala
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.yarn.glue
-
-import org.apache.hadoop.conf.Configuration
-import org.apache.hadoop.yarn.conf.YarnConfiguration
-
-/**
- * wrapper for yarn configuration
- */
-case class YarnConfig(conf: YarnConfiguration = new YarnConfiguration(new Configuration(true))) {
- def writeXml(out: java.io.Writer): Unit = conf.writeXml(out)
-
- def resourceManager: String = {
- conf.get("yarn.resourcemanager.hostname")
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/glue/package.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/glue/package.scala b/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/glue/package.scala
deleted file mode 100644
index 24adbaa..0000000
--- a/experiments/yarn/src/main/scala/io/gearpump/experiments/yarn/glue/package.scala
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.yarn
-
-
-/**
- * YARN facade to decouple Gearpump with YARN.
- */
-package object glue {
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/Constants.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/Constants.scala b/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/Constants.scala
new file mode 100644
index 0000000..33c3e97
--- /dev/null
+++ b/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/Constants.scala
@@ -0,0 +1,46 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.yarn
+
+object Constants {
+ val APPMASTER_NAME = "gearpump.yarn.applicationmaster.name"
+ val APPMASTER_COMMAND = "gearpump.yarn.applicationmaster.command"
+ val APPMASTER_MEMORY = "gearpump.yarn.applicationmaster.memory"
+ val APPMASTER_VCORES = "gearpump.yarn.applicationmaster.vcores"
+ val APPMASTER_QUEUE = "gearpump.yarn.applicationmaster.queue"
+
+ val PACKAGE_PATH = "gearpump.yarn.client.package-path"
+ val CONFIG_PATH = "gearpump.yarn.client.config-path"
+
+ val MASTER_COMMAND = "gearpump.yarn.master.command"
+ val MASTER_MEMORY = "gearpump.yarn.master.memory"
+ val MASTER_VCORES = "gearpump.yarn.master.vcores"
+
+ val WORKER_COMMAND = "gearpump.yarn.worker.command"
+ val WORKER_CONTAINERS = "gearpump.yarn.worker.containers"
+ val WORKER_MEMORY = "gearpump.yarn.worker.memory"
+ val WORKER_VCORES = "gearpump.yarn.worker.vcores"
+
+ val SERVICES_ENABLED = "gearpump.yarn.services.enabled"
+
+ val LOCAL_DIRS = org.apache.hadoop.yarn.api.ApplicationConstants.Environment.LOCAL_DIRS.$$()
+ val CONTAINER_ID = org.apache.hadoop.yarn.api.ApplicationConstants.Environment.CONTAINER_ID.$$()
+ val LOG_DIR_EXPANSION_VAR = org.apache.hadoop.yarn.api.ApplicationConstants.LOG_DIR_EXPANSION_VAR
+ val NODEMANAGER_HOST = org.apache.hadoop.yarn.api.ApplicationConstants.Environment.NM_HOST.$$()
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/appmaster/Command.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/appmaster/Command.scala b/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/appmaster/Command.scala
new file mode 100644
index 0000000..711506a
--- /dev/null
+++ b/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/appmaster/Command.scala
@@ -0,0 +1,126 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.yarn.appmaster
+
+import com.typesafe.config.Config
+
+import org.apache.gearpump.cluster.main.{Master, Worker}
+import org.apache.gearpump.experiments.yarn.Constants._
+import org.apache.gearpump.transport.HostPort
+import org.apache.gearpump.util.Constants
+
+/** Command to start a YARN container */
+trait Command {
+ def get: String
+ override def toString: String = get
+}
+
+abstract class AbstractCommand extends Command {
+ protected def config: Config
+ def version: String
+ def classPath: Array[String] = {
+ Array(
+ s"conf",
+ s"pack/$version/conf",
+ s"pack/$version/lib/daemon/*",
+ s"pack/$version/lib/*"
+ )
+ }
+
+ protected def buildCommand(
+ java: String, properties: Array[String], mainClazz: String, cliOpts: Array[String])
+ : String = {
+ val exe = config.getString(java)
+
+ s"$exe -cp ${classPath.mkString(":")}:" +
+ "$CLASSPATH " + properties.mkString(" ") +
+ s" $mainClazz ${cliOpts.mkString(" ")} 2>&1 | /usr/bin/tee -a ${LOG_DIR_EXPANSION_VAR}/stderr"
+ }
+
+ protected def clazz(any: AnyRef): String = {
+ val name = any.getClass.getName
+ if (name.endsWith("$")) {
+ name.dropRight(1)
+ } else {
+ name
+ }
+ }
+}
+
+case class MasterCommand(config: Config, version: String, masterAddr: HostPort)
+ extends AbstractCommand {
+
+ def get: String = {
+ val masterArguments = Array(s"-ip ${masterAddr.host}", s"-port ${masterAddr.port}")
+
+ val properties = Array(
+ s"-D${Constants.GEARPUMP_CLUSTER_MASTERS}.0=${masterAddr.host}:${masterAddr.port}",
+ s"-D${Constants.GEARPUMP_HOSTNAME}=${masterAddr.host}",
+ s"-D${Constants.GEARPUMP_MASTER_RESOURCE_MANAGER_CONTAINER_ID}=${CONTAINER_ID}",
+ s"-D${Constants.GEARPUMP_HOME}=${LOCAL_DIRS}/${CONTAINER_ID}/pack/$version",
+ s"-D${Constants.GEARPUMP_LOG_DAEMON_DIR}=${LOG_DIR_EXPANSION_VAR}",
+ s"-D${Constants.GEARPUMP_LOG_APPLICATION_DIR}=${LOG_DIR_EXPANSION_VAR}")
+
+ buildCommand(MASTER_COMMAND, properties, clazz(Master), masterArguments)
+ }
+}
+
+case class WorkerCommand(config: Config, version: String, masterAddr: HostPort, workerHost: String)
+ extends AbstractCommand {
+
+ def get: String = {
+ val properties = Array(
+ s"-D${Constants.GEARPUMP_CLUSTER_MASTERS}.0=${masterAddr.host}:${masterAddr.port}",
+ s"-D${Constants.GEARPUMP_LOG_DAEMON_DIR}=${LOG_DIR_EXPANSION_VAR}",
+ s"-D${Constants.GEARPUMP_WORKER_RESOURCE_MANAGER_CONTAINER_ID}=${CONTAINER_ID}",
+ s"-D${Constants.GEARPUMP_HOME}=${LOCAL_DIRS}/${CONTAINER_ID}/pack/$version",
+ s"-D${Constants.GEARPUMP_LOG_APPLICATION_DIR}=${LOG_DIR_EXPANSION_VAR}",
+ s"-D${Constants.GEARPUMP_HOSTNAME}=$workerHost")
+
+ buildCommand(WORKER_COMMAND, properties, clazz(Worker), Array.empty[String])
+ }
+}
+
+case class AppMasterCommand(config: Config, version: String, args: Array[String])
+ extends AbstractCommand {
+
+ override val classPath = Array(
+ "conf",
+ s"pack/$version/conf",
+ s"pack/$version/dashboard",
+ s"pack/$version/lib/*",
+ s"pack/$version/lib/daemon/*",
+ s"pack/$version/lib/services/*",
+ s"pack/$version/lib/yarn/*"
+ )
+
+ def get: String = {
+ val properties = Array(
+ s"-D${Constants.GEARPUMP_HOME}=${LOCAL_DIRS}/${CONTAINER_ID}/pack/$version",
+ s"-D${Constants.GEARPUMP_FULL_SCALA_VERSION}=$version",
+ s"-D${Constants.GEARPUMP_LOG_DAEMON_DIR}=${LOG_DIR_EXPANSION_VAR}",
+ s"-D${Constants.GEARPUMP_LOG_APPLICATION_DIR}=${LOG_DIR_EXPANSION_VAR}",
+ s"-D${Constants.GEARPUMP_HOSTNAME}=${NODEMANAGER_HOST}")
+
+ val arguments = Array(s"") ++ args
+
+ buildCommand(APPMASTER_COMMAND, properties, clazz(YarnAppMaster),
+ arguments)
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/appmaster/UIService.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/appmaster/UIService.scala b/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/appmaster/UIService.scala
new file mode 100644
index 0000000..1194f0b
--- /dev/null
+++ b/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/appmaster/UIService.scala
@@ -0,0 +1,93 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.yarn.appmaster
+
+import akka.actor._
+import com.typesafe.config.{ConfigFactory, ConfigValueFactory}
+import org.apache.gearpump.cluster.ClusterConfig
+import org.apache.gearpump.services.main.Services
+import org.apache.gearpump.transport.HostPort
+import org.apache.gearpump.util.{ActorUtil, Constants, LogUtil}
+
+import scala.concurrent.Future
+
+trait UIFactory {
+ def props(masters: List[HostPort], host: String, port: Int): Props
+}
+
+/** Wrapper of UI server */
+class UIService(masters: List[HostPort], host: String, port: Int) extends Actor {
+ private val LOG = LogUtil.getLogger(getClass)
+
+ private val supervisor = ActorUtil.getFullPath(context.system, context.parent.path)
+ private var configFile: java.io.File = null
+
+ private implicit val dispatcher = context.dispatcher
+
+ override def postStop(): Unit = {
+ if (configFile != null) {
+ configFile.delete()
+ configFile = null
+ }
+
+ // TODO: fix this
+ // Hack around to Kill the UI server
+ Services.kill()
+ }
+
+ override def preStart(): Unit = {
+ Future(start())
+ }
+
+ def start(): Unit = {
+ val mastersArg = masters.mkString(",")
+ LOG.info(s"Launching services -master $mastersArg")
+
+ configFile = java.io.File.createTempFile("uiserver", ".conf")
+
+ val config = context.system.settings.config.
+ withValue(Constants.GEARPUMP_SERVICE_HOST, ConfigValueFactory.fromAnyRef(host)).
+ withValue(Constants.GEARPUMP_SERVICE_HTTP, ConfigValueFactory.fromAnyRef(port.toString)).
+ withValue(Constants.NETTY_TCP_HOSTNAME, ConfigValueFactory.fromAnyRef(host))
+
+ ClusterConfig.saveConfig(config, configFile)
+
+ val master = masters.head
+
+ ConfigFactory.invalidateCaches()
+ launch(supervisor, master.host, master.port, configFile.toString)
+ }
+
+ // Launch the UI server
+ def launch(supervisor: String, masterHost: String, masterPort: Int, configFile: String): Unit = {
+ Services.main(Array("-supervisor", supervisor, "-master", s"$masterHost:$masterPort"
+ , "-conf", configFile))
+ }
+
+ override def receive: Receive = {
+ case _ =>
+ LOG.error(s"Unknown message received")
+ }
+}
+
+object UIService extends UIFactory {
+ override def props(masters: List[HostPort], host: String, port: Int): Props = {
+ Props(new UIService(masters, host, port))
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/appmaster/YarnAppMaster.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/appmaster/YarnAppMaster.scala b/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/appmaster/YarnAppMaster.scala
new file mode 100644
index 0000000..97577fb
--- /dev/null
+++ b/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/appmaster/YarnAppMaster.scala
@@ -0,0 +1,385 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.yarn.appmaster
+
+import java.io.IOException
+import java.util.concurrent.TimeUnit
+
+import akka.actor._
+import akka.util.Timeout
+import com.typesafe.config.ConfigValueFactory
+import org.apache.commons.httpclient.HttpClient
+import org.apache.commons.httpclient.methods.GetMethod
+import org.apache.gearpump.cluster.ClientToMaster._
+import org.apache.gearpump.cluster.ClusterConfig
+import org.apache.gearpump.cluster.main.{ArgumentsParser, CLIOption}
+import org.apache.gearpump.experiments.yarn.Constants._
+import org.apache.gearpump.experiments.yarn.glue.Records._
+import org.apache.gearpump.experiments.yarn.glue.{NMClient, RMClient, YarnConfig}
+import org.apache.gearpump.transport.HostPort
+import org.apache.gearpump.util._
+import org.slf4j.Logger
+
+import scala.collection.JavaConverters._
+import scala.concurrent.Await
+import scala.concurrent.duration.Duration
+
+/**
+ * YARN AppMaster. YARN AppMaster is responsible to start Gearpump masters, workers, UI server as
+ * YARN containers.
+ *
+ * NOTE: It is different with Gearpump AppMaster. Gearpump AppMaster is a sub-process of worker.
+ */
+class YarnAppMaster(rmClient: RMClient, nmClient: NMClient,
+ packagePath: String, hdfsConfDir: String,
+ uiFactory: UIFactory)
+ extends Actor {
+
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+ private val akkaConf = context.system.settings.config
+ private val servicesEnabled = akkaConf.getString(SERVICES_ENABLED).toBoolean
+ private var uiStarted = false
+ private val host = akkaConf.getString(Constants.GEARPUMP_HOSTNAME)
+
+ private val port = Util.findFreePort().get
+
+ private val trackingURL = "http://" + host + ":" + port
+
+ // TODO: for now, only one master is supported.
+ private val masterCount = 1
+ private val masterMemory = akkaConf.getString(MASTER_MEMORY).toInt
+ private val masterVCores = akkaConf.getString(MASTER_VCORES).toInt
+
+ private var workerCount = akkaConf.getString(WORKER_CONTAINERS).toInt
+ private val workerMemory = akkaConf.getString(WORKER_MEMORY).toInt
+ private val workerVCores = akkaConf.getString(WORKER_VCORES).toInt
+
+ val rootPath = System.getProperty(Constants.GEARPUMP_FULL_SCALA_VERSION)
+
+ rmClient.start(self)
+ nmClient.start(self)
+
+ def receive: Receive = null
+
+ private def registerAppMaster(): Unit = {
+ val target = host + ":" + port
+ rmClient.registerAppMaster(host, port, trackingURL)
+ }
+
+ registerAppMaster
+ context.become(waitForAppMasterRegistered)
+
+ import org.apache.gearpump.experiments.yarn.appmaster.YarnAppMaster._
+
+ def waitForAppMasterRegistered: Receive = {
+ case AppMasterRegistered =>
+ LOG.info("YarnAppMaster registration completed")
+ requestMasterContainers(masterCount)
+ context.become(startingMasters(remain = masterCount, List.empty[MasterInfo]))
+ }
+
+ private def startingMasters(remain: Int, masters: List[MasterInfo]): Receive = box {
+ case ContainersAllocated(containers) =>
+ LOG.info(s"ContainersAllocated: containers allocated for master(remain=$remain), count: "
+ + containers.size)
+ val count = Math.min(containers.length, remain)
+ val newMasters = (0 until count).toList.map { index =>
+ val container = containers(index)
+ MasterInfo(container.getId, container.getNodeId, launchMaster(container))
+ }
+
+ // Stops un-used containers
+ containers.drop(count).map { container =>
+ nmClient.stopContainer(container.getId, container.getNodeId)
+ }
+
+ context.become(startingMasters(remain, newMasters ++ masters))
+ case ContainerStarted(containerId) =>
+ LOG.info(s"ContainerStarted: container ${containerId} started for master(remain=$remain) ")
+ if (remain > 1) {
+ context.become(startingMasters(remain - 1, masters))
+ } else {
+ requestWorkerContainers(workerCount)
+ context.become(startingWorkers(workerCount, masters, List.empty[WorkerInfo]))
+ }
+ }
+
+ private def box(receive: Receive): Receive = {
+ onError orElse receive orElse unHandled
+ }
+
+ private def startingWorkers(remain: Int, masters: List[MasterInfo], workers: List[WorkerInfo])
+ : Receive = {
+ box {
+ case ContainersAllocated(containers) =>
+ LOG.info(s"ContainersAllocated: containers allocated for workers(remain=$remain), " +
+ s"count: " + containers.size)
+
+ val count = Math.min(containers.length, remain)
+ val newWorkers = (0 until count).toList.map { index =>
+ val container = containers(index)
+ launchWorker(container, masters)
+ WorkerInfo(container.getId, container.getNodeId)
+ }
+
+ // Stops un-used containers
+ containers.drop(count).map { container =>
+ nmClient.stopContainer(container.getId, container.getNodeId)
+ }
+ context.become(startingWorkers(remain, masters, workers ++ newWorkers))
+ case ContainerStarted(containerId) =>
+ LOG.info(s"ContainerStarted: container $containerId started for worker(remain=$remain)")
+ // The last one
+ if (remain > 1) {
+ context.become(startingWorkers(remain - 1, masters, workers))
+ } else {
+ if (servicesEnabled && !uiStarted) {
+ context.actorOf(uiFactory.props(masters.map(_.host), host, port))
+ uiStarted = true
+ }
+ context.become(service(effectiveConfig(masters.map(_.host)), masters, workers))
+ }
+ }
+ }
+
+ private def effectiveConfig(masters: List[HostPort]): Config = {
+ val masterList = masters.map(pair => s"${pair.host}:${pair.port}")
+ val config = context.system.settings.config
+ config.withValue(Constants.GEARPUMP_CLUSTER_MASTERS,
+ ConfigValueFactory.fromIterable(masterList.asJava))
+ }
+
+ private def onError: Receive = {
+ case ContainersCompleted(containers) =>
+ // TODO: we should recover the failed container from this...
+ containers.foreach { status =>
+ if (status.getExitStatus != 0) {
+ LOG.error(s"ContainersCompleted: container ${status.getContainerId}" +
+ s" failed with exit code ${status.getExitStatus}, msg: ${status.getDiagnostics}")
+ } else {
+ LOG.info(s"ContainersCompleted: container ${status.getContainerId} completed")
+ }
+ }
+ case ShutdownApplication =>
+ LOG.error("ShutdownApplication")
+ nmClient.stop()
+ rmClient.shutdownApplication()
+ context.stop(self)
+ case ResourceManagerException(ex) =>
+ LOG.error("ResourceManagerException: " + ex.getMessage, ex)
+ nmClient.stop()
+ rmClient.failApplication(ex)
+ context.stop(self)
+ case Kill =>
+ LOG.info("Kill: User asked to shutdown the application")
+ sender ! CommandResult(success = true)
+ self ! ShutdownApplication
+ }
+
+ private def service(config: Config, masters: List[MasterInfo], workers: List[WorkerInfo])
+ : Receive = box {
+ case GetActiveConfig(clientHost) =>
+ LOG.info("GetActiveConfig: Get active configuration for client: " + clientHost)
+ val filtered = ClusterConfig.filterOutDefaultConfig(
+ config.withValue(Constants.GEARPUMP_HOSTNAME,
+ ConfigValueFactory.fromAnyRef(clientHost)))
+ sender ! ActiveConfig(filtered)
+ case QueryVersion =>
+ LOG.info("QueryVersion")
+ sender ! Version(Util.version)
+ case QueryClusterInfo =>
+ LOG.info("QueryClusterInfo")
+ val masterContainers = masters.map { master =>
+ master.id.toString + s"(${master.nodeId.toString})"
+ }
+
+ val workerContainers = workers.map { worker =>
+ worker.id.toString + s"(${worker.nodeId.toString})"
+ }
+ sender ! ClusterInfo(masterContainers, workerContainers)
+ case AddMaster =>
+ sender ! CommandResult(success = false, "Not Implemented")
+ case RemoveMaster(masterId) =>
+ sender ! CommandResult(success = false, "Not Implemented")
+ case AddWorker(count) =>
+ if (count == 0) {
+ sender ! CommandResult(success = true)
+ } else {
+ LOG.info("AddWorker: Start to add new workers, count: " + count)
+ workerCount += count
+ requestWorkerContainers(count)
+ context.become(startingWorkers(count, masters, workers))
+ sender ! CommandResult(success = true)
+ }
+ case RemoveWorker(worker) =>
+ val workerId = ContainerId.fromString(worker)
+ LOG.info(s"RemoveWorker: remove worker $workerId")
+ val info = workers.find(_.id.toString == workerId.toString)
+ if (info.isDefined) {
+ nmClient.stopContainer(info.get.id, info.get.nodeId)
+ sender ! CommandResult(success = true)
+ val remainWorkers = workers.filter(_.id != info.get.id)
+ context.become(service(config, masters, remainWorkers))
+ } else {
+ sender ! CommandResult(success = false, "failed to find worker " + worker)
+ }
+ }
+
+ private def unHandled: Receive = {
+ case other =>
+ LOG.info(s"Received unknown message $other")
+ }
+
+ private def requestMasterContainers(masters: Int) = {
+ LOG.info(s"Request resource for masters($masters)")
+ val containers = (1 to masters).map(
+ i => Resource.newInstance(masterMemory, masterVCores)
+ ).toList
+ rmClient.requestContainers(containers)
+ }
+
+ private def launchMaster(container: Container): HostPort = {
+ LOG.info(s"Launch Master on container " + container.getNodeHttpAddress)
+ val host = container.getNodeId.getHost
+
+ val port = Util.findFreePort().get
+
+ LOG.info("=============PORT" + port)
+ val masterCommand = MasterCommand(akkaConf, rootPath, HostPort(host, port))
+ nmClient.launchCommand(container, masterCommand.get, packagePath, hdfsConfDir)
+ HostPort(host, port)
+ }
+
+ private def requestWorkerContainers(workers: Int): Unit = {
+ LOG.info(s"Request resource for workers($workers)")
+ val containers = (1 to workers).map(
+ i => Resource.newInstance(workerMemory, workerVCores)
+ ).toList
+
+ rmClient.requestContainers(containers)
+ }
+
+ private def launchWorker(container: Container, masters: List[MasterInfo]): Unit = {
+ LOG.info(s"Launch Worker on container " + container.getNodeHttpAddress)
+ val workerHost = container.getNodeId.getHost
+ val workerCommand = WorkerCommand(akkaConf, rootPath, masters.head.host, workerHost)
+ nmClient.launchCommand(container, workerCommand.get, packagePath, hdfsConfDir)
+ }
+}
+
+object YarnAppMaster extends AkkaApp with ArgumentsParser {
+ val LOG: Logger = LogUtil.getLogger(getClass)
+
+ override val options: Array[(String, CLIOption[Any])] = Array(
+ "conf" -> CLIOption[String]("<Gearpump configuration directory on HDFS>", required = true),
+ "package" -> CLIOption[String]("<Gearpump package path on HDFS>", required = true)
+ )
+
+ override def akkaConfig: Config = {
+ ClusterConfig.ui()
+ }
+
+ override def main(akkaConf: Config, args: Array[String]): Unit = {
+ implicit val timeout = Timeout(5, TimeUnit.SECONDS)
+ implicit val system = ActorSystem("GearpumpAM", akkaConf)
+
+ val yarnConf = new YarnConfig()
+
+ val confDir = parse(args).getString("conf")
+ val packagePath = parse(args).getString("package")
+
+ LOG.info("HADOOP_CONF_DIR: " + System.getenv("HADOOP_CONF_DIR"))
+ LOG.info("YARN Resource Manager: " + yarnConf.resourceManager)
+
+ val rmClient = new RMClient(yarnConf)
+ val nmClient = new NMClient(yarnConf, akkaConf)
+ val appMaster = system.actorOf(Props(new YarnAppMaster(rmClient,
+ nmClient, packagePath, confDir, UIService)))
+
+ val daemon = system.actorOf(Props(new Daemon(appMaster)))
+ Await.result(system.whenTerminated, Duration.Inf)
+ LOG.info("YarnAppMaster is shutdown")
+ }
+
+ class Daemon(appMaster: ActorRef) extends Actor {
+ context.watch(appMaster)
+
+ override def receive: Actor.Receive = {
+ case Terminated(actor) =>
+ if (actor.compareTo(appMaster) == 0) {
+ LOG.info(s"YarnAppMaster ${appMaster.path.toString} is terminated, " +
+ s"shutting down current ActorSystem")
+ context.system.terminate()
+ context.stop(self)
+ }
+ }
+ }
+
+ case class ResourceManagerException(throwable: Throwable)
+ case object ShutdownApplication
+ case class ContainersRequest(containers: List[Resource])
+ case class ContainersAllocated(containers: List[Container])
+ case class ContainersCompleted(containers: List[ContainerStatus])
+ case class ContainerStarted(containerId: ContainerId)
+ case object AppMasterRegistered
+
+ case class GetActiveConfig(clientHost: String)
+
+ case object QueryClusterInfo
+ case class ClusterInfo(masters: List[String], workers: List[String]) {
+ override def toString: String = {
+ val separator = "\n"
+ val masterSection = "masters: " + separator + masters.mkString("\n") + "\n"
+
+ val workerSection = "workers: " + separator + workers.mkString("\n") + "\n"
+ masterSection + workerSection
+ }
+ }
+
+ case object Kill
+ case class ActiveConfig(config: Config)
+
+ case object QueryVersion
+
+ case class Version(version: String)
+
+ case class MasterInfo(id: ContainerId, nodeId: NodeId, host: HostPort)
+
+ case class WorkerInfo(id: ContainerId, nodeId: NodeId)
+
+ def getAppMaster(report: ApplicationReport, system: ActorSystem): ActorRef = {
+ val client = new HttpClient()
+ val appMasterPath = s"${report.getOriginalTrackingUrl}/supervisor-actor-path"
+ val get = new GetMethod(appMasterPath)
+ var status = client.executeMethod(get)
+
+ if (status != 200) {
+ // Sleeps a little bit, and try again
+ Thread.sleep(3000)
+ status = client.executeMethod(get)
+ }
+
+ if (status == 200) {
+ AkkaHelper.actorFor(system, get.getResponseBodyAsString)
+ } else {
+ throw new IOException("Fail to resolve AppMaster address, please make sure " +
+ s"${report.getOriginalTrackingUrl} is accessible...")
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/client/AppMasterResolver.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/client/AppMasterResolver.scala b/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/client/AppMasterResolver.scala
new file mode 100644
index 0000000..9fb69b2
--- /dev/null
+++ b/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/client/AppMasterResolver.scala
@@ -0,0 +1,77 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.yarn.client
+
+import java.io.IOException
+
+import akka.actor.{ActorRef, ActorSystem}
+import org.apache.commons.httpclient.HttpClient
+import org.apache.commons.httpclient.methods.GetMethod
+import org.apache.gearpump.experiments.yarn.glue.Records.ApplicationId
+import org.apache.gearpump.experiments.yarn.glue.YarnClient
+import org.apache.gearpump.util.{AkkaHelper, LogUtil}
+
+import scala.util.Try
+
+/**
+ * Resolves AppMaster ActorRef
+ */
+class AppMasterResolver(yarnClient: YarnClient, system: ActorSystem) {
+ val LOG = LogUtil.getLogger(getClass)
+ val RETRY_INTERVAL_MS = 3000 // ms
+
+ def resolve(appId: ApplicationId, timeoutSeconds: Int = 30): ActorRef = {
+ val appMaster = retry(connect(appId), 1 + timeoutSeconds * 1000 / RETRY_INTERVAL_MS)
+ appMaster
+ }
+
+ private def connect(appId: ApplicationId): ActorRef = {
+ val report = yarnClient.getApplicationReport(appId)
+ val client = new HttpClient()
+ val appMasterPath = s"${report.getOriginalTrackingUrl}/supervisor-actor-path"
+ LOG.info(s"appMasterPath=$appMasterPath")
+ val get = new GetMethod(appMasterPath)
+ val status = client.executeMethod(get)
+ if (status == 200) {
+ val response = get.getResponseBodyAsString
+ LOG.info("Successfully resolved AppMaster address: " + response)
+ AkkaHelper.actorFor(system, response)
+ } else {
+ throw new IOException("Fail to resolve AppMaster address, please make sure " +
+ s"${report.getOriginalTrackingUrl} is accessible...")
+ }
+ }
+
+ private def retry(fun: => ActorRef, times: Int): ActorRef = {
+ var index = 0
+ var result: ActorRef = null
+ while (index < times && result == null) {
+ Thread.sleep(RETRY_INTERVAL_MS)
+ index += 1
+ val tryConnect = Try(fun)
+ if (tryConnect.isFailure) {
+ LOG.error(s"Failed to connect YarnAppMaster(tried $index)... " +
+ tryConnect.failed.get.getMessage)
+ } else {
+ result = tryConnect.get
+ }
+ }
+ result
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/client/Client.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/client/Client.scala b/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/client/Client.scala
new file mode 100644
index 0000000..9ec2eae
--- /dev/null
+++ b/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/client/Client.scala
@@ -0,0 +1,61 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.experiments.yarn.client
+
+import org.apache.gearpump.util.LogUtil
+import org.slf4j.Logger
+
+/** Command line tool to launch a Gearpump cluster on YARN, and also to manage Gearpump cluster */
+object Client {
+
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+ val LAUNCH = "launch"
+
+ val commands = Map(LAUNCH -> LaunchCluster) ++
+ ManageCluster.commands.map(key => (key, ManageCluster)).toMap
+
+ def usage(): Unit = {
+ val keys = commands.keys.toList.sorted
+ // scalastyle:off println
+ Console.err.println("Usage: " + "<" + keys.mkString("|") + ">")
+ // scalastyle:on println
+ }
+
+ def main(args: Array[String]): Unit = {
+ if (args.length == 0) {
+ usage()
+ } else {
+ val key = args(0)
+ val command = commands.get(key)
+ command match {
+ case Some(command) =>
+ if (key == LAUNCH) {
+ val remainArgs = args.drop(1)
+ command.main(remainArgs)
+ } else {
+ val commandArg = Array("-" + ManageCluster.COMMAND, key)
+ val remainArgs = args.drop(1)
+ val updatedArgs = commandArg ++ args.drop(1)
+ command.main(updatedArgs)
+ }
+ case None =>
+ usage
+ }
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/client/LaunchCluster.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/client/LaunchCluster.scala b/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/client/LaunchCluster.scala
new file mode 100644
index 0000000..2475728
--- /dev/null
+++ b/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/client/LaunchCluster.scala
@@ -0,0 +1,220 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.experiments.yarn.client
+
+import java.io.{File, IOException, OutputStreamWriter}
+import java.net.InetAddress
+import java.util.zip.ZipInputStream
+
+import akka.actor.ActorSystem
+import com.typesafe.config.{Config, ConfigValueFactory}
+import org.apache.gearpump.cluster.ClusterConfig
+import org.apache.gearpump.cluster.main.{ArgumentsParser, CLIOption, ParseResult}
+import org.apache.gearpump.experiments.yarn.Constants
+import org.apache.gearpump.experiments.yarn.appmaster.AppMasterCommand
+import org.apache.gearpump.experiments.yarn.appmaster.YarnAppMaster.{ActiveConfig, GetActiveConfig}
+import org.apache.gearpump.experiments.yarn.glue.Records.{ApplicationId, Resource}
+import org.apache.gearpump.experiments.yarn.glue.{FileSystem, YarnClient, YarnConfig}
+import org.apache.gearpump.util.ActorUtil.askActor
+import org.apache.gearpump.util.{AkkaApp, LogUtil, Util}
+import org.slf4j.Logger
+
+import scala.concurrent.duration.Duration
+import scala.concurrent.{Await, Future}
+
+/**
+ * Launch Gearpump on YARN
+ */
+class LaunchCluster(
+ akka: Config,
+ yarnConf: YarnConfig,
+ yarnClient: YarnClient,
+ fs: FileSystem,
+ actorSystem: ActorSystem,
+ appMasterResolver: AppMasterResolver,
+ version: String = Util.version) {
+
+ import org.apache.gearpump.experiments.yarn.Constants._
+ private implicit val dispatcher = actorSystem.dispatcher
+
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+ private val host = InetAddress.getLocalHost.getHostName
+ private val queue = akka.getString(APPMASTER_QUEUE)
+ private val memory = akka.getString(APPMASTER_MEMORY).toInt
+ private val vcore = akka.getString(APPMASTER_VCORES).toInt
+
+ def submit(appName: String, packagePath: String): ApplicationId = {
+ LOG.info("Starting AM")
+
+ // First step, check the version, to make sure local version matches remote version
+ if (!packagePath.endsWith(".zip")) {
+ throw new IOException(s"YarnClient only support .zip distribution package," +
+ s" now it is ${packagePath}. Please download the zip " +
+ "package from website or use sbt assembly packArchiveZip to build one.")
+ }
+
+ if (!fs.exists(packagePath)) {
+ throw new IOException(s"Cannot find package ${packagePath} on HDFS ${fs.name}. ")
+ }
+
+ val rootEntry = rootEntryPath(zip = packagePath)
+
+ if (!rootEntry.contains(version)) {
+ throw new IOException(s"Check version failed! Local gearpump binary" +
+ s" version $version doesn't match with remote path $packagePath")
+ }
+
+ val resource = Resource.newInstance(memory, vcore)
+ val appId = yarnClient.createApplication
+
+ // uploads the configs to HDFS home directory of current user.
+ val configPath = uploadConfigToHDFS(appId)
+
+ val command = AppMasterCommand(akka, rootEntry, Array(s"-conf $configPath",
+ s"-package $packagePath"))
+
+ yarnClient.submit(appName, appId, command.get, resource, queue, packagePath, configPath)
+
+ LOG.info("Waiting application to finish...")
+ val report = yarnClient.awaitApplication(appId, LaunchCluster.TIMEOUT_MILLISECONDS)
+ LOG.info(s"Application $appId finished with state ${report.getYarnApplicationState} " +
+ s"at ${report.getFinishTime}, info: ${report.getDiagnostics}")
+
+ // scalastyle:off println
+ Console.println("================================================")
+ Console.println("==Application Id: " + appId)
+ // scalastyle:on println
+ appId
+ }
+
+ def saveConfig(appId: ApplicationId, output: String): Future[File] = {
+ LOG.info(s"Trying to download active configuration to output path: " + output)
+ LOG.info(s"Resolving YarnAppMaster ActorRef for application " + appId)
+ val appMaster = appMasterResolver.resolve(appId)
+ LOG.info(s"appMaster=${appMaster.path} host=$host")
+ val future = askActor[ActiveConfig](appMaster, GetActiveConfig(host)).map(_.config)
+ future.map { config =>
+ val out = new File(output)
+ ClusterConfig.saveConfig(config, out)
+ out
+ }
+ }
+
+ private def uploadConfigToHDFS(appId: ApplicationId): String = {
+ // Uses personal home directory so that it will not conflict with other users
+ // conf path pattern: /user/<userid>/.gearpump_application_<timestamp>_<id>/conf
+ val confDir = s"${fs.getHomeDirectory}/.gearpump_${appId}/conf/"
+ LOG.info(s"Uploading configuration files to remote HDFS(under $confDir)...")
+
+ // Copies config from local to remote.
+ val remoteConfFile = s"$confDir/gear.conf"
+ var out = fs.create(remoteConfFile)
+ var writer = new OutputStreamWriter(out)
+
+ val cleanedConfig = ClusterConfig.filterOutDefaultConfig(akka)
+
+ writer.write(cleanedConfig.root().render())
+ writer.close()
+
+ // Saves yarn-site.xml to remote
+ val yarn_site_xml = s"$confDir/yarn-site.xml"
+ out = fs.create(yarn_site_xml)
+ writer = new OutputStreamWriter(out)
+ yarnConf.writeXml(writer)
+ writer.close()
+
+ // Saves log4j.properties to remote
+ val log4j_properties = s"$confDir/log4j.properties"
+ val log4j = LogUtil.loadConfiguration
+ out = fs.create(log4j_properties)
+ writer = new OutputStreamWriter(out)
+ log4j.store(writer, "gearpump on yarn")
+ writer.close()
+ confDir.toString
+ }
+
+ private def rootEntryPath(zip: String): String = {
+ val stream = new ZipInputStream(fs.open(zip))
+ val entry = stream.getNextEntry()
+ val name = entry.getName
+ name.substring(0, entry.getName.indexOf("/"))
+ }
+}
+
+object LaunchCluster extends AkkaApp with ArgumentsParser {
+
+ val PACKAGE = "package"
+ val NAME = "name"
+ val VERBOSE = "verbose"
+ val OUTPUT = "output"
+
+ override protected def akkaConfig: Config = {
+ ClusterConfig.default()
+ }
+
+ override val options: Array[(String, CLIOption[Any])] = Array(
+ PACKAGE -> CLIOption[String]("<Please specify the gearpump.zip package path on HDFS. " +
+ "If not specified, we will use default value /user/gearpump/gearpump.zip>", required = false),
+ NAME -> CLIOption[String]("<Application name showed in YARN>", required = false,
+ defaultValue = Some("Gearpump")),
+ VERBOSE -> CLIOption("<print verbose log on console>", required = false,
+ defaultValue = Some(false)),
+ OUTPUT -> CLIOption("<output path for configuration file>", required = false,
+ defaultValue = None)
+ )
+ private val TIMEOUT_MILLISECONDS = 30 * 1000
+
+ override def main(inputAkkaConf: Config, args: Array[String]): Unit = {
+ val parsed = parse(args)
+ if (parsed.getBoolean(VERBOSE)) {
+ LogUtil.verboseLogToConsole()
+ }
+
+ val yarnConfig = new YarnConfig()
+ val fs = new FileSystem(yarnConfig)
+ val yarnClient = new YarnClient(yarnConfig)
+ val akkaConf = updateConf(inputAkkaConf, parsed)
+ val actorSystem = ActorSystem("launchCluster", akkaConf)
+ val appMasterResolver = new AppMasterResolver(yarnClient, actorSystem)
+
+ val client = new LaunchCluster(akkaConf, yarnConfig, yarnClient, fs,
+ actorSystem, appMasterResolver)
+
+ val name = parsed.getString(NAME)
+ val appId = client.submit(name, akkaConf.getString(Constants.PACKAGE_PATH))
+
+ if (parsed.exists(OUTPUT)) {
+ import scala.concurrent.duration._
+ Await.result(client.saveConfig(appId, parsed.getString(OUTPUT)),
+ TIMEOUT_MILLISECONDS.milliseconds)
+ }
+
+ yarnClient.stop()
+ actorSystem.terminate()
+ Await.result(actorSystem.whenTerminated, Duration.Inf)
+ }
+
+ private def updateConf(akka: Config, parsed: ParseResult): Config = {
+ if (parsed.exists(PACKAGE)) {
+ akka.withValue(Constants.PACKAGE_PATH,
+ ConfigValueFactory.fromAnyRef(parsed.getString(PACKAGE)))
+ } else {
+ akka
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/client/ManageCluster.scala
----------------------------------------------------------------------
diff --git a/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/client/ManageCluster.scala b/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/client/ManageCluster.scala
new file mode 100644
index 0000000..5b12346
--- /dev/null
+++ b/experiments/yarn/src/main/scala/org/apache/gearpump/experiments/yarn/client/ManageCluster.scala
@@ -0,0 +1,156 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.yarn.client
+
+import java.io.{File, IOException}
+import java.net.InetAddress
+import scala.concurrent.{Await, Future}
+
+import akka.actor.{ActorRef, ActorSystem}
+
+import org.apache.gearpump.cluster.ClientToMaster.{AddWorker, CommandResult, RemoveWorker}
+import org.apache.gearpump.cluster.ClusterConfig
+import org.apache.gearpump.cluster.main.{ArgumentsParser, CLIOption, ParseResult}
+import org.apache.gearpump.experiments.yarn.appmaster.YarnAppMaster.{ActiveConfig, ClusterInfo, GetActiveConfig, Kill, QueryClusterInfo, QueryVersion, Version}
+import org.apache.gearpump.experiments.yarn.glue.Records.ApplicationId
+import org.apache.gearpump.experiments.yarn.glue.{YarnClient, YarnConfig}
+import org.apache.gearpump.util.ActorUtil.askActor
+import org.apache.gearpump.util.{AkkaApp, LogUtil}
+
+/** Manage current Gearpump cluster on YARN */
+class ManageCluster(appId: ApplicationId, appMaster: ActorRef, system: ActorSystem) {
+ import org.apache.gearpump.experiments.yarn.client.ManageCluster._
+
+ private val host = InetAddress.getLocalHost.getHostName
+ implicit val dispatcher = system.dispatcher
+
+ def getConfig: Future[ActiveConfig] = askActor[ActiveConfig](appMaster, GetActiveConfig(host))
+ def version: Future[Version] = askActor[Version](appMaster, QueryVersion)
+ def addWorker(count: Int): Future[CommandResult] = {
+ askActor[CommandResult](appMaster, AddWorker(count))
+ }
+
+ def removeWorker(worker: String): Future[CommandResult] = {
+ askActor[CommandResult](appMaster, RemoveWorker(worker))
+ }
+
+ def shutdown: Future[CommandResult] = askActor[CommandResult](appMaster, Kill)
+ def queryClusterInfo: Future[ClusterInfo] = askActor[ClusterInfo](appMaster, QueryClusterInfo)
+
+ def command(command: String, parsed: ParseResult): Future[AnyRef] = {
+ command match {
+ case GET_CONFIG =>
+ if (parsed.exists(OUTPUT)) {
+ getConfig.map { conf =>
+ ClusterConfig.saveConfig(conf.config, new File(parsed.getString(OUTPUT)))
+ conf
+ }
+ } else {
+ throw new IOException(s"Please specify -$OUTPUT option")
+ }
+ case ADD_WORKER =>
+ val count = parsed.getString(COUNT).toInt
+ addWorker(count)
+ case REMOVE_WORKER =>
+ val containerId = parsed.getString(CONTAINER)
+ if (containerId == null || containerId.isEmpty) {
+ throw new IOException(s"Please specify -$CONTAINER option")
+ } else {
+ removeWorker(containerId)
+ }
+ case KILL =>
+ shutdown
+ case QUERY =>
+ queryClusterInfo
+ case VERSION =>
+ version
+ }
+ }
+}
+
+object ManageCluster extends AkkaApp with ArgumentsParser {
+ val GET_CONFIG = "getconfig"
+ val ADD_WORKER = "addworker"
+ val REMOVE_WORKER = "removeworker"
+ val KILL = "kill"
+ val VERSION = "version"
+ val QUERY = "query"
+ val COMMAND = "command"
+ val CONTAINER = "container"
+ val OUTPUT = "output"
+ val COUNT = "count"
+ val APPID = "appid"
+ val VERBOSE = "verbose"
+
+ val commands = List(GET_CONFIG, ADD_WORKER, REMOVE_WORKER, KILL, VERSION, QUERY)
+
+ import scala.concurrent.duration._
+ val TIME_OUT_SECONDS = 30.seconds
+
+ override val options: Array[(String, CLIOption[Any])] = Array(
+ COMMAND -> CLIOption[String](s"<${commands.mkString("|")}>", required = true),
+ APPID -> CLIOption[String]("<Application id, format: application_timestamp_id>",
+ required = true),
+ COUNT -> CLIOption("<how many instance to add or remove>", required = false,
+ defaultValue = Some(1)),
+ VERBOSE -> CLIOption("<print verbose log on console>", required = false,
+ defaultValue = Some(false)),
+ OUTPUT -> CLIOption("<output path for configuration file>", required = false,
+ defaultValue = Some("")),
+ CONTAINER -> CLIOption("<container id for master or worker>", required = false,
+ defaultValue = Some(""))
+ )
+
+ override def main(akkaConf: Config, args: Array[String]): Unit = {
+
+ val yarnConfig = new YarnConfig()
+ val yarnClient = new YarnClient(yarnConfig)
+
+ val parsed = parse(args)
+
+ if (parsed.getBoolean(VERBOSE)) {
+ LogUtil.verboseLogToConsole()
+ }
+
+ val appId = parseAppId(parsed.getString(APPID))
+ val system = ActorSystem("manageCluster", akkaConf)
+
+ val appMasterResolver = new AppMasterResolver(yarnClient, system)
+ val appMaster = appMasterResolver.resolve(appId)
+
+ implicit val dispatcher = system.dispatcher
+ val manager = new ManageCluster(appId, appMaster, system)
+
+ val command = parsed.getString(COMMAND)
+ val result = manager.command(command, parsed)
+
+ // scalastyle:off println
+ Console.println(Await.result(result, TIME_OUT_SECONDS))
+ // scalastyle:on println
+ system.terminate()
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+
+ def parseAppId(str: String): ApplicationId = {
+ val parts = str.split("_")
+ val timestamp = parts(1).toLong
+ val id = parts(2).toInt
+ ApplicationId.newInstance(timestamp, id)
+ }
+}
\ No newline at end of file
[44/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/cluster/UserConfig.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/cluster/UserConfig.scala b/core/src/main/scala/org/apache/gearpump/cluster/UserConfig.scala
new file mode 100644
index 0000000..28a4907
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/cluster/UserConfig.scala
@@ -0,0 +1,162 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster
+
+import akka.actor.{ActorSystem, ExtendedActorSystem}
+import akka.serialization.JavaSerializer
+
+import io.gearpump.google.common.io.BaseEncoding
+
+/**
+ * Immutable configuration
+ */
+final class UserConfig(private val _config: Map[String, String]) extends Serializable {
+
+ def withBoolean(key: String, value: Boolean): UserConfig = {
+ new UserConfig(_config + (key -> value.toString))
+ }
+
+ def withDouble(key: String, value: Double): UserConfig = {
+ new UserConfig(_config + (key -> value.toString))
+ }
+
+ def withFloat(key: String, value: Float): UserConfig = {
+ new UserConfig(_config + (key -> value.toString))
+ }
+
+ def withInt(key: String, value: Int): UserConfig = {
+ new UserConfig(_config + (key -> value.toString))
+ }
+
+ def withLong(key: String, value: Long): UserConfig = {
+ new UserConfig(_config + (key -> value.toString))
+ }
+
+ def withString(key: String, value: String): UserConfig = {
+ if (null == value) {
+ this
+ } else {
+ new UserConfig(_config + (key -> value))
+ }
+ }
+
+ def without(key: String): UserConfig = {
+ val config = _config - key
+ new UserConfig(config)
+ }
+
+ def filter(p: ((String, String)) => Boolean): UserConfig = {
+ val updated = _config.filter(p)
+ new UserConfig(updated)
+ }
+
+ def getBoolean(key: String): Option[Boolean] = {
+ _config.get(key).map(_.toBoolean)
+ }
+
+ def getDouble(key: String): Option[Double] = {
+ _config.get(key).map(_.toDouble)
+ }
+
+ def getFloat(key: String): Option[Float] = {
+ _config.get(key).map(_.toFloat)
+ }
+
+ def getInt(key: String): Option[Int] = {
+ _config.get(key).map(_.toInt)
+ }
+
+ def getLong(key: String): Option[Long] = {
+ _config.get(key).map(_.toLong)
+ }
+
+ def getString(key: String): Option[String] = {
+ _config.get(key)
+ }
+
+ def getBytes(key: String): Option[Array[Byte]] = {
+ _config.get(key).map(BaseEncoding.base64().decode(_))
+ }
+
+ def withBytes(key: String, value: Array[Byte]): UserConfig = {
+ if (null == value) {
+ this
+ } else {
+ this.withString(key, BaseEncoding.base64().encode(value))
+ }
+ }
+
+ // scalastyle:off line.size.limit
+ /**
+ * This de-serializes value to object instance
+ *
+ * To do de-serialization, this requires an implicit ActorSystem, as
+ * the ActorRef and possibly other akka classes deserialization
+ * requires an implicit ActorSystem.
+ *
+ * See Link:
+ * http://doc.akka.io/docs/akka/snapshot/scala/serialization.html#A_Word_About_Java_Serialization
+ */
+
+ def getValue[T](key: String)(implicit system: ActorSystem): Option[T] = {
+ val serializer = new JavaSerializer(system.asInstanceOf[ExtendedActorSystem])
+ _config.get(key).map(BaseEncoding.base64().decode(_))
+ .map(serializer.fromBinary(_).asInstanceOf[T])
+ }
+
+ /**
+ * This serializes the object and store it as string.
+ *
+ * To do serialization, this requires an implicit ActorSystem, as
+ * the ActorRef and possibly other akka classes serialization
+ * requires an implicit ActorSystem.
+ *
+ * See Link:
+ * http://doc.akka.io/docs/akka/snapshot/scala/serialization.html#A_Word_About_Java_Serialization
+ */
+ def withValue[T <: AnyRef](key: String, value: T)(implicit system: ActorSystem): UserConfig = {
+
+ if (null == value) {
+ this
+ } else {
+ val serializer = new JavaSerializer(system.asInstanceOf[ExtendedActorSystem])
+ val bytes = serializer.toBinary(value)
+ val encoded = BaseEncoding.base64().encode(bytes)
+ this.withString(key, encoded)
+ }
+ }
+ // scalastyle:on line.size.limit
+
+ def withConfig(other: UserConfig): UserConfig = {
+ if (null == other) {
+ this
+ } else {
+ new UserConfig(_config ++ other._config)
+ }
+ }
+}
+
+object UserConfig {
+
+ def empty: UserConfig = new UserConfig(Map.empty[String, String])
+
+ def apply(config: Map[String, String]): UserConfig = new UserConfig(config)
+
+ def unapply(config: UserConfig): Option[Map[String, String]] = Option(config._config)
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/cluster/appmaster/AppMasterRuntimeEnvironment.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/cluster/appmaster/AppMasterRuntimeEnvironment.scala b/core/src/main/scala/org/apache/gearpump/cluster/appmaster/AppMasterRuntimeEnvironment.scala
new file mode 100644
index 0000000..170e56a
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/cluster/appmaster/AppMasterRuntimeEnvironment.scala
@@ -0,0 +1,195 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.appmaster
+
+import akka.actor._
+
+import org.apache.gearpump.cluster.AppMasterToMaster.RegisterAppMaster
+import org.apache.gearpump.cluster.appmaster.AppMasterRuntimeEnvironment._
+import org.apache.gearpump.cluster.appmaster.ExecutorSystemScheduler.{Session, StartExecutorSystems}
+import org.apache.gearpump.cluster.appmaster.MasterConnectionKeeper.MasterConnectionStatus._
+import org.apache.gearpump.cluster.master.MasterProxy
+import org.apache.gearpump.cluster.{AppDescription, AppMasterContext}
+import org.apache.gearpump.util.LogUtil
+
+/**
+ * This serves as runtime environment for AppMaster.
+ * When starting an AppMaster, we need to setup the connection to master,
+ * and prepare other environments.
+ *
+ * This also extend the function of Master, by providing a scheduler service for Executor System.
+ * AppMaster can ask Master for executor system directly. details like requesting resource,
+ * contacting worker to start a process, and then starting an executor system is hidden from
+ * AppMaster.
+ *
+ * Please use AppMasterRuntimeEnvironment.props() to construct this actor.
+ */
+private[appmaster]
+class AppMasterRuntimeEnvironment(
+ appContextInput: AppMasterContext,
+ app: AppDescription,
+ masters: Iterable[ActorPath],
+ masterFactory: (AppId, MasterActorRef) => Props,
+ appMasterFactory: (AppMasterContext, AppDescription) => Props,
+ masterConnectionKeeperFactory: (MasterActorRef, RegisterAppMaster, ListenerActorRef) => Props)
+ extends Actor {
+
+ val appId = appContextInput.appId
+ private val LOG = LogUtil.getLogger(getClass, app = appId)
+
+ import scala.concurrent.duration._
+
+ private val master = context.actorOf(
+ masterFactory(appId, context.actorOf(Props(new MasterProxy(masters, 30.seconds)))))
+ private val appContext = appContextInput.copy(masterProxy = master)
+
+ // Create appMaster proxy to receive command and forward to appmaster
+ private val appMaster = context.actorOf(appMasterFactory(appContext, app))
+ context.watch(appMaster)
+
+ private val registerAppMaster = RegisterAppMaster(appMaster, appContext.registerData)
+ private val masterConnectionKeeper = context.actorOf(
+ masterConnectionKeeperFactory(master, registerAppMaster, self))
+ context.watch(masterConnectionKeeper)
+
+ def receive: Receive = {
+ case MasterConnected =>
+ LOG.info(s"Master is connected, start AppMaster ${appId}...")
+ appMaster ! StartAppMaster
+ case MasterStopped =>
+ LOG.error(s"Master is stopped, stop AppMaster ${appId}...")
+ context.stop(self)
+ case Terminated(actor) => actor match {
+ case `appMaster` =>
+ LOG.error(s"AppMaster ${appId} is stopped, shutdown myself")
+ context.stop(self)
+ case `masterConnectionKeeper` =>
+ LOG.error(s"Master connection keeper is stopped, appId: ${appId}, shutdown myself")
+ context.stop(self)
+ case _ => // Skip
+ }
+ }
+}
+
+object AppMasterRuntimeEnvironment {
+
+ def props(
+ masters: Iterable[ActorPath], app: AppDescription, appContextInput: AppMasterContext)
+ : Props = {
+
+ val master = (appId: AppId, masterProxy: MasterActorRef) =>
+ MasterWithExecutorSystemProvider.props(appId, masterProxy)
+
+ val appMaster = (appContext: AppMasterContext, app: AppDescription) =>
+ LazyStartAppMaster.props(appContext, app)
+
+ val masterConnectionKeeper = (master: MasterActorRef, registerAppMaster:
+ RegisterAppMaster, listener: ListenerActorRef) => Props(new MasterConnectionKeeper(
+ registerAppMaster, master, masterStatusListener = listener))
+
+ Props(new AppMasterRuntimeEnvironment(
+ appContextInput, app, masters, master, appMaster, masterConnectionKeeper))
+ }
+
+ /**
+ * This behavior like a AppMaster. Under the hood, It start start the real AppMaster in a lazy
+ * way. When real AppMaster is not started yet, all messages are stashed. The stashed
+ * messages are forwarded to real AppMaster when the real AppMaster is started.
+ *
+ * Please use LazyStartAppMaster.props to construct this actor
+ *
+ * @param appMasterProps underlying AppMaster Props
+ */
+ private[appmaster]
+ class LazyStartAppMaster(appId: Int, appMasterProps: Props) extends Actor with Stash {
+
+ private val LOG = LogUtil.getLogger(getClass, app = appId)
+
+ def receive: Receive = null
+
+ context.become(startAppMaster)
+
+ def startAppMaster: Receive = {
+ case StartAppMaster =>
+ val appMaster = context.actorOf(appMasterProps, "appmaster")
+ context.watch(appMaster)
+ context.become(terminationWatch(appMaster) orElse appMasterService(appMaster))
+ unstashAll()
+ case _ =>
+ stash()
+ }
+
+ def terminationWatch(appMaster: ActorRef): Receive = {
+ case Terminated(appMaster) =>
+ LOG.error("appmaster is stopped")
+ context.stop(self)
+ }
+
+ def appMasterService(appMaster: ActorRef): Receive = {
+ case msg => appMaster forward msg
+ }
+ }
+
+ private[appmaster]
+ object LazyStartAppMaster {
+ def props(appContext: AppMasterContext, app: AppDescription): Props = {
+ val appMasterProps = Props(Class.forName(app.appMaster), appContext, app)
+ Props(new LazyStartAppMaster(appContext.appId, appMasterProps))
+ }
+ }
+
+ private[appmaster] case object StartAppMaster
+
+ /**
+ * This enhance Master by providing new service: StartExecutorSystems
+ *
+ * Please use MasterWithExecutorSystemProvider.props to construct this actor
+ *
+ */
+ private[appmaster]
+ class MasterWithExecutorSystemProvider(master: ActorRef, executorSystemProviderProps: Props)
+ extends Actor {
+
+ val executorSystemProvider: ActorRef = context.actorOf(executorSystemProviderProps)
+
+ override def receive: Receive = {
+ case request: StartExecutorSystems =>
+ executorSystemProvider forward request
+ case msg =>
+ master forward msg
+ }
+ }
+
+ private[appmaster]
+ object MasterWithExecutorSystemProvider {
+ def props(appId: Int, master: ActorRef): Props = {
+
+ val executorSystemLauncher = (appId: Int, session: Session) =>
+ Props(new ExecutorSystemLauncher(appId, session))
+
+ val scheduler = Props(new ExecutorSystemScheduler(appId, master, executorSystemLauncher))
+
+ Props(new MasterWithExecutorSystemProvider(master, scheduler))
+ }
+ }
+
+ private[appmaster] type AppId = Int
+ private[appmaster] type MasterActorRef = ActorRef
+ private[appmaster] type ListenerActorRef = ActorRef
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/cluster/appmaster/AppMasterRuntimeInfo.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/cluster/appmaster/AppMasterRuntimeInfo.scala b/core/src/main/scala/org/apache/gearpump/cluster/appmaster/AppMasterRuntimeInfo.scala
new file mode 100644
index 0000000..b3ec88c
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/cluster/appmaster/AppMasterRuntimeInfo.scala
@@ -0,0 +1,38 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.appmaster
+
+import akka.actor.ActorRef
+import com.typesafe.config.Config
+
+import org.apache.gearpump._
+import org.apache.gearpump.cluster.AppMasterRegisterData
+
+/** Run time info used to start an AppMaster */
+case class AppMasterRuntimeInfo(
+ appId: Int,
+ // AppName is the unique Id for an application
+ appName: String,
+ worker: ActorRef = null,
+ user: String = null,
+ submissionTime: TimeStamp = 0,
+ startTime: TimeStamp = 0,
+ finishTime: TimeStamp = 0,
+ config: Config = null)
+ extends AppMasterRegisterData
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/cluster/appmaster/ApplicationState.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/cluster/appmaster/ApplicationState.scala b/core/src/main/scala/org/apache/gearpump/cluster/appmaster/ApplicationState.scala
new file mode 100644
index 0000000..7240113
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/cluster/appmaster/ApplicationState.scala
@@ -0,0 +1,47 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.appmaster
+
+import org.apache.gearpump.cluster.{AppDescription, AppJar}
+
+/**
+ * This state for single application, it is be distributed across the masters.
+ */
+case class ApplicationState(
+ appId: Int, appName: String, attemptId: Int, app: AppDescription, jar: Option[AppJar],
+ username: String, state: Any) extends Serializable {
+
+ override def equals(other: Any): Boolean = {
+ other match {
+ case that: ApplicationState =>
+ if (appId == that.appId && attemptId == that.attemptId) {
+ true
+ } else {
+ false
+ }
+ case _ =>
+ false
+ }
+ }
+
+ override def hashCode: Int = {
+ import akka.routing.MurmurHash._
+ extendHash(appId, attemptId, startMagicA, startMagicB)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/cluster/appmaster/ExecutorSystem.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/cluster/appmaster/ExecutorSystem.scala b/core/src/main/scala/org/apache/gearpump/cluster/appmaster/ExecutorSystem.scala
new file mode 100644
index 0000000..5c44652
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/cluster/appmaster/ExecutorSystem.scala
@@ -0,0 +1,43 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.appmaster
+
+import akka.actor.{ActorRef, Address, PoisonPill}
+
+import org.apache.gearpump.cluster.scheduler.Resource
+import org.apache.gearpump.cluster.worker.WorkerId
+import org.apache.gearpump.util.ActorSystemBooter.BindLifeCycle
+
+case class WorkerInfo(workerId: WorkerId, ref: ActorRef)
+
+/**
+ * Configurations to start an executor system on remote machine
+ *
+ * @param address Remote address where we start an Actor System.
+ */
+case class ExecutorSystem(executorSystemId: Int, address: Address, daemon:
+ ActorRef, resource: Resource, worker: WorkerInfo) {
+ def bindLifeCycleWith(actor: ActorRef): Unit = {
+ daemon ! BindLifeCycle(actor)
+ }
+
+ def shutdown(): Unit = {
+ daemon ! PoisonPill
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/cluster/appmaster/ExecutorSystemLauncher.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/cluster/appmaster/ExecutorSystemLauncher.scala b/core/src/main/scala/org/apache/gearpump/cluster/appmaster/ExecutorSystemLauncher.scala
new file mode 100644
index 0000000..0c5dbff
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/cluster/appmaster/ExecutorSystemLauncher.scala
@@ -0,0 +1,114 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.appmaster
+
+import scala.concurrent.duration._
+
+import akka.actor._
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.AppMasterToWorker.LaunchExecutor
+import org.apache.gearpump.cluster.ExecutorJVMConfig
+import org.apache.gearpump.cluster.WorkerToAppMaster._
+import org.apache.gearpump.cluster.appmaster.ExecutorSystemLauncher._
+import org.apache.gearpump.cluster.appmaster.ExecutorSystemScheduler.{ExecutorSystemJvmConfig, Session}
+import org.apache.gearpump.cluster.scheduler.Resource
+import org.apache.gearpump.util.ActorSystemBooter.{ActorSystemRegistered, RegisterActorSystem}
+import org.apache.gearpump.util.{ActorSystemBooter, ActorUtil, Constants, LogUtil}
+
+/**
+ * This launches single executor system on target worker.
+ *
+ * Please use ExecutorSystemLauncher.props() to construct this actor
+ *
+ * @param session The session that request to launch executor system
+ */
+private[appmaster]
+class ExecutorSystemLauncher(appId: Int, session: Session) extends Actor {
+
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+
+ val scheduler = context.system.scheduler
+ implicit val executionContext = context.dispatcher
+
+ private val systemConfig = context.system.settings.config
+ val timeoutSetting = systemConfig.getInt(Constants.GEARPUMP_START_EXECUTOR_SYSTEM_TIMEOUT_MS)
+
+ val timeout = scheduler.scheduleOnce(timeoutSetting.milliseconds,
+ self, LaunchExecutorSystemTimeout(session))
+
+ def receive: Receive = waitForLaunchCommand
+
+ def waitForLaunchCommand: Receive = {
+ case LaunchExecutorSystem(worker, executorSystemId, resource) =>
+ val launcherPath = ActorUtil.getFullPath(context.system, self.path)
+ val jvmConfig = Option(session.executorSystemJvmConfig)
+ .map(getExecutorJvmConfig(_, s"app${appId}system${executorSystemId}", launcherPath)).orNull
+
+ val launch = LaunchExecutor(appId, executorSystemId, resource, jvmConfig)
+ LOG.info(s"Launching Executor ...appId: $appId, executorSystemId: $executorSystemId, " +
+ s"slots: ${resource.slots} on worker $worker")
+
+ worker.ref ! launch
+ context.become(waitForActorSystemToStart(sender, launch, worker, executorSystemId))
+ }
+
+ def waitForActorSystemToStart(
+ replyTo: ActorRef, launch: LaunchExecutor, worker: WorkerInfo, executorSystemId: Int)
+ : Receive = {
+ case RegisterActorSystem(systemPath) =>
+ import launch._
+ timeout.cancel()
+ LOG.info(s"Received RegisterActorSystem $systemPath for session ${session.requestor}")
+ sender ! ActorSystemRegistered(worker.ref)
+ val system =
+ ExecutorSystem(executorId, AddressFromURIString(systemPath), sender, resource, worker)
+ replyTo ! LaunchExecutorSystemSuccess(system, session)
+ context.stop(self)
+ case reject@ExecutorLaunchRejected(reason, ex) =>
+ LOG.error(s"Executor Launch ${launch.resource} failed reason: $reason", ex)
+ replyTo ! LaunchExecutorSystemRejected(launch.resource, reason, session)
+ context.stop(self)
+ case timeout: LaunchExecutorSystemTimeout =>
+ LOG.error(s"The Executor ActorSystem $executorSystemId has not been started in time")
+ replyTo ! timeout
+ context.stop(self)
+ }
+}
+
+private[appmaster]
+object ExecutorSystemLauncher {
+
+ case class LaunchExecutorSystem(worker: WorkerInfo, systemId: Int, resource: Resource)
+
+ case class LaunchExecutorSystemSuccess(system: ExecutorSystem, session: Session)
+
+ case class LaunchExecutorSystemRejected(resource: Resource, reason: Any, session: Session)
+
+ case class LaunchExecutorSystemTimeout(session: Session)
+
+ private def getExecutorJvmConfig(conf: ExecutorSystemJvmConfig, systemName: String,
+ reportBack: String): ExecutorJVMConfig = {
+ Option(conf).map { conf =>
+ import conf._
+ ExecutorJVMConfig(classPath, jvmArguments, classOf[ActorSystemBooter].getName,
+ Array(systemName, reportBack), jar, username, executorAkkaConfig)
+ }.getOrElse(null)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/cluster/appmaster/ExecutorSystemScheduler.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/cluster/appmaster/ExecutorSystemScheduler.scala b/core/src/main/scala/org/apache/gearpump/cluster/appmaster/ExecutorSystemScheduler.scala
new file mode 100644
index 0000000..d73cc2f
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/cluster/appmaster/ExecutorSystemScheduler.scala
@@ -0,0 +1,191 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.appmaster
+
+import org.apache.gearpump.cluster.worker.WorkerId
+
+import scala.concurrent.duration._
+
+import akka.actor._
+import com.typesafe.config.Config
+
+import org.apache.gearpump.cluster.AppMasterToMaster.RequestResource
+import org.apache.gearpump.cluster.MasterToAppMaster.ResourceAllocated
+import org.apache.gearpump.cluster._
+import org.apache.gearpump.cluster.appmaster.ExecutorSystemLauncher._
+import org.apache.gearpump.cluster.appmaster.ExecutorSystemScheduler._
+import org.apache.gearpump.cluster.scheduler.{ResourceAllocation, ResourceRequest}
+import org.apache.gearpump.util.{Constants, LogUtil}
+
+/**
+ * ExecutorSystem is also a type of resource, this class schedules ExecutorSystem for AppMaster.
+ * AppMaster can use this class to directly request a live executor actor systems. The communication
+ * in the background with Master and Worker is hidden from AppMaster.
+ *
+ * Please use ExecutorSystemScheduler.props() to construct this actor
+ */
+private[appmaster]
+class ExecutorSystemScheduler(appId: Int, masterProxy: ActorRef,
+ executorSystemLauncher: (Int, Session) => Props) extends Actor {
+
+ private val LOG = LogUtil.getLogger(getClass, app = appId)
+ implicit val timeout = Constants.FUTURE_TIMEOUT
+ implicit val actorSystem = context.system
+ var currentSystemId = 0
+
+ var resourceAgents = Map.empty[Session, ActorRef]
+
+ def receive: Receive = {
+ clientCommands orElse resourceAllocationMessageHandler orElse executorSystemMessageHandler
+ }
+
+ def clientCommands: Receive = {
+ case start: StartExecutorSystems =>
+ LOG.info(s"starting executor systems (ExecutorSystemConfig(${start.executorSystemConfig}), " +
+ s"Resources(${start.resources.mkString(",")}))")
+ val requestor = sender()
+ val executorSystemConfig = start.executorSystemConfig
+ val session = Session(requestor, executorSystemConfig)
+ val agent = resourceAgents.getOrElse(session,
+ context.actorOf(Props(new ResourceAgent(masterProxy, session))))
+ resourceAgents = resourceAgents + (session -> agent)
+
+ start.resources.foreach { resource =>
+ agent ! RequestResource(appId, resource)
+ }
+
+ case StopExecutorSystem(executorSystem) =>
+ executorSystem.shutdown
+ }
+
+ def resourceAllocationMessageHandler: Receive = {
+ case ResourceAllocatedForSession(allocations, session) =>
+ if (isSessionAlive(session)) {
+ allocations.foreach { resourceAllocation =>
+ val ResourceAllocation(resource, worker, workerId) = resourceAllocation
+
+ val launcher = context.actorOf(executorSystemLauncher(appId, session))
+ launcher ! LaunchExecutorSystem(WorkerInfo(workerId, worker), currentSystemId, resource)
+ currentSystemId = currentSystemId + 1
+ }
+ }
+ case ResourceAllocationTimeOut(session) =>
+ if (isSessionAlive(session)) {
+ resourceAgents = resourceAgents - session
+ session.requestor ! StartExecutorSystemTimeout
+ }
+ }
+
+ def executorSystemMessageHandler: Receive = {
+ case LaunchExecutorSystemSuccess(system, session) =>
+ if (isSessionAlive(session)) {
+ LOG.info("LaunchExecutorSystemSuccess, send back to " + session.requestor)
+ system.bindLifeCycleWith(self)
+ session.requestor ! ExecutorSystemStarted(system, session.executorSystemJvmConfig.jar)
+ } else {
+ LOG.error("We get a ExecutorSystem back, but resource requestor is no longer valid. " +
+ "Will shutdown the allocated system")
+ system.shutdown
+ }
+ case LaunchExecutorSystemTimeout(session) =>
+ if (isSessionAlive(session)) {
+ LOG.error(s"Failed to launch executor system for ${session.requestor} due to timeout")
+ session.requestor ! StartExecutorSystemTimeout
+ }
+
+ case LaunchExecutorSystemRejected(resource, reason, session) =>
+ if (isSessionAlive(session)) {
+ LOG.error(s"Failed to launch executor system, due to $reason, " +
+ s"will ask master to allocate new resources $resource")
+ resourceAgents.get(session).map { resourceAgent: ActorRef =>
+ resourceAgent ! RequestResource(appId, ResourceRequest(resource, WorkerId.unspecified))
+ }
+ }
+ }
+
+ private def isSessionAlive(session: Session): Boolean = {
+ Option(session).flatMap(session => resourceAgents.get(session)).nonEmpty
+ }
+}
+
+object ExecutorSystemScheduler {
+
+ case class StartExecutorSystems(
+ resources: Array[ResourceRequest], executorSystemConfig: ExecutorSystemJvmConfig)
+
+ case class ExecutorSystemStarted(system: ExecutorSystem, boundedJar: Option[AppJar])
+
+ case class StopExecutorSystem(system: ExecutorSystem)
+
+ case object StartExecutorSystemTimeout
+
+ case class ExecutorSystemJvmConfig(classPath: Array[String], jvmArguments: Array[String],
+ jar: Option[AppJar], username: String, executorAkkaConfig: Config = null)
+
+ /**
+ * For each client which ask for an executor system, the scheduler will create a session for it.
+ *
+ */
+ private[appmaster]
+ case class Session(requestor: ActorRef, executorSystemJvmConfig: ExecutorSystemJvmConfig)
+
+ /**
+ * This is a agent for session to request resource
+ *
+ * @param session the original requester of the resource requests
+ */
+ private[appmaster]
+ class ResourceAgent(master: ActorRef, session: Session) extends Actor {
+ private var resourceRequestor: ActorRef = null
+ var timeOutClock: Cancellable = null
+ private var unallocatedResource: Int = 0
+
+ import context.dispatcher
+
+ import org.apache.gearpump.util.Constants._
+
+ val timeout = context.system.settings.config.getInt(GEARPUMP_RESOURCE_ALLOCATION_TIMEOUT)
+
+ def receive: Receive = {
+ case request: RequestResource =>
+ unallocatedResource += request.request.resource.slots
+ Option(timeOutClock).map(_.cancel)
+ timeOutClock = context.system.scheduler.scheduleOnce(
+ timeout.seconds, self, ResourceAllocationTimeOut(session))
+ resourceRequestor = sender
+ master ! request
+ case ResourceAllocated(allocations) =>
+ unallocatedResource -= allocations.map(_.resource.slots).sum
+ resourceRequestor forward ResourceAllocatedForSession(allocations, session)
+ case timeout: ResourceAllocationTimeOut =>
+ if (unallocatedResource > 0) {
+ resourceRequestor ! ResourceAllocationTimeOut(session)
+ // We will not receive any ResourceAllocation after timeout
+ context.stop(self)
+ }
+ }
+ }
+
+ private[ExecutorSystemScheduler]
+ case class ResourceAllocatedForSession(resource: Array[ResourceAllocation], session: Session)
+
+ private[ExecutorSystemScheduler]
+ case class ResourceAllocationTimeOut(session: Session)
+
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/cluster/appmaster/MasterConnectionKeeper.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/cluster/appmaster/MasterConnectionKeeper.scala b/core/src/main/scala/org/apache/gearpump/cluster/appmaster/MasterConnectionKeeper.scala
new file mode 100644
index 0000000..fd2d11a
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/cluster/appmaster/MasterConnectionKeeper.scala
@@ -0,0 +1,98 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.appmaster
+
+import java.util.concurrent.TimeUnit
+import scala.concurrent.duration.FiniteDuration
+
+import akka.actor._
+
+import org.apache.gearpump.cluster.AppMasterToMaster.RegisterAppMaster
+import org.apache.gearpump.cluster.MasterToAppMaster.AppMasterRegistered
+import org.apache.gearpump.cluster.appmaster.MasterConnectionKeeper.AppMasterRegisterTimeout
+import org.apache.gearpump.cluster.appmaster.MasterConnectionKeeper.MasterConnectionStatus.{MasterConnected, MasterStopped}
+import org.apache.gearpump.cluster.master.MasterProxy.{MasterRestarted, WatchMaster}
+import org.apache.gearpump.util.LogUtil
+
+/**
+ * Watches the liveness of Master.
+ *
+ * When Master is restarted, it sends RegisterAppMaster to the new Master instance.
+ * If Master is stopped, it sends the MasterConnectionStatus to listener
+ *
+ * please use MasterConnectionKeeper.props() to construct this actor
+ */
+private[appmaster]
+class MasterConnectionKeeper(
+ register: RegisterAppMaster, masterProxy: ActorRef, masterStatusListener: ActorRef)
+ extends Actor {
+
+ import context.dispatcher
+
+ private val LOG = LogUtil.getLogger(getClass)
+ private var master: ActorRef = null
+
+ // Subscribe self to masterProxy,
+ masterProxy ! WatchMaster(self)
+
+ def registerAppMaster: Cancellable = {
+ masterProxy ! register
+ context.system.scheduler.scheduleOnce(FiniteDuration(30, TimeUnit.SECONDS),
+ self, AppMasterRegisterTimeout)
+ }
+
+ context.become(waitMasterToConfirm(registerAppMaster))
+
+ def waitMasterToConfirm(cancelRegister: Cancellable): Receive = {
+ case AppMasterRegistered(appId) =>
+ cancelRegister.cancel()
+ masterStatusListener ! MasterConnected
+ context.become(masterLivenessListener)
+ case AppMasterRegisterTimeout =>
+ cancelRegister.cancel()
+ masterStatusListener ! MasterStopped
+ context.stop(self)
+ }
+
+ def masterLivenessListener: Receive = {
+ case MasterRestarted =>
+ LOG.info("Master restarted, re-registering appmaster....")
+ context.become(waitMasterToConfirm(registerAppMaster))
+ case MasterStopped =>
+ LOG.info("Master is dead, killing this AppMaster....")
+ masterStatusListener ! MasterStopped
+ context.stop(self)
+ }
+
+ def receive: Receive = null
+}
+
+private[appmaster] object MasterConnectionKeeper {
+
+ case object AppMasterRegisterTimeout
+
+ object MasterConnectionStatus {
+
+ case object MasterConnected
+
+ case object MasterStopped
+
+ }
+
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/cluster/client/ClientContext.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/cluster/client/ClientContext.scala b/core/src/main/scala/org/apache/gearpump/cluster/client/ClientContext.scala
new file mode 100644
index 0000000..245f1bc
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/cluster/client/ClientContext.scala
@@ -0,0 +1,185 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.client
+
+import java.util.concurrent.TimeUnit
+import scala.collection.JavaConverters._
+import scala.concurrent.duration.Duration
+import scala.concurrent.{Await, Future}
+import scala.util.Try
+
+import akka.actor.{ActorRef, ActorSystem}
+import akka.util.Timeout
+import com.typesafe.config.{Config, ConfigValueFactory}
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.MasterToAppMaster.{AppMastersData, ReplayFromTimestampWindowTrailingEdge}
+import org.apache.gearpump.cluster.MasterToClient.ReplayApplicationResult
+import org.apache.gearpump.cluster._
+import org.apache.gearpump.cluster.master.MasterProxy
+import org.apache.gearpump.jarstore.JarStoreService
+import org.apache.gearpump.util.Constants._
+import org.apache.gearpump.util.{ActorUtil, Constants, LogUtil, Util}
+
+/**
+ * ClientContext is a user facing util to submit/manage an application.
+ *
+ * TODO: add interface to query master here
+ */
+class ClientContext(config: Config, sys: ActorSystem, _master: ActorRef) {
+
+ def this(system: ActorSystem) = {
+ this(system.settings.config, system, null)
+ }
+
+ def this(config: Config) = {
+ this(config, null, null)
+ }
+
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+ private implicit val timeout = Timeout(5, TimeUnit.SECONDS)
+
+ implicit val system = Option(sys).getOrElse(ActorSystem(s"client${Util.randInt()}", config))
+ LOG.info(s"Starting system ${system.name}")
+ val shouldCleanupSystem = Option(sys).isEmpty
+
+ private val jarStoreService = JarStoreService.get(config)
+ jarStoreService.init(config, system)
+
+ private lazy val master: ActorRef = {
+ val masters = config.getStringList(Constants.GEARPUMP_CLUSTER_MASTERS).asScala
+ .flatMap(Util.parseHostList)
+ val master = Option(_master).getOrElse(system.actorOf(MasterProxy.props(masters),
+ s"masterproxy${system.name}"))
+ LOG.info(s"Creating master proxy ${master} for master list: $masters")
+ master
+ }
+
+ /**
+ * Submits an application with default jar setting. Use java property "gearpump.app.jar" if
+ * defined. Otherwise, it assumes the jar is on the target runtime classpath, thus will
+ * not send the jar across the wire.
+ */
+ def submit(app: Application): Int = {
+ submit(app, System.getProperty(GEARPUMP_APP_JAR))
+ }
+
+ def submit(app: Application, jar: String): Int = {
+ submit(app, jar, getExecutorNum())
+ }
+
+ def submit(app: Application, jar: String, executorNum: Int): Int = {
+ val client = getMasterClient
+ val appName = checkAndAddNamePrefix(app.name, System.getProperty(GEARPUMP_APP_NAME_PREFIX))
+ val submissionConfig = getSubmissionConfig(config)
+ .withValue(APPLICATION_EXECUTOR_NUMBER, ConfigValueFactory.fromAnyRef(executorNum))
+ val appDescription =
+ AppDescription(appName, app.appMaster.getName, app.userConfig, submissionConfig)
+ val appJar = Option(jar).map(loadFile)
+ client.submitApplication(appDescription, appJar)
+ }
+
+ private def getExecutorNum(): Int = {
+ Try(System.getProperty(APPLICATION_EXECUTOR_NUMBER).toInt).getOrElse(1)
+ }
+
+ private def getSubmissionConfig(config: Config): Config = {
+ ClusterConfig.filterOutDefaultConfig(config)
+ }
+
+ def replayFromTimestampWindowTrailingEdge(appId: Int): ReplayApplicationResult = {
+ import scala.concurrent.ExecutionContext.Implicits.global
+ val result = Await.result(
+ ActorUtil.askAppMaster[ReplayApplicationResult](master,
+ appId, ReplayFromTimestampWindowTrailingEdge(appId)), Duration.Inf)
+ result
+ }
+
+ def askAppMaster[T](appId: Int, msg: Any): Future[T] = {
+ import scala.concurrent.ExecutionContext.Implicits.global
+ ActorUtil.askAppMaster[T](master, appId, msg)
+ }
+
+ def listApps: AppMastersData = {
+ val client = getMasterClient
+ client.listApplications
+ }
+
+ def shutdown(appId: Int): Unit = {
+ val client = getMasterClient
+ client.shutdownApplication(appId)
+ }
+
+ def resolveAppID(appId: Int): ActorRef = {
+ val client = getMasterClient
+ client.resolveAppId(appId)
+ }
+
+ def close(): Unit = {
+ if (shouldCleanupSystem) {
+ LOG.info(s"Shutting down system ${system.name}")
+ system.terminate()
+ }
+ }
+
+ private def loadFile(jarPath: String): AppJar = {
+ val jarFile = new java.io.File(jarPath)
+ val path = jarStoreService.copyFromLocal(jarFile)
+ AppJar(jarFile.getName, path)
+ }
+
+ private def checkAndAddNamePrefix(appName: String, namePrefix: String): String = {
+ val fullName = if (namePrefix != null && namePrefix != "") {
+ namePrefix + "_" + appName
+ } else {
+ appName
+ }
+ if (!Util.validApplicationName(fullName)) {
+ close()
+ val error = s"The application name $appName is not a proper name. An app name can " +
+ "be a sequence of letters, numbers or underscore character \"_\""
+ throw new Exception(error)
+ }
+ fullName
+ }
+
+ private def getMasterClient: MasterClient = {
+ val timeout = Try(config.getInt(Constants.GEARPUMP_MASTERCLIENT_TIMEOUT)).getOrElse(90)
+ new MasterClient(master, akka.util.Timeout(timeout, TimeUnit.SECONDS))
+ }
+}
+
+object ClientContext {
+
+ def apply(): ClientContext = new ClientContext(ClusterConfig.default(), null, null)
+
+ def apply(system: ActorSystem): ClientContext = {
+ new ClientContext(ClusterConfig.default(), system, null)
+ }
+
+ def apply(system: ActorSystem, master: ActorRef): ClientContext = {
+ new ClientContext(ClusterConfig.default(), system, master)
+ }
+
+ def apply(config: Config): ClientContext = new ClientContext(config, null, null)
+
+ def apply(config: Config, system: ActorSystem, master: ActorRef): ClientContext = {
+ new ClientContext(config, system, master)
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/cluster/client/MasterClient.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/cluster/client/MasterClient.scala b/core/src/main/scala/org/apache/gearpump/cluster/client/MasterClient.scala
new file mode 100644
index 0000000..77ebedf
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/cluster/client/MasterClient.scala
@@ -0,0 +1,81 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.client
+
+import scala.concurrent.duration.Duration
+import scala.concurrent.{Await, Future}
+import scala.util.{Failure, Success}
+
+import akka.actor.ActorRef
+import akka.pattern.ask
+import akka.util.Timeout
+
+import org.apache.gearpump.cluster.ClientToMaster._
+import org.apache.gearpump.cluster.MasterToAppMaster.{AppMastersData, AppMastersDataRequest}
+import org.apache.gearpump.cluster.MasterToClient.{ResolveAppIdResult, ShutdownApplicationResult, SubmitApplicationResult}
+import org.apache.gearpump.cluster.{AppDescription, AppJar}
+
+/**
+ * Client to inter-operate with Master node.
+ *
+ * NOTE: Stateless, thread safe
+ */
+class MasterClient(master: ActorRef, timeout: Timeout) {
+ implicit val masterClientTimeout = timeout
+
+ def submitApplication(app: AppDescription, appJar: Option[AppJar]): Int = {
+ val result = Await.result(
+ (master ? SubmitApplication(app, appJar)).asInstanceOf[Future[SubmitApplicationResult]],
+ Duration.Inf)
+ val appId = result.appId match {
+ case Success(appId) =>
+ // scalastyle:off println
+ Console.println(s"Submit application succeed. The application id is $appId")
+ // scalastyle:on println
+ appId
+ case Failure(ex) => throw ex
+ }
+ appId
+ }
+
+ def resolveAppId(appId: Int): ActorRef = {
+ val result = Await.result(
+ (master ? ResolveAppId(appId)).asInstanceOf[Future[ResolveAppIdResult]], Duration.Inf)
+ result.appMaster match {
+ case Success(appMaster) => appMaster
+ case Failure(ex) => throw ex
+ }
+ }
+
+ def shutdownApplication(appId: Int): Unit = {
+ val result = Await.result(
+ (master ? ShutdownApplication(appId)).asInstanceOf[Future[ShutdownApplicationResult]],
+ Duration.Inf)
+ result.appId match {
+ case Success(_) =>
+ case Failure(ex) => throw ex
+ }
+ }
+
+ def listApplications: AppMastersData = {
+ val result = Await.result(
+ (master ? AppMastersDataRequest).asInstanceOf[Future[AppMastersData]], Duration.Inf)
+ result
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/cluster/main/ArgumentsParser.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/cluster/main/ArgumentsParser.scala b/core/src/main/scala/org/apache/gearpump/cluster/main/ArgumentsParser.scala
new file mode 100644
index 0000000..02c6f1a
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/cluster/main/ArgumentsParser.scala
@@ -0,0 +1,139 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.main
+
+import org.apache.gearpump.cluster.main.ArgumentsParser.Syntax
+
+case class CLIOption[+T](
+ description: String = "", required: Boolean = false, defaultValue: Option[T] = None)
+
+class ParseResult(optionMap: Map[String, String], remainArguments: Array[String]) {
+ def getInt(key: String): Int = optionMap.get(key).get.toInt
+
+ def getString(key: String): String = optionMap.get(key).get
+
+ def getBoolean(key: String): Boolean = optionMap.get(key).get.toBoolean
+
+ def exists(key: String): Boolean = !(optionMap.getOrElse(key, "").isEmpty)
+
+ def remainArgs: Array[String] = this.remainArguments
+}
+
+/**
+ * Parser for command line arguments
+ *
+ * Grammar: -option1 value1 -option2 value3 -flag1 -flag2 remainArg1 remainArg2...
+ */
+trait ArgumentsParser {
+
+ val ignoreUnknownArgument = false
+
+ // scalastyle:off println
+ def help(): Unit = {
+ Console.println(s"\nHelp: $description")
+ var usage = List.empty[String]
+ options.map(kv => if (kv._2.required) {
+ usage = usage :+ s"-${kv._1} (required:${kv._2.required})${kv._2.description}"
+ } else {
+ usage = usage :+ s"-${kv._1} (required:${kv._2.required}, " +
+ s"default:${kv._2.defaultValue.getOrElse("")})${kv._2.description}"
+ })
+ usage :+= remainArgs.map(k => s"<$k>").mkString(" ")
+ usage.foreach(Console.println(_))
+ }
+ // scalastyle:on println
+
+ def parse(args: Array[String]): ParseResult = {
+ val syntax = Syntax(options, remainArgs, ignoreUnknownArgument)
+ ArgumentsParser.parse(syntax, args)
+ }
+
+ val description: String = ""
+ val options: Array[(String, CLIOption[Any])] = Array.empty[(String, CLIOption[Any])]
+ val remainArgs: Array[String] = Array.empty[String]
+}
+
+object ArgumentsParser {
+
+ case class Syntax(
+ val options: Array[(String, CLIOption[Any])], val remainArgs: Array[String],
+ val ignoreUnknownArgument: Boolean)
+
+ def parse(syntax: Syntax, args: Array[String]): ParseResult = {
+ import syntax.{ignoreUnknownArgument, options, remainArgs}
+ var config = Map.empty[String, String]
+ var remain = Array.empty[String]
+
+ def doParse(argument: List[String]): Unit = {
+ argument match {
+ case Nil => Unit // true if everything processed successfully
+
+ case key :: value :: rest if key.startsWith("-") && !value.startsWith("-") =>
+ val fixedKey = key.substring(1)
+ if (!options.map(_._1).contains(fixedKey)) {
+ if (!ignoreUnknownArgument) {
+ throw new Exception(s"found unknown option $fixedKey")
+ } else {
+ remain ++= Array(key, value)
+ }
+ } else {
+ config += fixedKey -> value
+ }
+ doParse(rest)
+
+ case key :: rest if key.startsWith("-") =>
+ val fixedKey = key.substring(1)
+ if (!options.map(_._1).contains(fixedKey)) {
+ throw new Exception(s"found unknown option $fixedKey")
+ } else {
+ config += fixedKey -> "true"
+ }
+ doParse(rest)
+
+ case value :: rest =>
+ // scalastyle:off println
+ Console.err.println(s"Warning: get unknown argument $value, maybe it is a main class")
+ // scalastyle:on println
+ remain ++= value :: rest
+ doParse(Nil)
+ }
+ }
+ doParse(args.toList)
+
+ options.foreach { pair =>
+ val (key, option) = pair
+ if (!config.contains(key) && !option.required) {
+ config += key -> option.defaultValue.getOrElse("").toString
+ }
+ }
+
+ options.foreach { pair =>
+ val (key, value) = pair
+ if (config.get(key).isEmpty) {
+ throw new Exception(s"Missing option ${key}...")
+ }
+ }
+
+ if (remain.length < remainArgs.length) {
+ throw new Exception(s"Missing arguments ...")
+ }
+
+ new ParseResult(config, remain)
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/cluster/master/AppMasterLauncher.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/cluster/master/AppMasterLauncher.scala b/core/src/main/scala/org/apache/gearpump/cluster/master/AppMasterLauncher.scala
new file mode 100644
index 0000000..9305d5c
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/cluster/master/AppMasterLauncher.scala
@@ -0,0 +1,148 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.master
+
+import java.util.concurrent.{TimeUnit, TimeoutException}
+import org.apache.gearpump.cluster.worker.WorkerId
+
+import scala.collection.JavaConverters._
+import scala.concurrent.duration.Duration
+import scala.util.{Failure, Success}
+
+import akka.actor.{Actor, ActorRef, Props, _}
+import com.typesafe.config.Config
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.AppMasterToMaster.RequestResource
+import org.apache.gearpump.cluster.AppMasterToWorker.{LaunchExecutor, ShutdownExecutor}
+import org.apache.gearpump.cluster.MasterToAppMaster.ResourceAllocated
+import org.apache.gearpump.cluster.MasterToClient.SubmitApplicationResult
+import org.apache.gearpump.cluster.WorkerToAppMaster.ExecutorLaunchRejected
+import org.apache.gearpump.cluster.appmaster.{AppMasterRuntimeEnvironment, AppMasterRuntimeInfo, WorkerInfo}
+import org.apache.gearpump.cluster.scheduler.{Resource, ResourceAllocation, ResourceRequest}
+import org.apache.gearpump.cluster.{AppDescription, AppJar, _}
+import org.apache.gearpump.transport.HostPort
+import org.apache.gearpump.util.ActorSystemBooter._
+import org.apache.gearpump.util.Constants._
+import org.apache.gearpump.util.{ActorSystemBooter, ActorUtil, LogUtil, Util}
+
+/**
+ *
+ * AppMasterLauncher is a child Actor of AppManager, it is responsible
+ * to launch the AppMaster on the cluster.
+ */
+class AppMasterLauncher(
+ appId: Int, executorId: Int, app: AppDescription,
+ jar: Option[AppJar], username: String, master: ActorRef, client: Option[ActorRef])
+ extends Actor {
+ private val LOG: Logger = LogUtil.getLogger(getClass, app = appId)
+
+ val scheduler = context.system.scheduler
+ val systemConfig = context.system.settings.config
+ val TIMEOUT = Duration(15, TimeUnit.SECONDS)
+
+ val appMasterAkkaConfig: Config = app.clusterConfig
+
+ LOG.info(s"Ask Master resource to start AppMaster $appId...")
+ master ! RequestResource(appId, ResourceRequest(Resource(1), WorkerId.unspecified))
+
+ def receive: Receive = waitForResourceAllocation
+
+ def waitForResourceAllocation: Receive = {
+ case ResourceAllocated(allocations) =>
+
+ val ResourceAllocation(resource, worker, workerId) = allocations(0)
+ LOG.info(s"Resource allocated for appMaster $appId on worker ${workerId}(${worker.path})")
+
+ val submissionTime = System.currentTimeMillis()
+
+ val appMasterInfo = AppMasterRuntimeInfo(appId, app.name, worker, username,
+ submissionTime, config = appMasterAkkaConfig)
+ val workerInfo = WorkerInfo(workerId, worker)
+ val appMasterContext =
+ AppMasterContext(appId, username, resource, workerInfo, jar, null, appMasterInfo)
+ LOG.info(s"Try to launch a executor for AppMaster on worker ${workerId} for app $appId")
+ val name = ActorUtil.actorNameForExecutor(appId, executorId)
+ val selfPath = ActorUtil.getFullPath(context.system, self.path)
+
+ val jvmSetting =
+ Util.resolveJvmSetting(appMasterAkkaConfig.withFallback(systemConfig)).appMater
+ val executorJVM = ExecutorJVMConfig(jvmSetting.classPath, jvmSetting.vmargs,
+ classOf[ActorSystemBooter].getName, Array(name, selfPath), jar,
+ username, appMasterAkkaConfig)
+
+ worker ! LaunchExecutor(appId, executorId, resource, executorJVM)
+ context.become(waitForActorSystemToStart(worker, appMasterContext, app.userConfig, resource))
+ }
+
+ def waitForActorSystemToStart(
+ worker: ActorRef, appContext: AppMasterContext, user: UserConfig, resource: Resource)
+ : Receive = {
+ case ExecutorLaunchRejected(reason, ex) =>
+ LOG.error(s"Executor Launch failed reason: $reason", ex)
+ LOG.info(s"reallocate resource $resource to start appmaster")
+ master ! RequestResource(appId, ResourceRequest(resource, WorkerId.unspecified))
+ context.become(waitForResourceAllocation)
+ case RegisterActorSystem(systemPath) =>
+ LOG.info(s"Received RegisterActorSystem $systemPath for AppMaster")
+ sender ! ActorSystemRegistered(worker)
+
+ val masterAddress = systemConfig.getStringList(GEARPUMP_CLUSTER_MASTERS)
+ .asScala.map(HostPort(_)).map(ActorUtil.getMasterActorPath)
+ sender ! CreateActor(
+ AppMasterRuntimeEnvironment.props(masterAddress, app, appContext), s"appdaemon$appId")
+
+ import context.dispatcher
+ val appMasterTimeout = scheduler.scheduleOnce(TIMEOUT, self,
+ CreateActorFailed(app.appMaster, new TimeoutException))
+ context.become(waitForAppMasterToStart(worker, appMasterTimeout))
+ }
+
+ def waitForAppMasterToStart(worker: ActorRef, cancel: Cancellable): Receive = {
+ case ActorCreated(appMaster, _) =>
+ cancel.cancel()
+ sender ! BindLifeCycle(appMaster)
+ LOG.info(s"AppMaster is created, mission complete...")
+ replyToClient(SubmitApplicationResult(Success(appId)))
+ context.stop(self)
+ case CreateActorFailed(name, reason) =>
+ cancel.cancel()
+ worker ! ShutdownExecutor(appId, executorId, reason.getMessage)
+ replyToClient(SubmitApplicationResult(Failure(reason)))
+ context.stop(self)
+ }
+
+ def replyToClient(result: SubmitApplicationResult): Unit = {
+ if (client.isDefined) {
+ client.get.tell(result, master)
+ }
+ }
+}
+
+object AppMasterLauncher extends AppMasterLauncherFactory {
+ def props(appId: Int, executorId: Int, app: AppDescription, jar: Option[AppJar],
+ username: String, master: ActorRef, client: Option[ActorRef]): Props = {
+ Props(new AppMasterLauncher(appId, executorId, app, jar, username, master, client))
+ }
+}
+
+trait AppMasterLauncherFactory {
+ def props(appId: Int, executorId: Int, app: AppDescription, jar: Option[AppJar],
+ username: String, master: ActorRef, client: Option[ActorRef]): Props
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/cluster/master/MasterProxy.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/cluster/master/MasterProxy.scala b/core/src/main/scala/org/apache/gearpump/cluster/master/MasterProxy.scala
new file mode 100644
index 0000000..e2ee00e
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/cluster/master/MasterProxy.scala
@@ -0,0 +1,134 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.master
+
+import scala.concurrent.duration.FiniteDuration
+
+import akka.actor._
+import org.slf4j.Logger
+
+import org.apache.gearpump.transport.HostPort
+import org.apache.gearpump.util.{ActorUtil, LogUtil}
+
+/**
+ * This works with Master HA. When there are multiple Master nodes,
+ * This will find a active one.
+ */
+class MasterProxy(masters: Iterable[ActorPath], timeout: FiniteDuration)
+ extends Actor with Stash {
+ import org.apache.gearpump.cluster.master.MasterProxy._
+
+ val LOG: Logger = LogUtil.getLogger(getClass, name = self.path.name)
+
+ val contacts = masters.map { url =>
+ LOG.info(s"Contacts point URL: $url")
+ context.actorSelection(url)
+ }
+
+ var watchers: List[ActorRef] = List.empty[ActorRef]
+
+ import context.dispatcher
+
+ def findMaster(): Cancellable = {
+ repeatActionUtil(timeout) {
+ contacts foreach { contact =>
+ LOG.info(s"sending identity to $contact")
+ contact ! Identify(None)
+ }
+ }
+ }
+
+ context.become(establishing(findMaster()))
+
+ LOG.info("Master Proxy is started...")
+
+ override def postStop(): Unit = {
+ watchers.foreach(_ ! MasterStopped)
+ super.postStop()
+ }
+
+ override def receive: Receive = {
+ case _ =>
+ }
+
+ def establishing(findMaster: Cancellable): Actor.Receive = {
+ case ActorIdentity(_, Some(receptionist)) =>
+ context watch receptionist
+ LOG.info("Connected to [{}]", receptionist.path)
+ context.watch(receptionist)
+
+ watchers.foreach(_ ! MasterRestarted)
+ unstashAll()
+ findMaster.cancel()
+ context.become(active(receptionist) orElse messageHandler(receptionist))
+ case ActorIdentity(_, None) => // ok, use another instead
+ case msg =>
+ LOG.info(s"Stashing ${msg.getClass.getSimpleName}")
+ stash()
+ }
+
+ def active(receptionist: ActorRef): Actor.Receive = {
+ case Terminated(receptionist) =>
+ LOG.info("Lost contact with [{}], restablishing connection", receptionist)
+ context.become(establishing(findMaster))
+ case _: ActorIdentity => // ok, from previous establish, already handled
+ case WatchMaster(watcher) =>
+ watchers = watchers :+ watcher
+ }
+
+ def messageHandler(master: ActorRef): Receive = {
+ case msg =>
+ LOG.debug(s"Get msg ${msg.getClass.getSimpleName}, forwarding to ${master.path}")
+ master forward msg
+ }
+
+ def scheduler: Scheduler = context.system.scheduler
+ import scala.concurrent.duration._
+ private def repeatActionUtil(timeout: FiniteDuration)(action: => Unit): Cancellable = {
+ val send = scheduler.schedule(0.seconds, 2.seconds)(action)
+ val suicide = scheduler.scheduleOnce(timeout) {
+ send.cancel()
+ self ! PoisonPill
+ }
+
+ new Cancellable {
+ def cancel(): Boolean = {
+ val result1 = send.cancel()
+ val result2 = suicide.cancel()
+ result1 && result2
+ }
+
+ def isCancelled: Boolean = {
+ send.isCancelled && suicide.isCancelled
+ }
+ }
+ }
+}
+
+object MasterProxy {
+ case object MasterRestarted
+ case object MasterStopped
+ case class WatchMaster(watcher: ActorRef)
+
+ import scala.concurrent.duration._
+ def props(masters: Iterable[HostPort], duration: FiniteDuration = 30.seconds): Props = {
+ val contacts = masters.map(ActorUtil.getMasterActorPath(_))
+ Props(new MasterProxy(contacts, duration))
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/cluster/master/MasterSummary.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/cluster/master/MasterSummary.scala b/core/src/main/scala/org/apache/gearpump/cluster/master/MasterSummary.scala
new file mode 100644
index 0000000..d182b22
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/cluster/master/MasterSummary.scala
@@ -0,0 +1,51 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.master
+
+import org.apache.gearpump.util.HistoryMetricsService.HistoryMetricsConfig
+
+/** Master status. Synced means all masters are live and synced. */
+object MasterStatus {
+ type Type = String
+ val Synced = "synced"
+ val UnSynced = "unsynced"
+}
+
+case class MasterNode(host: String, port: Int) {
+ def toTuple: (String, Int) = {
+ (host, port)
+ }
+}
+
+/**
+ * Master information returned for REST API call
+ */
+case class MasterSummary(
+ leader: MasterNode,
+ cluster: List[MasterNode],
+ aliveFor: Long,
+ logFile: String,
+ jarStore: String,
+ masterStatus: MasterStatus.Type,
+ homeDirectory: String,
+ activities: List[MasterActivity],
+ jvmName: String,
+ historyMetricsConfig: HistoryMetricsConfig = null)
+
+case class MasterActivity(time: Long, event: String)
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/cluster/scheduler/Resource.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/cluster/scheduler/Resource.scala b/core/src/main/scala/org/apache/gearpump/cluster/scheduler/Resource.scala
new file mode 100644
index 0000000..c21d396
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/cluster/scheduler/Resource.scala
@@ -0,0 +1,79 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.scheduler
+
+import akka.actor.ActorRef
+import org.apache.gearpump.cluster.worker.WorkerId
+
+case class Resource(slots: Int) {
+
+ // scalastyle:off spaces.after.plus
+ def +(other: Resource): Resource = Resource(slots + other.slots)
+ // scalastyle:on spaces.after.plus
+
+ def -(other: Resource): Resource = Resource(slots - other.slots)
+
+ def >(other: Resource): Boolean = slots > other.slots
+
+ def >=(other: Resource): Boolean = !(this < other)
+
+ def <(other: Resource): Boolean = slots < other.slots
+
+ def <=(other: Resource): Boolean = !(this > other)
+
+ def isEmpty: Boolean = {
+ slots == 0
+ }
+}
+
+/**
+ * Each streaming job can have a priority, the job with higher priority
+ * will get scheduled resource earlier than those with lower priority.
+ */
+object Priority extends Enumeration {
+ type Priority = Value
+ val LOW, NORMAL, HIGH = Value
+}
+
+/**
+ * Relaxation.ONEWORKER means only resource (slot) from that worker will be accepted by
+ * the requestor application job.
+ */
+object Relaxation extends Enumeration {
+ type Relaxation = Value
+
+ // Option ONEWORKER allow user to schedule a task on specific worker.
+ val ANY, ONEWORKER, SPECIFICWORKER = Value
+}
+
+import org.apache.gearpump.cluster.scheduler.Priority._
+import org.apache.gearpump.cluster.scheduler.Relaxation._
+
+case class ResourceRequest(
+ resource: Resource, workerId: WorkerId, priority: Priority = NORMAL,
+ relaxation: Relaxation = ANY, executorNum: Int = 1)
+
+case class ResourceAllocation(resource: Resource, worker: ActorRef, workerId: WorkerId)
+
+object Resource {
+ def empty: Resource = new Resource(0)
+
+ def min(res1: Resource, res2: Resource): Resource = if (res1.slots < res2.slots) res1 else res2
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/cluster/worker/ExecutorProcessLauncher.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/cluster/worker/ExecutorProcessLauncher.scala b/core/src/main/scala/org/apache/gearpump/cluster/worker/ExecutorProcessLauncher.scala
new file mode 100644
index 0000000..58f7dd8
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/cluster/worker/ExecutorProcessLauncher.scala
@@ -0,0 +1,56 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.worker
+
+import com.typesafe.config.Config
+
+import org.apache.gearpump.cluster.scheduler.Resource
+import org.apache.gearpump.util.RichProcess
+
+/**
+ * ExecutorProcessLauncher is used to launch a process for Executor using given parameters.
+ *
+ * User can implement this interface to decide the behavior of launching a process.
+ * Set "gearpump.worker.executor-process-launcher" to your implemented class name.
+ */
+trait ExecutorProcessLauncher {
+ val config: Config
+
+ /**
+ * This function launches a process for Executor using given parameters.
+ *
+ * @param appId The appId of the executor to be launched
+ * @param executorId The executorId of the executor to be launched
+ * @param resource The resource allocated for that executor
+ * @param options The command options
+ * @param classPath The classpath of the process
+ * @param mainClass The main class of the process
+ * @param arguments The rest arguments
+ */
+ def createProcess(
+ appId: Int, executorId: Int, resource: Resource, config: Config, options: Array[String],
+ classPath: Array[String], mainClass: String, arguments: Array[String]): RichProcess
+
+ /**
+ * This function will clean resources for a launched process.
+ * @param appId The appId of the launched executor
+ * @param executorId The executorId of launched executor
+ */
+ def cleanProcess(appId: Int, executorId: Int): Unit
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/cluster/worker/WorkerId.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/cluster/worker/WorkerId.scala b/core/src/main/scala/org/apache/gearpump/cluster/worker/WorkerId.scala
new file mode 100644
index 0000000..93213e4
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/cluster/worker/WorkerId.scala
@@ -0,0 +1,63 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.worker
+
+/**
+ * WorkerId is used to uniquely track a worker machine.
+ *
+ * @param sessionId sessionId is assigned by Master node for easy tracking. It is possible that
+ * sessionId is **NOT** unique, so always use WorkerId for comparison.
+ * @param registerTime the timestamp when a worker node register itself to master node
+ */
+case class WorkerId(sessionId: Int, registerTime: Long)
+
+object WorkerId {
+ val unspecified: WorkerId = new WorkerId(-1, 0L)
+
+ def render(workerId: WorkerId): String = {
+ workerId.registerTime + "_" + workerId.sessionId
+ }
+
+ def parse(str: String): WorkerId = {
+ val pair = str.split("_")
+ new WorkerId(pair(1).toInt, pair(0).toLong)
+ }
+
+ implicit val workerIdOrdering: Ordering[WorkerId] = {
+ new Ordering[WorkerId] {
+
+ /** Compare timestamp first, then id */
+ override def compare(x: WorkerId, y: WorkerId): Int = {
+ if (x.registerTime < y.registerTime) {
+ -1
+ } else if (x.registerTime == y.registerTime) {
+ if (x.sessionId < y.sessionId) {
+ -1
+ } else if (x.sessionId == y.sessionId) {
+ 0
+ } else {
+ 1
+ }
+ } else {
+ 1
+ }
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/cluster/worker/WorkerSummary.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/cluster/worker/WorkerSummary.scala b/core/src/main/scala/org/apache/gearpump/cluster/worker/WorkerSummary.scala
new file mode 100644
index 0000000..f4c0587
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/cluster/worker/WorkerSummary.scala
@@ -0,0 +1,47 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.cluster.worker
+import org.apache.gearpump.util.HistoryMetricsService.HistoryMetricsConfig
+
+/**
+ * Worker summary information for REST API.
+ */
+case class WorkerSummary(
+ workerId: WorkerId,
+ state: String,
+ actorPath: String,
+ aliveFor: Long,
+ logFile: String,
+ executors: Array[ExecutorSlots],
+ totalSlots: Int,
+ availableSlots: Int,
+ homeDirectory: String,
+ jvmName: String,
+ // Id used to uniquely identity this worker process in low level resource manager like YARN.
+ resourceManagerContainerId: String,
+ historyMetricsConfig: HistoryMetricsConfig = null)
+
+object WorkerSummary {
+ def empty: WorkerSummary = {
+ WorkerSummary(WorkerId.unspecified, "", "", 0L, "",
+ Array.empty[ExecutorSlots], 0, 0, "", jvmName = "", resourceManagerContainerId = "")
+ }
+}
+
+case class ExecutorSlots(appId: Int, executorId: Int, slots: Int)
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/jarstore/JarStoreService.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/jarstore/JarStoreService.scala b/core/src/main/scala/org/apache/gearpump/jarstore/JarStoreService.scala
new file mode 100644
index 0000000..0ba9558
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/jarstore/JarStoreService.scala
@@ -0,0 +1,86 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.jarstore
+
+import java.io.File
+import java.net.URI
+import java.util.ServiceLoader
+import scala.collection.JavaConverters._
+
+import akka.actor.ActorSystem
+import com.typesafe.config.Config
+
+import org.apache.gearpump.util.{Constants, Util}
+
+case class FilePath(path: String)
+
+/**
+ * JarStoreService is used to manage the upload/download of binary files,
+ * like user submitted application jar.
+ */
+trait JarStoreService {
+ /**
+ * The scheme of the JarStoreService.
+ * Like "hdfs" for HDFS file system, and "file" for a local
+ * file system.
+ */
+ val scheme: String
+
+ /**
+ * Init the Jar Store.
+ */
+ def init(config: Config, system: ActorSystem)
+
+ /**
+ * This function will copy the local file to the remote JarStore, called from client side.
+ * @param localFile The local file
+ */
+ def copyFromLocal(localFile: File): FilePath
+
+ /**
+ * This function will copy the remote file to local file system, called from client side.
+ *
+ * @param localFile The destination of file path
+ * @param remotePath The remote file path from JarStore
+ */
+ def copyToLocalFile(localFile: File, remotePath: FilePath)
+}
+
+object JarStoreService {
+
+ /**
+ * Get a active JarStoreService by specifying a scheme.
+ *
+ * Please see config [[org.apache.gearpump.util.Constants#GEARPUMP_APP_JAR_STORE_ROOT_PATH]] for
+ * more information.
+ */
+ def get(config: Config): JarStoreService = {
+ val jarStoreRootPath = config.getString(Constants.GEARPUMP_APP_JAR_STORE_ROOT_PATH)
+ get(jarStoreRootPath)
+ }
+
+ private lazy val jarstoreServices: List[JarStoreService] = {
+ ServiceLoader.load(classOf[JarStoreService]).asScala.toList
+ }
+
+ private def get(rootPath: String): JarStoreService = {
+ val scheme = new URI(Util.resolvePath(rootPath)).getScheme
+ jarstoreServices.find(_.scheme == scheme).get
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/metrics/AkkaReporter.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/metrics/AkkaReporter.scala b/core/src/main/scala/org/apache/gearpump/metrics/AkkaReporter.scala
new file mode 100644
index 0000000..7010048
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/metrics/AkkaReporter.scala
@@ -0,0 +1,78 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.metrics
+
+import scala.collection.JavaConverters._
+
+import akka.actor.{ActorRef, ActorSystem}
+
+import io.gearpump.codahale.metrics.{Gauge => CodaGauge, MetricRegistry}
+import org.apache.gearpump.metrics.Metrics.{Counter => CounterData, Gauge => GaugeData, Histogram => HistogramData, Meter => MeterData}
+import org.apache.gearpump.metrics.MetricsReporterService.ReportTo
+import org.apache.gearpump.util.LogUtil
+
+/**
+ * A reporter class for logging metrics values to a remote actor periodically
+ */
+class AkkaReporter(
+ system: ActorSystem,
+ registry: MetricRegistry)
+ extends ReportTo {
+ private val LOG = LogUtil.getLogger(getClass)
+ LOG.info("Start Metrics AkkaReporter")
+
+ override def report(to: ActorRef): Unit = {
+ val counters = registry.getCounters()
+ val histograms = registry.getHistograms()
+ val meters = registry.getMeters()
+ val gauges = registry.getGauges()
+
+ counters.entrySet().asScala.foreach { pair =>
+ to ! CounterData(pair.getKey, pair.getValue.getCount)
+ }
+
+ histograms.entrySet().asScala.foreach { pair =>
+ val key = pair.getKey
+ val value = pair.getValue
+ val s = value.getSnapshot
+ to ! HistogramData(
+ key, s.getMean, s.getStdDev, s.getMedian,
+ s.get95thPercentile, s.get99thPercentile, s.get999thPercentile)
+ }
+
+ meters.entrySet().asScala.foreach { pair =>
+ val key = pair.getKey
+ val value = pair.getValue
+ to ! MeterData(key,
+ value.getCount,
+ value.getMeanRate,
+ value.getOneMinuteRate,
+ getRateUnit)
+ }
+
+ gauges.entrySet().asScala.foreach { kv =>
+ val value = kv.getValue.asInstanceOf[CodaGauge[Number]].getValue.longValue()
+ to ! GaugeData(kv.getKey, value)
+ }
+ }
+
+ private def getRateUnit: String = {
+ "events/s"
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/metrics/Counter.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/metrics/Counter.scala b/core/src/main/scala/org/apache/gearpump/metrics/Counter.scala
new file mode 100644
index 0000000..a6ce799
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/metrics/Counter.scala
@@ -0,0 +1,42 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.metrics
+
+import io.gearpump.codahale.metrics.{Counter => CodaHaleCounter}
+
+/**
+ * @see io.gearpump.codahale.metrics.Counter
+ */
+class Counter(val name: String, counter: CodaHaleCounter, sampleRate: Int = 1) {
+ private var sampleCount = 0L
+ private var toBeIncremented = 0L
+
+ def inc() {
+ inc(1)
+ }
+
+ def inc(n: Long) {
+ toBeIncremented += n
+ sampleCount += 1
+ if (null != counter && sampleCount % sampleRate == 0) {
+ counter.inc(toBeIncremented)
+ toBeIncremented = 0
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/metrics/Histogram.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/metrics/Histogram.scala b/core/src/main/scala/org/apache/gearpump/metrics/Histogram.scala
new file mode 100644
index 0000000..7d7e19b
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/metrics/Histogram.scala
@@ -0,0 +1,43 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.metrics
+
+import io.gearpump.codahale.metrics.{Histogram => CodaHaleHistogram}
+
+/**
+ * @see io.gearpump.codahale.metrics.Histogram
+ */
+class Histogram(val name: String, histogram: CodaHaleHistogram, sampleRate: Int = 1) {
+ private var sampleCount = 0L
+
+ def update(value: Long) {
+ sampleCount += 1
+ if (null != histogram && sampleCount % sampleRate == 0) {
+ histogram.update(value)
+ }
+ }
+
+ def getMean(): Double = {
+ histogram.getSnapshot.getMean
+ }
+
+ def getStdDev(): Double = {
+ histogram.getSnapshot.getStdDev
+ }
+}
\ No newline at end of file
[15/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/main/scala/io/gearpump/services/RestServices.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/main/scala/io/gearpump/services/RestServices.scala b/services/jvm/src/main/scala/io/gearpump/services/RestServices.scala
deleted file mode 100644
index d0fea30..0000000
--- a/services/jvm/src/main/scala/io/gearpump/services/RestServices.scala
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.services
-
-import scala.concurrent.Await
-import scala.concurrent.duration._
-
-import akka.actor.{ActorRef, ActorSystem}
-import akka.http.scaladsl.model.StatusCodes._
-import akka.http.scaladsl.server.Directives._
-import akka.http.scaladsl.server.{Route, _}
-import akka.stream.ActorMaterializer
-import akka.util.Timeout
-import org.apache.commons.lang.exception.ExceptionUtils
-
-import io.gearpump.jarstore.JarStoreService
-import io.gearpump.util.{Constants, LogUtil}
-// NOTE: This cannot be removed!!!
-import io.gearpump.services.util.UpickleUtil._
-
-/** Contains all REST API service endpoints */
-class RestServices(master: ActorRef, mat: ActorMaterializer, system: ActorSystem)
- extends RouteService {
-
- implicit val timeout = Constants.FUTURE_TIMEOUT
-
- private val config = system.settings.config
-
- private val jarStoreService = JarStoreService.get(config)
- jarStoreService.init(config, system)
-
- private val LOG = LogUtil.getLogger(getClass)
-
- private val securityEnabled = config.getBoolean(
- Constants.GEARPUMP_UI_SECURITY_AUTHENTICATION_ENABLED)
-
- private val supervisorPath = system.settings.config.getString(
- Constants.GEARPUMP_SERVICE_SUPERVISOR_PATH)
-
- private val myExceptionHandler: ExceptionHandler = ExceptionHandler {
- case ex: Throwable => {
- extractUri { uri =>
- LOG.error(s"Request to $uri could not be handled normally", ex)
- complete(InternalServerError, ExceptionUtils.getStackTrace(ex))
- }
- }
- }
-
- // Makes sure staticRoute is the final one, as it will try to lookup resource in local path
- // if there is no match in previous routes
- private val static = new StaticService(system, supervisorPath).route
-
- def supervisor: ActorRef = {
- if (supervisorPath == null || supervisorPath.isEmpty()) {
- null
- } else {
- val actorRef = system.actorSelection(supervisorPath).resolveOne()
- Await.result(actorRef, new Timeout(Duration.create(5, "seconds")).duration)
- }
- }
-
- override def route: Route = {
- if (securityEnabled) {
- val security = new SecurityService(services, system)
- handleExceptions(myExceptionHandler) {
- security.route ~ static
- }
- } else {
- handleExceptions(myExceptionHandler) {
- services.route ~ static
- }
- }
- }
-
- private def services: RouteService = {
-
- val admin = new AdminService(system)
- val masterService = new MasterService(master, jarStoreService, system)
- val worker = new WorkerService(master, system)
- val app = new AppMasterService(master, jarStoreService, system)
- val sup = new SupervisorService(master, supervisor, system)
-
- new RouteService {
- override def route: Route = {
- admin.route ~ sup.route ~ masterService.route ~ worker.route ~ app.route
- }
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/main/scala/io/gearpump/services/SecurityService.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/main/scala/io/gearpump/services/SecurityService.scala b/services/jvm/src/main/scala/io/gearpump/services/SecurityService.scala
deleted file mode 100644
index b1abf62..0000000
--- a/services/jvm/src/main/scala/io/gearpump/services/SecurityService.scala
+++ /dev/null
@@ -1,290 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.services
-
-import scala.concurrent.{ExecutionContext, Future}
-import scala.util.{Failure, Success, Try}
-
-import akka.actor.ActorSystem
-import akka.http.scaladsl.model.headers.{HttpChallenge, HttpCookie, HttpCookiePair}
-import akka.http.scaladsl.model.{RemoteAddress, StatusCodes, Uri}
-import akka.http.scaladsl.server.AuthenticationFailedRejection.{CredentialsMissing, CredentialsRejected}
-import akka.http.scaladsl.server.Directives._
-import akka.http.scaladsl.server._
-import akka.http.scaladsl.server.directives.FormFieldDirectives.FieldMagnet
-import akka.stream.Materializer
-import com.typesafe.config.Config
-import com.softwaremill.session.SessionDirectives._
-import com.softwaremill.session.SessionOptions._
-import com.softwaremill.session.{MultiValueSessionSerializer, SessionConfig, SessionManager}
-import upickle.default.write
-
-import io.gearpump.security.{Authenticator => BaseAuthenticator}
-import io.gearpump.services.SecurityService.{User, UserSession}
-import io.gearpump.services.security.oauth2.OAuth2Authenticator
-import io.gearpump.util.{Constants, LogUtil}
-// NOTE: This cannot be removed!!!
-import io.gearpump.services.util.UpickleUtil._
-
-/**
- * Security authentication endpoint.
- *
- * - When user cannot be authenticated, will reject with 401 AuthenticationFailedRejection
- * - When user can be authenticated, but are not authorized to access certail resource, will
- * return a 405 AuthorizationFailedRejection.
- * - When web UI frontend receive 401, it should redirect the UI to login page.
- * - When web UI receive 405,it should display errors like
- * "current user is not authorized to access this resource."
- *
- * The Authenticator used is pluggable, the current Authenticator is resolved by looking up
- * config path [[io.gearpump.util.Constants.GEARPUMP_UI_AUTHENTICATOR_CLASS]].
- *
- * See [[io.gearpump.security.Authenticator]] to find more info on custom Authenticator.
- */
-class SecurityService(inner: RouteService, implicit val system: ActorSystem) extends RouteService {
-
- // Use scheme "GearpumpBasic" to avoid popping up web browser native authentication box.
- private val challenge = HttpChallenge(scheme = "GearpumpBasic", realm = "gearpump",
- params = Map.empty)
-
- val LOG = LogUtil.getLogger(getClass, "AUDIT")
-
- private val config = system.settings.config
- private val sessionConfig = SessionConfig.fromConfig(config)
- private implicit val sessionManager: SessionManager[UserSession] =
- new SessionManager[UserSession](sessionConfig)
-
- private val authenticator = {
- val clazz = Class.forName(config.getString(Constants.GEARPUMP_UI_AUTHENTICATOR_CLASS))
- val constructor = clazz.getConstructor(classOf[Config])
- val authenticator = constructor.newInstance(config).asInstanceOf[BaseAuthenticator]
- authenticator
- }
-
- private def configToMap(config: Config, path: String) = {
- import scala.collection.JavaConverters._
- config.getConfig(path).root.unwrapped.asScala.toMap map { case (k, v) => k -> v.toString }
- }
-
- private val oauth2Providers: Map[String, String] = {
- if (config.getBoolean(Constants.GEARPUMP_UI_OAUTH2_AUTHENTICATOR_ENABLED)) {
- val map = configToMap(config, Constants.GEARPUMP_UI_OAUTH2_AUTHENTICATORS)
- map.keys.toList.map { key =>
- val iconPath = config.getString(s"${Constants.GEARPUMP_UI_OAUTH2_AUTHENTICATORS}.$key.icon")
- (key, iconPath)
- }.toMap
- } else {
- Map.empty[String, String]
- }
- }
-
- private def authenticate(user: String, pass: String)(implicit ec: ExecutionContext)
- : Future[Option[UserSession]] = {
- authenticator.authenticate(user, pass, ec).map { result =>
- if (result.authenticated) {
- Some(UserSession(user, result.permissionLevel))
- } else {
- None
- }
- }
- }
-
- private def rejectMissingCredentials: Route = {
- reject(AuthenticationFailedRejection(CredentialsMissing, challenge))
- }
-
- private def rejectWrongCredentials: Route = {
- reject(AuthenticationFailedRejection(CredentialsRejected, challenge))
- }
-
- private def requireAuthentication(inner: UserSession => Route): Route = {
- optionalSession(oneOff, usingCookiesOrHeaders) { sessionOption =>
- sessionOption match {
- case Some(session) => {
- inner(session)
- }
- case None =>
- rejectMissingCredentials
- }
- }
- }
-
- private def login(session: UserSession, ip: String, redirectToRoot: Boolean = false): Route = {
- setSession(oneOff, usingCookies, session) {
- val user = session.user
- // Default: 1 day
- val maxAgeMs = 1000 * sessionConfig.sessionMaxAgeSeconds.getOrElse(24 * 3600L)
- setCookie(HttpCookie.fromPair(HttpCookiePair("username", user), path = Some("/"),
- maxAge = Some(maxAgeMs))) {
- LOG.info(s"user $user login from $ip")
- if (redirectToRoot) {
- redirect(Uri("/"), StatusCodes.TemporaryRedirect)
- } else {
- complete(write(new User(user)))
- }
- }
- }
- }
-
- private def logout(user: UserSession, ip: String): Route = {
- invalidateSession(oneOff, usingCookies) { ctx =>
- LOG.info(s"user ${user.user} logout from $ip")
- ctx.complete(write(new User(user.user)))
- }
- }
-
- // Only admin are able to access operation like post/delete/put
- private def requireAuthorization(user: UserSession, route: => Route): Route = {
- // Valid user
- if (user.permissionLevel >= BaseAuthenticator.User.permissionLevel) {
- route
- } else {
- // Possibly a guest or not authenticated.
- (put | delete | post) {
- // Reject with 405 authorization error
- reject(AuthorizationFailedRejection)
- } ~
- get {
- route
- }
- }
- }
-
- private val unknownIp: Directive1[RemoteAddress] = {
- Directive[Tuple1[RemoteAddress]]{ inner =>
- inner(new Tuple1(RemoteAddress.Unknown))
- }
- }
-
- override val route: Route = {
-
- extractExecutionContext{implicit ec: ExecutionContext =>
- extractMaterializer{implicit mat: Materializer =>
- (extractClientIP | unknownIp) { ip =>
- pathPrefix("login") {
- pathEndOrSingleSlash {
- get {
- getFromResource("login/login.html")
- } ~
- post {
- // Guest account don't have permission to submit new application in UI
- formField(FieldMagnet('username.as[String])) {user: String =>
- formFields(FieldMagnet('password.as[String])) {pass: String =>
- val result = authenticate(user, pass)
- onSuccess(result) {
- case Some(session) =>
- login(session, ip.toString)
- case None =>
- rejectWrongCredentials
- }
- }
- }
- }
- } ~
- path ("oauth2" / "providers") {
- // Responds with a list of OAuth2 providers.
- complete(write(oauth2Providers))
- } ~
- // Support OAUTH Authentication
- pathPrefix ("oauth2"/ Segment) {providerName =>
- // Resolve OAUTH Authentication Provider
- val oauthService = OAuth2Authenticator.get(config, providerName, ec)
-
- if (oauthService == null) {
- // OAuth2 is disabled.
- complete(StatusCodes.NotFound)
- } else {
-
- def loginWithOAuth2Parameters(parameters: Map[String, String]): Route = {
- val result = oauthService.authenticate(parameters)
- onComplete(result) {
- case Success(session) =>
- login(session, ip.toString, redirectToRoot = true)
- case Failure(ex) => {
- LOG.info(s"Failed to login user from ${ip.toString}", ex)
- rejectWrongCredentials
- }
- }
- }
-
- path ("authorize") {
- // Redirects to OAuth2 service provider for authorization.
- redirect(Uri(oauthService.getAuthorizationUrl), StatusCodes.TemporaryRedirect)
- } ~
- path ("accesstoken") {
- post {
- // Guest account don't have permission to submit new application in UI
- formField(FieldMagnet('accesstoken.as[String])) {accesstoken: String =>
- loginWithOAuth2Parameters(Map("accesstoken" -> accesstoken))
- }
- }
- } ~
- path("callback") {
- // Login with authorization code or access token.
- parameterMap {parameters =>
- loginWithOAuth2Parameters(parameters)
- }
- }
- }
- }
- } ~
- path("logout") {
- post {
- requireAuthentication {session =>
- logout(session, ip.toString())
- }
- }
- } ~
- requireAuthentication {user =>
- requireAuthorization(user, inner.route)
- }
- }}}
-
- }
-}
-
-object SecurityService {
-
- val SESSION_MANAGER_KEY = "akka.http.session.server-secret"
-
- case class UserSession(user: String, permissionLevel: Int)
-
- object UserSession {
-
- private val User = "user"
- private val PermissionLevel = "permissionLevel"
-
- implicit def serializer: MultiValueSessionSerializer[UserSession] = {
- new MultiValueSessionSerializer[UserSession](
- toMap = {t: UserSession =>
- Map(User -> t.user, PermissionLevel -> t.permissionLevel.toString)
- },
- fromMap = {m: Map[String, String] =>
- if (m.contains(User)) {
- Try(UserSession(m(User), m(PermissionLevel).toInt))
- } else {
- Failure[UserSession](new Exception("Fail to parse session "))
- }
- }
- )
- }
- }
-
- case class User(user: String)
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/main/scala/io/gearpump/services/StaticService.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/main/scala/io/gearpump/services/StaticService.scala b/services/jvm/src/main/scala/io/gearpump/services/StaticService.scala
deleted file mode 100644
index fc990a1..0000000
--- a/services/jvm/src/main/scala/io/gearpump/services/StaticService.scala
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.services
-
-import akka.actor.ActorSystem
-import akka.http.scaladsl.model._
-import akka.http.scaladsl.server.Directives._
-import akka.stream.Materializer
-
-import io.gearpump.util.Util
-// NOTE: This cannot be removed!!!
-import io.gearpump.services.util.UpickleUtil._
-
-/**
- * static resource files.
- */
-class StaticService(override val system: ActorSystem, supervisorPath: String)
- extends BasicService {
-
- private val version = Util.version
-
- protected override def prefix = Neutral
-
- override def cache: Boolean = true
-
- protected override def doRoute(implicit mat: Materializer) = {
- path("version") {
- get { ctx =>
- ctx.complete(version)
- }
- } ~
- // For YARN usage, we need to make sure supervisor-path
- // can be accessed without authentication.
- path("supervisor-actor-path") {
- get {
- complete(supervisorPath)
- }
- } ~
- pathEndOrSingleSlash {
- getFromResource("index.html")
- } ~
- path("favicon.ico") {
- complete(StatusCodes.NotFound)
- } ~
- pathPrefix("webjars") {
- get {
- getFromResourceDirectory("META-INF/resources/webjars")
- }
- } ~
- path(Rest) { path =>
- getFromResource("%s" format path)
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/main/scala/io/gearpump/services/SupervisorService.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/main/scala/io/gearpump/services/SupervisorService.scala b/services/jvm/src/main/scala/io/gearpump/services/SupervisorService.scala
deleted file mode 100644
index c7f19e4..0000000
--- a/services/jvm/src/main/scala/io/gearpump/services/SupervisorService.scala
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.services
-
-import scala.concurrent.Future
-import scala.util.{Failure, Success}
-
-import akka.actor.{ActorRef, ActorSystem}
-import akka.http.scaladsl.server.Directives._
-import akka.http.scaladsl.server.Route
-import akka.stream.Materializer
-
-import io.gearpump.cluster.AppMasterToMaster.{GetWorkerData, WorkerData}
-import io.gearpump.cluster.ClientToMaster._
-import io.gearpump.cluster.worker.WorkerId
-import io.gearpump.services.SupervisorService.{Path, Status}
-import io.gearpump.util.ActorUtil._
-// NOTE: This cannot be removed!!!
-import io.gearpump.services.util.UpickleUtil._
-
-/** Responsible for adding/removing machines. Typically it delegates to YARN. */
-class SupervisorService(
- val master: ActorRef, val supervisor: ActorRef, override val system: ActorSystem)
- extends BasicService {
-
- import upickle.default.write
-
- /**
- * TODO: Add additional check to ensure the user have enough authorization to
- * add/remove a worker machine
- */
- private def authorize(internal: Route): Route = {
- if (supervisor == null) {
- failWith(new Exception("API not enabled, cannot find a valid supervisor! " +
- "Please make sure Gearpump is running on top of YARN or other resource managers"))
- } else {
- internal
- }
- }
-
- protected override def doRoute(implicit mat: Materializer) = pathPrefix("supervisor") {
- pathEnd {
- get {
- val path = if (supervisor == null) {
- null
- } else {
- supervisor.path.toString
- }
- complete(write(Path(path)))
- }
- } ~
- path("status") {
- post {
- if (supervisor == null) {
- complete(write(Status(enabled = false)))
- } else {
- complete(write(Status(enabled = true)))
- }
- }
- } ~
- path("addworker" / IntNumber) { workerCount =>
- post {
- authorize {
- onComplete(askActor[CommandResult](supervisor, AddWorker(workerCount))) {
- case Success(value) =>
- complete(write(value))
- case Failure(ex) =>
- failWith(ex)
- }
- }
- }
- } ~
- path("removeworker" / Segment) { workerIdString =>
- post {
- authorize {
- val workerId = WorkerId.parse(workerIdString)
- def future(): Future[CommandResult] = {
- askWorker[WorkerData](master, workerId, GetWorkerData(workerId)).flatMap{workerData =>
- val containerId = workerData.workerDescription.resourceManagerContainerId
- askActor[CommandResult](supervisor, RemoveWorker(containerId))
- }
- }
-
- onComplete[CommandResult](future()) {
- case Success(value) =>
- complete(write(value))
- case Failure(ex) =>
- failWith(ex)
- }
- }
- }
- }
- }
-}
-
-object SupervisorService {
- case class Status(enabled: Boolean)
-
- case class Path(path: String)
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/main/scala/io/gearpump/services/WorkerService.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/main/scala/io/gearpump/services/WorkerService.scala b/services/jvm/src/main/scala/io/gearpump/services/WorkerService.scala
deleted file mode 100644
index 78cdb37..0000000
--- a/services/jvm/src/main/scala/io/gearpump/services/WorkerService.scala
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.services
-
-import scala.util.{Failure, Success}
-
-import akka.actor.{ActorRef, ActorSystem}
-import akka.http.scaladsl.server.Directives._
-import akka.stream.Materializer
-
-import io.gearpump.cluster.AppMasterToMaster.{GetWorkerData, WorkerData}
-import io.gearpump.cluster.ClientToMaster.{QueryHistoryMetrics, QueryWorkerConfig, ReadOption}
-import io.gearpump.cluster.ClusterConfig
-import io.gearpump.cluster.MasterToClient.{HistoryMetrics, WorkerConfig}
-import io.gearpump.cluster.worker.WorkerId
-import io.gearpump.util.ActorUtil._
-import io.gearpump.util.Constants
-// NOTE: This cannot be removed!!!
-import io.gearpump.services.util.UpickleUtil._
-
-/** Service to handle worker related queries */
-class WorkerService(val master: ActorRef, override val system: ActorSystem)
- extends BasicService {
-
- import upickle.default.write
- private val systemConfig = system.settings.config
- private val concise = systemConfig.getBoolean(Constants.GEARPUMP_SERVICE_RENDER_CONFIG_CONCISE)
-
- protected override def doRoute(implicit mat: Materializer) = pathPrefix("worker" / Segment) {
- workerIdString => {
- pathEnd {
- val workerId = WorkerId.parse(workerIdString)
- onComplete(askWorker[WorkerData](master, workerId, GetWorkerData(workerId))) {
- case Success(value: WorkerData) =>
- complete(write(value.workerDescription))
- case Failure(ex) => failWith(ex)
- }
- }
- }~
- path("config") {
- val workerId = WorkerId.parse(workerIdString)
- onComplete(askWorker[WorkerConfig](master, workerId, QueryWorkerConfig(workerId))) {
- case Success(value: WorkerConfig) =>
- val config = Option(value.config).map(ClusterConfig.render(_, concise)).getOrElse("{}")
- complete(config)
- case Failure(ex) =>
- failWith(ex)
- }
- } ~
- path("metrics" / RestPath ) { path =>
- val workerId = WorkerId.parse(workerIdString)
- parameter(ReadOption.Key ? ReadOption.ReadLatest) { readOption =>
- val query = QueryHistoryMetrics(path.head.toString, readOption)
- onComplete(askWorker[HistoryMetrics](master, workerId, query)) {
- case Success(value) =>
- complete(write(value))
- case Failure(ex) =>
- failWith(ex)
- }
- }
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/main/scala/io/gearpump/services/main/Services.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/main/scala/io/gearpump/services/main/Services.scala b/services/jvm/src/main/scala/io/gearpump/services/main/Services.scala
deleted file mode 100644
index a647a8d..0000000
--- a/services/jvm/src/main/scala/io/gearpump/services/main/Services.scala
+++ /dev/null
@@ -1,148 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.services.main
-
-import java.util.Random
-import scala.collection.JavaConverters._
-import scala.concurrent.Await
-
-import akka.actor.ActorSystem
-import akka.http.scaladsl.Http
-import akka.http.scaladsl.server.Route
-import akka.stream.ActorMaterializer
-import com.typesafe.config.ConfigValueFactory
-import org.slf4j.Logger
-import sun.misc.BASE64Encoder
-
-import io.gearpump.cluster.ClusterConfig
-import io.gearpump.cluster.main.{ArgumentsParser, CLIOption, Gear}
-import io.gearpump.cluster.master.MasterProxy
-import io.gearpump.services.{RestServices, SecurityService}
-import io.gearpump.util.LogUtil.ProcessType
-import io.gearpump.util.{AkkaApp, Constants, LogUtil, Util}
-
-/** Command line to start UI server */
-object Services extends AkkaApp with ArgumentsParser {
-
- private val LOG = LogUtil.getLogger(getClass)
-
- override val options: Array[(String, CLIOption[Any])] = Array(
- "master" -> CLIOption("<host:port>", required = false),
- Gear.OPTION_CONFIG -> CLIOption("<provide a custom configuration file>", required = false),
- "supervisor" -> CLIOption("<Supervisor Actor Path>", required = false, Some("")))
-
- override val description = "UI Server"
-
- override def akkaConfig: Config = {
- ClusterConfig.ui()
- }
-
- override def help(): Unit = {
- // scalastyle:off println
- Console.println("UI Server")
- // scalastyle:on println
- }
-
- private var killFunction: Option[() => Unit] = None
-
- override def main(inputAkkaConf: Config, args: Array[String]): Unit = {
-
- val argConfig = parse(args)
- var akkaConf =
- if (argConfig.exists(Gear.OPTION_CONFIG)) {
- ClusterConfig.ui(argConfig.getString(Gear.OPTION_CONFIG))
- } else {
- inputAkkaConf
- }
-
- val LOG: Logger = {
- LogUtil.loadConfiguration(akkaConf, ProcessType.UI)
- LogUtil.getLogger(getClass)
- }
-
- if (argConfig.exists("master")) {
- val master = argConfig.getString("master")
- akkaConf = akkaConf.withValue(Constants.GEARPUMP_CLUSTER_MASTERS,
- ConfigValueFactory.fromIterable(List(master).asJava))
- }
-
- akkaConf = akkaConf.withValue(Constants.GEARPUMP_SERVICE_SUPERVISOR_PATH,
- ConfigValueFactory.fromAnyRef(argConfig.getString("supervisor")))
- // Creates a random unique secret key for session manager.
- // All previous stored session token cookies will be invalidated when UI
- // server is restarted.
- .withValue(SecurityService.SESSION_MANAGER_KEY,
- ConfigValueFactory.fromAnyRef(randomSeverSecret()))
-
- val masterCluster = akkaConf.getStringList(Constants.GEARPUMP_CLUSTER_MASTERS).asScala
- .flatMap(Util.parseHostList)
-
- implicit val system = ActorSystem("services", akkaConf)
- implicit val executionContext = system.dispatcher
-
- import scala.concurrent.duration._
- val master = system.actorOf(MasterProxy.props(masterCluster, 1.day),
- s"masterproxy${system.name}")
- val (host, port) = parseHostPort(system.settings.config)
-
- implicit val mat = ActorMaterializer()
- val services = new RestServices(master, mat, system)
-
- val bindFuture = Http().bindAndHandle(Route.handlerFlow(services.route), host, port)
- Await.result(bindFuture, 15.seconds)
-
- val displayHost = if (host == "0.0.0.0") "127.0.0.1" else host
- LOG.info(s"Please browse to http://$displayHost:$port to see the web UI")
-
- // scalastyle:off println
- println(s"Please browse to http://$displayHost:$port to see the web UI")
- // scalastyle:on println
-
- killFunction = Some { () =>
- LOG.info("Shutting down UI Server")
- system.terminate()
- }
-
- Await.result(system.whenTerminated, Duration.Inf)
- }
-
- private def randomSeverSecret(): String = {
- val random = new Random()
- val length = 64 // Required
- val bytes = new Array[Byte](length)
- random.nextBytes(bytes)
- val endecoder = new BASE64Encoder()
- endecoder.encode(bytes)
- }
-
- private def parseHostPort(config: Config): (String, Int) = {
- val port = config.getInt(Constants.GEARPUMP_SERVICE_HTTP)
- val host = config.getString(Constants.GEARPUMP_SERVICE_HOST)
- (host, port)
- }
-
- // TODO: fix this
- // Hacks around for YARN module, so that we can kill the UI server
- // when application is shutting down.
- def kill(): Unit = {
- if (killFunction.isDefined) {
- killFunction.get.apply()
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/main/scala/io/gearpump/services/package.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/main/scala/io/gearpump/services/package.scala b/services/jvm/src/main/scala/io/gearpump/services/package.scala
deleted file mode 100644
index 7b38134..0000000
--- a/services/jvm/src/main/scala/io/gearpump/services/package.scala
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump
-
-package object services {
- final val REST_VERSION = "v1.0"
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/main/scala/io/gearpump/services/security/oauth2/OAuth2Authenticator.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/main/scala/io/gearpump/services/security/oauth2/OAuth2Authenticator.scala b/services/jvm/src/main/scala/io/gearpump/services/security/oauth2/OAuth2Authenticator.scala
deleted file mode 100644
index 158d406..0000000
--- a/services/jvm/src/main/scala/io/gearpump/services/security/oauth2/OAuth2Authenticator.scala
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.services.security.oauth2
-
-import scala.concurrent.{ExecutionContext, Future}
-
-import com.typesafe.config.Config
-
-import io.gearpump.services.SecurityService.UserSession
-import io.gearpump.util.Constants
-import io.gearpump.util.Constants._
-
-/**
- *
- * Uses OAuth2 social-login as the mechanism for authentication.
- * @see [[https://tools.ietf.org/html/rfc6749]] to find what is OAuth2, and how it works.
- *
- * Basically flow for OAuth2 Authentication:
- * 1. User accesses Gearpump UI website, and choose to login with OAuth2 server.
- * 2. Gearpump UI website redirects user to OAuth2 server domain authorization endpoint.
- * 3. End user complete the authorization in the domain of OAuth2 server.
- * 4. OAuth2 server redirects user back to Gearpump UI server.
- * 5. Gearpump UI server verify the tokens and extract credentials from query
- * parameters and form fields.
- *
- * NOTE: '''Thread-safety''' is a MUST requirement. Developer need to ensure the sub-class is
- * thread-safe. Sub-class should have a parameterless constructor.
- *
- * NOTE: OAuth2 Authenticator requires access of Internet. Please make sure HTTP proxy are
- * set properly if applied.
- *
- * Example: Config proxy when UI server is started on Windows:
- * {{{
- * > set JAVA_OPTS=-Dhttp.proxyHost=xx.com -Dhttp.proxyPort=8088 -Dhttps.proxyHost=xx.com
- * -Dhttps.proxyPort=8088
- * > bin\services
- * }}}
- *
- * Example: Config proxy when UI server is started on Linux:
- * {{{
- * $ export JAVA_OPTS="-Dhttp.proxyHost=xx.com -Dhttp.proxyPort=8088 -Dhttps.proxyHost=xx.com
- * -Dhttps.proxyPort=8088"
- * $ bin/services
- * }}}
- */
-trait OAuth2Authenticator {
-
- /**
- * Inits authenticator with config which contains client ID, client secret, and etc..
- *
- * Typically, the client key and client secret is provided by OAuth2 Authorization server
- * when user register an application there.
- * See [[https://tools.ietf.org/html/rfc6749]] for definition of client, client Id,
- * and client secret.
- *
- * See [[https://developer.github.com/v3/oauth/]] for an actual example of how Github
- * use client key, and client secret.
- *
- * NOTE: '''Thread-Safety''': Framework ensures this call is synchronized.
- *
- * @param config Client Id, client secret, callback URL and etc..
- * @param executionContext ExecutionContext from hosting environment.
- */
- def init(config: Config, executionContext: ExecutionContext): Unit
-
- /**
- * Returns the OAuth Authorization URL so for redirection to that address to do OAuth2
- * authorization.
- *
- * NOTE: '''Thread-Safety''': This can be called in a multi-thread environment. Developer
- * need to ensure thread safety.
- */
- def getAuthorizationUrl: String
-
- /**
- * After authorization, OAuth2 server redirects user back with tokens. This verify the
- * tokens, retrieve the profiles, and return [[UserSession]] information.
- *
- * NOTE: This is an Async call.
- *
- * NOTE: This call requires external internet access.
- *
- * NOTE: '''Thread-Safety''': This can be called in a multi-thread environment. Developer
- * need to ensure thread safety.
- *
- * @param parameters HTTP Query and Post parameters, which typically contains Authorization code.
- * @return UserSession if authentication pass.
- */
- def authenticate(parameters: Map[String, String]): Future[UserSession]
-
- /**
- * Clean up resource
- */
- def close(): Unit
-}
-
-object OAuth2Authenticator {
-
- // Serves as a quick immutable lookup cache
- private var providers = Map.empty[String, OAuth2Authenticator]
-
- /**
- * Load Authenticator from [[Constants.GEARPUMP_UI_OAUTH2_AUTHENTICATORS]]
- *
- * @param provider, Name for the OAuth2 Authentication Service.
- * @return Returns null if the OAuth2 Authentication is disabled.
- */
- def get(config: Config, provider: String, executionContext: ExecutionContext)
- : OAuth2Authenticator = {
-
- if (providers.contains(provider)) {
- providers(provider)
- } else {
- val path = s"${Constants.GEARPUMP_UI_OAUTH2_AUTHENTICATORS}.$provider"
- val enabled = config.getBoolean(Constants.GEARPUMP_UI_OAUTH2_AUTHENTICATOR_ENABLED)
- if (enabled && config.hasPath(path)) {
- this.synchronized {
- if (providers.contains(provider)) {
- providers(provider)
- } else {
- val authenticatorConfig = config.getConfig(path)
- val authenticatorClass = authenticatorConfig.getString(
- GEARPUMP_UI_OAUTH2_AUTHENTICATOR_CLASS)
- val clazz = Thread.currentThread().getContextClassLoader.loadClass(authenticatorClass)
- val authenticator = clazz.newInstance().asInstanceOf[OAuth2Authenticator]
- authenticator.init(authenticatorConfig, executionContext)
- providers += provider -> authenticator
- authenticator
- }
- }
- } else {
- null
- }
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/main/scala/io/gearpump/services/security/oauth2/impl/BaseOAuth2Authenticator.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/main/scala/io/gearpump/services/security/oauth2/impl/BaseOAuth2Authenticator.scala b/services/jvm/src/main/scala/io/gearpump/services/security/oauth2/impl/BaseOAuth2Authenticator.scala
deleted file mode 100644
index e422d3f..0000000
--- a/services/jvm/src/main/scala/io/gearpump/services/security/oauth2/impl/BaseOAuth2Authenticator.scala
+++ /dev/null
@@ -1,231 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.services.security.oauth2.impl
-
-import java.util.concurrent.atomic.AtomicBoolean
-import scala.collection.mutable.StringBuilder
-import scala.concurrent.{ExecutionContext, Future, Promise}
-import scala.util.{Failure, Success}
-
-import com.typesafe.config.Config
-import com.github.scribejava.core.builder.ServiceBuilderAsync
-import com.github.scribejava.core.builder.api.DefaultApi20
-import com.github.scribejava.core.model._
-import com.github.scribejava.core.oauth.OAuth20Service
-import com.github.scribejava.core.utils.OAuthEncoder
-import com.ning.http.client.AsyncHttpClientConfig
-
-import io.gearpump.security.Authenticator
-import io.gearpump.services.SecurityService.UserSession
-import io.gearpump.services.security.oauth2.OAuth2Authenticator
-import io.gearpump.services.security.oauth2.impl.BaseOAuth2Authenticator.BaseApi20
-import io.gearpump.util.Constants._
-import io.gearpump.util.Util
-
-/**
- * Uses Ning AsyncClient to connect to OAuth2 service.
- *
- * See [[io.gearpump.services.security.oauth2.OAuth2Authenticator]] for more API information.
- */
-abstract class BaseOAuth2Authenticator extends OAuth2Authenticator {
-
- // Authorize Url for end user to authorize
- protected def authorizeUrl: String
-
- // Used to fetch the Access Token.
- protected def accessTokenEndpoint: String
-
- // Protected resource Url to get the user profile
- protected def protectedResourceUrl: String
-
- // Extracts the username information from response of protectedResourceUrl
- protected def extractUserName(body: String): String
-
- // Scope required to access protectedResourceUrl
- protected def scope: String
-
- // OAuth2 endpoint definition for ScribeJava.
- protected def oauth2Api(): DefaultApi20 = {
- new BaseApi20(authorizeUrl, accessTokenEndpoint)
- }
-
- protected var oauthService: OAuth20Service = null
-
- protected var executionContext: ExecutionContext = null
-
- private var defaultPermissionLevel = Authenticator.Guest.permissionLevel
-
- // Synchronization ensured by the caller
- override def init(config: Config, executionContext: ExecutionContext): Unit = {
- if (this.oauthService == null) {
- val callback = config.getString(GEARPUMP_UI_OAUTH2_AUTHENTICATOR_CALLBACK)
- val clientId = config.getString(GEARPUMP_UI_OAUTH2_AUTHENTICATOR_CLIENT_ID)
- val clientSecret = config.getString(GEARPUMP_UI_OAUTH2_AUTHENTICATOR_CLIENT_SECRET)
- defaultPermissionLevel = {
- val role = config.getString(GEARPUMP_UI_OAUTH2_AUTHENTICATOR_DEFAULT_USER_ROLE)
- role match {
- case "guest" => Authenticator.Guest.permissionLevel
- case "user" => Authenticator.User.permissionLevel
- case "admin" => Authenticator.Admin.permissionLevel
- case _ => Authenticator.UnAuthenticated.permissionLevel
- }
- }
- this.oauthService = buildOAuth2Service(clientId, clientSecret, callback)
- this.executionContext = executionContext
- }
- }
-
- private val isClosed: AtomicBoolean = new AtomicBoolean(false)
-
- override def close(): Unit = {
- if (isClosed.compareAndSet(false, true)) {
- if (null != oauthService && null != oauthService.getAsyncHttpClient()) {
- oauthService.getAsyncHttpClient().close()
- }
- }
- }
-
- override def getAuthorizationUrl(): String = {
- oauthService.getAuthorizationUrl()
- }
-
- protected def authenticateWithAccessToken(accessToken: OAuth2AccessToken): Future[UserSession] = {
- val promise = Promise[UserSession]()
- val request = new OAuthRequestAsync(Verb.GET, protectedResourceUrl, oauthService)
- oauthService.signRequest(accessToken, request)
- request.sendAsync {
- new OAuthAsyncRequestCallback[Response] {
- override def onCompleted(response: Response): Unit = {
- try {
- val user = extractUserName(response.getBody)
- promise.success(new UserSession(user, defaultPermissionLevel))
- } catch {
- case ex: Throwable =>
- promise.failure(ex)
- }
- }
-
- override def onThrowable(throwable: Throwable): Unit = {
- promise.failure(throwable)
- }
- }
- }
- promise.future
- }
-
- protected def authenticateWithAuthorizationCode(code: String): Future[UserSession] = {
-
- implicit val ec: ExecutionContext = executionContext
-
- val promise = Promise[UserSession]()
- oauthService.getAccessTokenAsync(code,
-
- new OAuthAsyncRequestCallback[OAuth2AccessToken] {
- override def onCompleted(accessToken: OAuth2AccessToken): Unit = {
- authenticateWithAccessToken(accessToken).onComplete {
- case Success(user) => promise.success(user)
- case Failure(ex) => promise.failure(ex)
- }
- }
-
- override def onThrowable(throwable: Throwable): Unit = {
- promise.failure(throwable)
- }
- })
- promise.future
- }
-
- override def authenticate(parameters: Map[String, String]): Future[UserSession] = {
-
- val code = parameters.get(GEARPUMP_UI_OAUTH2_AUTHENTICATOR_AUTHORIZATION_CODE)
- val accessToken = parameters.get(GEARPUMP_UI_OAUTH2_AUTHENTICATOR_ACCESS_TOKEN)
-
- if (accessToken.isDefined) {
- authenticateWithAccessToken(new OAuth2AccessToken(accessToken.get))
- } else if (code.isDefined) {
- authenticateWithAuthorizationCode(code.get)
- } else {
- // Fails authentication if code not exist
- Future.failed(new Exception("Fail to authenticate user as there is no code parameter in URL"))
- }
- }
-
- private def buildOAuth2Service(clientId: String, clientSecret: String, callback: String)
- : OAuth20Service = {
- val state: String = "state" + Util.randInt()
- ScribeJavaConfig.setForceTypeOfHttpRequests(
- ForceTypeOfHttpRequest.FORCE_ASYNC_ONLY_HTTP_REQUESTS)
- val clientConfig: AsyncHttpClientConfig = new AsyncHttpClientConfig.Builder()
- .setMaxConnections(5)
- .setUseProxyProperties(true)
- .setRequestTimeout(60000)
- .setAllowPoolingConnections(false)
- .setPooledConnectionIdleTimeout(60000)
- .setReadTimeout(60000).build
-
- val service: OAuth20Service = new ServiceBuilderAsync()
- .apiKey(clientId)
- .apiSecret(clientSecret)
- .scope(scope)
- .state(state)
- .callback(callback)
- .asyncHttpClientConfig(clientConfig)
- .build(oauth2Api())
-
- service
- }
-}
-
-object BaseOAuth2Authenticator {
-
- class BaseApi20(authorizeUrl: String, accessTokenEndpoint: String) extends DefaultApi20 {
- def getAccessTokenEndpoint: String = {
- accessTokenEndpoint
- }
-
- def getAuthorizationUrl(config: OAuthConfig): String = {
- val sb: StringBuilder = new StringBuilder(String.format(authorizeUrl,
- config.getResponseType, config.getApiKey, OAuthEncoder.encode(config.getCallback),
- OAuthEncoder.encode(config.getScope)))
- val state: String = config.getState
- if (state != null) {
- sb.append('&').append(OAuthConstants.STATE).append('=').append(OAuthEncoder.encode(state))
- }
- sb.toString
- }
-
- override def createService(config: OAuthConfig): OAuth20Service = {
- new OAuth20Service(this, config) {
-
- protected override def createAccessTokenRequest[T <: AbstractRequest](
- code: String, request: T): T = {
- super.createAccessTokenRequest(code, request)
-
- if (!getConfig.hasGrantType) {
- request.addParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.AUTHORIZATION_CODE)
- }
-
- // Work-around for issue https://github.com/scribejava/scribejava/issues/641
- request.addHeader("Content-Type", "application/x-www-form-urlencoded")
- request
- }
- }
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/main/scala/io/gearpump/services/security/oauth2/impl/CloudFoundryUAAOAuth2Authenticator.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/main/scala/io/gearpump/services/security/oauth2/impl/CloudFoundryUAAOAuth2Authenticator.scala b/services/jvm/src/main/scala/io/gearpump/services/security/oauth2/impl/CloudFoundryUAAOAuth2Authenticator.scala
deleted file mode 100644
index 98e37ea..0000000
--- a/services/jvm/src/main/scala/io/gearpump/services/security/oauth2/impl/CloudFoundryUAAOAuth2Authenticator.scala
+++ /dev/null
@@ -1,244 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.services.security.oauth2.impl
-
-import scala.concurrent.{ExecutionContext, Future, Promise}
-
-import com.typesafe.config.Config
-import com.github.scribejava.core.builder.api.DefaultApi20
-import com.github.scribejava.core.model._
-import com.github.scribejava.core.oauth.OAuth20Service
-import com.ning.http.client
-import com.ning.http.client.{AsyncCompletionHandler, AsyncHttpClient}
-import spray.json.{JsString, _}
-import sun.misc.BASE64Encoder
-
-import io.gearpump.services.SecurityService.UserSession
-import io.gearpump.services.security.oauth2.impl.BaseOAuth2Authenticator.BaseApi20
-import io.gearpump.util.Constants._
-
-/**
- *
- * Does authentication with CloudFoundry UAA service. Currently it only
- * extract the email address of end user.
- *
- * For what is UAA,
- * See [[https://github.com/cloudfoundry/uaa for information about CloudFoundry UAA]]
- * (User Account and Authentication Service)
- *
- * Pre-requisite steps to use this Authenticator:
- *
- * Step1: Register your website to UAA with tool uaac.
- * 1) Check tutorial on uaac at
- * [[https://docs.cloudfoundry.org/adminguide/uaa-user-management.html]]
- *
- * 2) Open a bash shell, set the UAA server by command `uaac target`
- * {{{
- * uaac target [your uaa server url]
- * }}}
- *
- * NOTE: [your uaa server url] should match the uaahost settings in gear.conf
- *
- * 3) Login in as user admin by
- * {{{
- * uaac token client get admin -s MyAdminPassword
- * }}}
- *
- * 4) Create a new Application (Client) in UAA,
- * {{{
- * uaac client add [your_client_id]
- * --scope "openid cloud_controller.read"
- * --authorized_grant_types "authorization_code client_credentials refresh_token"
- * --authorities "openid cloud_controller.read"
- * --redirect_uri [your_redirect_url]
- * --autoapprove true
- * --secret [your_client_secret]
- * }}}
- *
- * Step2: Configure the OAuth2 information in gear.conf
- *
- * 1) Enable OAuth2 authentication by setting "gearpump.ui-security.oauth2-authenticator-enabled"
- * as true.
- *
- * 2) Navigate to section "gearpump.ui-security.oauth2-authenticators.cloudfoundryuaa"
- *
- * 3) Config gear.conf "gearpump.ui-security.oauth2-authenticators.cloudfoundryuaa" section.
- * Please make sure class name, client ID, client Secret, and callback URL are set properly.
- *
- * NOTE: The callback URL here should match what you set on CloudFoundry UAA in step1.
- *
- * Step3: Restart the UI service and try the "social login" button for UAA.
- *
- * NOTE: OAuth requires Internet access, @see
- * [[io.gearpump.services.security.oauth2.OAuth2Authenticator]] to find tutorials to
- * configure Internet proxy.
- *
- * See [[io.gearpump.services.security.oauth2.OAuth2Authenticator]] for more background
- * information of OAuth2.
- */
-class CloudFoundryUAAOAuth2Authenticator extends BaseOAuth2Authenticator {
-
- import io.gearpump.services.security.oauth2.impl.CloudFoundryUAAOAuth2Authenticator._
-
- private var host: String = null
-
- protected override def authorizeUrl: String =
- s"$host/oauth/authorize?response_type=%s&client_id=%s&redirect_uri=%s&scope=%s"
-
- protected override def accessTokenEndpoint: String = s"$host/oauth/token"
-
- protected override def protectedResourceUrl: String = s"$host/userinfo"
-
- protected override def scope: String = "openid,cloud_controller.read"
-
- private var additionalAuthenticator: Option[AdditionalAuthenticator] = None
-
- override def init(config: Config, executionContext: ExecutionContext): Unit = {
- host = config.getString("uaahost")
- super.init(config, executionContext)
-
- if (config.getBoolean(ADDITIONAL_AUTHENTICATOR_ENABLED)) {
- val additionalAuthenticatorConfig = config.getConfig(ADDITIONAL_AUTHENTICATOR)
- val authenticatorClass = additionalAuthenticatorConfig
- .getString(GEARPUMP_UI_OAUTH2_AUTHENTICATOR_CLASS)
- val clazz = Thread.currentThread().getContextClassLoader.loadClass(authenticatorClass)
- val authenticator = clazz.newInstance().asInstanceOf[AdditionalAuthenticator]
- authenticator.init(additionalAuthenticatorConfig, executionContext)
- additionalAuthenticator = Option(authenticator)
- }
- }
-
- protected override def extractUserName(body: String): String = {
- val email = body.parseJson.asJsObject.fields("email").asInstanceOf[JsString]
- email.value
- }
-
- protected override def oauth2Api(): DefaultApi20 = {
- new CloudFoundryUAAService(authorizeUrl, accessTokenEndpoint)
- }
-
- protected override def authenticateWithAccessToken(accessToken: OAuth2AccessToken)
- : Future[UserSession] = {
-
- implicit val ec: ExecutionContext = executionContext
-
- if (additionalAuthenticator.isDefined) {
- super.authenticateWithAccessToken(accessToken).flatMap { user =>
- additionalAuthenticator.get.authenticate(oauthService.getAsyncHttpClient, accessToken, user)
- }
- } else {
- super.authenticateWithAccessToken(accessToken)
- }
- }
-}
-
-object CloudFoundryUAAOAuth2Authenticator {
- private val RESPONSE_TYPE = "response_type"
-
- val ADDITIONAL_AUTHENTICATOR_ENABLED = "additional-authenticator-enabled"
- val ADDITIONAL_AUTHENTICATOR = "additional-authenticator"
-
- private class CloudFoundryUAAService(authorizeUrl: String, accessTokenEndpoint: String)
- extends BaseApi20(authorizeUrl, accessTokenEndpoint) {
-
- private def base64(in: String): String = {
- val encoder = new BASE64Encoder()
- val utf8 = "UTF-8"
- encoder.encode(in.getBytes(utf8))
- }
-
- override def createService(config: OAuthConfig): OAuth20Service = {
- new OAuth20Service(this, config) {
-
- protected override def createAccessTokenRequest[T <: AbstractRequest](
- code: String, request: T): T = {
- val config: OAuthConfig = getConfig()
-
- request.addParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.AUTHORIZATION_CODE)
- request.addParameter(OAuthConstants.CODE, code)
- request.addParameter(RESPONSE_TYPE, "token")
- request.addParameter(OAuthConstants.REDIRECT_URI, config.getCallback)
-
- // Work around issue https://github.com/scribejava/scribejava/issues/641
- request.addHeader("Content-Type", "application/x-www-form-urlencoded")
-
- // CloudFoundry requires a Authorization header encoded with client Id and secret.
- val authorizationHeader = "Basic " + base64(config.getApiKey + ":" + config.getApiSecret)
- request.addHeader("Authorization", authorizationHeader)
- request
- }
- }
- }
- }
-
- /**
- * Additional authenticator to check more credential attributes of user before logging in.
- * This authenticator is applied AFTER user pass the initial (default) authenticator.
- */
- trait AdditionalAuthenticator {
-
- /**
- * Initialization
- *
- * @param config Configurations specifically used for this authenticator.
- * @param executionContext Execution Context to use to run futures.
- */
- def init(config: Config, executionContext: ExecutionContext): Unit
-
- /**
- *
- * @param accessToken, the accessToken for the UAA
- * @param user user session returned by previous authenticator
- * @return an updated UserSession
- */
- def authenticate(
- asyncClient: AsyncHttpClient, accessToken: OAuth2AccessToken, user: UserSession)
- : Future[UserSession]
- }
-
- val ORGANIZATION_URL = "organization-url"
-
- class OrganizationAccessChecker extends AdditionalAuthenticator {
- private var organizationUrl: String = null
- private implicit var executionContext: ExecutionContext = null
-
- override def init(config: Config, executionContext: ExecutionContext): Unit = {
- this.organizationUrl = config.getString(ORGANIZATION_URL)
- this.executionContext = executionContext
- }
-
- override def authenticate(asyncClient: AsyncHttpClient, accessToken: OAuth2AccessToken,
- user: UserSession): Future[UserSession] = {
-
- val promise = Promise[UserSession]()
- val builder = asyncClient.prepareGet(organizationUrl)
- builder.addHeader("Authorization", s"bearer ${accessToken.getAccessToken}")
- builder.execute(new AsyncCompletionHandler[Unit] {
- override def onCompleted(response: client.Response): Unit = {
- if (response.getStatusCode == 200) {
- promise.success(user)
- } else {
- promise.failure(new Exception(response.getResponseBody))
- }
- }
- })
- promise.future
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/main/scala/io/gearpump/services/security/oauth2/impl/GoogleOAuth2Authenticator.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/main/scala/io/gearpump/services/security/oauth2/impl/GoogleOAuth2Authenticator.scala b/services/jvm/src/main/scala/io/gearpump/services/security/oauth2/impl/GoogleOAuth2Authenticator.scala
deleted file mode 100644
index c2b18fd..0000000
--- a/services/jvm/src/main/scala/io/gearpump/services/security/oauth2/impl/GoogleOAuth2Authenticator.scala
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.services.security.oauth2.impl
-
-import com.github.scribejava.apis.google.GoogleJsonTokenExtractor
-import com.github.scribejava.core.builder.api.DefaultApi20
-import com.github.scribejava.core.extractors.TokenExtractor
-import com.github.scribejava.core.model._
-import spray.json._
-
-/**
- *
- * Does authentication with Google OAuth2 service. It only extract the email address
- * from user profile of Google.
- *
- * Pre-requisite steps to use this Authenticator:
- *
- * Step1: Register your website as an OAuth2 Application on Google
- * 1) Create an application representing your website at [[https://console.developers.google.com]]
- *
- * 2) In "API Manager" of your created application, enable API "Google+ API"
- *
- * 3) Create OAuth client ID for this application. In "Credentials" tab of "API Manager",
- * choose "Create credentials", and then select OAuth client ID. Follow the wizard
- * to set callback URL, and generate client ID, and client Secret. Callback URL is NOT optional.
- *
- * Step2: Configure the OAuth2 information in gear.conf
- *
- * 1) Enable OAuth2 authentication by setting "gearpump.ui-security.oauth2-authenticator-enabled"
- * as true.
- *
- * 2) Configure section "gearpump.ui-security.oauth2-authenticators.google". Please make sure
- * class name, client ID, client Secret, and callback URL are set properly.
- *
- * NOTE: callback URL set here should match what is configured on Google in step1.
- *
- * Step3: Restart the UI service and try out the Google social login button in UI.
- *
- * NOTE: OAuth requires Internet access, @see
- * [[io.gearpump.services.security.oauth2.OAuth2Authenticator]] to find some helpful tutorials
- *
- * NOTE: Google use scope to define what data can be fetched by OAuth2. Currently we use profile
- * [[https://www.googleapis.com/auth/userinfo.email]]. However, Google may change the profile
- * in future.
- *
- * TODO Currently, this doesn't verify the state from Google OAuth2 response.
- *
- * See [[io.gearpump.services.security.oauth2.OAuth2Authenticator]] for more API information.
- */
-class GoogleOAuth2Authenticator extends BaseOAuth2Authenticator {
-
- import io.gearpump.services.security.oauth2.impl.GoogleOAuth2Authenticator._
-
- protected override def authorizeUrl: String = AuthorizeUrl
-
- protected override def accessTokenEndpoint: String = AccessEndpoint
-
- protected override def protectedResourceUrl: String = ResourceUrl
-
- protected override def scope: String = GoogleOAuth2Authenticator.Scope
-
- protected override def extractUserName(body: String): String = {
- val emails = body.parseJson.asJsObject.fields("emails").asInstanceOf[JsArray]
- val email = emails.elements(0).asJsObject("Cannot find email account")
- .fields("value").asInstanceOf[JsString].value
- email
- }
-
- override def oauth2Api(): DefaultApi20 = new AsyncGoogleApi20(authorizeUrl, accessTokenEndpoint)
-}
-
-object GoogleOAuth2Authenticator {
-
- import io.gearpump.services.security.oauth2.impl.BaseOAuth2Authenticator._
-
- // scalastyle:off line.size.limit
- val AuthorizeUrl = "https://accounts.google.com/o/oauth2/auth?response_type=%s&client_id=%s&redirect_uri=%s&scope=%s"
- // scalastyle:on line.size.limit
- val AccessEndpoint = "https://www.googleapis.com/oauth2/v4/token"
- val ResourceUrl = "https://www.googleapis.com/plus/v1/people/me"
- val Scope = "https://www.googleapis.com/auth/userinfo.email"
-
- private class AsyncGoogleApi20(authorizeUrl: String, accessEndpoint: String)
- extends BaseApi20(authorizeUrl, accessEndpoint) {
-
- override def getAccessTokenExtractor: TokenExtractor[OAuth2AccessToken] = {
- GoogleJsonTokenExtractor.instance
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/main/scala/io/gearpump/services/util/UpickleUtil.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/main/scala/io/gearpump/services/util/UpickleUtil.scala b/services/jvm/src/main/scala/io/gearpump/services/util/UpickleUtil.scala
deleted file mode 100644
index f95474e..0000000
--- a/services/jvm/src/main/scala/io/gearpump/services/util/UpickleUtil.scala
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.services.util
-
-import upickle.Js
-
-import io.gearpump.cluster.worker.WorkerId
-import io.gearpump.util.Graph
-
-object UpickleUtil {
-
- // For implicit type, we need to add EXPLICIT return type, otherwise, upickle may NOT infer the
- // reader type automatically.
- // See issue https://github.com/lihaoyi/upickle-pprint/issues/102
- implicit val graphReader: upickle.default.Reader[Graph[Int, String]] = {
- upickle.default.Reader[Graph[Int, String]] {
- case Js.Obj(verties, edges) =>
- val vertexList = upickle.default.readJs[List[Int]](verties._2)
- val edgeList = upickle.default.readJs[List[(Int, String, Int)]](edges._2)
- Graph(vertexList, edgeList)
- }
- }
-
- implicit val workerIdReader: upickle.default.Reader[WorkerId] = upickle.default.Reader[WorkerId] {
- case Js.Str(str) =>
- WorkerId.parse(str)
- }
-
- implicit val workerIdWriter: upickle.default.Writer[WorkerId] = upickle.default.Writer[WorkerId] {
- case workerId: WorkerId =>
- Js.Str(WorkerId.render(workerId))
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/main/scala/org/apache/gearpump/services/AdminService.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/main/scala/org/apache/gearpump/services/AdminService.scala b/services/jvm/src/main/scala/org/apache/gearpump/services/AdminService.scala
new file mode 100644
index 0000000..4d1ba22
--- /dev/null
+++ b/services/jvm/src/main/scala/org/apache/gearpump/services/AdminService.scala
@@ -0,0 +1,53 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.services
+
+import akka.actor.ActorSystem
+import akka.http.scaladsl.model._
+import akka.http.scaladsl.server.Directives._
+import akka.stream.Materializer
+
+// NOTE: This cannot be removed!!!
+import org.apache.gearpump.services.util.UpickleUtil._
+
+/**
+ * AdminService is for cluster-wide managements. it is not related with
+ * specific application.
+ *
+ * For example:
+ * - Security management: Add user, remove user.
+ * - Configuration management: Change configurations.
+ * - Machine management: Add worker machines, remove worker machines, and add masters.
+ */
+
+// TODO: Add YARN resource manager capacities to add/remove machines.
+class AdminService(override val system: ActorSystem)
+ extends BasicService {
+
+ protected override def prefix = Neutral
+
+ protected override def doRoute(implicit mat: Materializer) = {
+ path("terminate") {
+ post {
+ system.terminate()
+ complete(StatusCodes.NotFound)
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/main/scala/org/apache/gearpump/services/AppMasterService.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/main/scala/org/apache/gearpump/services/AppMasterService.scala b/services/jvm/src/main/scala/org/apache/gearpump/services/AppMasterService.scala
new file mode 100644
index 0000000..1ca2306
--- /dev/null
+++ b/services/jvm/src/main/scala/org/apache/gearpump/services/AppMasterService.scala
@@ -0,0 +1,226 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.services
+
+import scala.util.{Failure, Success, Try}
+
+import akka.actor.{ActorRef, ActorSystem}
+import akka.http.scaladsl.model.{FormData, Multipart}
+import akka.http.scaladsl.server.Directives._
+import akka.http.scaladsl.server.Route
+import akka.http.scaladsl.server.directives.ParameterDirectives.ParamMagnet
+import akka.stream.Materializer
+import upickle.default.{read, write}
+
+import org.apache.gearpump.cluster.AppMasterToMaster.{AppMasterSummary, GeneralAppMasterSummary}
+import org.apache.gearpump.cluster.ClientToMaster._
+import org.apache.gearpump.cluster.ClusterConfig
+import org.apache.gearpump.cluster.MasterToAppMaster.{AppMasterData, AppMasterDataDetailRequest, AppMasterDataRequest}
+import org.apache.gearpump.cluster.MasterToClient._
+import org.apache.gearpump.jarstore.JarStoreService
+import org.apache.gearpump.services.AppMasterService.Status
+// NOTE: This cannot be removed!!!
+import org.apache.gearpump.services.util.UpickleUtil._
+import org.apache.gearpump.streaming.AppMasterToMaster.StallingTasks
+import org.apache.gearpump.streaming.appmaster.DagManager._
+import org.apache.gearpump.streaming.appmaster.StreamAppMasterSummary
+import org.apache.gearpump.streaming.executor.Executor.{ExecutorConfig, ExecutorSummary, GetExecutorSummary, QueryExecutorConfig}
+import org.apache.gearpump.util.ActorUtil.{askActor, askAppMaster}
+import org.apache.gearpump.util.FileDirective._
+import org.apache.gearpump.util.{Constants, Util}
+
+/**
+ * Management service for AppMaster
+ */
+class AppMasterService(val master: ActorRef,
+ val jarStore: JarStoreService, override val system: ActorSystem)
+ extends BasicService {
+
+ private val systemConfig = system.settings.config
+ private val concise = systemConfig.getBoolean(Constants.GEARPUMP_SERVICE_RENDER_CONFIG_CONCISE)
+
+ protected override def doRoute(implicit mat: Materializer) = pathPrefix("appmaster" / IntNumber) {
+ appId => {
+ path("dynamicdag") {
+ parameters(ParamMagnet("args")) { args: String =>
+ def replaceProcessor(dagOperation: DAGOperation): Route = {
+ onComplete(askAppMaster[DAGOperationResult](master, appId, dagOperation)) {
+ case Success(value) =>
+ complete(write(value))
+ case Failure(ex) =>
+ failWith(ex)
+ }
+ }
+
+ val msg = java.net.URLDecoder.decode(args, "UTF-8")
+ val dagOperation = read[DAGOperation](msg)
+ (post & entity(as[Multipart.FormData])) { _ =>
+ uploadFile { form =>
+ val jar = form.getFile("jar").map(_.file)
+
+ if (jar.nonEmpty) {
+ dagOperation match {
+ case replace: ReplaceProcessor =>
+ val description = replace.newProcessorDescription.copy(jar =
+ Util.uploadJar(jar.get, jarStore))
+ val dagOperationWithJar = replace.copy(newProcessorDescription = description)
+ replaceProcessor(dagOperationWithJar)
+ }
+ } else {
+ replaceProcessor(dagOperation)
+ }
+ }
+ } ~ (post & entity(as[FormData])) { _ =>
+ replaceProcessor(dagOperation)
+ }
+ }
+ } ~
+ path("stallingtasks") {
+ onComplete(askAppMaster[StallingTasks](master, appId, GetStallingTasks(appId))) {
+ case Success(value) =>
+ complete(write(value))
+ case Failure(ex) => failWith(ex)
+ }
+ } ~
+ path("errors") {
+ onComplete(askAppMaster[LastFailure](master, appId, GetLastFailure(appId))) {
+ case Success(value) =>
+ complete(write(value))
+ case Failure(ex) => failWith(ex)
+ }
+ } ~
+ path("restart") {
+ post {
+ onComplete(askActor[SubmitApplicationResult](master, RestartApplication(appId))) {
+ case Success(_) =>
+ complete(write(Status(true)))
+ case Failure(ex) =>
+ complete(write(Status(false, ex.getMessage)))
+ }
+ }
+ } ~
+ path("config") {
+ onComplete(askActor[AppMasterConfig](master, QueryAppMasterConfig(appId))) {
+ case Success(value: AppMasterConfig) =>
+ val config = Option(value.config).map(ClusterConfig.render(_, concise)).getOrElse("{}")
+ complete(config)
+ case Failure(ex) =>
+ failWith(ex)
+ }
+ } ~
+ pathPrefix("executor" / Segment) { executorIdString =>
+ path("config") {
+ val executorId = Integer.parseInt(executorIdString)
+ onComplete(askAppMaster[ExecutorConfig](master, appId, QueryExecutorConfig(executorId))) {
+ case Success(value) =>
+ val config = Option(value.config).map(ClusterConfig.render(_, concise))
+ .getOrElse("{}")
+ complete(config)
+ case Failure(ex) =>
+ failWith(ex)
+ }
+ } ~
+ pathEnd {
+ get {
+ val executorId = Integer.parseInt(executorIdString)
+ onComplete(askAppMaster[ExecutorSummary](master, appId,
+ GetExecutorSummary(executorId))) {
+ case Success(value) =>
+ complete(write(value))
+ case Failure(ex) =>
+ failWith(ex)
+ }
+ }
+ }
+ } ~
+ path("metrics" / RestPath) { path =>
+ parameterMap { optionMap =>
+ parameter("aggregator" ? "") { aggregator =>
+ parameter(ReadOption.Key ? ReadOption.ReadLatest) { readOption =>
+ val query = QueryHistoryMetrics(path.head.toString, readOption, aggregator, optionMap)
+ onComplete(askAppMaster[HistoryMetrics](master, appId, query)) {
+ case Success(value) =>
+ complete(write(value))
+ case Failure(ex) =>
+ failWith(ex)
+ }
+ }
+ }
+ }
+ } ~
+ pathEnd {
+ get {
+ parameter("detail" ? "false") { detail =>
+ val queryDetails = Try(detail.toBoolean).getOrElse(false)
+ val request = AppMasterDataDetailRequest(appId)
+ queryDetails match {
+ case true =>
+ onComplete(askAppMaster[AppMasterSummary](master, appId, request)) {
+ case Success(value) =>
+ value match {
+ case data: GeneralAppMasterSummary =>
+ complete(write(data))
+ case data: StreamAppMasterSummary =>
+ complete(write(data))
+ }
+ case Failure(ex) =>
+ failWith(ex)
+ }
+
+ case false =>
+ onComplete(askActor[AppMasterData](master, AppMasterDataRequest(appId))) {
+ case Success(value) =>
+ complete(write(value))
+ case Failure(ex) =>
+ failWith(ex)
+ }
+ }
+ }
+ }
+ } ~
+ pathEnd {
+ delete {
+ val writer = (result: ShutdownApplicationResult) => {
+ val output = if (result.appId.isSuccess) {
+ Map("status" -> "success", "info" -> null)
+ } else {
+ Map("status" -> "fail", "info" -> result.appId.failed.get.toString)
+ }
+ write(output)
+ }
+ onComplete(askActor[ShutdownApplicationResult](master, ShutdownApplication(appId))) {
+ case Success(result) =>
+ val output = if (result.appId.isSuccess) {
+ Map("status" -> "success", "info" -> null)
+ } else {
+ Map("status" -> "fail", "info" -> result.appId.failed.get.toString)
+ }
+ complete(write(output))
+ case Failure(ex) =>
+ failWith(ex)
+ }
+ }
+ }
+ }
+ }
+}
+
+object AppMasterService {
+ case class Status(success: Boolean, reason: String = null)
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/services/jvm/src/main/scala/org/apache/gearpump/services/BasicService.scala
----------------------------------------------------------------------
diff --git a/services/jvm/src/main/scala/org/apache/gearpump/services/BasicService.scala b/services/jvm/src/main/scala/org/apache/gearpump/services/BasicService.scala
new file mode 100644
index 0000000..3846c33
--- /dev/null
+++ b/services/jvm/src/main/scala/org/apache/gearpump/services/BasicService.scala
@@ -0,0 +1,71 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.services
+
+import scala.concurrent.ExecutionContext
+
+import akka.actor.ActorSystem
+import akka.http.scaladsl.model.headers.CacheDirectives.{`max-age`, `no-cache`}
+import akka.http.scaladsl.model.headers.`Cache-Control`
+import akka.http.scaladsl.server.Directives._
+import akka.http.scaladsl.server.Route
+import akka.stream.Materializer
+
+import org.apache.gearpump.util.{Constants, LogUtil}
+// NOTE: This cannot be removed!!!
+import org.apache.gearpump.services.util.UpickleUtil._
+
+trait RouteService {
+ def route: Route
+}
+
+/**
+ * Wraps the cache behavior, and some common utils.
+ */
+trait BasicService extends RouteService {
+
+ implicit def system: ActorSystem
+
+ implicit def timeout: akka.util.Timeout = Constants.FUTURE_TIMEOUT
+
+ implicit def ec: ExecutionContext = system.dispatcher
+
+ protected def doRoute(implicit mat: Materializer): Route
+
+ protected def prefix = Slash ~ "api" / s"$REST_VERSION"
+
+ protected val LOG = LogUtil.getLogger(getClass)
+
+ protected def cache = false
+ private val noCacheHeader = `Cache-Control`(`no-cache`, `max-age`(0L))
+
+ def route: Route = encodeResponse {
+ extractMaterializer { implicit mat =>
+ rawPathPrefix(prefix) {
+ if (cache) {
+ doRoute(mat)
+ } else {
+ respondWithHeader(noCacheHeader) {
+ doRoute(mat)
+ }
+ }
+ }
+ }
+ }
+}
[29/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/transport/src/main/scala/io/gearpump/streaming/examples/transport/generator/PassRecordGenerator.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/transport/src/main/scala/io/gearpump/streaming/examples/transport/generator/PassRecordGenerator.scala b/examples/streaming/transport/src/main/scala/io/gearpump/streaming/examples/transport/generator/PassRecordGenerator.scala
deleted file mode 100644
index ee06b25..0000000
--- a/examples/streaming/transport/src/main/scala/io/gearpump/streaming/examples/transport/generator/PassRecordGenerator.scala
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.examples.transport.generator
-
-import scala.util.Random
-
-import io.gearpump.streaming.examples.transport.PassRecord
-import io.gearpump.util.LogUtil
-
-class PassRecordGenerator(vehicleId: String, city: MockCity, overdriveThreshold: Int) {
- private val LOG = LogUtil.getLogger(getClass)
- LOG.info(s"Generate pass record for vehicle $vehicleId")
- private var timeStamp = System.currentTimeMillis()
-
- private var locationId = city.randomLocationId()
- private val random = new Random()
- private val fakePlate = random.nextInt(1000) < 1000 * PassRecordGenerator.FAKE_PLATE_RATE
- private val (randomMin, randomRange) = {
- val lowerBound = MockCity.LENGTH_PER_BLOCK * 1000 * 60 * 60 / overdriveThreshold.toFloat
- val upperBound = MockCity.LENGTH_PER_BLOCK * 1000 * 60 * 60 / MockCity.MINIMAL_SPEED.toFloat
- val overdrive = (upperBound - lowerBound) * PassRecordGenerator.OVERDRIVE_RATE
- val randomMin = Math.max(lowerBound - overdrive, PassRecordGenerator.TWOMINUTES)
- val randomRange = upperBound - randomMin
- (randomMin.toInt, randomRange.toInt)
- }
-
- def getNextPassRecord(): PassRecord = {
- locationId = if (fakePlate) {
- city.randomLocationId()
- } else {
- city.nextLocation(locationId)
- }
- timeStamp += (random.nextInt(randomRange) + randomMin)
- PassRecord(vehicleId, locationId, timeStamp)
- }
-}
-
-object PassRecordGenerator {
- final val FAKE_PLATE_RATE = 0.01F
- final val OVERDRIVE_RATE = 0.05F
- final val TWOMINUTES = 2 * 60 * 1000
-
- def create(generatorNum: Int, prefix: String, city: MockCity, overdriveThreshold: Int)
- : Array[PassRecordGenerator] = {
- var result = Map.empty[String, PassRecordGenerator]
- val digitsNum = (Math.log10(generatorNum) + 1).toInt
- for (i <- 1 to generatorNum) {
- val vehicleId = prefix + s"%0${digitsNum}d".format(i)
- val generator = new PassRecordGenerator(vehicleId, city, overdriveThreshold)
- result += vehicleId -> generator
- }
- result.values.toArray
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/transport/src/main/scala/org/apache/gearpump/streaming/examples/transport/Data.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/transport/src/main/scala/org/apache/gearpump/streaming/examples/transport/Data.scala b/examples/streaming/transport/src/main/scala/org/apache/gearpump/streaming/examples/transport/Data.scala
new file mode 100644
index 0000000..0aaf72c
--- /dev/null
+++ b/examples/streaming/transport/src/main/scala/org/apache/gearpump/streaming/examples/transport/Data.scala
@@ -0,0 +1,32 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.examples.transport
+
+case class LocationInfo(id: String, row: Int, column: Int)
+
+// scalastyle:off equals.hash.code
+case class PassRecord(vehicleId: String, locationId: String, timeStamp: Long) {
+ override def hashCode: Int = vehicleId.hashCode
+}
+// scalastyle:on equals.hash.code
+
+case class GetTrace(vehicleId: String)
+
+case class VehicleTrace(records: Array[PassRecord])
+
+case class OverSpeedReport(vehicleId: String, speed: String, timestamp: Long, locationId: String)
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/transport/src/main/scala/org/apache/gearpump/streaming/examples/transport/DataSource.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/transport/src/main/scala/org/apache/gearpump/streaming/examples/transport/DataSource.scala b/examples/streaming/transport/src/main/scala/org/apache/gearpump/streaming/examples/transport/DataSource.scala
new file mode 100644
index 0000000..555e850
--- /dev/null
+++ b/examples/streaming/transport/src/main/scala/org/apache/gearpump/streaming/examples/transport/DataSource.scala
@@ -0,0 +1,56 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.examples.transport
+
+import scala.concurrent.duration._
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.examples.transport.generator.{MockCity, PassRecordGenerator}
+import org.apache.gearpump.streaming.task.{StartTime, Task, TaskContext, TaskId}
+
+class DataSource(taskContext: TaskContext, conf: UserConfig) extends Task(taskContext, conf) {
+ import taskContext.{output, parallelism, scheduleOnce, taskId}
+ private val overdriveThreshold = conf.getInt(VelocityInspector.OVER_DRIVE_THRESHOLD).get
+ private val vehicleNum = conf.getInt(DataSource.VEHICLE_NUM).get / parallelism
+ private val citySize = conf.getInt(DataSource.MOCK_CITY_SIZE).get
+ private val mockCity = new MockCity(citySize)
+ private val recordGenerators: Array[PassRecordGenerator] =
+ PassRecordGenerator.create(vehicleNum, getIdentifier(taskId), mockCity, overdriveThreshold)
+
+ override def onStart(startTime: StartTime): Unit = {
+ self ! Message("start", System.currentTimeMillis())
+ }
+
+ override def onNext(msg: Message): Unit = {
+ recordGenerators.foreach(generator =>
+ output(Message(generator.getNextPassRecord(), System.currentTimeMillis())))
+ scheduleOnce(1.second)(self ! Message("continue", System.currentTimeMillis()))
+ }
+
+ private def getIdentifier(taskId: TaskId): String = {
+ // scalastyle:off non.ascii.character.disallowed
+ s"\u6caaA${taskId.processorId}${taskId.index}"
+ // scalastyle:on non.ascii.character.disallowed
+ }
+}
+
+object DataSource {
+ final val VEHICLE_NUM = "vehicle.number"
+ final val MOCK_CITY_SIZE = "mock.city.size"
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/transport/src/main/scala/org/apache/gearpump/streaming/examples/transport/QueryServer.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/transport/src/main/scala/org/apache/gearpump/streaming/examples/transport/QueryServer.scala b/examples/streaming/transport/src/main/scala/org/apache/gearpump/streaming/examples/transport/QueryServer.scala
new file mode 100644
index 0000000..ff3b4b4
--- /dev/null
+++ b/examples/streaming/transport/src/main/scala/org/apache/gearpump/streaming/examples/transport/QueryServer.scala
@@ -0,0 +1,154 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.examples.transport
+
+import java.util.concurrent.TimeUnit
+import scala.concurrent.Future
+import scala.util.{Failure, Success}
+
+import akka.actor.Actor._
+import akka.actor.{Actor, ActorRefFactory, Props}
+import akka.io.IO
+import akka.pattern.ask
+import spray.can.Http
+import spray.http.StatusCodes
+import spray.json._
+import spray.routing.{HttpService, Route}
+import upickle.default.write
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.partitioner.PartitionerDescription
+import org.apache.gearpump.streaming.appmaster.AppMaster.{LookupTaskActorRef, TaskActorRef}
+import org.apache.gearpump.streaming.examples.transport.QueryServer.{GetAllRecords, WebServer}
+import org.apache.gearpump.streaming.task.{StartTime, Task, TaskContext, TaskId}
+import org.apache.gearpump.streaming.{DAG, ProcessorDescription, ProcessorId, StreamApplication}
+import org.apache.gearpump.util.Graph
+
+class QueryServer(taskContext: TaskContext, conf: UserConfig) extends Task(taskContext, conf) {
+ import system.dispatcher
+ import taskContext.appMaster
+
+ var inspector: (ProcessorId, ProcessorDescription) = null
+ implicit val timeOut = akka.util.Timeout(3, TimeUnit.SECONDS)
+ private var overSpeedRecords = List.empty[OverSpeedReport]
+
+ override def onStart(startTime: StartTime): Unit = {
+ val dag = DAG(conf.getValue[Graph[ProcessorDescription, PartitionerDescription]](
+ StreamApplication.DAG).get)
+ inspector = dag.processors.find { kv =>
+ val (_, processor) = kv
+ processor.taskClass == classOf[VelocityInspector].getName
+ }.get
+ taskContext.actorOf(Props(new WebServer))
+ }
+
+ override def onNext(msg: Message): Unit = {
+ }
+
+ override def receiveUnManagedMessage: Receive = {
+ case getTrace@GetTrace(vehicleId: String) =>
+ val parallism = inspector._2.parallelism
+ val processorId = inspector._1
+ val analyzerTaskId = TaskId(processorId, (vehicleId.hashCode & Integer.MAX_VALUE) % parallism)
+ val requester = sender
+ (appMaster ? LookupTaskActorRef(analyzerTaskId))
+ .asInstanceOf[Future[TaskActorRef]].flatMap { task =>
+ (task.task ? getTrace).asInstanceOf[Future[VehicleTrace]]
+ }.map { trace =>
+ LOG.info(s"reporting $trace")
+ requester ! trace
+ }
+ case record@OverSpeedReport(vehicleId, speed, timestamp, locationId) =>
+ LOG.info(s"vehicle $vehicleId is over speed, the speed is $speed km/h")
+ overSpeedRecords :+= record
+ case GetAllRecords =>
+ sender ! QueryServer.OverSpeedRecords(overSpeedRecords.toArray.sortBy(_.timestamp))
+ overSpeedRecords = List.empty[OverSpeedReport]
+ case _ =>
+ // Ignore
+ }
+}
+
+object QueryServer {
+ object GetAllRecords
+
+ case class OverSpeedRecords(records: Array[OverSpeedReport])
+
+ class WebServer extends Actor with HttpService {
+
+ import context.dispatcher
+ implicit val timeOut = akka.util.Timeout(3, TimeUnit.SECONDS)
+ def actorRefFactory: ActorRefFactory = context
+ implicit val system = context.system
+
+ IO(Http) ! Http.Bind(self, interface = "0.0.0.0", port = 8080)
+
+ override def receive: Receive = runRoute(webServer ~ staticRoute)
+
+ def webServer: Route = {
+ path("trace" / Segment) { vehicleId =>
+ get {
+ onComplete((context.parent ? GetTrace(vehicleId)).asInstanceOf[Future[VehicleTrace]]) {
+ case Success(trace: VehicleTrace) =>
+ val json = write(trace)
+ complete(pretty(json))
+ case Failure(ex) => complete(StatusCodes.InternalServerError,
+ s"An error occurred: ${ex.getMessage}")
+ }
+ }
+ } ~
+ path("records") {
+ get {
+ onComplete((context.parent ? GetAllRecords).asInstanceOf[Future[OverSpeedRecords]]) {
+ case Success(records: OverSpeedRecords) =>
+ val json = write(records)
+ complete(pretty(json))
+ case Failure(ex) => complete(StatusCodes.InternalServerError,
+ s"An error occurred: ${ex.getMessage}")
+ }
+ }
+ }
+ }
+
+ val staticRoute = {
+ pathEndOrSingleSlash {
+ getFromResource("transport/transport.html")
+ } ~
+ pathPrefix("css") {
+ get {
+ getFromResourceDirectory("transport/css")
+ }
+ } ~
+ pathPrefix("svg") {
+ get {
+ getFromResourceDirectory("transport/svg")
+ }
+ } ~
+ pathPrefix("js") {
+ get {
+ getFromResourceDirectory("transport/js")
+ }
+ }
+ }
+
+ private def pretty(json: String): String = {
+ json.parseJson.prettyPrint
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/transport/src/main/scala/org/apache/gearpump/streaming/examples/transport/Transport.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/transport/src/main/scala/org/apache/gearpump/streaming/examples/transport/Transport.scala b/examples/streaming/transport/src/main/scala/org/apache/gearpump/streaming/examples/transport/Transport.scala
new file mode 100644
index 0000000..5beb2e1
--- /dev/null
+++ b/examples/streaming/transport/src/main/scala/org/apache/gearpump/streaming/examples/transport/Transport.scala
@@ -0,0 +1,69 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.examples.transport
+
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.cluster.client.ClientContext
+import org.apache.gearpump.cluster.main.{ArgumentsParser, CLIOption, ParseResult}
+import org.apache.gearpump.partitioner.HashPartitioner
+import org.apache.gearpump.streaming.{Processor, StreamApplication}
+import org.apache.gearpump.util.Graph._
+import org.apache.gearpump.util.{AkkaApp, Graph}
+
+/** A city smart transportation streaming application */
+object Transport extends AkkaApp with ArgumentsParser {
+ override val options: Array[(String, CLIOption[Any])] = Array(
+ "source" -> CLIOption[Int]("<how many task to generate data>", required = false,
+ defaultValue = Some(10)),
+ "inspector" -> CLIOption[Int]("<how many over speed inspector>", required = false,
+ defaultValue = Some(4)),
+ "vehicle" -> CLIOption[Int]("<how many vehicles's to generate>", required = false,
+ defaultValue = Some(1000)),
+ "citysize" -> CLIOption[Int]("<the blocks number of the mock city>", required = false,
+ defaultValue = Some(10)),
+ "threshold" -> CLIOption[Int]("<overdrive threshold, km/h>", required = false,
+ defaultValue = Some(60)))
+
+ def application(config: ParseResult): StreamApplication = {
+ val sourceNum = config.getInt("source")
+ val inspectorNum = config.getInt("inspector")
+ val vehicleNum = config.getInt("vehicle")
+ val citysize = config.getInt("citysize")
+ val threshold = config.getInt("threshold")
+ val source = Processor[DataSource](sourceNum)
+ val inspector = Processor[VelocityInspector](inspectorNum)
+ val queryServer = Processor[QueryServer](1)
+ val partitioner = new HashPartitioner
+
+ val userConfig = UserConfig.empty.withInt(DataSource.VEHICLE_NUM, vehicleNum).
+ withInt(DataSource.MOCK_CITY_SIZE, citysize).
+ withInt(VelocityInspector.OVER_DRIVE_THRESHOLD, threshold).
+ withInt(VelocityInspector.FAKE_PLATE_THRESHOLD, 200)
+ StreamApplication("transport", Graph(source ~ partitioner ~> inspector,
+ Node(queryServer)), userConfig)
+ }
+
+ override def main(akkaConf: Config, args: Array[String]): Unit = {
+ val config = parse(args)
+ val context = ClientContext(akkaConf)
+ implicit val system = context.system
+ context.submit(application(config))
+ context.close()
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/transport/src/main/scala/org/apache/gearpump/streaming/examples/transport/VelocityInspector.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/transport/src/main/scala/org/apache/gearpump/streaming/examples/transport/VelocityInspector.scala b/examples/streaming/transport/src/main/scala/org/apache/gearpump/streaming/examples/transport/VelocityInspector.scala
new file mode 100644
index 0000000..4d9bd04
--- /dev/null
+++ b/examples/streaming/transport/src/main/scala/org/apache/gearpump/streaming/examples/transport/VelocityInspector.scala
@@ -0,0 +1,123 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.examples.transport
+
+import java.util.concurrent.TimeUnit
+import scala.collection.immutable.Queue
+import scala.collection.mutable
+import scala.concurrent.Future
+
+import akka.actor.Actor._
+import akka.actor.ActorRef
+import akka.pattern.ask
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.partitioner.PartitionerDescription
+import org.apache.gearpump.streaming.appmaster.AppMaster.{LookupTaskActorRef, TaskActorRef}
+import org.apache.gearpump.streaming.examples.transport.generator.MockCity
+import org.apache.gearpump.streaming.task.{StartTime, Task, TaskContext, TaskId}
+import org.apache.gearpump.streaming.{DAG, ProcessorDescription, StreamApplication}
+import org.apache.gearpump.util.Graph
+
+class VelocityInspector(taskContext: TaskContext, conf: UserConfig)
+ extends Task(taskContext, conf) {
+
+ import system.dispatcher
+ import taskContext.appMaster
+ implicit val timeOut = akka.util.Timeout(3, TimeUnit.SECONDS)
+ private val passRecords = mutable.Map.empty[String, Queue[PassRecord]]
+ private val fakePlateThreshold = conf.getInt(VelocityInspector.FAKE_PLATE_THRESHOLD).get
+ private val overdriveThreshold = conf.getInt(VelocityInspector.OVER_DRIVE_THRESHOLD).get
+ private val citySize = conf.getInt(DataSource.MOCK_CITY_SIZE).get
+ private val mockCity = new MockCity(citySize)
+ private var queryServerActor: ActorRef = null
+
+ override def onStart(startTime: StartTime): Unit = {
+ val dag = DAG(conf.getValue[Graph[ProcessorDescription, PartitionerDescription]](
+ StreamApplication.DAG).get)
+ val queryServer = dag.processors.find { kv =>
+ val (_, processor) = kv
+ processor.taskClass == classOf[QueryServer].getName
+ }.get
+ val queryServerTaskId = TaskId(queryServer._1, 0)
+ (appMaster ? LookupTaskActorRef(queryServerTaskId)).asInstanceOf[Future[TaskActorRef]]
+ .map { task =>
+ queryServerActor = task.task
+ }
+ }
+
+ import org.apache.gearpump.streaming.examples.transport.VelocityInspector._
+ override def onNext(msg: Message): Unit = {
+ msg.msg match {
+ case passRecord: PassRecord =>
+ val records = passRecords.getOrElse(passRecord.vehicleId, Queue.empty[PassRecord])
+ if (records.size > 0) {
+ val velocity = getVelocity(passRecord, records.last)
+ val formatted = "%.2f".format(velocity)
+ if (velocity > overdriveThreshold) {
+ if (velocity > fakePlateThreshold) {
+ LOG.info(s"vehicle ${passRecord.vehicleId} maybe a fake plate, " +
+ s"the speed is $formatted km/h")
+ }
+ if (queryServerActor != null) {
+ queryServerActor ! OverSpeedReport(passRecord.vehicleId, formatted,
+ passRecord.timeStamp, passRecord.locationId)
+ }
+ }
+ }
+ passRecords.update(passRecord.vehicleId, records.enqueueFinite(passRecord, RECORDS_NUM))
+ }
+ }
+
+ override def receiveUnManagedMessage: Receive = {
+ case GetTrace(vehicleId) =>
+ val records = passRecords.getOrElse(vehicleId, Queue.empty[PassRecord])
+ sender ! VehicleTrace(records.toArray.sortBy(_.timeStamp))
+ }
+
+ private def getVelocity(passRecord: PassRecord, lastPassRecord: PassRecord): Float = {
+ val distanceInKm = getDistance(lastPassRecord.locationId, passRecord.locationId)
+ val timeInHour = (passRecord.timeStamp - lastPassRecord.timeStamp).toFloat / (1000 * 60 * 60)
+ distanceInKm / timeInHour
+ }
+
+ private def getDistance(location1: String, location2: String): Long = {
+ mockCity.getDistance(location1, location2)
+ }
+}
+
+object VelocityInspector {
+ final val OVER_DRIVE_THRESHOLD = "overdrive.threshold"
+ final val FAKE_PLATE_THRESHOLD = "fakeplate.threshold"
+ final val RECORDS_NUM = 20
+
+ class FiniteQueue[T](q: Queue[T]) {
+ def enqueueFinite[B >: T](elem: B, maxSize: Int): Queue[B] = {
+ var result = q.enqueue(elem)
+ while (result.size > maxSize) {
+ result = result.dequeue._2
+ }
+ result
+ }
+ }
+
+ import scala.language.implicitConversions
+
+ implicit def queue2FiniteQueue[T](q: Queue[T]): FiniteQueue[T] = new FiniteQueue[T](q)
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/transport/src/main/scala/org/apache/gearpump/streaming/examples/transport/generator/MockCity.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/transport/src/main/scala/org/apache/gearpump/streaming/examples/transport/generator/MockCity.scala b/examples/streaming/transport/src/main/scala/org/apache/gearpump/streaming/examples/transport/generator/MockCity.scala
new file mode 100644
index 0000000..60e0bcf
--- /dev/null
+++ b/examples/streaming/transport/src/main/scala/org/apache/gearpump/streaming/examples/transport/generator/MockCity.scala
@@ -0,0 +1,88 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.examples.transport.generator
+
+import scala.util.Random
+
+import org.apache.gearpump.streaming.examples.transport.generator.MockCity._
+
+class MockCity(size: Int) {
+ private val random = new Random()
+ private val directions = Array(UP, DOWN, LEFT, RIGHT)
+
+ def nextLocation(currentLocationId: String): String = {
+ val coordinate = idToCoordinate(currentLocationId)
+ val direction = directions(random.nextInt(4))
+ val newCoordinate = coordinate.addOffset(direction)
+ if (inCity(newCoordinate)) {
+ coordinateToId(newCoordinate)
+ } else {
+ nextLocation(currentLocationId)
+ }
+ }
+
+ def getDistance(locationId1: String, locationId2: String): Long = {
+ val coordinate1 = idToCoordinate(locationId1)
+ val coordinate2 = idToCoordinate(locationId2)
+ val blocks = Math.abs(coordinate1.row - coordinate2.row) +
+ Math.abs(coordinate1.column - coordinate2.column)
+ blocks * LENGTH_PER_BLOCK
+ }
+
+ def randomLocationId(): String = {
+ val row = random.nextInt(size)
+ val column = random.nextInt(size)
+ coordinateToId(Coordinate(row, column))
+ }
+
+ private def coordinateToId(coordinate: Coordinate): String = {
+ s"Id_${coordinate.row}_${coordinate.column}"
+ }
+
+ private def idToCoordinate(locationId: String): Coordinate = {
+ val attr = locationId.split("_")
+ val row = attr(1).toInt
+ val column = attr(2).toInt
+ Coordinate(row, column)
+ }
+
+ private def inCity(coordinate: Coordinate): Boolean = {
+ coordinate.row >= 0 &&
+ coordinate.row < size &&
+ coordinate.column >= 0 &&
+ coordinate.column < size
+ }
+}
+
+object MockCity {
+ // The length of the mock city, km
+ final val LENGTH_PER_BLOCK = 5
+ // The minimal speed, km/h
+ final val MINIMAL_SPEED = 10
+
+ final val UP = Coordinate(0, 1)
+ final val DOWN = Coordinate(0, -1)
+ final val LEFT = Coordinate(-1, 0)
+ final val RIGHT = Coordinate(1, 0)
+
+ case class Coordinate(row: Int, column: Int) {
+ def addOffset(coordinate: Coordinate): Coordinate = {
+ Coordinate(this.row + coordinate.row, this.column + coordinate.column)
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/transport/src/main/scala/org/apache/gearpump/streaming/examples/transport/generator/PassRecordGenerator.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/transport/src/main/scala/org/apache/gearpump/streaming/examples/transport/generator/PassRecordGenerator.scala b/examples/streaming/transport/src/main/scala/org/apache/gearpump/streaming/examples/transport/generator/PassRecordGenerator.scala
new file mode 100644
index 0000000..e8c1c59
--- /dev/null
+++ b/examples/streaming/transport/src/main/scala/org/apache/gearpump/streaming/examples/transport/generator/PassRecordGenerator.scala
@@ -0,0 +1,69 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.examples.transport.generator
+
+import scala.util.Random
+
+import org.apache.gearpump.streaming.examples.transport.PassRecord
+import org.apache.gearpump.util.LogUtil
+
+class PassRecordGenerator(vehicleId: String, city: MockCity, overdriveThreshold: Int) {
+ private val LOG = LogUtil.getLogger(getClass)
+ LOG.info(s"Generate pass record for vehicle $vehicleId")
+ private var timeStamp = System.currentTimeMillis()
+
+ private var locationId = city.randomLocationId()
+ private val random = new Random()
+ private val fakePlate = random.nextInt(1000) < 1000 * PassRecordGenerator.FAKE_PLATE_RATE
+ private val (randomMin, randomRange) = {
+ val lowerBound = MockCity.LENGTH_PER_BLOCK * 1000 * 60 * 60 / overdriveThreshold.toFloat
+ val upperBound = MockCity.LENGTH_PER_BLOCK * 1000 * 60 * 60 / MockCity.MINIMAL_SPEED.toFloat
+ val overdrive = (upperBound - lowerBound) * PassRecordGenerator.OVERDRIVE_RATE
+ val randomMin = Math.max(lowerBound - overdrive, PassRecordGenerator.TWOMINUTES)
+ val randomRange = upperBound - randomMin
+ (randomMin.toInt, randomRange.toInt)
+ }
+
+ def getNextPassRecord(): PassRecord = {
+ locationId = if (fakePlate) {
+ city.randomLocationId()
+ } else {
+ city.nextLocation(locationId)
+ }
+ timeStamp += (random.nextInt(randomRange) + randomMin)
+ PassRecord(vehicleId, locationId, timeStamp)
+ }
+}
+
+object PassRecordGenerator {
+ final val FAKE_PLATE_RATE = 0.01F
+ final val OVERDRIVE_RATE = 0.05F
+ final val TWOMINUTES = 2 * 60 * 1000
+
+ def create(generatorNum: Int, prefix: String, city: MockCity, overdriveThreshold: Int)
+ : Array[PassRecordGenerator] = {
+ var result = Map.empty[String, PassRecordGenerator]
+ val digitsNum = (Math.log10(generatorNum) + 1).toInt
+ for (i <- 1 to generatorNum) {
+ val vehicleId = prefix + s"%0${digitsNum}d".format(i)
+ val generator = new PassRecordGenerator(vehicleId, city, overdriveThreshold)
+ result += vehicleId -> generator
+ }
+ result.values.toArray
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/transport/src/test/scala/io/gearpump/streaming/examples/transport/DataSourceSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/transport/src/test/scala/io/gearpump/streaming/examples/transport/DataSourceSpec.scala b/examples/streaming/transport/src/test/scala/io/gearpump/streaming/examples/transport/DataSourceSpec.scala
deleted file mode 100644
index 75f9d60..0000000
--- a/examples/streaming/transport/src/test/scala/io/gearpump/streaming/examples/transport/DataSourceSpec.scala
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.examples.transport
-
-import org.mockito.Matchers._
-import org.mockito.Mockito._
-import org.scalatest.{FlatSpec, Matchers}
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.MockUtil
-import io.gearpump.streaming.task.StartTime
-
-class DataSourceSpec extends FlatSpec with Matchers {
- it should "create the pass record" in {
- val vehicleNum = 2
- val context = MockUtil.mockTaskContext
-
- val userConfig = UserConfig.empty.withInt(DataSource.VEHICLE_NUM, vehicleNum).
- withInt(DataSource.MOCK_CITY_SIZE, 10).
- withInt(VelocityInspector.OVER_DRIVE_THRESHOLD, 60).
- withInt(VelocityInspector.FAKE_PLATE_THRESHOLD, 200)
-
- val source = new DataSource(context, userConfig)
- source.onStart(StartTime(0))
- source.onNext(Message("start"))
- verify(context, times(vehicleNum)).output(any[Message])
- source.onStop()
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/transport/src/test/scala/io/gearpump/streaming/examples/transport/TransportSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/transport/src/test/scala/io/gearpump/streaming/examples/transport/TransportSpec.scala b/examples/streaming/transport/src/test/scala/io/gearpump/streaming/examples/transport/TransportSpec.scala
deleted file mode 100644
index b61fd43..0000000
--- a/examples/streaming/transport/src/test/scala/io/gearpump/streaming/examples/transport/TransportSpec.scala
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.examples.transport
-
-import scala.concurrent.Future
-import scala.util.Success
-
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{BeforeAndAfterAll, Matchers, PropSpec}
-
-import io.gearpump.cluster.ClientToMaster.SubmitApplication
-import io.gearpump.cluster.MasterToClient.SubmitApplicationResult
-import io.gearpump.cluster.{MasterHarness, TestUtil}
-
-class TransportSpec
- extends PropSpec with PropertyChecks with Matchers with BeforeAndAfterAll with MasterHarness {
-
- override def beforeAll {
- startActorSystem()
- }
-
- override def afterAll {
- shutdownActorSystem()
- }
-
- protected override def config = TestUtil.DEFAULT_CONFIG
-
- property("Transport should succeed to submit application with required arguments") {
- val requiredArgs = Array.empty[String]
- val optionalArgs = Array(
- "-source", "1",
- "-inspector", "1",
- "-vehicle", "100",
- "-citysize", "10",
- "-threshold", "60")
-
- val args = {
- Table(
- ("requiredArgs", "optionalArgs"),
- (requiredArgs, optionalArgs)
- )
- }
- val masterReceiver = createMockMaster()
- forAll(args) { (requiredArgs: Array[String], optionalArgs: Array[String]) =>
- val args = requiredArgs ++ optionalArgs
-
- Future {
- Transport.main(masterConfig, args)
- }
- masterReceiver.expectMsgType[SubmitApplication](PROCESS_BOOT_TIME)
- masterReceiver.reply(SubmitApplicationResult(Success(0)))
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/transport/src/test/scala/io/gearpump/streaming/examples/transport/generator/MockCitySpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/transport/src/test/scala/io/gearpump/streaming/examples/transport/generator/MockCitySpec.scala b/examples/streaming/transport/src/test/scala/io/gearpump/streaming/examples/transport/generator/MockCitySpec.scala
deleted file mode 100644
index e91d91c..0000000
--- a/examples/streaming/transport/src/test/scala/io/gearpump/streaming/examples/transport/generator/MockCitySpec.scala
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.examples.transport.generator
-
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{Matchers, PropSpec}
-
-class MockCitySpec extends PropSpec with PropertyChecks with Matchers {
-
- property("MockCity should maintain the location properly") {
- val city = new MockCity(10)
- val start = city.randomLocationId()
- val nextLocation = city.nextLocation(start)
- assert(city.getDistance(start, nextLocation) == MockCity.LENGTH_PER_BLOCK)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/transport/src/test/scala/io/gearpump/streaming/examples/transport/generator/PassRecordGeneratorSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/transport/src/test/scala/io/gearpump/streaming/examples/transport/generator/PassRecordGeneratorSpec.scala b/examples/streaming/transport/src/test/scala/io/gearpump/streaming/examples/transport/generator/PassRecordGeneratorSpec.scala
deleted file mode 100644
index 1c1901e..0000000
--- a/examples/streaming/transport/src/test/scala/io/gearpump/streaming/examples/transport/generator/PassRecordGeneratorSpec.scala
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.examples.transport.generator
-
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{Matchers, PropSpec}
-
-class PassRecordGeneratorSpec extends PropSpec with PropertyChecks with Matchers {
-
- property("PassRecordGenerator should generate pass record") {
- val id = "test"
- val city = new MockCity(10)
- val generator = new PassRecordGenerator(id, city, 60)
- val passrecord1 = generator.getNextPassRecord()
- val passrecord2 = generator.getNextPassRecord()
- assert(city.getDistance(passrecord1.locationId, passrecord2.locationId) ==
- MockCity.LENGTH_PER_BLOCK)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/transport/src/test/scala/org/apache/gearpump/streaming/examples/transport/DataSourceSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/transport/src/test/scala/org/apache/gearpump/streaming/examples/transport/DataSourceSpec.scala b/examples/streaming/transport/src/test/scala/org/apache/gearpump/streaming/examples/transport/DataSourceSpec.scala
new file mode 100644
index 0000000..1f525ae
--- /dev/null
+++ b/examples/streaming/transport/src/test/scala/org/apache/gearpump/streaming/examples/transport/DataSourceSpec.scala
@@ -0,0 +1,45 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.examples.transport
+
+import org.mockito.Matchers._
+import org.mockito.Mockito._
+import org.scalatest.{FlatSpec, Matchers}
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.MockUtil
+import org.apache.gearpump.streaming.task.StartTime
+
+class DataSourceSpec extends FlatSpec with Matchers {
+ it should "create the pass record" in {
+ val vehicleNum = 2
+ val context = MockUtil.mockTaskContext
+
+ val userConfig = UserConfig.empty.withInt(DataSource.VEHICLE_NUM, vehicleNum).
+ withInt(DataSource.MOCK_CITY_SIZE, 10).
+ withInt(VelocityInspector.OVER_DRIVE_THRESHOLD, 60).
+ withInt(VelocityInspector.FAKE_PLATE_THRESHOLD, 200)
+
+ val source = new DataSource(context, userConfig)
+ source.onStart(StartTime(0))
+ source.onNext(Message("start"))
+ verify(context, times(vehicleNum)).output(any[Message])
+ source.onStop()
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/transport/src/test/scala/org/apache/gearpump/streaming/examples/transport/TransportSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/transport/src/test/scala/org/apache/gearpump/streaming/examples/transport/TransportSpec.scala b/examples/streaming/transport/src/test/scala/org/apache/gearpump/streaming/examples/transport/TransportSpec.scala
new file mode 100644
index 0000000..2f83de5
--- /dev/null
+++ b/examples/streaming/transport/src/test/scala/org/apache/gearpump/streaming/examples/transport/TransportSpec.scala
@@ -0,0 +1,69 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.examples.transport
+
+import scala.concurrent.Future
+import scala.util.Success
+
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{BeforeAndAfterAll, Matchers, PropSpec}
+
+import org.apache.gearpump.cluster.ClientToMaster.SubmitApplication
+import org.apache.gearpump.cluster.MasterToClient.SubmitApplicationResult
+import org.apache.gearpump.cluster.{MasterHarness, TestUtil}
+
+class TransportSpec
+ extends PropSpec with PropertyChecks with Matchers with BeforeAndAfterAll with MasterHarness {
+
+ override def beforeAll {
+ startActorSystem()
+ }
+
+ override def afterAll {
+ shutdownActorSystem()
+ }
+
+ protected override def config = TestUtil.DEFAULT_CONFIG
+
+ property("Transport should succeed to submit application with required arguments") {
+ val requiredArgs = Array.empty[String]
+ val optionalArgs = Array(
+ "-source", "1",
+ "-inspector", "1",
+ "-vehicle", "100",
+ "-citysize", "10",
+ "-threshold", "60")
+
+ val args = {
+ Table(
+ ("requiredArgs", "optionalArgs"),
+ (requiredArgs, optionalArgs)
+ )
+ }
+ val masterReceiver = createMockMaster()
+ forAll(args) { (requiredArgs: Array[String], optionalArgs: Array[String]) =>
+ val args = requiredArgs ++ optionalArgs
+
+ Future {
+ Transport.main(masterConfig, args)
+ }
+ masterReceiver.expectMsgType[SubmitApplication](PROCESS_BOOT_TIME)
+ masterReceiver.reply(SubmitApplicationResult(Success(0)))
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/transport/src/test/scala/org/apache/gearpump/streaming/examples/transport/generator/MockCitySpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/transport/src/test/scala/org/apache/gearpump/streaming/examples/transport/generator/MockCitySpec.scala b/examples/streaming/transport/src/test/scala/org/apache/gearpump/streaming/examples/transport/generator/MockCitySpec.scala
new file mode 100644
index 0000000..ba4eb2d
--- /dev/null
+++ b/examples/streaming/transport/src/test/scala/org/apache/gearpump/streaming/examples/transport/generator/MockCitySpec.scala
@@ -0,0 +1,31 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.examples.transport.generator
+
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{Matchers, PropSpec}
+
+class MockCitySpec extends PropSpec with PropertyChecks with Matchers {
+
+ property("MockCity should maintain the location properly") {
+ val city = new MockCity(10)
+ val start = city.randomLocationId()
+ val nextLocation = city.nextLocation(start)
+ assert(city.getDistance(start, nextLocation) == MockCity.LENGTH_PER_BLOCK)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/transport/src/test/scala/org/apache/gearpump/streaming/examples/transport/generator/PassRecordGeneratorSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/transport/src/test/scala/org/apache/gearpump/streaming/examples/transport/generator/PassRecordGeneratorSpec.scala b/examples/streaming/transport/src/test/scala/org/apache/gearpump/streaming/examples/transport/generator/PassRecordGeneratorSpec.scala
new file mode 100644
index 0000000..f0eebbf
--- /dev/null
+++ b/examples/streaming/transport/src/test/scala/org/apache/gearpump/streaming/examples/transport/generator/PassRecordGeneratorSpec.scala
@@ -0,0 +1,34 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.examples.transport.generator
+
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{Matchers, PropSpec}
+
+class PassRecordGeneratorSpec extends PropSpec with PropertyChecks with Matchers {
+
+ property("PassRecordGenerator should generate pass record") {
+ val id = "test"
+ val city = new MockCity(10)
+ val generator = new PassRecordGenerator(id, city, 60)
+ val passrecord1 = generator.getNextPassRecord()
+ val passrecord2 = generator.getNextPassRecord()
+ assert(city.getDistance(passrecord1.locationId, passrecord2.locationId) ==
+ MockCity.LENGTH_PER_BLOCK)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/wordcount-java/src/main/java/io/gearpump/streaming/examples/wordcountjava/Split.java
----------------------------------------------------------------------
diff --git a/examples/streaming/wordcount-java/src/main/java/io/gearpump/streaming/examples/wordcountjava/Split.java b/examples/streaming/wordcount-java/src/main/java/io/gearpump/streaming/examples/wordcountjava/Split.java
deleted file mode 100644
index 720e179..0000000
--- a/examples/streaming/wordcount-java/src/main/java/io/gearpump/streaming/examples/wordcountjava/Split.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.wordcountjava;
-
-import io.gearpump.Message;
-import io.gearpump.cluster.UserConfig;
-import io.gearpump.streaming.javaapi.Task;
-import io.gearpump.streaming.task.StartTime;
-import io.gearpump.streaming.task.TaskContext;
-
-public class Split extends Task {
-
- public static String TEXT = "This is a good start for java! bingo! bingo! ";
-
- public Split(TaskContext taskContext, UserConfig userConf) {
- super(taskContext, userConf);
- }
-
- private Long now() {
- return System.currentTimeMillis();
- }
-
- @Override
- public void onStart(StartTime startTime) {
- self().tell(new Message("start", now()), self());
- }
-
- @Override
- public void onNext(Message msg) {
-
- // Split the TEXT to words
- String[] words = TEXT.split(" ");
- for (int i = 0; i < words.length; i++) {
- context.output(new Message(words[i], now()));
- }
- self().tell(new Message("next", now()), self());
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/wordcount-java/src/main/java/io/gearpump/streaming/examples/wordcountjava/Sum.java
----------------------------------------------------------------------
diff --git a/examples/streaming/wordcount-java/src/main/java/io/gearpump/streaming/examples/wordcountjava/Sum.java b/examples/streaming/wordcount-java/src/main/java/io/gearpump/streaming/examples/wordcountjava/Sum.java
deleted file mode 100644
index 28cf8cb..0000000
--- a/examples/streaming/wordcount-java/src/main/java/io/gearpump/streaming/examples/wordcountjava/Sum.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.wordcountjava;
-
-import io.gearpump.Message;
-import io.gearpump.cluster.UserConfig;
-import io.gearpump.streaming.javaapi.Task;
-import io.gearpump.streaming.task.StartTime;
-import io.gearpump.streaming.task.TaskContext;
-import org.slf4j.Logger;
-
-import java.util.HashMap;
-
-public class Sum extends Task {
-
- private Logger LOG = super.LOG();
- private HashMap<String, Integer> wordCount = new HashMap<String, Integer>();
-
- public Sum(TaskContext taskContext, UserConfig userConf) {
- super(taskContext, userConf);
- }
-
- @Override
- public void onStart(StartTime startTime) {
- //skip
- }
-
- @Override
- public void onNext(Message messagePayLoad) {
- String word = (String) (messagePayLoad.msg());
- Integer current = wordCount.get(word);
- if (current == null) {
- current = 0;
- }
- Integer newCount = current + 1;
- wordCount.put(word, newCount);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/wordcount-java/src/main/java/io/gearpump/streaming/examples/wordcountjava/WordCount.java
----------------------------------------------------------------------
diff --git a/examples/streaming/wordcount-java/src/main/java/io/gearpump/streaming/examples/wordcountjava/WordCount.java b/examples/streaming/wordcount-java/src/main/java/io/gearpump/streaming/examples/wordcountjava/WordCount.java
deleted file mode 100644
index 40054d3..0000000
--- a/examples/streaming/wordcount-java/src/main/java/io/gearpump/streaming/examples/wordcountjava/WordCount.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.wordcountjava;
-
-import com.typesafe.config.Config;
-import io.gearpump.cluster.ClusterConfig;
-import io.gearpump.cluster.UserConfig;
-import io.gearpump.cluster.client.ClientContext;
-import io.gearpump.cluster.embedded.EmbeddedCluster;
-import io.gearpump.partitioner.HashPartitioner;
-import io.gearpump.partitioner.Partitioner;
-import io.gearpump.streaming.javaapi.Graph;
-import io.gearpump.streaming.javaapi.Processor;
-import io.gearpump.streaming.javaapi.StreamApplication;
-
-/** Java version of WordCount with Processor Graph API */
-public class WordCount {
-
- public static void main(String[] args) throws InterruptedException {
- main(ClusterConfig.defaultConfig(), args);
- }
-
- public static void main(Config akkaConf, String[] args) throws InterruptedException {
-
- // For split task, we config to create two tasks
- int splitTaskNumber = 2;
- Processor split = new Processor(Split.class).withParallelism(splitTaskNumber);
-
- // For sum task, we have two summer.
- int sumTaskNumber = 2;
- Processor sum = new Processor(Sum.class).withParallelism(sumTaskNumber);
-
- // construct the graph
- Graph graph = new Graph();
- graph.addVertex(split);
- graph.addVertex(sum);
-
- Partitioner partitioner = new HashPartitioner();
- graph.addEdge(split, partitioner, sum);
-
- UserConfig conf = UserConfig.empty();
- StreamApplication app = new StreamApplication("wordcountJava", conf, graph);
-
- EmbeddedCluster localCluster = null;
-
- Boolean debugMode = System.getProperty("DEBUG") != null;
-
- if (debugMode) {
- localCluster = new EmbeddedCluster(akkaConf);
- localCluster.start();
- }
-
- ClientContext masterClient = null;
-
- if (localCluster != null) {
- masterClient = localCluster.newClientContext();
- } else {
- // create master client
- // It will read the master settings under gearpump.cluster.masters
- masterClient = new ClientContext(akkaConf);
- }
-
- masterClient.submit(app);
-
- if (debugMode) {
- Thread.sleep(30 * 1000); // sleep for 30 seconds.
- }
-
- masterClient.close();
-
- if (localCluster != null) {
- localCluster.stop();
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/wordcount-java/src/main/java/io/gearpump/streaming/examples/wordcountjava/dsl/WordCount.java
----------------------------------------------------------------------
diff --git a/examples/streaming/wordcount-java/src/main/java/io/gearpump/streaming/examples/wordcountjava/dsl/WordCount.java b/examples/streaming/wordcount-java/src/main/java/io/gearpump/streaming/examples/wordcountjava/dsl/WordCount.java
deleted file mode 100644
index 3aefd7f..0000000
--- a/examples/streaming/wordcount-java/src/main/java/io/gearpump/streaming/examples/wordcountjava/dsl/WordCount.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.wordcountjava.dsl;
-
-import com.typesafe.config.Config;
-import io.gearpump.cluster.ClusterConfig;
-import io.gearpump.cluster.UserConfig;
-import io.gearpump.cluster.client.ClientContext;
-import io.gearpump.google.common.collect.Lists;
-import io.gearpump.streaming.dsl.javaapi.JavaStream;
-import io.gearpump.streaming.dsl.javaapi.JavaStreamApp;
-import io.gearpump.streaming.javaapi.dsl.functions.FlatMapFunction;
-import io.gearpump.streaming.javaapi.dsl.functions.GroupByFunction;
-import io.gearpump.streaming.javaapi.dsl.functions.MapFunction;
-import io.gearpump.streaming.javaapi.dsl.functions.ReduceFunction;
-import scala.Tuple2;
-
-import java.util.Iterator;
-import java.util.List;
-
-/** Java version of WordCount with high level DSL API */
-public class WordCount {
-
- public static void main(String[] args) throws InterruptedException {
- main(ClusterConfig.defaultConfig(), args);
- }
-
- public static void main(Config akkaConf, String[] args) throws InterruptedException {
- ClientContext context = new ClientContext(akkaConf);
- JavaStreamApp app = new JavaStreamApp("JavaDSL", context, UserConfig.empty());
- List<String> source = Lists.newArrayList("This is a good start, bingo!! bingo!!");
-
- JavaStream<String> sentence = app.source(source, 1, UserConfig.empty(), "source");
-
- JavaStream<String> words = sentence.flatMap(new FlatMapFunction<String, String>() {
- @Override
- public Iterator<String> apply(String s) {
- return Lists.newArrayList(s.split("\\s+")).iterator();
- }
- }, "flatMap");
-
- JavaStream<Tuple2<String, Integer>> ones = words.map(new MapFunction<String, Tuple2<String, Integer>>() {
- @Override
- public Tuple2<String, Integer> apply(String s) {
- return new Tuple2<String, Integer>(s, 1);
- }
- }, "map");
-
- JavaStream<Tuple2<String, Integer>> groupedOnes = ones.groupBy(new GroupByFunction<Tuple2<String, Integer>, String>() {
- @Override
- public String apply(Tuple2<String, Integer> tuple) {
- return tuple._1();
- }
- }, 1, "groupBy");
-
- JavaStream<Tuple2<String, Integer>> wordcount = groupedOnes.reduce(new ReduceFunction<Tuple2<String, Integer>>() {
- @Override
- public Tuple2<String, Integer> apply(Tuple2<String, Integer> t1, Tuple2<String, Integer> t2) {
- return new Tuple2<String, Integer>(t1._1(), t1._2() + t2._2());
- }
- }, "reduce");
-
- wordcount.log();
-
- app.run();
- context.close();
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/wordcount-java/src/main/java/org/apache/gearpump/streaming/examples/wordcountjava/Split.java
----------------------------------------------------------------------
diff --git a/examples/streaming/wordcount-java/src/main/java/org/apache/gearpump/streaming/examples/wordcountjava/Split.java b/examples/streaming/wordcount-java/src/main/java/org/apache/gearpump/streaming/examples/wordcountjava/Split.java
new file mode 100644
index 0000000..76069c1
--- /dev/null
+++ b/examples/streaming/wordcount-java/src/main/java/org/apache/gearpump/streaming/examples/wordcountjava/Split.java
@@ -0,0 +1,54 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.wordcountjava;
+
+import org.apache.gearpump.Message;
+import org.apache.gearpump.cluster.UserConfig;
+import org.apache.gearpump.streaming.javaapi.Task;
+import org.apache.gearpump.streaming.task.StartTime;
+import org.apache.gearpump.streaming.task.TaskContext;
+
+public class Split extends Task {
+
+ public static String TEXT = "This is a good start for java! bingo! bingo! ";
+
+ public Split(TaskContext taskContext, UserConfig userConf) {
+ super(taskContext, userConf);
+ }
+
+ private Long now() {
+ return System.currentTimeMillis();
+ }
+
+ @Override
+ public void onStart(StartTime startTime) {
+ self().tell(new Message("start", now()), self());
+ }
+
+ @Override
+ public void onNext(Message msg) {
+
+ // Split the TEXT to words
+ String[] words = TEXT.split(" ");
+ for (int i = 0; i < words.length; i++) {
+ context.output(new Message(words[i], now()));
+ }
+ self().tell(new Message("next", now()), self());
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/wordcount-java/src/main/java/org/apache/gearpump/streaming/examples/wordcountjava/Sum.java
----------------------------------------------------------------------
diff --git a/examples/streaming/wordcount-java/src/main/java/org/apache/gearpump/streaming/examples/wordcountjava/Sum.java b/examples/streaming/wordcount-java/src/main/java/org/apache/gearpump/streaming/examples/wordcountjava/Sum.java
new file mode 100644
index 0000000..89c3b14
--- /dev/null
+++ b/examples/streaming/wordcount-java/src/main/java/org/apache/gearpump/streaming/examples/wordcountjava/Sum.java
@@ -0,0 +1,54 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.wordcountjava;
+
+import org.apache.gearpump.Message;
+import org.apache.gearpump.cluster.UserConfig;
+import org.apache.gearpump.streaming.javaapi.Task;
+import org.apache.gearpump.streaming.task.StartTime;
+import org.apache.gearpump.streaming.task.TaskContext;
+import org.slf4j.Logger;
+
+import java.util.HashMap;
+
+public class Sum extends Task {
+
+ private Logger LOG = super.LOG();
+ private HashMap<String, Integer> wordCount = new HashMap<String, Integer>();
+
+ public Sum(TaskContext taskContext, UserConfig userConf) {
+ super(taskContext, userConf);
+ }
+
+ @Override
+ public void onStart(StartTime startTime) {
+ //skip
+ }
+
+ @Override
+ public void onNext(Message messagePayLoad) {
+ String word = (String) (messagePayLoad.msg());
+ Integer current = wordCount.get(word);
+ if (current == null) {
+ current = 0;
+ }
+ Integer newCount = current + 1;
+ wordCount.put(word, newCount);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/wordcount-java/src/main/java/org/apache/gearpump/streaming/examples/wordcountjava/WordCount.java
----------------------------------------------------------------------
diff --git a/examples/streaming/wordcount-java/src/main/java/org/apache/gearpump/streaming/examples/wordcountjava/WordCount.java b/examples/streaming/wordcount-java/src/main/java/org/apache/gearpump/streaming/examples/wordcountjava/WordCount.java
new file mode 100644
index 0000000..ee44536
--- /dev/null
+++ b/examples/streaming/wordcount-java/src/main/java/org/apache/gearpump/streaming/examples/wordcountjava/WordCount.java
@@ -0,0 +1,91 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.wordcountjava;
+
+import com.typesafe.config.Config;
+import org.apache.gearpump.cluster.ClusterConfig;
+import org.apache.gearpump.cluster.UserConfig;
+import org.apache.gearpump.cluster.client.ClientContext;
+import org.apache.gearpump.cluster.embedded.EmbeddedCluster;
+import org.apache.gearpump.partitioner.HashPartitioner;
+import org.apache.gearpump.partitioner.Partitioner;
+import org.apache.gearpump.streaming.javaapi.Graph;
+import org.apache.gearpump.streaming.javaapi.Processor;
+import org.apache.gearpump.streaming.javaapi.StreamApplication;
+
+/** Java version of WordCount with Processor Graph API */
+public class WordCount {
+
+ public static void main(String[] args) throws InterruptedException {
+ main(ClusterConfig.defaultConfig(), args);
+ }
+
+ public static void main(Config akkaConf, String[] args) throws InterruptedException {
+
+ // For split task, we config to create two tasks
+ int splitTaskNumber = 2;
+ Processor split = new Processor(Split.class).withParallelism(splitTaskNumber);
+
+ // For sum task, we have two summer.
+ int sumTaskNumber = 2;
+ Processor sum = new Processor(Sum.class).withParallelism(sumTaskNumber);
+
+ // construct the graph
+ Graph graph = new Graph();
+ graph.addVertex(split);
+ graph.addVertex(sum);
+
+ Partitioner partitioner = new HashPartitioner();
+ graph.addEdge(split, partitioner, sum);
+
+ UserConfig conf = UserConfig.empty();
+ StreamApplication app = new StreamApplication("wordcountJava", conf, graph);
+
+ EmbeddedCluster localCluster = null;
+
+ Boolean debugMode = System.getProperty("DEBUG") != null;
+
+ if (debugMode) {
+ localCluster = new EmbeddedCluster(akkaConf);
+ localCluster.start();
+ }
+
+ ClientContext masterClient = null;
+
+ if (localCluster != null) {
+ masterClient = localCluster.newClientContext();
+ } else {
+ // create master client
+ // It will read the master settings under gearpump.cluster.masters
+ masterClient = new ClientContext(akkaConf);
+ }
+
+ masterClient.submit(app);
+
+ if (debugMode) {
+ Thread.sleep(30 * 1000); // sleep for 30 seconds.
+ }
+
+ masterClient.close();
+
+ if (localCluster != null) {
+ localCluster.stop();
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/wordcount-java/src/main/java/org/apache/gearpump/streaming/examples/wordcountjava/dsl/WordCount.java
----------------------------------------------------------------------
diff --git a/examples/streaming/wordcount-java/src/main/java/org/apache/gearpump/streaming/examples/wordcountjava/dsl/WordCount.java b/examples/streaming/wordcount-java/src/main/java/org/apache/gearpump/streaming/examples/wordcountjava/dsl/WordCount.java
new file mode 100644
index 0000000..0ecc42e
--- /dev/null
+++ b/examples/streaming/wordcount-java/src/main/java/org/apache/gearpump/streaming/examples/wordcountjava/dsl/WordCount.java
@@ -0,0 +1,85 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.wordcountjava.dsl;
+
+import com.typesafe.config.Config;
+import org.apache.gearpump.cluster.ClusterConfig;
+import org.apache.gearpump.cluster.UserConfig;
+import org.apache.gearpump.cluster.client.ClientContext;
+import org.apache.gearpump.streaming.dsl.javaapi.JavaStream;
+import org.apache.gearpump.streaming.dsl.javaapi.JavaStreamApp;
+import org.apache.gearpump.streaming.javaapi.dsl.functions.FlatMapFunction;
+import org.apache.gearpump.streaming.javaapi.dsl.functions.GroupByFunction;
+import org.apache.gearpump.streaming.javaapi.dsl.functions.MapFunction;
+import org.apache.gearpump.streaming.javaapi.dsl.functions.ReduceFunction;
+import scala.Tuple2;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
+
+/** Java version of WordCount with high level DSL API */
+public class WordCount {
+
+ public static void main(String[] args) throws InterruptedException {
+ main(ClusterConfig.defaultConfig(), args);
+ }
+
+ public static void main(Config akkaConf, String[] args) throws InterruptedException {
+ ClientContext context = new ClientContext(akkaConf);
+ JavaStreamApp app = new JavaStreamApp("JavaDSL", context, UserConfig.empty());
+ List<String> source = new ArrayList<>(Arrays.asList("This is a good start, bingo!! bingo!!"));
+
+ JavaStream<String> sentence = app.source(source, 1, UserConfig.empty(), "source");
+
+ JavaStream<String> words = sentence.flatMap(new FlatMapFunction<String, String>() {
+ @Override
+ public Iterator<String> apply(String s) {
+ return new ArrayList<String>(Arrays.asList(s.split("\\s+"))).iterator();
+ }
+ }, "flatMap");
+
+ JavaStream<Tuple2<String, Integer>> ones = words.map(new MapFunction<String, Tuple2<String, Integer>>() {
+ @Override
+ public Tuple2<String, Integer> apply(String s) {
+ return new Tuple2<String, Integer>(s, 1);
+ }
+ }, "map");
+
+ JavaStream<Tuple2<String, Integer>> groupedOnes = ones.groupBy(new GroupByFunction<Tuple2<String, Integer>, String>() {
+ @Override
+ public String apply(Tuple2<String, Integer> tuple) {
+ return tuple._1();
+ }
+ }, 1, "groupBy");
+
+ JavaStream<Tuple2<String, Integer>> wordcount = groupedOnes.reduce(new ReduceFunction<Tuple2<String, Integer>>() {
+ @Override
+ public Tuple2<String, Integer> apply(Tuple2<String, Integer> t1, Tuple2<String, Integer> t2) {
+ return new Tuple2<String, Integer>(t1._1(), t1._2() + t2._2());
+ }
+ }, "reduce");
+
+ wordcount.log();
+
+ app.run();
+ context.close();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/wordcount-java/src/test/scala/io/gearpump/streaming/examples/wordcountjava/WordCountSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/wordcount-java/src/test/scala/io/gearpump/streaming/examples/wordcountjava/WordCountSpec.scala b/examples/streaming/wordcount-java/src/test/scala/io/gearpump/streaming/examples/wordcountjava/WordCountSpec.scala
deleted file mode 100644
index 1a1d019..0000000
--- a/examples/streaming/wordcount-java/src/test/scala/io/gearpump/streaming/examples/wordcountjava/WordCountSpec.scala
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.wordcount
-
-import scala.concurrent.Future
-import scala.util.Success
-
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{BeforeAndAfter, Matchers, PropSpec}
-
-import io.gearpump.cluster.ClientToMaster.SubmitApplication
-import io.gearpump.cluster.MasterToClient.SubmitApplicationResult
-import io.gearpump.cluster.{MasterHarness, TestUtil}
-import io.gearpump.streaming.examples.wordcountjava.WordCount
-
-class WordCountSpec
- extends PropSpec with PropertyChecks with Matchers with BeforeAndAfter with MasterHarness {
-
- before {
- startActorSystem()
- }
-
- after {
- shutdownActorSystem()
- }
-
- protected override def config = TestUtil.DEFAULT_CONFIG
-
- property("WordCount should succeed to submit application with required arguments") {
- val requiredArgs = Array.empty[String]
-
- val masterReceiver = createMockMaster()
-
- val args = requiredArgs
-
- Future {
- WordCount.main(masterConfig, args)
- }
-
- masterReceiver.expectMsgType[SubmitApplication](PROCESS_BOOT_TIME)
- masterReceiver.reply(SubmitApplicationResult(Success(0)))
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/wordcount-java/src/test/scala/org/apache/gearpump/streaming/examples/wordcountjava/WordCountSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/wordcount-java/src/test/scala/org/apache/gearpump/streaming/examples/wordcountjava/WordCountSpec.scala b/examples/streaming/wordcount-java/src/test/scala/org/apache/gearpump/streaming/examples/wordcountjava/WordCountSpec.scala
new file mode 100644
index 0000000..3736c86
--- /dev/null
+++ b/examples/streaming/wordcount-java/src/test/scala/org/apache/gearpump/streaming/examples/wordcountjava/WordCountSpec.scala
@@ -0,0 +1,59 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.wordcountjava
+
+import scala.concurrent.Future
+import scala.util.Success
+
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{BeforeAndAfter, Matchers, PropSpec}
+
+import org.apache.gearpump.cluster.ClientToMaster.SubmitApplication
+import org.apache.gearpump.cluster.MasterToClient.SubmitApplicationResult
+import org.apache.gearpump.cluster.{MasterHarness, TestUtil}
+import org.apache.gearpump.streaming.examples.wordcountjava.WordCount
+
+class WordCountSpec
+ extends PropSpec with PropertyChecks with Matchers with BeforeAndAfter with MasterHarness {
+
+ before {
+ startActorSystem()
+ }
+
+ after {
+ shutdownActorSystem()
+ }
+
+ protected override def config = TestUtil.DEFAULT_CONFIG
+
+ property("WordCount should succeed to submit application with required arguments") {
+ val requiredArgs = Array.empty[String]
+
+ val masterReceiver = createMockMaster()
+
+ val args = requiredArgs
+
+ Future {
+ WordCount.main(masterConfig, args)
+ }
+
+ masterReceiver.expectMsgType[SubmitApplication](PROCESS_BOOT_TIME)
+ masterReceiver.reply(SubmitApplicationResult(Success(0)))
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/wordcount/src/main/scala/io/gearpump/streaming/examples/wordcount/Split.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/wordcount/src/main/scala/io/gearpump/streaming/examples/wordcount/Split.scala b/examples/streaming/wordcount/src/main/scala/io/gearpump/streaming/examples/wordcount/Split.scala
deleted file mode 100644
index 387bc75..0000000
--- a/examples/streaming/wordcount/src/main/scala/io/gearpump/streaming/examples/wordcount/Split.scala
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.wordcount
-
-import java.util.concurrent.TimeUnit
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.task.{StartTime, Task, TaskContext}
-
-class Split(taskContext: TaskContext, conf: UserConfig) extends Task(taskContext, conf) {
- import taskContext.output
-
- override def onStart(startTime: StartTime): Unit = {
- self ! Message("start")
- }
-
- override def onNext(msg: Message): Unit = {
- Split.TEXT_TO_SPLIT.lines.foreach { line =>
- line.split("[\\s]+").filter(_.nonEmpty).foreach { msg =>
- output(new Message(msg, System.currentTimeMillis()))
- }
- }
-
- import scala.concurrent.duration._
- taskContext.scheduleOnce(Duration(100, TimeUnit.MILLISECONDS))(self !
- Message("continue", System.currentTimeMillis()))
- }
-}
-
-object Split {
- val TEXT_TO_SPLIT =
- """
- | 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.
- """.stripMargin
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/wordcount/src/main/scala/io/gearpump/streaming/examples/wordcount/Sum.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/wordcount/src/main/scala/io/gearpump/streaming/examples/wordcount/Sum.scala b/examples/streaming/wordcount/src/main/scala/io/gearpump/streaming/examples/wordcount/Sum.scala
deleted file mode 100644
index 6560066..0000000
--- a/examples/streaming/wordcount/src/main/scala/io/gearpump/streaming/examples/wordcount/Sum.scala
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.wordcount
-
-import java.util.concurrent.TimeUnit
-import scala.collection.mutable
-import scala.concurrent.duration.FiniteDuration
-
-import akka.actor.Cancellable
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.task.{StartTime, Task, TaskContext}
-
-class Sum(taskContext: TaskContext, conf: UserConfig) extends Task(taskContext, conf) {
- private[wordcount] val map: mutable.HashMap[String, Long] = new mutable.HashMap[String, Long]()
-
- private[wordcount] var wordCount: Long = 0
- private var snapShotTime: Long = System.currentTimeMillis()
- private var snapShotWordCount: Long = 0
-
- private var scheduler: Cancellable = null
-
- override def onStart(startTime: StartTime): Unit = {
- scheduler = taskContext.schedule(new FiniteDuration(5, TimeUnit.SECONDS),
- new FiniteDuration(30, TimeUnit.SECONDS))(reportWordCount)
- }
-
- override def onNext(msg: Message): Unit = {
- if (null != msg) {
- val current = map.getOrElse(msg.msg.asInstanceOf[String], 0L)
- wordCount += 1
- map.put(msg.msg.asInstanceOf[String], current + 1)
- }
- }
-
- override def onStop(): Unit = {
- if (scheduler != null) {
- scheduler.cancel()
- }
- }
-
- def reportWordCount(): Unit = {
- val current: Long = System.currentTimeMillis()
- LOG.info(s"Task ${taskContext.taskId} Throughput:" +
- s" ${(wordCount - snapShotWordCount, (current - snapShotTime) / 1000)} (words, second)")
- snapShotWordCount = wordCount
- snapShotTime = current
- }
-}
\ No newline at end of file
[25/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/scala/io/gearpump/experiments/storm/util/StormUtil.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/scala/io/gearpump/experiments/storm/util/StormUtil.scala b/experiments/storm/src/main/scala/io/gearpump/experiments/storm/util/StormUtil.scala
deleted file mode 100644
index 554210c..0000000
--- a/experiments/storm/src/main/scala/io/gearpump/experiments/storm/util/StormUtil.scala
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.experiments.storm.util
-
-import java.lang.{Boolean => JBoolean}
-import java.util.{HashMap => JHashMap, Map => JMap}
-
-import akka.actor.ActorSystem
-import backtype.storm.Config
-import backtype.storm.generated._
-import org.apache.storm.shade.org.json.simple.JSONValue
-
-import io.gearpump.cluster.UserConfig
-import io.gearpump.experiments.storm.topology.GearpumpStormComponent.{GearpumpBolt, GearpumpSpout}
-import io.gearpump.experiments.storm.topology._
-import io.gearpump.experiments.storm.util.StormConstants._
-import io.gearpump.streaming.task.{TaskContext, TaskId}
-import io.gearpump.util.Util
-
-object StormUtil {
-
- /**
- * Convert storm task id to gearpump [[io.gearpump.streaming.task.TaskId]]
- *
- * The high 16 bit of an Int is TaskId.processorId
- * The low 16 bit of an Int is TaskId.index
- */
- def stormTaskIdToGearpump(id: Integer): TaskId = {
- val index = id & 0xFFFF
- val processorId = id >> 16
- TaskId(processorId, index)
- }
-
- /**
- * convert gearpump [[TaskId]] to storm task id
- * TaskId.processorId is the high 16 bit of an Int
- * TaskId.index is the low 16 bit of an Int
- */
- def gearpumpTaskIdToStorm(taskId: TaskId): Integer = {
- val index = taskId.index
- val processorId = taskId.processorId
- (processorId << 16) + (index & 0xFFFF)
- }
-
- /**
- * @return a configured [[GearpumpStormComponent]]
- */
- def getGearpumpStormComponent(
- taskContext: TaskContext, conf: UserConfig)(implicit system: ActorSystem)
- : GearpumpStormComponent = {
- val topology = conf.getValue[StormTopology](STORM_TOPOLOGY).get
- val stormConfig = conf.getValue[JMap[AnyRef, AnyRef]](STORM_CONFIG).get
- val componentId = conf.getString(STORM_COMPONENT).get
- val spouts = topology.get_spouts
- val bolts = topology.get_bolts
- if (spouts.containsKey(componentId)) {
- GearpumpSpout(topology, stormConfig, spouts.get(componentId), taskContext)
- } else if (bolts.containsKey(componentId)) {
- GearpumpBolt(topology, stormConfig, bolts.get(componentId), taskContext)
- } else {
- throw new Exception(s"storm component $componentId not found")
- }
- }
-
- /**
- * Parses config in json to map, returns empty map for invalid json string
- *
- * @param json config in json
- * @return config in map
- */
- def parseJsonStringToMap(json: String): JMap[AnyRef, AnyRef] = {
- Option(json).flatMap(json => JSONValue.parse(json) match {
- case m: JMap[_, _] => Option(m.asInstanceOf[JMap[AnyRef, AnyRef]])
- case _ => None
- }).getOrElse(new JHashMap[AnyRef, AnyRef])
- }
-
- /**
- * get Int value of the config name
- */
- def getInt(conf: JMap[_, _], name: String): Option[Int] = {
- Option(conf.get(name)).map {
- case number: Number => number.intValue
- case invalid => throw new IllegalArgumentException(
- s"$name must be Java Integer; actual: ${invalid.getClass}")
- }
- }
-
- /**
- * get Boolean value of the config name
- */
- def getBoolean(conf: JMap[_, _], name: AnyRef): Option[Boolean] = {
- Option(conf.get(name)).map {
- case b: JBoolean => b.booleanValue()
- case invalid => throw new IllegalArgumentException(
- s"$name must be a Java Boolean; acutal: ${invalid.getClass}")
- }
- }
-
- /**
- * clojure mod ported from Storm
- * see https://clojuredocs.org/clojure.core/mod
- */
- def mod(num: Int, div: Int): Int = {
- (num % div + div) % div
- }
-
- def ackEnabled(config: JMap[AnyRef, AnyRef]): Boolean = {
- if (config.containsKey(Config.TOPOLOGY_ACKER_EXECUTORS)) {
- getInt(config, Config.TOPOLOGY_ACKER_EXECUTORS).map(_ != 0).getOrElse(true)
- } else {
- false
- }
- }
-
- def getThriftPort(): Int = {
- Util.findFreePort().getOrElse(
- throw new Exception("unable to find free port for thrift server"))
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/StormRunner.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/StormRunner.scala b/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/StormRunner.scala
new file mode 100644
index 0000000..51760ba
--- /dev/null
+++ b/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/StormRunner.scala
@@ -0,0 +1,54 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.storm
+
+import org.apache.gearpump.experiments.storm.main.{GearpumpNimbus, GearpumpStormClient}
+import org.apache.gearpump.util.LogUtil
+import org.slf4j.Logger
+
+object StormRunner {
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+
+ private val commands = Map("nimbus" -> GearpumpNimbus, "app" -> GearpumpStormClient)
+
+ private def usage(): Unit = {
+ val keys = commands.keys.toList.sorted
+ // scalastyle:off println
+ Console.err.println("Usage: " + "<" + keys.mkString("|") + ">")
+ // scalastyle:on println
+ }
+
+ private def executeCommand(command: String, commandArgs: Array[String]): Unit = {
+ if (!commands.contains(command)) {
+ usage()
+ } else {
+ commands(command).main(commandArgs)
+ }
+ }
+
+ def main(args: Array[String]): Unit = {
+ if (args.length == 0) {
+ usage()
+ } else {
+ val command = args(0)
+ val commandArgs = args.drop(1)
+ executeCommand(command, commandArgs)
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/main/GearpumpNimbus.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/main/GearpumpNimbus.scala b/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/main/GearpumpNimbus.scala
new file mode 100644
index 0000000..544a4eb
--- /dev/null
+++ b/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/main/GearpumpNimbus.scala
@@ -0,0 +1,289 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.storm.main
+
+import java.io.{File, FileOutputStream, FileWriter}
+import java.nio.ByteBuffer
+import java.nio.channels.{Channels, WritableByteChannel}
+import java.util.{HashMap => JHashMap, Map => JMap, UUID}
+import scala.collection.JavaConverters._
+import scala.concurrent.duration.Duration
+import scala.concurrent.{Await, Future}
+
+import akka.actor.ActorSystem
+import com.typesafe.config.ConfigValueFactory
+import backtype.storm.Config
+import backtype.storm.generated._
+import backtype.storm.security.auth.{ThriftConnectionType, ThriftServer}
+import backtype.storm.utils.Utils
+import org.apache.storm.shade.org.json.simple.JSONValue
+import org.apache.storm.shade.org.yaml.snakeyaml.Yaml
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.client.ClientContext
+import org.apache.gearpump.cluster.main.{ArgumentsParser, CLIOption}
+import org.apache.gearpump.cluster.{MasterToAppMaster, UserConfig}
+import org.apache.gearpump.experiments.storm.topology.GearpumpStormTopology
+import org.apache.gearpump.experiments.storm.util.TimeCacheMapWrapper.Callback
+import org.apache.gearpump.experiments.storm.util.{GraphBuilder, StormConstants, StormUtil, TimeCacheMapWrapper}
+import org.apache.gearpump.streaming.StreamApplication
+import org.apache.gearpump.util.{AkkaApp, Constants, LogUtil}
+
+object GearpumpNimbus extends AkkaApp with ArgumentsParser {
+ private val THRIFT_PORT = StormUtil.getThriftPort()
+ private val OUTPUT = "output"
+ private val LOG: Logger = LogUtil.getLogger(classOf[GearpumpNimbus])
+
+ override val options: Array[(String, CLIOption[Any])] = Array(
+ OUTPUT -> CLIOption[String]("<output path for configuration file>",
+ required = false, defaultValue = Some("app.yaml"))
+ )
+
+ override def main(inputAkkaConf: Config, args: Array[String]): Unit = {
+ val parsed = parse(args)
+ val output = parsed.getString(OUTPUT)
+ val akkaConf = updateClientConfig(inputAkkaConf)
+ val system = ActorSystem("storm", akkaConf)
+
+ val clientContext = new ClientContext(akkaConf, system, null)
+ val stormConf = Utils.readStormConfig().asInstanceOf[JMap[AnyRef, AnyRef]]
+ val thriftConf: JMap[AnyRef, AnyRef] = Map(
+ Config.NIMBUS_HOST -> akkaConf.getString(Constants.GEARPUMP_HOSTNAME),
+ Config.NIMBUS_THRIFT_PORT -> s"$THRIFT_PORT").asJava.asInstanceOf[JMap[AnyRef, AnyRef]]
+ updateStormConfig(thriftConf, output)
+ stormConf.putAll(thriftConf)
+
+ import scala.concurrent.ExecutionContext.Implicits.global
+ Future {
+ val thriftServer = createServer(clientContext, stormConf)
+ thriftServer.serve()
+ }
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+
+ private def createServer(
+ clientContext: ClientContext, stormConf: JMap[AnyRef, AnyRef]): ThriftServer = {
+ val processor = new Nimbus.Processor[GearpumpNimbus](new GearpumpNimbus(clientContext,
+ stormConf))
+ val connectionType = ThriftConnectionType.NIMBUS
+ new ThriftServer(stormConf, processor, connectionType)
+ }
+
+ private def updateStormConfig(thriftConfig: JMap[AnyRef, AnyRef], output: String): Unit = {
+ val updatedConfig: JMap[AnyRef, AnyRef] = new JHashMap[AnyRef, AnyRef]
+ val outputConfig = Utils.findAndReadConfigFile(output, false).asInstanceOf[JMap[AnyRef, AnyRef]]
+ updatedConfig.putAll(outputConfig)
+ updatedConfig.putAll(thriftConfig)
+ val yaml = new Yaml
+ val serialized = yaml.dumpAsMap(updatedConfig)
+ val writer = new FileWriter(new File(output))
+ try {
+ writer.write(serialized)
+ } catch {
+ case e: Exception => throw e
+ } finally {
+ writer.close()
+ }
+ }
+
+ import org.apache.gearpump.util.Constants._
+ private def updateClientConfig(config: Config): Config = {
+ val storm = s"<${GEARPUMP_HOME}>/lib/storm/*"
+ val appClassPath = s"$storm${File.pathSeparator}" +
+ config.getString(GEARPUMP_APPMASTER_EXTRA_CLASSPATH)
+ val executorClassPath = s"$storm${File.pathSeparator}" +
+ config.getString(Constants.GEARPUMP_EXECUTOR_EXTRA_CLASSPATH)
+
+ val updated = config
+ .withValue(GEARPUMP_APPMASTER_EXTRA_CLASSPATH, ConfigValueFactory.fromAnyRef(appClassPath))
+ .withValue(GEARPUMP_EXECUTOR_EXTRA_CLASSPATH,
+ ConfigValueFactory.fromAnyRef(executorClassPath))
+
+ if (config.hasPath(StormConstants.STORM_SERIALIZATION_FRAMEWORK)) {
+ val serializerConfig = ConfigValueFactory.fromAnyRef(
+ config.getString(StormConstants.STORM_SERIALIZATION_FRAMEWORK))
+ updated.withValue(GEARPUMP_SERIALIZER_POOL, serializerConfig)
+ } else {
+ updated
+ }
+ }
+}
+
+class GearpumpNimbus(clientContext: ClientContext, stormConf: JMap[AnyRef, AnyRef])
+ extends Nimbus.Iface {
+
+ import org.apache.gearpump.experiments.storm.main.GearpumpNimbus._
+
+ private var applications = Map.empty[String, Int]
+ private var topologies = Map.empty[String, TopologyData]
+ private val expireSeconds = StormUtil.getInt(stormConf,
+ Config.NIMBUS_FILE_COPY_EXPIRATION_SECS).get
+ private val expiredCallback = new Callback[String, WritableByteChannel] {
+ override def expire(k: String, v: WritableByteChannel): Unit = {
+ v.close()
+ }
+ }
+ private val fileCacheMap = new TimeCacheMapWrapper[String, WritableByteChannel](expireSeconds,
+ expiredCallback)
+
+ override def submitTopology(
+ name: String, uploadedJarLocation: String, jsonConf: String, topology: StormTopology)
+ : Unit = {
+ submitTopologyWithOpts(name, uploadedJarLocation, jsonConf, topology,
+ new SubmitOptions(TopologyInitialStatus.ACTIVE))
+ }
+
+ override def submitTopologyWithOpts(
+ name: String, uploadedJarLocation: String,
+ jsonConf: String, topology: StormTopology, options: SubmitOptions): Unit = {
+ LOG.info(s"Submitted topology $name")
+ implicit val system = clientContext.system
+ val gearpumpStormTopology = GearpumpStormTopology(name, topology, jsonConf)
+ val stormConfig = gearpumpStormTopology.getStormConfig
+ val workerNum = StormUtil.getInt(stormConfig, Config.TOPOLOGY_WORKERS).getOrElse(1)
+ val processorGraph = GraphBuilder.build(gearpumpStormTopology)
+ val config = UserConfig.empty
+ .withValue[StormTopology](StormConstants.STORM_TOPOLOGY, topology)
+ .withValue[JMap[AnyRef, AnyRef]](StormConstants.STORM_CONFIG, stormConfig)
+ val app = StreamApplication(name, processorGraph, config)
+ LOG.info(s"jar file uploaded to $uploadedJarLocation")
+ val appId = clientContext.submit(app, uploadedJarLocation, workerNum)
+ applications += name -> appId
+ topologies += name -> TopologyData(topology, stormConfig, uploadedJarLocation)
+ LOG.info(s"Storm Application $appId submitted")
+ }
+
+ override def killTopologyWithOpts(name: String, options: KillOptions): Unit = {
+ if (applications.contains(name)) {
+ clientContext.shutdown(applications(name))
+ removeTopology(name)
+ LOG.info(s"Killed topology $name")
+ } else {
+ throw new RuntimeException(s"topology $name not found")
+ }
+ }
+
+ override def getNimbusConf: String = {
+ JSONValue.toJSONString(stormConf)
+ }
+
+ override def getTopology(name: String): StormTopology = {
+ updateApps()
+ topologies.getOrElse(name,
+ throw new RuntimeException(s"topology $name not found")).topology
+ }
+
+ override def getTopologyConf(name: String): String = {
+ updateApps()
+ JSONValue.toJSONString(topologies.getOrElse(name,
+ throw new RuntimeException(s"topology $name not found")).config)
+ }
+
+ override def getUserTopology(id: String): StormTopology = getTopology(id)
+
+ override def beginFileUpload(): String = {
+ val file = File.createTempFile(s"storm-jar-${UUID.randomUUID()}", ".jar")
+ val location = file.getAbsolutePath
+ val channel = Channels.newChannel(new FileOutputStream(location))
+ fileCacheMap.put(location, channel)
+ LOG.info(s"Uploading file from client to $location")
+ location
+ }
+
+ override def uploadChunk(location: String, chunk: ByteBuffer): Unit = {
+ if (!fileCacheMap.containsKey(location)) {
+ throw new RuntimeException(s"File for $location does not exist (or timed out)")
+ } else {
+ val channel = fileCacheMap.get(location)
+ channel.write(chunk)
+ fileCacheMap.put(location, channel)
+ }
+ }
+
+ override def finishFileUpload(location: String): Unit = {
+ if (!fileCacheMap.containsKey(location)) {
+ throw new RuntimeException(s"File for $location does not exist (or timed out)")
+ } else {
+ val channel = fileCacheMap.get(location)
+ channel.close()
+ fileCacheMap.remove(location)
+ }
+ }
+
+ override def getClusterInfo: ClusterSummary = {
+ updateApps()
+ val topologySummaryList = topologies.map { case (name, _) =>
+ new TopologySummary(name, name, 0, 0, 0, 0, "")
+ }.toSeq
+ new ClusterSummary(List[SupervisorSummary]().asJava, 0, topologySummaryList.asJava)
+ }
+
+ override def beginFileDownload(file: String): String = {
+ throw new UnsupportedOperationException
+ }
+
+ override def uploadNewCredentials(s: String, credentials: Credentials): Unit = {
+ throw new UnsupportedOperationException
+ }
+ override def activate(name: String): Unit = {
+ throw new UnsupportedOperationException
+ }
+
+ override def rebalance(name: String, options: RebalanceOptions): Unit = {
+ throw new UnsupportedOperationException
+ }
+
+ override def deactivate(name: String): Unit = {
+ throw new UnsupportedOperationException
+ }
+
+ override def getTopologyInfo(name: String): TopologyInfo = {
+ throw new UnsupportedOperationException
+ }
+
+ override def getTopologyInfoWithOpts(s: String, getInfoOptions: GetInfoOptions): TopologyInfo = {
+ throw new UnsupportedOperationException
+ }
+
+ override def killTopology(name: String): Unit = killTopologyWithOpts(name, new KillOptions())
+
+ override def downloadChunk(name: String): ByteBuffer = {
+ throw new UnsupportedOperationException
+ }
+
+ private def updateApps(): Unit = {
+ clientContext.listApps.appMasters.foreach { app =>
+ val name = app.appName
+ if (applications.contains(name)) {
+ if (app.status != MasterToAppMaster.AppMasterActive) {
+ removeTopology(name)
+ }
+ }
+ }
+ }
+
+ private def removeTopology(name: String): Unit = {
+ applications -= name
+ val jar = topologies(name).jar
+ new File(jar).delete()
+ topologies -= name
+ }
+}
+
+case class TopologyData(topology: StormTopology, config: JMap[AnyRef, AnyRef], jar: String)
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/main/GearpumpStormClient.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/main/GearpumpStormClient.scala b/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/main/GearpumpStormClient.scala
new file mode 100644
index 0000000..1cfd5a4
--- /dev/null
+++ b/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/main/GearpumpStormClient.scala
@@ -0,0 +1,73 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.storm.main
+
+import backtype.storm.Config
+import backtype.storm.utils.Utils
+import org.apache.gearpump.cluster.main.{ArgumentsParser, CLIOption}
+import org.apache.gearpump.util.Constants._
+import org.apache.gearpump.util.{AkkaApp, LogUtil, Util}
+
+object GearpumpStormClient extends AkkaApp with ArgumentsParser {
+
+ override val options: Array[(String, CLIOption[Any])] = Array(
+ "jar" -> CLIOption[String]("<storm jar>", required = true),
+ "config" -> CLIOption[Int]("<storm config file>", required = true),
+ "verbose" -> CLIOption("<print verbose log on console>", required = false,
+ defaultValue = Some(false)))
+
+ override def main(inputAkkaConf: Config, args: Array[String]): Unit = {
+ val config = parse(args)
+
+ val verbose = config.getBoolean("verbose")
+ if (verbose) {
+ LogUtil.verboseLogToConsole()
+ }
+
+ val jar = config.getString("jar")
+ val stormConfig = config.getString("config")
+ val topology = config.remainArgs(0)
+ val stormArgs = config.remainArgs.drop(1)
+ val stormOptions = Array(
+ s"-Dstorm.options=${getThriftOptions(stormConfig)}",
+ s"-Dstorm.jar=$jar",
+ s"-Dstorm.conf.file=$stormConfig",
+ s"-D${PREFER_IPV4}=true"
+ )
+
+ val gearpumpHome = System.getProperty(GEARPUMP_HOME)
+ val classPath = Array(s"$gearpumpHome/lib/*", s"$gearpumpHome/lib/storm/*", jar)
+ val process = Util.startProcess(stormOptions, classPath, topology, stormArgs)
+
+ // Waits till the process exit
+ val exit = process.exitValue()
+
+ if (exit != 0) {
+ throw new Exception(s"failed to submit jar, exit code $exit, " +
+ s"error summary: ${process.logger.error}")
+ }
+ }
+
+ private def getThriftOptions(stormConfig: String): String = {
+ val config = Utils.findAndReadConfigFile(stormConfig, true)
+ val host = config.get(Config.NIMBUS_HOST)
+ val thriftPort = config.get(Config.NIMBUS_THRIFT_PORT)
+ s"${Config.NIMBUS_HOST}=$host,${Config.NIMBUS_THRIFT_PORT}=$thriftPort"
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/partitioner/StormPartitioner.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/partitioner/StormPartitioner.scala b/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/partitioner/StormPartitioner.scala
new file mode 100644
index 0000000..aaa0a99
--- /dev/null
+++ b/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/partitioner/StormPartitioner.scala
@@ -0,0 +1,49 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.storm.partitioner
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.experiments.storm.topology.GearpumpTuple
+import org.apache.gearpump.partitioner.{MulticastPartitioner, Partitioner}
+
+/**
+ * Partitioner bound to a target Storm component
+ *
+ * Partitioning is already done in
+ * [[org.apache.gearpump.experiments.storm.util.StormOutputCollector]] and
+ * kept in "targetPartitions" of [[org.apache.gearpump.experiments.storm.topology.GearpumpTuple]]
+ * the partitioner just returns the partitions of the target
+ *
+ * In Gearpump, a message is sent from a task to all the subscribers.
+ * In Storm, however, a message is sent to one or more of the subscribers.
+ * Hence, we have to do the partitioning in
+ * [[org.apache.gearpump.experiments.storm.util.StormOutputCollector]] till the Storm way is
+ * supported in Gearpump
+ *
+ * @param target target storm component id
+ */
+private[storm] class StormPartitioner(target: String) extends MulticastPartitioner {
+
+ override def getPartitions(msg: Message, partitionNum: Int, currentPartitionId: Int)
+ : Array[Int] = {
+ val stormTuple = msg.msg.asInstanceOf[GearpumpTuple]
+ stormTuple.targetPartitions.getOrElse(target, Array(Partitioner.UNKNOWN_PARTITION_ID))
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/processor/StormBoltOutputCollector.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/processor/StormBoltOutputCollector.scala b/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/processor/StormBoltOutputCollector.scala
new file mode 100644
index 0000000..a70ce48
--- /dev/null
+++ b/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/processor/StormBoltOutputCollector.scala
@@ -0,0 +1,75 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.storm.processor
+
+import java.util.{Collection => JCollection, List => JList}
+
+import backtype.storm.task.IOutputCollector
+import backtype.storm.tuple.Tuple
+import org.apache.gearpump.experiments.storm.topology.TimedTuple
+import org.apache.gearpump.experiments.storm.util.StormConstants._
+import org.apache.gearpump.experiments.storm.util.StormOutputCollector
+import org.apache.gearpump.streaming.task.ReportCheckpointClock
+
+/**
+ * this is used by Storm bolt to emit messages
+ */
+private[storm] class StormBoltOutputCollector(collector: StormOutputCollector,
+ ackEnabled: Boolean = false) extends IOutputCollector {
+ private var reportTime = 0L
+ private var maxAckTime = 0L
+
+ override def emit(
+ streamId: String, anchors: JCollection[Tuple], tuple: JList[AnyRef]): JList[Integer] = {
+ collector.emit(streamId, tuple)
+ }
+
+ override def emitDirect(
+ taskId: Int, streamId: String, anchors: JCollection[Tuple], tuple: JList[AnyRef]): Unit = {
+ collector.emitDirect(taskId, streamId, tuple)
+ }
+
+ override def fail(tuple: Tuple): Unit = {
+ // application failure, throw exception such that the tuple can be replayed
+ // Note: do not print the tuple which will trigger NPE since its messageId is null
+ throw new Exception("Storm Bolt.execute failed")
+ }
+
+ override def ack(tuple: Tuple): Unit = {
+ if (ackEnabled) {
+ tuple match {
+ case timedTuple: TimedTuple =>
+ maxAckTime = Math.max(maxAckTime, timedTuple.timestamp)
+ val taskContext = collector.taskContext
+ val upstreamMinClock = taskContext.upstreamMinClock
+ if (reportTime <= upstreamMinClock && upstreamMinClock <= maxAckTime) {
+ reportTime = upstreamMinClock / CHECKPOINT_INTERVAL_MILLIS * CHECKPOINT_INTERVAL_MILLIS
+ taskContext.appMaster ! ReportCheckpointClock(taskContext.taskId, reportTime)
+ reportTime += CHECKPOINT_INTERVAL_MILLIS
+ }
+ case _ =>
+ // ignore other tuples
+ }
+ }
+ }
+
+ override def reportError(throwable: Throwable): Unit = {
+ throw throwable
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/processor/StormProcessor.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/processor/StormProcessor.scala b/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/processor/StormProcessor.scala
new file mode 100644
index 0000000..1d3048e
--- /dev/null
+++ b/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/processor/StormProcessor.scala
@@ -0,0 +1,71 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.storm.processor
+
+import java.util.concurrent.TimeUnit
+import scala.concurrent.duration.Duration
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.experiments.storm.topology.GearpumpStormComponent.GearpumpBolt
+import org.apache.gearpump.experiments.storm.util._
+import org.apache.gearpump.streaming.task._
+
+object StormProcessor {
+ private[storm] val TICK = Message("tick")
+}
+
+/**
+ * this is runtime container for Storm bolt
+ */
+private[storm] class StormProcessor(gearpumpBolt: GearpumpBolt,
+ taskContext: TaskContext, conf: UserConfig)
+ extends Task(taskContext, conf) {
+ import org.apache.gearpump.experiments.storm.processor.StormProcessor._
+
+ def this(taskContext: TaskContext, conf: UserConfig) = {
+ this(StormUtil.getGearpumpStormComponent(taskContext, conf)(taskContext.system)
+ .asInstanceOf[GearpumpBolt], taskContext, conf)
+ }
+
+ private val freqOpt = gearpumpBolt.getTickFrequency
+
+ override def onStart(startTime: StartTime): Unit = {
+ gearpumpBolt.start(startTime)
+ freqOpt.foreach(scheduleTick)
+ }
+
+ override def onNext(message: Message): Unit = {
+ message match {
+ case TICK =>
+ freqOpt.foreach { freq =>
+ gearpumpBolt.tick(freq)
+ scheduleTick(freq)
+ }
+ case _ =>
+ gearpumpBolt.next(message)
+ }
+ }
+
+ private def scheduleTick(freq: Int): Unit = {
+ taskContext.scheduleOnce(Duration(freq, TimeUnit.SECONDS)) {
+ self ! TICK
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/producer/StormProducer.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/producer/StormProducer.scala b/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/producer/StormProducer.scala
new file mode 100644
index 0000000..5d4a6a2
--- /dev/null
+++ b/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/producer/StormProducer.scala
@@ -0,0 +1,91 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.storm.producer
+
+import java.util.concurrent.TimeUnit
+
+import akka.actor.Actor.Receive
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.experiments.storm.topology.GearpumpStormComponent.GearpumpSpout
+import org.apache.gearpump.experiments.storm.util._
+import org.apache.gearpump.streaming.task._
+
+import scala.concurrent.duration.Duration
+
+object StormProducer {
+ private[storm] val TIMEOUT = Message("timeout")
+}
+
+/**
+ * this is runtime container for Storm spout
+ */
+private[storm] class StormProducer(gearpumpSpout: GearpumpSpout,
+ taskContext: TaskContext, conf: UserConfig)
+ extends Task(taskContext, conf) {
+ import org.apache.gearpump.experiments.storm.producer.StormProducer._
+
+ def this(taskContext: TaskContext, conf: UserConfig) = {
+ this(StormUtil.getGearpumpStormComponent(taskContext, conf)(taskContext.system)
+ .asInstanceOf[GearpumpSpout], taskContext, conf)
+ }
+
+ private val timeoutMillis = gearpumpSpout.getMessageTimeout
+
+ override def onStart(startTime: StartTime): Unit = {
+ gearpumpSpout.start(startTime)
+ if (gearpumpSpout.ackEnabled) {
+ getCheckpointClock
+ }
+ timeoutMillis.foreach(scheduleTimeout)
+ self ! Message("start")
+ }
+
+ override def onNext(msg: Message): Unit = {
+ msg match {
+ case TIMEOUT =>
+ timeoutMillis.foreach { timeout =>
+ gearpumpSpout.timeout(timeout)
+ scheduleTimeout(timeout)
+ }
+ case _ =>
+ gearpumpSpout.next(msg)
+ }
+ self ! Message("continue")
+ }
+
+ override def receiveUnManagedMessage: Receive = {
+ case CheckpointClock(optClock) =>
+ optClock.foreach { clock =>
+ gearpumpSpout.checkpoint(clock)
+ }
+ getCheckpointClock()
+ }
+
+ def getCheckpointClock(): Unit = {
+ taskContext.scheduleOnce(Duration(StormConstants.CHECKPOINT_INTERVAL_MILLIS,
+ TimeUnit.MILLISECONDS))(taskContext.appMaster ! GetCheckpointClock)
+ }
+
+ private def scheduleTimeout(timeout: Long): Unit = {
+ taskContext.scheduleOnce(Duration(timeout, TimeUnit.MILLISECONDS)) {
+ self ! TIMEOUT
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/producer/StormSpoutOutputCollector.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/producer/StormSpoutOutputCollector.scala b/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/producer/StormSpoutOutputCollector.scala
new file mode 100644
index 0000000..5794b1d
--- /dev/null
+++ b/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/producer/StormSpoutOutputCollector.scala
@@ -0,0 +1,104 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.storm.producer
+
+import java.util.{List => JList}
+
+import backtype.storm.spout.{ISpout, ISpoutOutputCollector}
+import org.apache.gearpump.TimeStamp
+import org.apache.gearpump.experiments.storm.util.StormOutputCollector
+
+case class PendingMessage(id: Object, messageTime: TimeStamp, startTime: TimeStamp)
+
+/**
+ * this is used by Storm Spout to emit messages
+ */
+private[storm] class StormSpoutOutputCollector(
+ collector: StormOutputCollector, spout: ISpout, ackEnabled: Boolean)
+ extends ISpoutOutputCollector {
+
+ private var checkpointClock = 0L
+ private var pendingMessage: Option[PendingMessage] = None
+ private var nextPendingMessage: Option[PendingMessage] = None
+
+ override def emit(streamId: String, values: JList[AnyRef], messageId: Object): JList[Integer] = {
+ val curTime = System.currentTimeMillis()
+ collector.setTimestamp(curTime)
+ val outTasks = collector.emit(streamId, values)
+ setPendingOrAck(messageId, curTime, curTime)
+ outTasks
+ }
+
+ override def reportError(throwable: Throwable): Unit = {
+ throw throwable
+ }
+
+ override def emitDirect(taskId: Int, streamId: String, values: JList[AnyRef], messageId: Object)
+ : Unit = {
+ val curTime = System.currentTimeMillis()
+ collector.setTimestamp(curTime)
+ collector.emitDirect(taskId, streamId, values)
+ setPendingOrAck(messageId, curTime, curTime)
+ }
+
+ def ackPendingMessage(checkpointClock: TimeStamp): Unit = {
+ this.checkpointClock = checkpointClock
+ nextPendingMessage.foreach { case PendingMessage(_, messageTime, _) =>
+ if (messageTime <= this.checkpointClock) {
+ pendingMessage.foreach { case PendingMessage(id, _, _) =>
+ spout.ack(id)
+ reset()
+ }
+ }
+ }
+ }
+
+ def failPendingMessage(timeoutMillis: Long): Unit = {
+ pendingMessage.foreach { case PendingMessage(id, _, startTime) =>
+ if (System.currentTimeMillis() - startTime >= timeoutMillis) {
+ spout.fail(id)
+ reset()
+ }
+ }
+ }
+
+ private def reset(): Unit = {
+ pendingMessage = nextPendingMessage
+ nextPendingMessage = None
+ }
+
+ private def setPendingOrAck(messageId: Object, startTime: TimeStamp, messageTime: TimeStamp)
+ : Unit = {
+ if (ackEnabled) {
+ val newPendingMessage = PendingMessage(messageId, messageTime, startTime)
+ pendingMessage match {
+ case Some(msg) =>
+ if (nextPendingMessage.isEmpty && msg.messageTime <= this.checkpointClock) {
+ nextPendingMessage = Some(newPendingMessage)
+ } else {
+ spout.ack(messageId)
+ }
+ case None =>
+ pendingMessage = Some(newPendingMessage)
+ }
+ } else {
+ spout.ack(messageId)
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/topology/GearpumpStormComponent.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/topology/GearpumpStormComponent.scala b/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/topology/GearpumpStormComponent.scala
new file mode 100644
index 0000000..d0f2949
--- /dev/null
+++ b/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/topology/GearpumpStormComponent.scala
@@ -0,0 +1,385 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.storm.topology
+
+import java.io.{File, FileOutputStream, IOException}
+import java.util
+import java.util.jar.JarFile
+import java.util.{HashMap => JHashMap, List => JList, Map => JMap}
+
+import akka.actor.ActorRef
+import akka.pattern.ask
+import backtype.storm.Config
+import backtype.storm.generated.{Bolt, ComponentCommon, SpoutSpec, StormTopology}
+import backtype.storm.metric.api.IMetric
+import backtype.storm.spout.{ISpout, SpoutOutputCollector}
+import backtype.storm.task.{GeneralTopologyContext, IBolt, OutputCollector, TopologyContext}
+import backtype.storm.tuple.{Fields, Tuple, TupleImpl}
+import backtype.storm.utils.Utils
+import clojure.lang.Atom
+import org.apache.commons.io.{FileUtils, IOUtils}
+import org.apache.gearpump.experiments.storm.processor.StormBoltOutputCollector
+import org.apache.gearpump.experiments.storm.producer.StormSpoutOutputCollector
+import org.apache.gearpump.experiments.storm.util.StormConstants._
+import org.apache.gearpump.experiments.storm.util.StormUtil._
+import org.apache.gearpump.experiments.storm.util.{StormOutputCollector, StormUtil}
+import org.apache.gearpump.streaming.DAG
+import org.apache.gearpump.streaming.task.{GetDAG, TaskId, TaskContext, StartTime}
+import org.apache.gearpump.util.{Constants, LogUtil}
+import org.apache.gearpump.{Message, TimeStamp}
+import org.slf4j.Logger
+
+import scala.collection.JavaConverters._
+import scala.concurrent.{Await, Future}
+
+/**
+ * subclass wraps Storm Spout and Bolt, and their lifecycles
+ * hides the complexity from Gearpump applications
+ */
+trait GearpumpStormComponent {
+ /**
+ * invoked at Task.onStart
+ * @param startTime task start time
+ */
+ def start(startTime: StartTime): Unit
+
+ /**
+ * invoked at Task.onNext
+ * @param message incoming message
+ */
+ def next(message: Message): Unit
+
+ /**
+ * invoked at Task.onStop
+ */
+ def stop(): Unit = {}
+}
+
+object GearpumpStormComponent {
+ private val LOG: Logger = LogUtil.getLogger(classOf[GearpumpStormComponent])
+
+ object GearpumpSpout {
+ def apply(topology: StormTopology, config: JMap[AnyRef, AnyRef],
+ spoutSpec: SpoutSpec, taskContext: TaskContext): GearpumpSpout = {
+ val componentCommon = spoutSpec.get_common()
+ val scalaMap = config.asScala.toMap // Convert to scala immutable map
+ val normalizedConfig = normalizeConfig(scalaMap, componentCommon)
+ val getTopologyContext = (dag: DAG, taskId: TaskId) => {
+ val stormTaskId = gearpumpTaskIdToStorm(taskId)
+ buildTopologyContext(dag, topology, normalizedConfig, stormTaskId)
+ }
+ val spout = Utils.getSetComponentObject(spoutSpec.get_spout_object()).asInstanceOf[ISpout]
+ val ackEnabled = StormUtil.ackEnabled(config)
+ if (ackEnabled) {
+ val className = spout.getClass.getName
+ if (!isSequentiallyReplayableSpout(className)) {
+ LOG.warn(s"at least once is not supported for $className")
+ }
+ }
+ val getOutputCollector = (taskContext: TaskContext, topologyContext: TopologyContext) => {
+ new StormSpoutOutputCollector(
+ StormOutputCollector(taskContext, topologyContext), spout, ackEnabled)
+ }
+ GearpumpSpout(
+ normalizedConfig,
+ spout,
+ askAppMasterForDAG,
+ getTopologyContext,
+ getOutputCollector,
+ ackEnabled,
+ taskContext)
+ }
+
+ private def isSequentiallyReplayableSpout(className: String): Boolean = {
+ className.equals("storm.kafka.KafkaSpout")
+ }
+ }
+
+ case class GearpumpSpout(
+ config: JMap[AnyRef, AnyRef],
+ spout: ISpout,
+ getDAG: ActorRef => DAG,
+ getTopologyContext: (DAG, TaskId) => TopologyContext,
+ getOutputCollector: (TaskContext, TopologyContext) => StormSpoutOutputCollector,
+ ackEnabled: Boolean,
+ taskContext: TaskContext)
+ extends GearpumpStormComponent {
+
+ private var collector: StormSpoutOutputCollector = null
+
+ override def start(startTime: StartTime): Unit = {
+ val dag = getDAG(taskContext.appMaster)
+ val topologyContext = getTopologyContext(dag, taskContext.taskId)
+ collector = getOutputCollector(taskContext, topologyContext)
+ spout.open(config, topologyContext, new SpoutOutputCollector(collector))
+ }
+
+ override def next(message: Message): Unit = {
+ spout.nextTuple()
+ }
+
+ /**
+ * @return timeout in milliseconds if enabled
+ */
+ def getMessageTimeout: Option[Long] = {
+ StormUtil.getBoolean(config, Config.TOPOLOGY_ENABLE_MESSAGE_TIMEOUTS).flatMap {
+ timeoutEnabled =>
+ if (timeoutEnabled) {
+ StormUtil.getInt(config, Config.TOPOLOGY_MESSAGE_TIMEOUT_SECS).map(_ * 1000L)
+ } else {
+ None
+ }
+ }
+ }
+
+ def checkpoint(clock: TimeStamp): Unit = {
+ collector.ackPendingMessage(clock)
+ }
+
+ def timeout(timeoutMillis: Long): Unit = {
+ collector.failPendingMessage(timeoutMillis)
+ }
+ }
+
+ object GearpumpBolt {
+ def apply(topology: StormTopology, config: JMap[AnyRef, AnyRef],
+ boltSpec: Bolt, taskContext: TaskContext): GearpumpBolt = {
+ val configAsScalaMap = config.asScala.toMap // Convert to scala immutable map
+ val normalizedConfig = normalizeConfig(configAsScalaMap, boltSpec.get_common())
+ val getTopologyContext = (dag: DAG, taskId: TaskId) => {
+ val stormTaskId = gearpumpTaskIdToStorm(taskId)
+ buildTopologyContext(dag, topology, normalizedConfig, stormTaskId)
+ }
+ val getGeneralTopologyContext = (dag: DAG) => {
+ buildGeneralTopologyContext(dag, topology, normalizedConfig)
+ }
+ val getOutputCollector = (taskContext: TaskContext, topologyContext: TopologyContext) => {
+ StormOutputCollector(taskContext, topologyContext)
+ }
+ val getTickTuple = (topologyContext: GeneralTopologyContext, freq: Int) => {
+
+ val values = new util.ArrayList[Object] // To be compatible with Java interface
+ values.add(freq.asInstanceOf[java.lang.Integer])
+ new TupleImpl(topologyContext, values, SYSTEM_TASK_ID, SYSTEM_TICK_STREAM_ID, null)
+ }
+ GearpumpBolt(
+ normalizedConfig,
+ Utils.getSetComponentObject(boltSpec.get_bolt_object()).asInstanceOf[IBolt],
+ askAppMasterForDAG,
+ getTopologyContext,
+ getGeneralTopologyContext,
+ getOutputCollector,
+ getTickTuple,
+ taskContext)
+ }
+ }
+
+ case class GearpumpBolt(
+ config: JMap[AnyRef, AnyRef],
+ bolt: IBolt,
+ getDAG: ActorRef => DAG,
+ getTopologyContext: (DAG, TaskId) => TopologyContext,
+ getGeneralTopologyContext: DAG => GeneralTopologyContext,
+ getOutputCollector: (TaskContext, TopologyContext) => StormOutputCollector,
+ getTickTuple: (GeneralTopologyContext, Int) => Tuple,
+ taskContext: TaskContext)
+ extends GearpumpStormComponent {
+
+ private var collector: StormOutputCollector = null
+ private var topologyContext: TopologyContext = null
+ private var generalTopologyContext: GeneralTopologyContext = null
+ private var tickTuple: Tuple = null
+
+ override def start(startTime: StartTime): Unit = {
+ val dag = getDAG(taskContext.appMaster)
+ topologyContext = getTopologyContext(dag, taskContext.taskId)
+ generalTopologyContext = getGeneralTopologyContext(dag)
+ collector = getOutputCollector(taskContext, topologyContext)
+ val delegate = new StormBoltOutputCollector(collector, StormUtil.ackEnabled(config))
+ bolt.prepare(config, topologyContext, new OutputCollector(delegate))
+ }
+
+ override def next(message: Message): Unit = {
+ val timestamp = message.timestamp
+ collector.setTimestamp(timestamp)
+ bolt.execute(message.msg.asInstanceOf[GearpumpTuple].toTuple(generalTopologyContext,
+ timestamp))
+ }
+
+ def getTickFrequency: Option[Int] = {
+ StormUtil.getInt(config, Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS)
+ }
+
+ /**
+ * invoked at TICK message when "topology.tick.tuple.freq.secs" is configured
+ * @param freq tick frequency
+ */
+ def tick(freq: Int): Unit = {
+ if (null == tickTuple) {
+ tickTuple = getTickTuple(generalTopologyContext, freq)
+ }
+ bolt.execute(tickTuple)
+ }
+ }
+
+ /**
+ * normalize general config with per component configs
+ * "topology.transactional.id" and "topology.tick.tuple.freq.secs"
+ * @param stormConfig general config for all components
+ * @param componentCommon common component parts
+ */
+ private def normalizeConfig(stormConfig: Map[AnyRef, AnyRef],
+ componentCommon: ComponentCommon): JMap[AnyRef, AnyRef] = {
+ val config: JMap[AnyRef, AnyRef] = new JHashMap[AnyRef, AnyRef]
+ config.putAll(stormConfig.asJava)
+ val componentConfig = parseJsonStringToMap(componentCommon.get_json_conf())
+ Option(componentConfig.get(Config.TOPOLOGY_TRANSACTIONAL_ID))
+ .foreach(config.put(Config.TOPOLOGY_TRANSACTIONAL_ID, _))
+ Option(componentConfig.get(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS))
+ .foreach(config.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, _))
+ config
+ }
+
+ private def askAppMasterForDAG(appMaster: ActorRef): DAG = {
+ implicit val timeout = Constants.FUTURE_TIMEOUT
+ val dagFuture = (appMaster ? GetDAG).asInstanceOf[Future[DAG]]
+ Await.result(dagFuture, timeout.duration)
+ }
+
+ private def buildGeneralTopologyContext(dag: DAG, topology: StormTopology, stormConf: JMap[_, _])
+ : GeneralTopologyContext = {
+ val taskToComponent = getTaskToComponent(dag)
+ val componentToSortedTasks: JMap[String, JList[Integer]] =
+ getComponentToSortedTasks(taskToComponent)
+ val componentToStreamFields: JMap[String, JMap[String, Fields]] =
+ getComponentToStreamFields(topology)
+ new GeneralTopologyContext(
+ topology, stormConf, taskToComponent.asJava, componentToSortedTasks,
+ componentToStreamFields, null)
+ }
+
+ private def buildTopologyContext(
+ dag: DAG, topology: StormTopology, stormConf: JMap[_, _], stormTaskId: Integer)
+ : TopologyContext = {
+ val taskToComponent = getTaskToComponent(dag)
+ val componentToSortedTasks: JMap[String, JList[Integer]] =
+ getComponentToSortedTasks(taskToComponent)
+ val componentToStreamFields: JMap[String, JMap[String, Fields]] =
+ getComponentToStreamFields(topology)
+ val codeDir = mkCodeDir
+ val pidDir = mkPidDir
+
+ new TopologyContext(topology, stormConf, taskToComponent.asJava, componentToSortedTasks,
+ componentToStreamFields, null, codeDir, pidDir, stormTaskId, null, null, null, null,
+ new JHashMap[String, AnyRef], new JHashMap[Integer, JMap[Integer, JMap[String, IMetric]]],
+ new Atom(false))
+ }
+
+ private def getComponentToStreamFields(topology: StormTopology)
+ : JMap[String, JMap[String, Fields]] = {
+ val spouts = topology.get_spouts().asScala
+ val bolts = topology.get_bolts().asScala
+
+ val spoutFields = spouts.map {
+ case (id, component) => id -> getComponentToFields(component.get_common())
+ }
+
+ val boltFields = bolts.map {
+ case (id, component) => id -> getComponentToFields(component.get_common())
+ }
+
+ val systemFields = Map(SYSTEM_COMPONENT_ID ->
+ Map(SYSTEM_TICK_STREAM_ID -> new Fields(SYSTEM_COMPONENT_OUTPUT_FIELDS)).asJava)
+
+ (spoutFields ++ boltFields ++ systemFields).asJava
+ }
+
+ private def getComponentToFields(common: ComponentCommon): JMap[String, Fields] = {
+ val streams = common.get_streams.asScala
+ streams.map { case (sid, stream) =>
+ sid -> new Fields(stream.get_output_fields())
+ }.asJava
+ }
+
+ private def getComponentToSortedTasks(
+ taskToComponent: Map[Integer, String]): JMap[String, JList[Integer]] = {
+ taskToComponent.groupBy(_._2).map { case (component, map) =>
+ val sortedTasks = map.keys.toList.sorted.asJava
+ component -> sortedTasks
+ }.asJava
+ }
+
+ private def getTaskToComponent(dag: DAG): Map[Integer, String] = {
+ val taskToComponent = dag.processors.flatMap { case (processorId, processorDescription) =>
+ val parallelism = processorDescription.parallelism
+ val component = processorDescription.taskConf.getString(STORM_COMPONENT).get
+ (0 until parallelism).map(index =>
+ gearpumpTaskIdToStorm(TaskId(processorId, index)) -> component)
+ }
+ taskToComponent
+ }
+
+ // Workarounds to support storm ShellBolt
+ private def mkPidDir: String = {
+ val pidDir = FileUtils.getTempDirectoryPath + File.separator + "pid"
+ try {
+ FileUtils.forceMkdir(new File(pidDir))
+ } catch {
+ case ex: IOException =>
+ LOG.error(s"failed to create pid directory $pidDir")
+ }
+ pidDir
+ }
+
+ // a workaround to support storm ShellBolt
+ private def mkCodeDir: String = {
+ val jarPath = System.getProperty("java.class.path").split(":").last
+ val destDir = FileUtils.getTempDirectoryPath + File.separator + "storm"
+
+ try {
+ FileUtils.forceMkdir(new File(destDir))
+
+ val jar = new JarFile(jarPath)
+ val enumEntries = jar.entries().asScala
+ enumEntries.foreach { entry =>
+ val file = new File(destDir + File.separator + entry.getName)
+ if (!entry.isDirectory) {
+ file.getParentFile.mkdirs()
+
+ val is = jar.getInputStream(entry)
+ val fos = new FileOutputStream(file)
+ try {
+ IOUtils.copy(is, fos)
+ } catch {
+ case ex: IOException =>
+ LOG.error(s"failed to copy data from ${entry.getName} to ${file.getName}")
+ } finally {
+ fos.close()
+ is.close()
+ }
+ }
+ }
+ } catch {
+ case ex: IOException =>
+ LOG.error(s"could not extract $destDir from $jarPath")
+ }
+
+ destDir + File.separator + "resources"
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/topology/GearpumpStormTopology.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/topology/GearpumpStormTopology.scala b/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/topology/GearpumpStormTopology.scala
new file mode 100644
index 0000000..62bc25c
--- /dev/null
+++ b/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/topology/GearpumpStormTopology.scala
@@ -0,0 +1,320 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.storm.topology
+
+import java.lang.{Iterable => JIterable}
+import java.util.{ArrayList => JArrayList, HashMap => JHashMap, List => JList, Map => JMap}
+
+import akka.actor.ActorSystem
+import backtype.storm.Config
+import backtype.storm.generated._
+import backtype.storm.utils.{ThriftTopologyUtils, Utils}
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.experiments.storm.processor.StormProcessor
+import org.apache.gearpump.experiments.storm.producer.StormProducer
+import org.apache.gearpump.experiments.storm.util.StormConstants._
+import org.apache.gearpump.experiments.storm.util.StormUtil
+import org.apache.gearpump.experiments.storm.util.StormUtil._
+import org.apache.gearpump.streaming.Processor
+import org.apache.gearpump.streaming.task.Task
+import org.apache.gearpump.util.LogUtil
+import org.slf4j.Logger
+
+// TODO: Refactor this file, we should disable using of JavaConversions
+// scalastyle:off javaconversions
+import scala.collection.JavaConversions._
+// scalastyle:on javaconversions
+
+object GearpumpStormTopology {
+ private val LOG: Logger = LogUtil.getLogger(classOf[GearpumpStormTopology])
+
+ def apply(
+ name: String,
+ topology: StormTopology,
+ appConfigInJson: String)(implicit system: ActorSystem): GearpumpStormTopology = {
+ new GearpumpStormTopology(
+ name,
+ topology,
+ Utils.readStormConfig().asInstanceOf[JMap[AnyRef, AnyRef]],
+ parseJsonStringToMap(appConfigInJson)
+ )
+ }
+}
+
+/**
+ * this is a wrapper over Storm topology which
+ * 1. merges Storm and Gearpump configs
+ * 2. creates Gearpump processors
+ * 3. provides interface for Gearpump applications to use Storm topology
+ *
+ * an implicit ActorSystem is required to create Gearpump processors
+ * @param name topology name
+ * @param topology Storm topology
+ * @param sysConfig configs from "defaults.yaml" and custom config file
+ * @param appConfig config submitted from user application
+ */
+private[storm] class GearpumpStormTopology(
+ name: String,
+ topology: StormTopology,
+ sysConfig: JMap[AnyRef, AnyRef],
+ appConfig: JMap[AnyRef, AnyRef])(implicit system: ActorSystem) {
+
+ private val spouts = topology.get_spouts()
+ private val bolts = topology.get_bolts()
+ private val stormConfig = mergeConfigs(sysConfig, appConfig, getComponentConfigs(spouts, bolts))
+ private val spoutProcessors = spouts.map { case (id, spout) =>
+ id -> spoutToProcessor(id, spout, stormConfig.toMap)
+ }.toMap
+ private val boltProcessors = bolts.map { case (id, bolt) =>
+ id -> boltToProcessor(id, bolt, stormConfig.toMap)
+ }.toMap
+ private val allProcessors = spoutProcessors ++ boltProcessors
+
+ /**
+ * @return merged Storm config with priority
+ * defaults.yaml < custom file config < application config < component config
+ */
+ def getStormConfig: JMap[AnyRef, AnyRef] = stormConfig
+
+ /**
+ * @return Storm components to Gearpump processors
+ */
+ def getProcessors: Map[String, Processor[Task]] = allProcessors
+
+ /**
+ * @param sourceId source component id
+ * @return target Storm components and Gearpump processors
+ */
+ def getTargets(sourceId: String): Map[String, Processor[Task]] = {
+ getTargets(sourceId, topology).map { case (targetId, _) =>
+ targetId -> boltProcessors(targetId)
+ }
+ }
+
+ /**
+ * merge configs from application, custom config file and component
+ */
+ private def mergeConfigs(
+ sysConfig: JMap[AnyRef, AnyRef],
+ appConfig: JMap[AnyRef, AnyRef],
+ componentConfigs: Iterable[JMap[AnyRef, AnyRef]]): JMap[AnyRef, AnyRef] = {
+ val allConfig = new JHashMap[AnyRef, AnyRef]
+ allConfig.putAll(sysConfig)
+ allConfig.putAll(appConfig)
+ allConfig.putAll(getMergedComponentConfig(componentConfigs, allConfig.toMap))
+ allConfig.put(Config.TOPOLOGY_NAME, name)
+ allConfig
+ }
+
+ /**
+ * creates Gearpump processor from Storm spout
+ * @param spoutId spout id
+ * @param spoutSpec spout spec
+ * @param stormConfig merged storm config
+ * @param system actor system
+ * @return a Processor[StormProducer]
+ */
+ private def spoutToProcessor(spoutId: String, spoutSpec: SpoutSpec,
+ stormConfig: Map[AnyRef, AnyRef])(implicit system: ActorSystem): Processor[Task] = {
+ val componentCommon = spoutSpec.get_common()
+ val taskConf = UserConfig.empty
+ .withString(STORM_COMPONENT, spoutId)
+ val parallelism = getParallelism(stormConfig, componentCommon)
+ Processor[StormProducer](parallelism, spoutId, taskConf)
+ }
+
+ /**
+ * creates Gearpump processor from Storm bolt
+ * @param boltId bolt id
+ * @param boltSpec bolt spec
+ * @param stormConfig merged storm config
+ * @param system actor system
+ * @return a Processor[StormProcessor]
+ */
+ private def boltToProcessor(boltId: String, boltSpec: Bolt,
+ stormConfig: Map[AnyRef, AnyRef])(implicit system: ActorSystem): Processor[Task] = {
+ val componentCommon = boltSpec.get_common()
+ val taskConf = UserConfig.empty
+ .withString(STORM_COMPONENT, boltId)
+ .withBoolean("state.checkpoint.enable", StormUtil.ackEnabled(stormConfig))
+ val parallelism = getParallelism(stormConfig, componentCommon)
+ Processor[StormProcessor](parallelism, boltId, taskConf)
+ }
+
+ /**
+ * @return target components and streams
+ */
+ private def getTargets(componentId: String, topology: StormTopology)
+ : Map[String, Map[String, Grouping]] = {
+ val componentIds = ThriftTopologyUtils.getComponentIds(topology)
+ componentIds.flatMap { otherComponentId =>
+ getInputs(otherComponentId, topology).toList.map(otherComponentId -> _)
+ }.foldLeft(Map.empty[String, Map[String, Grouping]]) {
+ (allTargets, componentAndInput) =>
+ val (otherComponentId, (globalStreamId, grouping)) = componentAndInput
+ val inputStreamId = globalStreamId.get_streamId()
+ val inputComponentId = globalStreamId.get_componentId
+ if (inputComponentId.equals(componentId)) {
+ val curr = allTargets.getOrElse(otherComponentId, Map.empty[String, Grouping])
+ allTargets + (otherComponentId -> (curr + (inputStreamId -> grouping)))
+ } else {
+ allTargets
+ }
+ }
+ }
+
+ /**
+ * @return input stream and grouping for a Storm component
+ */
+ private def getInputs(componentId: String, topology: StormTopology)
+ : JMap[GlobalStreamId, Grouping] = {
+ ThriftTopologyUtils.getComponentCommon(topology, componentId).get_inputs
+ }
+
+ /**
+ * get Storm component parallelism according to the following rule,
+ * 1. use "topology.tasks" if defined; otherwise use parallelism_hint
+ * 2. parallelism should not be larger than "topology.max.task.parallelism" if defined
+ * 3. component config overrides system config
+ * @param stormConfig System configs without merging "topology.tasks" and
+ * "topology.max.task.parallelism" of component
+ * @return number of task instances for a component
+ */
+ private def getParallelism(stormConfig: Map[AnyRef, AnyRef], component: ComponentCommon): Int = {
+ val parallelismHint: Int = if (component.is_set_parallelism_hint()) {
+ component.get_parallelism_hint()
+ } else {
+ 1
+ }
+ val mergedConfig = new JHashMap[AnyRef, AnyRef]
+ val componentConfig = parseJsonStringToMap(component.get_json_conf)
+ mergedConfig.putAll(stormConfig)
+ mergedConfig.putAll(componentConfig)
+ val numTasks: Int = getInt(mergedConfig, Config.TOPOLOGY_TASKS).getOrElse(parallelismHint)
+ val parallelism: Int = getInt(mergedConfig, Config.TOPOLOGY_MAX_TASK_PARALLELISM)
+ .fold(numTasks)(p => math.min(p, numTasks))
+ parallelism
+ }
+
+ private def getComponentConfigs(spouts: JMap[String, SpoutSpec],
+ bolts: JMap[String, Bolt]): Iterable[JMap[AnyRef, AnyRef]] = {
+ spouts.map { case (id, spoutSpec) =>
+ parseJsonStringToMap(spoutSpec.get_common().get_json_conf())
+ } ++ bolts.map { case (id, boltSpec) =>
+ parseJsonStringToMap(boltSpec.get_common().get_json_conf())
+ }
+ }
+
+ /**
+ * merge component configs "topology.kryo.decorators" and "topology.kryo.register"
+ * @param componentConfigs list of component configs
+ * @param allConfig existing configs without merging component configs
+ * @return the two configs merged from all the component configs and existing configs
+ */
+ private def getMergedComponentConfig(componentConfigs: Iterable[JMap[AnyRef, AnyRef]],
+ allConfig: Map[AnyRef, AnyRef]): JMap[AnyRef, AnyRef] = {
+ val mergedConfig: JMap[AnyRef, AnyRef] = new JHashMap[AnyRef, AnyRef]
+ mergedConfig.putAll(getMergedKryoDecorators(componentConfigs, allConfig))
+ mergedConfig.putAll(getMergedKryoRegister(componentConfigs, allConfig))
+ mergedConfig
+ }
+
+ /**
+ * @param componentConfigs list of component configs
+ * @param allConfig existing configs without merging component configs
+ * @return a merged config with a list of distinct kryo decorators from component and
+ * existing configs
+ */
+ private def getMergedKryoDecorators(componentConfigs: Iterable[JMap[AnyRef, AnyRef]],
+ allConfig: Map[AnyRef, AnyRef]): JMap[AnyRef, AnyRef] = {
+ val mergedConfig: JMap[AnyRef, AnyRef] = new JHashMap[AnyRef, AnyRef](1)
+ val key = Config.TOPOLOGY_KRYO_DECORATORS
+ val configs = getConfigValues(componentConfigs, allConfig, key)
+ val distincts = configs.foldLeft(Set.empty[String]) {
+ case (accum, config: JIterable[_]) =>
+ accum ++ config.map {
+ case s: String => s
+ case illegal =>
+ throw new IllegalArgumentException(s"$key must be a List of Strings; actually $illegal")
+ }
+ case (accum, null) =>
+ accum
+ case illegal =>
+ throw new IllegalArgumentException(s"$key must be a List of Strings; actually $illegal")
+ }
+ if (distincts.nonEmpty) {
+ val decorators: JList[String] = new JArrayList(distincts.size)
+ decorators.addAll(distincts)
+ mergedConfig.put(key, decorators)
+ }
+ mergedConfig
+ }
+
+ /**
+ * @param componentConfigs list of component configs
+ * @param allConfig existing configs without merging component configs
+ * @return a merged config with component config overriding existing configs
+ */
+ private def getMergedKryoRegister(componentConfigs: Iterable[JMap[AnyRef, AnyRef]],
+ allConfig: Map[AnyRef, AnyRef]): JMap[AnyRef, AnyRef] = {
+ val mergedConfig: JMap[AnyRef, AnyRef] = new JHashMap[AnyRef, AnyRef](1)
+ val key = Config.TOPOLOGY_KRYO_REGISTER
+ val configs = getConfigValues(componentConfigs, allConfig, key)
+ val merged = configs.foldLeft(Map.empty[String, String]) {
+ case (accum, config: JIterable[_]) =>
+ accum ++ config.map {
+ case m: JMap[_, _] =>
+ m.map {
+ case (k: String, v: String) => k -> v
+ case illegal =>
+ throw new IllegalArgumentException(
+ s"each element of $key must be a String or a Map of Strings; actually $illegal")
+ }
+ case s: String =>
+ Map(s -> null)
+ case illegal =>
+ throw new IllegalArgumentException(s"each element of $key must be a String or " +
+ s"a Map of Strings; actually $illegal")
+ }.reduce(_ ++ _)
+ case (accum, null) =>
+ accum
+ case (accum, illegal) =>
+ throw new IllegalArgumentException(
+ s"$key must be an Iterable containing only Strings or Maps of Strings; actually $illegal")
+ }
+ if (merged.nonEmpty) {
+ val registers: JMap[String, String] = new JHashMap[String, String](merged.size)
+ registers.putAll(merged)
+ mergedConfig.put(key, registers)
+ }
+ mergedConfig
+ }
+
+ /**
+ * @param componentConfigs list of raw component configs
+ * @param allConfig existing configs without merging component configs
+ * @param key config key
+ * @return a list of values for a config from both component configs and existing configs
+ */
+ private def getConfigValues(componentConfigs: Iterable[JMap[AnyRef, AnyRef]],
+ allConfig: Map[AnyRef, AnyRef], key: String): Iterable[AnyRef] = {
+ componentConfigs.map(config => config.get(key)) ++ allConfig.get(key).toList
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/topology/GearpumpTuple.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/topology/GearpumpTuple.scala b/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/topology/GearpumpTuple.scala
new file mode 100644
index 0000000..eb61acb
--- /dev/null
+++ b/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/topology/GearpumpTuple.scala
@@ -0,0 +1,69 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.storm.topology
+
+import java.util.{List => JList}
+
+import backtype.storm.task.GeneralTopologyContext
+import backtype.storm.tuple.{Tuple, TupleImpl}
+
+import org.apache.gearpump.TimeStamp
+
+/**
+ * this carries Storm tuple values in the Gearpump world
+ * the targetPartitions field dictate which tasks a GearpumpTuple should be sent to
+ * see [[org.apache.gearpump.experiments.storm.partitioner.StormPartitioner]] for more info
+ */
+private[storm] class GearpumpTuple(
+ val values: JList[AnyRef],
+ val sourceTaskId: Integer,
+ val sourceStreamId: String,
+ @transient val targetPartitions: Map[String, Array[Int]]) extends Serializable {
+ /**
+ * creates a Storm [[backtype.storm.tuple.Tuple]] to be passed to a Storm component
+ * this is needed for each incoming message
+ * because we cannot get [[backtype.storm.task.GeneralTopologyContext]] at deserialization
+ * @param topologyContext topology context used for all tasks
+ * @return a Tuple
+ */
+ def toTuple(topologyContext: GeneralTopologyContext, timestamp: TimeStamp): Tuple = {
+ TimedTuple(topologyContext, values, sourceTaskId, sourceStreamId, timestamp)
+ }
+
+ def canEqual(other: Any): Boolean = other.isInstanceOf[GearpumpTuple]
+
+ override def equals(other: Any): Boolean = other match {
+ case that: GearpumpTuple =>
+ (that canEqual this) &&
+ values == that.values &&
+ sourceTaskId == that.sourceTaskId &&
+ sourceStreamId == that.sourceStreamId
+ case _ => false
+ }
+
+ override def hashCode(): Int = {
+ val state = Seq(values, sourceTaskId, sourceStreamId)
+ state.map(_.hashCode()).foldLeft(0)((a, b) => 31 * a + b)
+ }
+}
+
+case class TimedTuple(topologyContext: GeneralTopologyContext, tuple: JList[AnyRef],
+ sourceTaskId: Integer, sourceStreamId: String, timestamp: TimeStamp)
+ extends TupleImpl(topologyContext, tuple, sourceTaskId, sourceStreamId, null)
+
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/util/GraphBuilder.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/util/GraphBuilder.scala b/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/util/GraphBuilder.scala
new file mode 100644
index 0000000..777acab
--- /dev/null
+++ b/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/util/GraphBuilder.scala
@@ -0,0 +1,46 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.storm.util
+
+import org.apache.gearpump.experiments.storm.partitioner.StormPartitioner
+import org.apache.gearpump.experiments.storm.topology.GearpumpStormTopology
+import org.apache.gearpump.partitioner.Partitioner
+import org.apache.gearpump.streaming.Processor
+import org.apache.gearpump.streaming.task.Task
+import org.apache.gearpump.util.Graph
+
+object GraphBuilder {
+
+ /**
+ * build a Gearpump DAG from a Storm topology
+ * @param topology a wrapper over Storm topology
+ * @return a DAG
+ */
+ def build(topology: GearpumpStormTopology): Graph[Processor[_ <: Task], _ <: Partitioner] = {
+ val processorGraph = Graph.empty[Processor[Task], Partitioner]
+
+ topology.getProcessors.foreach { case (sourceId, sourceProcessor) =>
+ topology.getTargets(sourceId).foreach { case (targetId, targetProcessor) =>
+ processorGraph.addEdge(sourceProcessor, new StormPartitioner(targetId), targetProcessor)
+ }
+ }
+
+ processorGraph
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/util/Grouper.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/util/Grouper.scala b/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/util/Grouper.scala
new file mode 100644
index 0000000..1d04af6
--- /dev/null
+++ b/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/util/Grouper.scala
@@ -0,0 +1,142 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.storm.util
+
+import java.util.{List => JList}
+import scala.util.Random
+
+import backtype.storm.generated.GlobalStreamId
+import backtype.storm.grouping.CustomStreamGrouping
+import backtype.storm.task.TopologyContext
+import backtype.storm.tuple.Fields
+
+/**
+ * Grouper is identical to that in storm but return gearpump partitions for storm tuple values
+ */
+sealed trait Grouper {
+ /**
+ * @param taskId storm task id of source task
+ * @param values storm tuple values
+ * @return a list of gearpump partitions
+ */
+ def getPartitions(taskId: Int, values: JList[AnyRef]): Array[Int]
+}
+
+/**
+ * GlobalGrouper always returns partition 0
+ */
+class GlobalGrouper extends Grouper {
+ override def getPartitions(taskId: Int, values: JList[AnyRef]): Array[Int] = Array(0)
+}
+
+/**
+ * NoneGrouper randomly returns partition
+ *
+ * @param numTasks number of target tasks
+ */
+class NoneGrouper(numTasks: Int) extends Grouper {
+ private val random = new Random
+
+ override def getPartitions(taskId: Int, values: JList[AnyRef]): Array[Int] = {
+ val partition = StormUtil.mod(random.nextInt, numTasks)
+ Array(partition)
+ }
+}
+
+/**
+ * ShuffleGrouper shuffles partitions and returns them sequentially, and then shuffles again
+ *
+ * @param numTasks number of target tasks
+ */
+class ShuffleGrouper(numTasks: Int) extends Grouper {
+ private val random = new Random
+ private var index = -1
+ private var partitions = List.empty[Int]
+
+ override def getPartitions(taskId: Int, values: JList[AnyRef]): Array[Int] = {
+ index += 1
+ if (partitions.isEmpty) {
+ partitions = 0.until(numTasks).toList
+ partitions = random.shuffle(partitions)
+ } else if (index >= numTasks) {
+ index = 0
+ partitions = random.shuffle(partitions)
+ }
+ Array(partitions(index))
+ }
+}
+
+/**
+ * FieldsGrouper returns partition based on value of groupFields
+ *
+ * @param outFields declared output fields of source task
+ * @param groupFields grouping fields of target tasks
+ * @param numTasks number of target tasks
+ */
+class FieldsGrouper(outFields: Fields, groupFields: Fields, numTasks: Int) extends Grouper {
+
+ override def getPartitions(taskId: Int, values: JList[AnyRef]): Array[Int] = {
+ val hash = outFields.select(groupFields, values).hashCode()
+ val partition = StormUtil.mod(hash, numTasks)
+ Array(partition)
+ }
+}
+
+/**
+ * AllGrouper returns all partitions
+ *
+ * @param numTasks number of target tasks
+ */
+class AllGrouper(numTasks: Int) extends Grouper {
+ val partitions = (0 until numTasks).toArray
+
+ override def getPartitions(taskId: Int, values: JList[AnyRef]): Array[Int] = {
+ partitions
+ }
+}
+
+/**
+ * CustomGrouper allows users to specify grouping strategy
+ *
+ * @param grouping see [[backtype.storm.grouping.CustomStreamGrouping]]
+ */
+class CustomGrouper(grouping: CustomStreamGrouping) extends Grouper {
+
+ def prepare(
+ topologyContext: TopologyContext, globalStreamId: GlobalStreamId, targetTasks: JList[Integer])
+ : Unit = {
+ grouping.prepare(topologyContext, globalStreamId, targetTasks)
+ }
+
+ override def getPartitions(taskId: Int, values: JList[AnyRef]): Array[Int] = {
+ val tasks = grouping.chooseTasks(taskId, values)
+ val result = new Array[Int](tasks.size())
+
+ val iter = tasks.iterator()
+
+ var index = 0
+ while (iter.hasNext()) {
+ val value = iter.next()
+ result(index) = StormUtil.stormTaskIdToGearpump(value).index
+ index += 1
+ }
+ result
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/util/StormConstants.scala
----------------------------------------------------------------------
diff --git a/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/util/StormConstants.scala b/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/util/StormConstants.scala
new file mode 100644
index 0000000..f1c736c
--- /dev/null
+++ b/experiments/storm/src/main/scala/org/apache/gearpump/experiments/storm/util/StormConstants.scala
@@ -0,0 +1,33 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.experiments.storm.util
+
+object StormConstants {
+ val STORM_COMPONENT = "storm_component"
+ val STORM_TOPOLOGY = "storm_topology"
+ val STORM_CONFIG = "storm_config"
+ val SYSTEM_COMPONENT_ID = "__system"
+ val SYSTEM_COMPONENT_OUTPUT_FIELDS = "rate_secs"
+ val SYSTEM_TASK_ID: Integer = -1
+ val SYSTEM_TICK_STREAM_ID = "__tick"
+
+ val CHECKPOINT_INTERVAL_MILLIS = 2000 // 2 seconds
+
+ val STORM_SERIALIZATION_FRAMEWORK = "gearpump.storm.serialization-framework"
+}
[28/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/wordcount/src/main/scala/io/gearpump/streaming/examples/wordcount/WordCount.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/wordcount/src/main/scala/io/gearpump/streaming/examples/wordcount/WordCount.scala b/examples/streaming/wordcount/src/main/scala/io/gearpump/streaming/examples/wordcount/WordCount.scala
deleted file mode 100644
index f23604a..0000000
--- a/examples/streaming/wordcount/src/main/scala/io/gearpump/streaming/examples/wordcount/WordCount.scala
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.wordcount
-
-import org.slf4j.Logger
-
-import io.gearpump.cluster.UserConfig
-import io.gearpump.cluster.client.ClientContext
-import io.gearpump.cluster.embedded.EmbeddedCluster
-import io.gearpump.cluster.main.{ArgumentsParser, CLIOption, ParseResult}
-import io.gearpump.partitioner.HashPartitioner
-import io.gearpump.streaming.{Processor, StreamApplication}
-import io.gearpump.util.Graph.Node
-import io.gearpump.util.{AkkaApp, Graph, LogUtil}
-
-/** Same WordCount with low level Processor Graph syntax */
-object WordCount extends AkkaApp with ArgumentsParser {
- private val LOG: Logger = LogUtil.getLogger(getClass)
- val RUN_FOR_EVER = -1
-
- override val options: Array[(String, CLIOption[Any])] = Array(
- "split" -> CLIOption[Int]("<how many split tasks>", required = false, defaultValue = Some(1)),
- "sum" -> CLIOption[Int]("<how many sum tasks>", required = false, defaultValue = Some(1)),
- "debug" -> CLIOption[Boolean]("<true|false>", required = false, defaultValue = Some(false)),
- "sleep" -> CLIOption[Int]("how many seconds to sleep for debug mode", required = false,
- defaultValue = Some(30))
- )
-
- def application(config: ParseResult): StreamApplication = {
- val splitNum = config.getInt("split")
- val sumNum = config.getInt("sum")
- val split = Processor[Split](splitNum)
- val sum = Processor[Sum](sumNum)
- val partitioner = new HashPartitioner
-
- val app = StreamApplication("wordCount", Graph(split ~ partitioner ~> sum), UserConfig.empty)
- app
- }
-
- override def main(akkaConf: Config, args: Array[String]): Unit = {
- val config = parse(args)
-
- val debugMode = config.getBoolean("debug")
- val sleepSeconds = config.getInt("sleep")
-
- val localCluster = if (debugMode) {
- val cluster = new EmbeddedCluster(akkaConf: Config)
- cluster.start()
- Some(cluster)
- } else {
- None
- }
-
- val context: ClientContext = localCluster match {
- case Some(local) => local.newClientContext
- case None => ClientContext(akkaConf)
- }
-
- val app = application(config)
- context.submit(app)
-
- if (debugMode) {
- Thread.sleep(sleepSeconds * 1000) // Sleeps for 30 seconds for debugging.
- }
-
- context.close()
- localCluster.map(_.stop())
- }
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/wordcount/src/main/scala/io/gearpump/streaming/examples/wordcount/dsl/WordCount.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/wordcount/src/main/scala/io/gearpump/streaming/examples/wordcount/dsl/WordCount.scala b/examples/streaming/wordcount/src/main/scala/io/gearpump/streaming/examples/wordcount/dsl/WordCount.scala
deleted file mode 100644
index ab8e8d0..0000000
--- a/examples/streaming/wordcount/src/main/scala/io/gearpump/streaming/examples/wordcount/dsl/WordCount.scala
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.wordcount.dsl
-
-import io.gearpump.cluster.client.ClientContext
-import io.gearpump.cluster.main.{ArgumentsParser, CLIOption}
-import io.gearpump.streaming.dsl.StreamApp
-import io.gearpump.streaming.dsl.StreamApp._
-import io.gearpump.util.AkkaApp
-
-/** Same WordCount with High level DSL syntax */
-object WordCount extends AkkaApp with ArgumentsParser {
-
- override val options: Array[(String, CLIOption[Any])] = Array.empty
-
- override def main(akkaConf: Config, args: Array[String]): Unit = {
- val context = ClientContext(akkaConf)
- val app = StreamApp("dsl", context)
- val data = "This is a good start, bingo!! bingo!!"
- app.source(data.lines.toList, 1, "source").
- // word => (word, count)
- flatMap(line => line.split("[\\s]+")).map((_, 1)).
- // (word, count1), (word, count2) => (word, count1 + count2)
- groupByKey().sum.log
-
- val appId = context.submit(app)
- context.close()
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/wordcount/src/main/scala/org/apache/gearpump/streaming/examples/wordcount/Split.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/wordcount/src/main/scala/org/apache/gearpump/streaming/examples/wordcount/Split.scala b/examples/streaming/wordcount/src/main/scala/org/apache/gearpump/streaming/examples/wordcount/Split.scala
new file mode 100644
index 0000000..ae63f10
--- /dev/null
+++ b/examples/streaming/wordcount/src/main/scala/org/apache/gearpump/streaming/examples/wordcount/Split.scala
@@ -0,0 +1,66 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.wordcount
+
+import java.util.concurrent.TimeUnit
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.task.{StartTime, Task, TaskContext}
+
+class Split(taskContext: TaskContext, conf: UserConfig) extends Task(taskContext, conf) {
+ import taskContext.output
+
+ override def onStart(startTime: StartTime): Unit = {
+ self ! Message("start")
+ }
+
+ override def onNext(msg: Message): Unit = {
+ Split.TEXT_TO_SPLIT.lines.foreach { line =>
+ line.split("[\\s]+").filter(_.nonEmpty).foreach { msg =>
+ output(new Message(msg, System.currentTimeMillis()))
+ }
+ }
+
+ import scala.concurrent.duration._
+ taskContext.scheduleOnce(Duration(100, TimeUnit.MILLISECONDS))(self !
+ Message("continue", System.currentTimeMillis()))
+ }
+}
+
+object Split {
+ val TEXT_TO_SPLIT =
+ """
+ | 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.
+ """.stripMargin
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/wordcount/src/main/scala/org/apache/gearpump/streaming/examples/wordcount/Sum.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/wordcount/src/main/scala/org/apache/gearpump/streaming/examples/wordcount/Sum.scala b/examples/streaming/wordcount/src/main/scala/org/apache/gearpump/streaming/examples/wordcount/Sum.scala
new file mode 100644
index 0000000..c3fa82a
--- /dev/null
+++ b/examples/streaming/wordcount/src/main/scala/org/apache/gearpump/streaming/examples/wordcount/Sum.scala
@@ -0,0 +1,66 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.wordcount
+
+import java.util.concurrent.TimeUnit
+import scala.collection.mutable
+import scala.concurrent.duration.FiniteDuration
+
+import akka.actor.Cancellable
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.task.{StartTime, Task, TaskContext}
+
+class Sum(taskContext: TaskContext, conf: UserConfig) extends Task(taskContext, conf) {
+ private[wordcount] val map: mutable.HashMap[String, Long] = new mutable.HashMap[String, Long]()
+
+ private[wordcount] var wordCount: Long = 0
+ private var snapShotTime: Long = System.currentTimeMillis()
+ private var snapShotWordCount: Long = 0
+
+ private var scheduler: Cancellable = null
+
+ override def onStart(startTime: StartTime): Unit = {
+ scheduler = taskContext.schedule(new FiniteDuration(5, TimeUnit.SECONDS),
+ new FiniteDuration(30, TimeUnit.SECONDS))(reportWordCount)
+ }
+
+ override def onNext(msg: Message): Unit = {
+ if (null != msg) {
+ val current = map.getOrElse(msg.msg.asInstanceOf[String], 0L)
+ wordCount += 1
+ map.put(msg.msg.asInstanceOf[String], current + 1)
+ }
+ }
+
+ override def onStop(): Unit = {
+ if (scheduler != null) {
+ scheduler.cancel()
+ }
+ }
+
+ def reportWordCount(): Unit = {
+ val current: Long = System.currentTimeMillis()
+ LOG.info(s"Task ${taskContext.taskId} Throughput:" +
+ s" ${(wordCount - snapShotWordCount, (current - snapShotTime) / 1000)} (words, second)")
+ snapShotWordCount = wordCount
+ snapShotTime = current
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/wordcount/src/main/scala/org/apache/gearpump/streaming/examples/wordcount/WordCount.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/wordcount/src/main/scala/org/apache/gearpump/streaming/examples/wordcount/WordCount.scala b/examples/streaming/wordcount/src/main/scala/org/apache/gearpump/streaming/examples/wordcount/WordCount.scala
new file mode 100644
index 0000000..9917d9f
--- /dev/null
+++ b/examples/streaming/wordcount/src/main/scala/org/apache/gearpump/streaming/examples/wordcount/WordCount.scala
@@ -0,0 +1,86 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.wordcount
+
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.cluster.client.ClientContext
+import org.apache.gearpump.cluster.embedded.EmbeddedCluster
+import org.apache.gearpump.cluster.main.{ArgumentsParser, CLIOption, ParseResult}
+import org.apache.gearpump.partitioner.HashPartitioner
+import org.apache.gearpump.streaming.{Processor, StreamApplication}
+import org.apache.gearpump.util.Graph.Node
+import org.apache.gearpump.util.{AkkaApp, Graph, LogUtil}
+
+/** Same WordCount with low level Processor Graph syntax */
+object WordCount extends AkkaApp with ArgumentsParser {
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+ val RUN_FOR_EVER = -1
+
+ override val options: Array[(String, CLIOption[Any])] = Array(
+ "split" -> CLIOption[Int]("<how many split tasks>", required = false, defaultValue = Some(1)),
+ "sum" -> CLIOption[Int]("<how many sum tasks>", required = false, defaultValue = Some(1)),
+ "debug" -> CLIOption[Boolean]("<true|false>", required = false, defaultValue = Some(false)),
+ "sleep" -> CLIOption[Int]("how many seconds to sleep for debug mode", required = false,
+ defaultValue = Some(30))
+ )
+
+ def application(config: ParseResult): StreamApplication = {
+ val splitNum = config.getInt("split")
+ val sumNum = config.getInt("sum")
+ val split = Processor[Split](splitNum)
+ val sum = Processor[Sum](sumNum)
+ val partitioner = new HashPartitioner
+
+ val app = StreamApplication("wordCount", Graph(split ~ partitioner ~> sum), UserConfig.empty)
+ app
+ }
+
+ override def main(akkaConf: Config, args: Array[String]): Unit = {
+ val config = parse(args)
+
+ val debugMode = config.getBoolean("debug")
+ val sleepSeconds = config.getInt("sleep")
+
+ val localCluster = if (debugMode) {
+ val cluster = new EmbeddedCluster(akkaConf: Config)
+ cluster.start()
+ Some(cluster)
+ } else {
+ None
+ }
+
+ val context: ClientContext = localCluster match {
+ case Some(local) => local.newClientContext
+ case None => ClientContext(akkaConf)
+ }
+
+ val app = application(config)
+ context.submit(app)
+
+ if (debugMode) {
+ Thread.sleep(sleepSeconds * 1000) // Sleeps for 30 seconds for debugging.
+ }
+
+ context.close()
+ localCluster.map(_.stop())
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/wordcount/src/main/scala/org/apache/gearpump/streaming/examples/wordcount/dsl/WordCount.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/wordcount/src/main/scala/org/apache/gearpump/streaming/examples/wordcount/dsl/WordCount.scala b/examples/streaming/wordcount/src/main/scala/org/apache/gearpump/streaming/examples/wordcount/dsl/WordCount.scala
new file mode 100644
index 0000000..22f597c
--- /dev/null
+++ b/examples/streaming/wordcount/src/main/scala/org/apache/gearpump/streaming/examples/wordcount/dsl/WordCount.scala
@@ -0,0 +1,45 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.wordcount.dsl
+
+import org.apache.gearpump.cluster.client.ClientContext
+import org.apache.gearpump.cluster.main.{ArgumentsParser, CLIOption}
+import org.apache.gearpump.streaming.dsl.StreamApp
+import org.apache.gearpump.streaming.dsl.StreamApp._
+import org.apache.gearpump.util.AkkaApp
+
+/** Same WordCount with High level DSL syntax */
+object WordCount extends AkkaApp with ArgumentsParser {
+
+ override val options: Array[(String, CLIOption[Any])] = Array.empty
+
+ override def main(akkaConf: Config, args: Array[String]): Unit = {
+ val context = ClientContext(akkaConf)
+ val app = StreamApp("dsl", context)
+ val data = "This is a good start, bingo!! bingo!!"
+ app.source(data.lines.toList, 1, "source").
+ // word => (word, count)
+ flatMap(line => line.split("[\\s]+")).map((_, 1)).
+ // (word, count1), (word, count2) => (word, count1 + count2)
+ groupByKey().sum.log
+
+ val appId = context.submit(app)
+ context.close()
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/wordcount/src/test/scala/io/gearpump/streaming/examples/wordcount/SplitSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/wordcount/src/test/scala/io/gearpump/streaming/examples/wordcount/SplitSpec.scala b/examples/streaming/wordcount/src/test/scala/io/gearpump/streaming/examples/wordcount/SplitSpec.scala
deleted file mode 100644
index 21e498e..0000000
--- a/examples/streaming/wordcount/src/test/scala/io/gearpump/streaming/examples/wordcount/SplitSpec.scala
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.examples.wordcount
-
-import scala.concurrent.Await
-import scala.concurrent.duration.Duration
-
-import akka.actor.ActorSystem
-import akka.testkit.TestProbe
-import org.mockito.Matchers._
-import org.mockito.Mockito._
-import org.scalatest.{Matchers, WordSpec}
-
-import io.gearpump.Message
-import io.gearpump.cluster.{TestUtil, UserConfig}
-import io.gearpump.streaming.MockUtil
-import io.gearpump.streaming.task.StartTime
-
-class SplitSpec extends WordSpec with Matchers {
-
- "Split" should {
- "split the text and deliver to next task" in {
-
- val taskContext = MockUtil.mockTaskContext
-
- implicit val system: ActorSystem = ActorSystem("test", TestUtil.DEFAULT_CONFIG)
-
- val mockTaskActor = TestProbe()
-
- // Mock self ActorRef
- when(taskContext.self).thenReturn(mockTaskActor.ref)
-
- val conf = UserConfig.empty
- val split = new Split(taskContext, conf)
- split.onStart(StartTime(0))
- mockTaskActor.expectMsgType[Message]
-
- val expectedWordCount = Split.TEXT_TO_SPLIT.split( """[\s\n]+""").filter(_.nonEmpty).length
-
- split.onNext(Message("next"))
- verify(taskContext, times(expectedWordCount)).output(anyObject())
-
- system.terminate()
- Await.result(system.whenTerminated, Duration.Inf)
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/wordcount/src/test/scala/io/gearpump/streaming/examples/wordcount/SumSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/wordcount/src/test/scala/io/gearpump/streaming/examples/wordcount/SumSpec.scala b/examples/streaming/wordcount/src/test/scala/io/gearpump/streaming/examples/wordcount/SumSpec.scala
deleted file mode 100644
index 48a3fa9..0000000
--- a/examples/streaming/wordcount/src/test/scala/io/gearpump/streaming/examples/wordcount/SumSpec.scala
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.examples.wordcount
-
-import org.scalacheck.Gen
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{BeforeAndAfter, Matchers, PropSpec}
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.MockUtil
-import io.gearpump.streaming.task.StartTime
-
-class SumSpec extends PropSpec with PropertyChecks with Matchers with BeforeAndAfter {
- val stringGenerator = Gen.alphaStr
-
- var wordcount = 0
-
- property("Sum should calculate the frequency of the word correctly") {
-
- val taskContext = MockUtil.mockTaskContext
-
- val conf = UserConfig.empty
-
- val sum = new Sum(taskContext, conf)
-
- sum.onStart(StartTime(0))
-
- forAll(stringGenerator) { txt =>
- wordcount += 1
- sum.onNext(Message(txt))
- }
- val all = sum.map.foldLeft(0L) { (total, kv) =>
- val (_, num) = kv
- total + num
- }
- assert(sum.wordCount == all && sum.wordCount == wordcount)
-
- sum.reportWordCount()
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/wordcount/src/test/scala/io/gearpump/streaming/examples/wordcount/WordCountSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/wordcount/src/test/scala/io/gearpump/streaming/examples/wordcount/WordCountSpec.scala b/examples/streaming/wordcount/src/test/scala/io/gearpump/streaming/examples/wordcount/WordCountSpec.scala
deleted file mode 100644
index 63b2312..0000000
--- a/examples/streaming/wordcount/src/test/scala/io/gearpump/streaming/examples/wordcount/WordCountSpec.scala
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.wordcount
-
-import scala.concurrent.Future
-import scala.util.Success
-
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{BeforeAndAfter, Matchers, PropSpec}
-
-import io.gearpump.cluster.ClientToMaster.SubmitApplication
-import io.gearpump.cluster.MasterToClient.SubmitApplicationResult
-import io.gearpump.cluster.{MasterHarness, TestUtil}
-
-class WordCountSpec
- extends PropSpec with PropertyChecks with Matchers with BeforeAndAfter with MasterHarness {
-
- before {
- startActorSystem()
- }
-
- after {
- shutdownActorSystem()
- }
-
- protected override def config = TestUtil.DEFAULT_CONFIG
-
- property("WordCount should succeed to submit application with required arguments") {
- val requiredArgs = Array.empty[String]
- val optionalArgs = Array(
- "-split", "1",
- "-sum", "1")
-
- val args = {
- Table(
- ("requiredArgs", "optionalArgs"),
- (requiredArgs, optionalArgs)
- )
- }
- val masterReceiver = createMockMaster()
- forAll(args) { (requiredArgs: Array[String], optionalArgs: Array[String]) =>
-
- val args = requiredArgs ++ optionalArgs
-
- Future {
- WordCount.main(masterConfig, args)
- }
-
- masterReceiver.expectMsgType[SubmitApplication](PROCESS_BOOT_TIME)
- masterReceiver.reply(SubmitApplicationResult(Success(0)))
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/wordcount/src/test/scala/org/apache/gearpump/streaming/examples/wordcount/SplitSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/wordcount/src/test/scala/org/apache/gearpump/streaming/examples/wordcount/SplitSpec.scala b/examples/streaming/wordcount/src/test/scala/org/apache/gearpump/streaming/examples/wordcount/SplitSpec.scala
new file mode 100644
index 0000000..cef9337
--- /dev/null
+++ b/examples/streaming/wordcount/src/test/scala/org/apache/gearpump/streaming/examples/wordcount/SplitSpec.scala
@@ -0,0 +1,62 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.examples.wordcount
+
+import scala.concurrent.Await
+import scala.concurrent.duration.Duration
+
+import akka.actor.ActorSystem
+import akka.testkit.TestProbe
+import org.mockito.Matchers._
+import org.mockito.Mockito._
+import org.scalatest.{Matchers, WordSpec}
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.{TestUtil, UserConfig}
+import org.apache.gearpump.streaming.MockUtil
+import org.apache.gearpump.streaming.task.StartTime
+
+class SplitSpec extends WordSpec with Matchers {
+
+ "Split" should {
+ "split the text and deliver to next task" in {
+
+ val taskContext = MockUtil.mockTaskContext
+
+ implicit val system: ActorSystem = ActorSystem("test", TestUtil.DEFAULT_CONFIG)
+
+ val mockTaskActor = TestProbe()
+
+ // Mock self ActorRef
+ when(taskContext.self).thenReturn(mockTaskActor.ref)
+
+ val conf = UserConfig.empty
+ val split = new Split(taskContext, conf)
+ split.onStart(StartTime(0))
+ mockTaskActor.expectMsgType[Message]
+
+ val expectedWordCount = Split.TEXT_TO_SPLIT.split( """[\s\n]+""").filter(_.nonEmpty).length
+
+ split.onNext(Message("next"))
+ verify(taskContext, times(expectedWordCount)).output(anyObject())
+
+ system.terminate()
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/wordcount/src/test/scala/org/apache/gearpump/streaming/examples/wordcount/SumSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/wordcount/src/test/scala/org/apache/gearpump/streaming/examples/wordcount/SumSpec.scala b/examples/streaming/wordcount/src/test/scala/org/apache/gearpump/streaming/examples/wordcount/SumSpec.scala
new file mode 100644
index 0000000..e42d696
--- /dev/null
+++ b/examples/streaming/wordcount/src/test/scala/org/apache/gearpump/streaming/examples/wordcount/SumSpec.scala
@@ -0,0 +1,56 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.examples.wordcount
+
+import org.scalacheck.Gen
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{BeforeAndAfter, Matchers, PropSpec}
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.MockUtil
+import org.apache.gearpump.streaming.task.StartTime
+
+class SumSpec extends PropSpec with PropertyChecks with Matchers with BeforeAndAfter {
+ val stringGenerator = Gen.alphaStr
+
+ var wordcount = 0
+
+ property("Sum should calculate the frequency of the word correctly") {
+
+ val taskContext = MockUtil.mockTaskContext
+
+ val conf = UserConfig.empty
+
+ val sum = new Sum(taskContext, conf)
+
+ sum.onStart(StartTime(0))
+
+ forAll(stringGenerator) { txt =>
+ wordcount += 1
+ sum.onNext(Message(txt))
+ }
+ val all = sum.map.foldLeft(0L) { (total, kv) =>
+ val (_, num) = kv
+ total + num
+ }
+ assert(sum.wordCount == all && sum.wordCount == wordcount)
+
+ sum.reportWordCount()
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/wordcount/src/test/scala/org/apache/gearpump/streaming/examples/wordcount/WordCountSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/wordcount/src/test/scala/org/apache/gearpump/streaming/examples/wordcount/WordCountSpec.scala b/examples/streaming/wordcount/src/test/scala/org/apache/gearpump/streaming/examples/wordcount/WordCountSpec.scala
new file mode 100644
index 0000000..f703552
--- /dev/null
+++ b/examples/streaming/wordcount/src/test/scala/org/apache/gearpump/streaming/examples/wordcount/WordCountSpec.scala
@@ -0,0 +1,69 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.wordcount
+
+import scala.concurrent.Future
+import scala.util.Success
+
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{BeforeAndAfter, Matchers, PropSpec}
+
+import org.apache.gearpump.cluster.ClientToMaster.SubmitApplication
+import org.apache.gearpump.cluster.MasterToClient.SubmitApplicationResult
+import org.apache.gearpump.cluster.{MasterHarness, TestUtil}
+
+class WordCountSpec
+ extends PropSpec with PropertyChecks with Matchers with BeforeAndAfter with MasterHarness {
+
+ before {
+ startActorSystem()
+ }
+
+ after {
+ shutdownActorSystem()
+ }
+
+ protected override def config = TestUtil.DEFAULT_CONFIG
+
+ property("WordCount should succeed to submit application with required arguments") {
+ val requiredArgs = Array.empty[String]
+ val optionalArgs = Array(
+ "-split", "1",
+ "-sum", "1")
+
+ val args = {
+ Table(
+ ("requiredArgs", "optionalArgs"),
+ (requiredArgs, optionalArgs)
+ )
+ }
+ val masterReceiver = createMockMaster()
+ forAll(args) { (requiredArgs: Array[String], optionalArgs: Array[String]) =>
+
+ val args = requiredArgs ++ optionalArgs
+
+ Future {
+ WordCount.main(masterConfig, args)
+ }
+
+ masterReceiver.expectMsgType[SubmitApplication](PROCESS_BOOT_TIME)
+ masterReceiver.reply(SubmitApplicationResult(Success(0)))
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/akkastream/src/main/scala/akka/stream/ModuleGraph.scala
----------------------------------------------------------------------
diff --git a/experiments/akkastream/src/main/scala/akka/stream/ModuleGraph.scala b/experiments/akkastream/src/main/scala/akka/stream/ModuleGraph.scala
index 8851083..7daebf1 100644
--- a/experiments/akkastream/src/main/scala/akka/stream/ModuleGraph.scala
+++ b/experiments/akkastream/src/main/scala/akka/stream/ModuleGraph.scala
@@ -33,8 +33,8 @@ import akka.stream.impl.StreamLayout._
import akka.stream.impl._
import akka.stream.{Graph => AkkaGraph}
-import _root_.io.gearpump.util
-import _root_.io.gearpump.util.Graph
+import _root_.org.apache.gearpump.util
+import _root_.org.apache.gearpump.util.Graph
/**
*
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/akkastream/src/main/scala/akka/stream/gearpump/example/Test3.scala
----------------------------------------------------------------------
diff --git a/experiments/akkastream/src/main/scala/akka/stream/gearpump/example/Test3.scala b/experiments/akkastream/src/main/scala/akka/stream/gearpump/example/Test3.scala
index b1bf01c..976b1e6 100644
--- a/experiments/akkastream/src/main/scala/akka/stream/gearpump/example/Test3.scala
+++ b/experiments/akkastream/src/main/scala/akka/stream/gearpump/example/Test3.scala
@@ -26,7 +26,7 @@ import akka.stream.gearpump.GearpumpMaterializer
import akka.stream.gearpump.scaladsl.GearSource
import akka.stream.scaladsl.Sink
-import io.gearpump.streaming.dsl.CollectionDataSource
+import org.apache.gearpump.streaming.dsl.CollectionDataSource
/**
* read from remote and write to local
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/akkastream/src/main/scala/akka/stream/gearpump/example/Test4.scala
----------------------------------------------------------------------
diff --git a/experiments/akkastream/src/main/scala/akka/stream/gearpump/example/Test4.scala b/experiments/akkastream/src/main/scala/akka/stream/gearpump/example/Test4.scala
index b1e2fcb..7b80b7b 100644
--- a/experiments/akkastream/src/main/scala/akka/stream/gearpump/example/Test4.scala
+++ b/experiments/akkastream/src/main/scala/akka/stream/gearpump/example/Test4.scala
@@ -26,7 +26,7 @@ import akka.stream.gearpump.GearpumpMaterializer
import akka.stream.gearpump.scaladsl.GearSink
import akka.stream.scaladsl.Source
-import io.gearpump.streaming.dsl.LoggerSink
+import org.apache.gearpump.streaming.dsl.LoggerSink
/**
* read from local and write to remote
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/akkastream/src/main/scala/akka/stream/gearpump/example/Test6.scala
----------------------------------------------------------------------
diff --git a/experiments/akkastream/src/main/scala/akka/stream/gearpump/example/Test6.scala b/experiments/akkastream/src/main/scala/akka/stream/gearpump/example/Test6.scala
index 38b40b7..0fccd30 100644
--- a/experiments/akkastream/src/main/scala/akka/stream/gearpump/example/Test6.scala
+++ b/experiments/akkastream/src/main/scala/akka/stream/gearpump/example/Test6.scala
@@ -26,7 +26,7 @@ import akka.stream.gearpump.GearpumpMaterializer
import akka.stream.gearpump.scaladsl.GearSource
import akka.stream.scaladsl.Sink
-import io.gearpump.streaming.dsl.CollectionDataSource
+import org.apache.gearpump.streaming.dsl.CollectionDataSource
/**
* WordCount example
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/akkastream/src/main/scala/akka/stream/gearpump/example/WikipediaApp.scala
----------------------------------------------------------------------
diff --git a/experiments/akkastream/src/main/scala/akka/stream/gearpump/example/WikipediaApp.scala b/experiments/akkastream/src/main/scala/akka/stream/gearpump/example/WikipediaApp.scala
index c2d0417..56b89bc 100644
--- a/experiments/akkastream/src/main/scala/akka/stream/gearpump/example/WikipediaApp.scala
+++ b/experiments/akkastream/src/main/scala/akka/stream/gearpump/example/WikipediaApp.scala
@@ -31,8 +31,8 @@ import akka.stream.scaladsl._
import akka.util.ByteString
import org.json4s.JsonAST.JString
-import io.gearpump.cluster.main.{ArgumentsParser, CLIOption}
-import io.gearpump.util.AkkaApp
+import org.apache.gearpump.cluster.main.{ArgumentsParser, CLIOption}
+import org.apache.gearpump.util.AkkaApp
/**
* this example is ported from http://engineering.intenthq.com/2015/06/wikidata-akka-streams/
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/akkastream/src/main/scala/akka/stream/gearpump/graph/GraphCutter.scala
----------------------------------------------------------------------
diff --git a/experiments/akkastream/src/main/scala/akka/stream/gearpump/graph/GraphCutter.scala b/experiments/akkastream/src/main/scala/akka/stream/gearpump/graph/GraphCutter.scala
index ef8c6fa..19083f6 100644
--- a/experiments/akkastream/src/main/scala/akka/stream/gearpump/graph/GraphCutter.scala
+++ b/experiments/akkastream/src/main/scala/akka/stream/gearpump/graph/GraphCutter.scala
@@ -28,7 +28,7 @@ import akka.stream.impl.Stages.DirectProcessor
import akka.stream.impl.StreamLayout.{MaterializedValueNode, Module}
import akka.stream.impl.{SinkModule, SourceModule}
-import io.gearpump.util.Graph
+import org.apache.gearpump.util.Graph
/**
*
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/akkastream/src/main/scala/akka/stream/gearpump/graph/LocalGraph.scala
----------------------------------------------------------------------
diff --git a/experiments/akkastream/src/main/scala/akka/stream/gearpump/graph/LocalGraph.scala b/experiments/akkastream/src/main/scala/akka/stream/gearpump/graph/LocalGraph.scala
index 473f32a..6ef8598 100644
--- a/experiments/akkastream/src/main/scala/akka/stream/gearpump/graph/LocalGraph.scala
+++ b/experiments/akkastream/src/main/scala/akka/stream/gearpump/graph/LocalGraph.scala
@@ -28,7 +28,7 @@ import akka.stream.impl.{PublisherSource, SubscriberSink}
import akka.stream.{Outlet, SinkShape, SourceShape}
import org.reactivestreams.{Publisher, Subscriber}
-import io.gearpump.util.Graph
+import org.apache.gearpump.util.Graph
/**
*
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/akkastream/src/main/scala/akka/stream/gearpump/graph/RemoteGraph.scala
----------------------------------------------------------------------
diff --git a/experiments/akkastream/src/main/scala/akka/stream/gearpump/graph/RemoteGraph.scala b/experiments/akkastream/src/main/scala/akka/stream/gearpump/graph/RemoteGraph.scala
index 5bb9a68..3cea78a 100644
--- a/experiments/akkastream/src/main/scala/akka/stream/gearpump/graph/RemoteGraph.scala
+++ b/experiments/akkastream/src/main/scala/akka/stream/gearpump/graph/RemoteGraph.scala
@@ -26,10 +26,10 @@ import akka.stream.gearpump.task.SinkBridgeTask.SinkBridgeTaskClient
import akka.stream.gearpump.task.SourceBridgeTask.SourceBridgeTaskClient
import akka.stream.impl.StreamLayout.Module
-import io.gearpump.cluster.client.ClientContext
-import io.gearpump.cluster.embedded.EmbeddedCluster
-import io.gearpump.streaming.ProcessorId
-import io.gearpump.util.Graph
+import org.apache.gearpump.cluster.client.ClientContext
+import org.apache.gearpump.cluster.embedded.EmbeddedCluster
+import org.apache.gearpump.streaming.ProcessorId
+import org.apache.gearpump.util.Graph
/**
*
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/akkastream/src/main/scala/akka/stream/gearpump/graph/SubGraph.scala
----------------------------------------------------------------------
diff --git a/experiments/akkastream/src/main/scala/akka/stream/gearpump/graph/SubGraph.scala b/experiments/akkastream/src/main/scala/akka/stream/gearpump/graph/SubGraph.scala
index 4364645..564b6c7 100644
--- a/experiments/akkastream/src/main/scala/akka/stream/gearpump/graph/SubGraph.scala
+++ b/experiments/akkastream/src/main/scala/akka/stream/gearpump/graph/SubGraph.scala
@@ -21,7 +21,7 @@ package akka.stream.gearpump.graph
import akka.stream.ModuleGraph.Edge
import akka.stream.impl.StreamLayout.Module
-import io.gearpump.util.Graph
+import org.apache.gearpump.util.Graph
/**
* [[SubGraph]] is a partial part of [[akka.stream.ModuleGraph]]
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/akkastream/src/main/scala/akka/stream/gearpump/materializer/LocalMaterializer.scala
----------------------------------------------------------------------
diff --git a/experiments/akkastream/src/main/scala/akka/stream/gearpump/materializer/LocalMaterializer.scala b/experiments/akkastream/src/main/scala/akka/stream/gearpump/materializer/LocalMaterializer.scala
index 78125c8..a5c6e48 100644
--- a/experiments/akkastream/src/main/scala/akka/stream/gearpump/materializer/LocalMaterializer.scala
+++ b/experiments/akkastream/src/main/scala/akka/stream/gearpump/materializer/LocalMaterializer.scala
@@ -29,7 +29,7 @@ import akka.stream.impl.StreamLayout.Module
import akka.stream.impl.StreamSupervisor
import akka.stream.{ActorAttributes, ActorMaterializer, ActorMaterializerSettings, Attributes, ClosedShape, Graph => AkkaGraph, MaterializationContext, ModuleGraph}
-import io.gearpump.util.Graph
+import org.apache.gearpump.util.Graph
/**
* [[LocalMaterializer]] will use local actor to materialize the graph
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/akkastream/src/main/scala/akka/stream/gearpump/materializer/LocalMaterializerImpl.scala
----------------------------------------------------------------------
diff --git a/experiments/akkastream/src/main/scala/akka/stream/gearpump/materializer/LocalMaterializerImpl.scala b/experiments/akkastream/src/main/scala/akka/stream/gearpump/materializer/LocalMaterializerImpl.scala
index 97d8f70..1ec724e 100644
--- a/experiments/akkastream/src/main/scala/akka/stream/gearpump/materializer/LocalMaterializerImpl.scala
+++ b/experiments/akkastream/src/main/scala/akka/stream/gearpump/materializer/LocalMaterializerImpl.scala
@@ -33,7 +33,7 @@ import akka.stream.impl.{ActorProcessorFactory, ActorPublisher, ExposedPublisher
import akka.stream.{ActorMaterializerSettings, Attributes, Graph => AkkaGraph, InPort, MaterializationContext, Materializer, OutPort, Shape}
import org.reactivestreams.{Processor, Publisher, Subscriber}
-import io.gearpump.util.Graph
+import org.apache.gearpump.util.Graph
/**
* This materializer is functional equivalent to [[akka.stream.impl.ActorMaterializerImpl]]
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/akkastream/src/main/scala/akka/stream/gearpump/materializer/RemoteMaterializerImpl.scala
----------------------------------------------------------------------
diff --git a/experiments/akkastream/src/main/scala/akka/stream/gearpump/materializer/RemoteMaterializerImpl.scala b/experiments/akkastream/src/main/scala/akka/stream/gearpump/materializer/RemoteMaterializerImpl.scala
index 9852ed0..47ed1f2 100644
--- a/experiments/akkastream/src/main/scala/akka/stream/gearpump/materializer/RemoteMaterializerImpl.scala
+++ b/experiments/akkastream/src/main/scala/akka/stream/gearpump/materializer/RemoteMaterializerImpl.scala
@@ -28,11 +28,11 @@ import akka.stream.impl.Stages.StageModule
import akka.stream.impl.StreamLayout.Module
import org.slf4j.LoggerFactory
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.dsl.StreamApp
-import io.gearpump.streaming.dsl.op.{DataSinkOp, DataSourceOp, Direct, FlatMapOp, GroupByOp, MasterOp, MergeOp, Op, OpEdge, ProcessorOp, Shuffle, SlaveOp}
-import io.gearpump.streaming.{ProcessorId, StreamApplication}
-import io.gearpump.util.Graph
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.dsl.StreamApp
+import org.apache.gearpump.streaming.dsl.op.{DataSinkOp, DataSourceOp, Direct, FlatMapOp, GroupByOp, MasterOp, MergeOp, Op, OpEdge, ProcessorOp, Shuffle, SlaveOp}
+import org.apache.gearpump.streaming.{ProcessorId, StreamApplication}
+import org.apache.gearpump.util.Graph
/**
* [[RemoteMaterializerImpl]] will materialize the [[Graph[Module, Edge]] to a Gearpump
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/akkastream/src/main/scala/akka/stream/gearpump/module/GearpumpTaskModule.scala
----------------------------------------------------------------------
diff --git a/experiments/akkastream/src/main/scala/akka/stream/gearpump/module/GearpumpTaskModule.scala b/experiments/akkastream/src/main/scala/akka/stream/gearpump/module/GearpumpTaskModule.scala
index 4b7d3ac..c4c78cc 100644
--- a/experiments/akkastream/src/main/scala/akka/stream/gearpump/module/GearpumpTaskModule.scala
+++ b/experiments/akkastream/src/main/scala/akka/stream/gearpump/module/GearpumpTaskModule.scala
@@ -22,10 +22,10 @@ import akka.stream.impl.FlowModule
import akka.stream.impl.StreamLayout.Module
import akka.stream.{Attributes, Inlet, Outlet, Shape, SinkShape, SourceShape}
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.sink.DataSink
-import io.gearpump.streaming.source.DataSource
-import io.gearpump.streaming.task.Task
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.sink.DataSink
+import org.apache.gearpump.streaming.source.DataSource
+import org.apache.gearpump.streaming.task.Task
/**
* [[GearpumpTaskModule]] represent modules that can be materialized as Gearpump Tasks.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/akkastream/src/main/scala/akka/stream/gearpump/scaladsl/Api.scala
----------------------------------------------------------------------
diff --git a/experiments/akkastream/src/main/scala/akka/stream/gearpump/scaladsl/Api.scala b/experiments/akkastream/src/main/scala/akka/stream/gearpump/scaladsl/Api.scala
index a9f6e97..9e35389 100644
--- a/experiments/akkastream/src/main/scala/akka/stream/gearpump/scaladsl/Api.scala
+++ b/experiments/akkastream/src/main/scala/akka/stream/gearpump/scaladsl/Api.scala
@@ -23,10 +23,10 @@ import akka.stream.gearpump.module.{DummySink, DummySource, GroupByModule, Proce
import akka.stream.scaladsl.{Flow, Keep, Sink, Source}
import org.reactivestreams.{Publisher, Subscriber}
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.sink.DataSink
-import io.gearpump.streaming.source.DataSource
-import io.gearpump.streaming.task.Task
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.sink.DataSink
+import org.apache.gearpump.streaming.source.DataSource
+import org.apache.gearpump.streaming.task.Task
object GearSource {
@@ -61,7 +61,7 @@ object GearSource {
}
/**
- * Construct a Source from Gearpump [[io.gearpump.streaming.Processor]].
+ * Construct a Source from Gearpump [[org.apache.gearpump.streaming.Processor]].
*
* [[ProcessorModule]] -> downstream Sink
*
@@ -106,7 +106,7 @@ object GearSink {
}
/**
- * Construct a Sink from Gearpump [[io.gearpump.streaming.Processor]].
+ * Construct a Sink from Gearpump [[org.apache.gearpump.streaming.Processor]].
*
* Upstream Source -> [[ProcessorModule]]
*
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/akkastream/src/main/scala/akka/stream/gearpump/task/BalanceTask.scala
----------------------------------------------------------------------
diff --git a/experiments/akkastream/src/main/scala/akka/stream/gearpump/task/BalanceTask.scala b/experiments/akkastream/src/main/scala/akka/stream/gearpump/task/BalanceTask.scala
index 58a04ca..2eb0612 100644
--- a/experiments/akkastream/src/main/scala/akka/stream/gearpump/task/BalanceTask.scala
+++ b/experiments/akkastream/src/main/scala/akka/stream/gearpump/task/BalanceTask.scala
@@ -18,9 +18,9 @@
package akka.stream.gearpump.task
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.task.TaskContext
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.task.TaskContext
class BalanceTask(context: TaskContext, userConf: UserConfig) extends GraphTask(context, userConf) {
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/akkastream/src/main/scala/akka/stream/gearpump/task/BroadcastTask.scala
----------------------------------------------------------------------
diff --git a/experiments/akkastream/src/main/scala/akka/stream/gearpump/task/BroadcastTask.scala b/experiments/akkastream/src/main/scala/akka/stream/gearpump/task/BroadcastTask.scala
index 388806e..925bf21 100644
--- a/experiments/akkastream/src/main/scala/akka/stream/gearpump/task/BroadcastTask.scala
+++ b/experiments/akkastream/src/main/scala/akka/stream/gearpump/task/BroadcastTask.scala
@@ -18,9 +18,9 @@
package akka.stream.gearpump.task
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.task.TaskContext
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.task.TaskContext
class BroadcastTask(context: TaskContext, userConf: UserConfig) extends GraphTask(context, userConf) {
override def onNext(msg: Message): Unit = {
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/akkastream/src/main/scala/akka/stream/gearpump/task/GraphTask.scala
----------------------------------------------------------------------
diff --git a/experiments/akkastream/src/main/scala/akka/stream/gearpump/task/GraphTask.scala b/experiments/akkastream/src/main/scala/akka/stream/gearpump/task/GraphTask.scala
index d3f483d..9a4e24e 100644
--- a/experiments/akkastream/src/main/scala/akka/stream/gearpump/task/GraphTask.scala
+++ b/experiments/akkastream/src/main/scala/akka/stream/gearpump/task/GraphTask.scala
@@ -20,10 +20,10 @@ package akka.stream.gearpump.task
import akka.stream.gearpump.task.GraphTask.{Index, PortId}
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.ProcessorId
-import io.gearpump.streaming.task.{StartTime, Task, TaskContext, TaskWrapper}
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.ProcessorId
+import org.apache.gearpump.streaming.task.{StartTime, Task, TaskContext, TaskWrapper}
class GraphTask(inputTaskContext: TaskContext, userConf: UserConfig)
extends Task(inputTaskContext, userConf) {
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/akkastream/src/main/scala/akka/stream/gearpump/task/SinkBridgeTask.scala
----------------------------------------------------------------------
diff --git a/experiments/akkastream/src/main/scala/akka/stream/gearpump/task/SinkBridgeTask.scala b/experiments/akkastream/src/main/scala/akka/stream/gearpump/task/SinkBridgeTask.scala
index d7bacd5..b681852 100644
--- a/experiments/akkastream/src/main/scala/akka/stream/gearpump/task/SinkBridgeTask.scala
+++ b/experiments/akkastream/src/main/scala/akka/stream/gearpump/task/SinkBridgeTask.scala
@@ -27,13 +27,13 @@ import akka.stream.gearpump.task.SinkBridgeTask.RequestMessage
import akka.util.Timeout
import org.reactivestreams.{Publisher, Subscriber, Subscription}
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.cluster.client.ClientContext
-import io.gearpump.streaming.ProcessorId
-import io.gearpump.streaming.appmaster.AppMaster.{LookupTaskActorRef, TaskActorRef}
-import io.gearpump.streaming.task.{StartTime, Task, TaskContext, TaskId}
-import io.gearpump.util.LogUtil
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.cluster.client.ClientContext
+import org.apache.gearpump.streaming.ProcessorId
+import org.apache.gearpump.streaming.appmaster.AppMaster.{LookupTaskActorRef, TaskActorRef}
+import org.apache.gearpump.streaming.task.{StartTime, Task, TaskContext, TaskId}
+import org.apache.gearpump.util.LogUtil
/**
* Bridge Task when data flow is from remote Gearpump Task to local Akka-Stream Module
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/akkastream/src/main/scala/akka/stream/gearpump/task/SourceBridgeTask.scala
----------------------------------------------------------------------
diff --git a/experiments/akkastream/src/main/scala/akka/stream/gearpump/task/SourceBridgeTask.scala b/experiments/akkastream/src/main/scala/akka/stream/gearpump/task/SourceBridgeTask.scala
index b433a7f..ccbd350 100644
--- a/experiments/akkastream/src/main/scala/akka/stream/gearpump/task/SourceBridgeTask.scala
+++ b/experiments/akkastream/src/main/scala/akka/stream/gearpump/task/SourceBridgeTask.scala
@@ -24,12 +24,12 @@ import akka.actor.Actor.Receive
import akka.stream.gearpump.task.SourceBridgeTask.{AkkaStreamMessage, Complete, Error}
import org.reactivestreams.{Subscriber, Subscription}
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.cluster.client.ClientContext
-import io.gearpump.streaming.ProcessorId
-import io.gearpump.streaming.appmaster.AppMaster.{LookupTaskActorRef, TaskActorRef}
-import io.gearpump.streaming.task.{StartTime, Task, TaskContext, TaskId}
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.cluster.client.ClientContext
+import org.apache.gearpump.streaming.ProcessorId
+import org.apache.gearpump.streaming.appmaster.AppMaster.{LookupTaskActorRef, TaskActorRef}
+import org.apache.gearpump.streaming.task.{StartTime, Task, TaskContext, TaskId}
/**
* Bridge Task when data flow is from local Akka-Stream Module to remote Gearpump Task
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/akkastream/src/main/scala/akka/stream/gearpump/task/UnZip2Task.scala
----------------------------------------------------------------------
diff --git a/experiments/akkastream/src/main/scala/akka/stream/gearpump/task/UnZip2Task.scala b/experiments/akkastream/src/main/scala/akka/stream/gearpump/task/UnZip2Task.scala
index 0b3b9a5..78fabbe 100644
--- a/experiments/akkastream/src/main/scala/akka/stream/gearpump/task/UnZip2Task.scala
+++ b/experiments/akkastream/src/main/scala/akka/stream/gearpump/task/UnZip2Task.scala
@@ -20,9 +20,9 @@ package akka.stream.gearpump.task
import akka.stream.gearpump.task.UnZip2Task.UnZipFunction
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.task.TaskContext
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.task.TaskContext
class UnZip2Task(context: TaskContext, userConf: UserConfig) extends GraphTask(context, userConf) {
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/CGroupResource.java
----------------------------------------------------------------------
diff --git a/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/CGroupResource.java b/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/CGroupResource.java
deleted file mode 100644
index 973ad03..0000000
--- a/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/CGroupResource.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.cluster.cgroup;
-
-public class CGroupResource {
-
- private ResourceType type;
-
- private int hierarchyID;
-
- private int cgroupsNum;
-
- private boolean enable;
-
- public CGroupResource(ResourceType type, int hierarchyID, int cgroupNum, boolean enable) {
- this.type = type;
- this.hierarchyID = hierarchyID;
- this.cgroupsNum = cgroupNum;
- this.enable = enable;
- }
-
- public ResourceType getType() {
- return type;
- }
-
- public void setType(ResourceType type) {
- this.type = type;
- }
-
- public int getHierarchyID() {
- return hierarchyID;
- }
-
- public void setHierarchyID(int hierarchyID) {
- this.hierarchyID = hierarchyID;
- }
-
- public int getCgroupsNum() {
- return cgroupsNum;
- }
-
- public void setCgroupsNum(int cgroupsNum) {
- this.cgroupsNum = cgroupsNum;
- }
-
- public boolean isEnable() {
- return enable;
- }
-
- public void setEnable(boolean enable) {
- this.enable = enable;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/CgroupCenter.java
----------------------------------------------------------------------
diff --git a/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/CgroupCenter.java b/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/CgroupCenter.java
deleted file mode 100644
index dc889ba..0000000
--- a/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/CgroupCenter.java
+++ /dev/null
@@ -1,212 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.cluster.cgroup;
-
-import io.gearpump.cluster.utils.SystemOperation;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileReader;
-import java.io.IOException;
-import java.util.*;
-
-public class CgroupCenter implements CgroupOperation {
-
- public static Logger LOG = LoggerFactory.getLogger(CgroupCenter.class);
-
- private static CgroupCenter instance;
-
- private CgroupCenter() {
-
- }
-
- /**
- * Thread unsafe
- *
- * @return
- */
- public synchronized static CgroupCenter getInstance() {
- if (instance == null)
- instance = new CgroupCenter();
- return CgroupUtils.enabled() ? instance : null;
- }
-
- @Override
- public List<Hierarchy> getHierarchies() {
- // TODO Auto-generated method stub
- Map<String, Hierarchy> hierarchies = new HashMap<String, Hierarchy>();
- FileReader reader = null;
- BufferedReader br = null;
- try {
- reader = new FileReader(Constants.MOUNT_STATUS_FILE);
- br = new BufferedReader(reader);
- String str = null;
- while ((str = br.readLine()) != null) {
- String[] strSplit = str.split(" ");
- if (!strSplit[2].equals("cgroup"))
- continue;
- String name = strSplit[0];
- String type = strSplit[3];
- String dir = strSplit[1];
- Hierarchy h = hierarchies.get(type);
- h = new Hierarchy(name, CgroupUtils.analyse(type), dir);
- hierarchies.put(type, h);
- }
- return new ArrayList<Hierarchy>(hierarchies.values());
- } catch (Exception e) {
- LOG.error("Get hierarchies error", e);
- } finally {
- CgroupUtils.close(reader, br);
- }
- return null;
- }
-
- @Override
- public Set<CGroupResource> getCGroupResources() {
- // TODO Auto-generated method stub
- Set<CGroupResource> resources = new HashSet<CGroupResource>();
- FileReader reader = null;
- BufferedReader br = null;
- try {
- reader = new FileReader(Constants.CGROUP_STATUS_FILE);
- br = new BufferedReader(reader);
- String str = null;
- while ((str = br.readLine()) != null) {
- String[] split = str.split("\t");
- ResourceType type = ResourceType.getResourceType(split[0]);
- if (type == null)
- continue;
- resources.add(new CGroupResource(type, Integer.valueOf(split[1]), Integer.valueOf(split[2]), Integer.valueOf(split[3]).intValue() == 1 ? true
- : false));
- }
- return resources;
- } catch (Exception e) {
- LOG.error("Get subSystems error ", e);
- } finally {
- CgroupUtils.close(reader, br);
- }
- return null;
- }
-
- @Override
- public boolean enabled(ResourceType resourceType) {
- // TODO Auto-generated method stub
- Set<CGroupResource> resources = this.getCGroupResources();
- for (CGroupResource resource : resources) {
- if (resource.getType() == resourceType)
- return true;
- }
- return false;
- }
-
- @Override
- public Hierarchy busy(ResourceType resourceType) {
- List<Hierarchy> hierarchies = this.getHierarchies();
- for (Hierarchy hierarchy : hierarchies) {
- for (ResourceType type : hierarchy.getResourceTypes()) {
- if (type == resourceType)
- return hierarchy;
- }
- }
- return null;
- }
-
- @Override
- public Hierarchy mounted(Hierarchy hierarchy) {
- // TODO Auto-generated method stub
- List<Hierarchy> hierarchies = this.getHierarchies();
- if (CgroupUtils.dirExists(hierarchy.getDir())) {
- for (Hierarchy h : hierarchies) {
- if (h.equals(hierarchy))
- return h;
- }
- }
- return null;
- }
-
- @Override
- public void mount(Hierarchy hierarchy) throws IOException {
- // TODO Auto-generated method stub
- if (this.mounted(hierarchy) != null) {
- LOG.error(hierarchy.getDir() + " is mounted");
- return;
- }
- Set<ResourceType> resourceTypes = hierarchy.getResourceTypes();
- for (ResourceType type : resourceTypes) {
- if (this.busy(type) != null) {
- LOG.error("subsystem: " + type.name() + " is busy");
- resourceTypes.remove(type);
- }
- }
- if (resourceTypes.size() == 0)
- return;
- if (!CgroupUtils.dirExists(hierarchy.getDir()))
- new File(hierarchy.getDir()).mkdirs();
- String subSystems = CgroupUtils.reAnalyse(resourceTypes);
- SystemOperation.mount(subSystems, hierarchy.getDir(), "cgroup", subSystems);
- }
-
- @Override
- public void umount(Hierarchy hierarchy) throws IOException {
- // TODO Auto-generated method stub
- if (this.mounted(hierarchy) != null) {
- hierarchy.getRootCgroups().delete();
- SystemOperation.umount(hierarchy.getDir());
- CgroupUtils.deleteDir(hierarchy.getDir());
- }
- }
-
- @Override
- public void create(CgroupCommon cgroup) throws SecurityException {
- // TODO Auto-generated method stub
- if (cgroup.isRoot()) {
- LOG.error("You can't create rootCgroup in this function");
- return;
- }
- CgroupCommon parent = cgroup.getParent();
- while (parent != null) {
- if (!CgroupUtils.dirExists(parent.getDir())) {
- LOG.error(parent.getDir() + "is not existed");
- return;
- }
- parent = parent.getParent();
- }
- Hierarchy h = cgroup.getHierarchy();
- if (mounted(h) == null) {
- LOG.error(h.getDir() + " is not mounted");
- return;
- }
- if (CgroupUtils.dirExists(cgroup.getDir())) {
- LOG.error(cgroup.getDir() + " is existed");
- return;
- }
- (new File(cgroup.getDir())).mkdir();
- }
-
- @Override
- public void delete(CgroupCommon cgroup) throws IOException {
- // TODO Auto-generated method stub
- cgroup.delete();
- }
-
- public static void main(String args[]) {
- System.out.println(CgroupCenter.getInstance().getHierarchies().get(0).getRootCgroups().getChildren().size());
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/CgroupCommon.java
----------------------------------------------------------------------
diff --git a/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/CgroupCommon.java b/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/CgroupCommon.java
deleted file mode 100644
index 5414814..0000000
--- a/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/CgroupCommon.java
+++ /dev/null
@@ -1,220 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.cluster.cgroup;
-
-import io.gearpump.cluster.cgroup.core.CgroupCore;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-public class CgroupCommon implements CgroupCommonOperation {
-
- public static final String TASKS = "/tasks";
- public static final String NOTIFY_ON_RELEASE = "/notify_on_release";
- public static final String RELEASE_AGENT = "/release_agent";
- public static final String CGROUP_CLONE_CHILDREN = "/cgroup.clone_children";
- public static final String CGROUP_EVENT_CONTROL = "/cgroup.event_control";
- public static final String CGROUP_PROCS = "/cgroup.procs";
-
- private final Hierarchy hierarchy;
-
- private final String name;
-
- private final String dir;
-
- private final CgroupCommon parent;
-
- private final Map<ResourceType, CgroupCore> cores;
-
- private final boolean isRoot;
-
- private final Set<CgroupCommon> children = new HashSet<CgroupCommon>();
-
- public CgroupCommon(String name, Hierarchy hierarchy, CgroupCommon parent) {
- this.name = parent.getName() + "/" + name;
- this.hierarchy = hierarchy;
- this.parent = parent;
- this.dir = parent.getDir() + "/" + name;
- this.init();
- cores = CgroupCoreFactory.getInstance(this.hierarchy.getResourceTypes(), this.dir);
- this.isRoot = false;
- }
-
- /**
- * rootCgroup
- */
- public CgroupCommon(Hierarchy hierarchy, String dir) {
- this.name = "";
- this.hierarchy = hierarchy;
- this.parent = null;
- this.dir = dir;
- this.init();
- cores = CgroupCoreFactory.getInstance(this.hierarchy.getResourceTypes(), this.dir);
- this.isRoot = true;
- }
-
- @Override
- public void addTask(int taskId) throws IOException {
- // TODO Auto-generated method stub
- CgroupUtils.writeFileByLine(Constants.getDir(this.dir, TASKS), String.valueOf(taskId));
- }
-
- @Override
- public Set<Integer> getTasks() throws IOException {
- List<String> stringTasks = CgroupUtils.readFileByLine(Constants.getDir(this.dir, TASKS));
- Set<Integer> tasks = new HashSet<Integer>();
- for (String task : stringTasks) {
- tasks.add(Integer.valueOf(task));
- }
- return tasks;
- }
-
- @Override
- public void addProcs(int pid) throws IOException {
- // TODO Auto-generated method stub
- CgroupUtils.writeFileByLine(Constants.getDir(this.dir, CGROUP_PROCS), String.valueOf(pid));
- }
-
- @Override
- public Set<Integer> getPids() throws IOException {
- // TODO Auto-generated method stub
- List<String> stringPids = CgroupUtils.readFileByLine(Constants.getDir(this.dir, CGROUP_PROCS));
- Set<Integer> pids = new HashSet<Integer>();
- for (String task : stringPids) {
- pids.add(Integer.valueOf(task));
- }
- return pids;
- }
-
- @Override
- public void setNotifyOnRelease(boolean flag) throws IOException {
- // TODO Auto-generated method stub
- CgroupUtils.writeFileByLine(Constants.getDir(this.dir, NOTIFY_ON_RELEASE), flag ? "1" : "0");
- }
-
- @Override
- public boolean getNotifyOnRelease() throws IOException {
- return CgroupUtils.readFileByLine(Constants.getDir(this.dir, NOTIFY_ON_RELEASE)).get(0).equals("1") ? true : false;
- }
-
- @Override
- public void setReleaseAgent(String command) throws IOException {
- // TODO Auto-generated method stub
- if (!this.isRoot)
- return;
- CgroupUtils.writeFileByLine(Constants.getDir(this.dir, RELEASE_AGENT), command);
- }
-
- @Override
- public String getReleaseAgent() throws IOException {
- if (!this.isRoot)
- return null;
- return CgroupUtils.readFileByLine(Constants.getDir(this.dir, RELEASE_AGENT)).get(0);
- }
-
- @Override
- public void setCgroupCloneChildren(boolean flag) throws IOException {
- // TODO Auto-generated method stub
- if (!this.cores.keySet().contains(ResourceType.cpuset))
- return;
- CgroupUtils.writeFileByLine(Constants.getDir(this.dir, CGROUP_CLONE_CHILDREN), flag ? "1" : "0");
- }
-
- @Override
- public boolean getCgroupCloneChildren() throws IOException {
- return CgroupUtils.readFileByLine(Constants.getDir(this.dir, CGROUP_CLONE_CHILDREN)).get(0).equals("1") ? true : false;
- }
-
- @Override
- public void setEventControl(String eventFd, String controlFd, String... args) throws IOException {
- // TODO Auto-generated method stub
- StringBuilder sb = new StringBuilder();
- sb.append(eventFd);
- sb.append(' ');
- sb.append(controlFd);
- for (String arg : args) {
- sb.append(' ');
- sb.append(arg);
- }
- CgroupUtils.writeFileByLine(Constants.getDir(this.dir, CGROUP_EVENT_CONTROL), sb.toString());
- }
-
- public Hierarchy getHierarchy() {
- return hierarchy;
- }
-
- public String getName() {
- return name;
- }
-
- public String getDir() {
- return dir;
- }
-
- public CgroupCommon getParent() {
- return parent;
- }
-
- public Set<CgroupCommon> getChildren() {
- return children;
- }
-
- public boolean isRoot() {
- return isRoot;
- }
-
- public Map<ResourceType, CgroupCore> getCores() {
- return cores;
- }
-
- public void delete() throws IOException {
- this.free();
- if (!this.isRoot)
- this.parent.getChildren().remove(this);
- }
-
- private void free() throws IOException {
- for (CgroupCommon child : this.children)
- child.free();
- if (this.isRoot)
- return;
- Set<Integer> tasks = this.getTasks();
- if (tasks != null) {
- for (Integer task : tasks) {
- this.parent.addTask(task);
- }
- }
- CgroupUtils.deleteDir(this.dir);
- }
-
- private void init() {
- File file = new File(this.dir);
- File[] files = file.listFiles();
- if (files == null)
- return;
- for (File child : files) {
- if (child.isDirectory()) {
- this.children.add(new CgroupCommon(child.getName(), this.hierarchy, this));
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/CgroupCommonOperation.java
----------------------------------------------------------------------
diff --git a/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/CgroupCommonOperation.java b/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/CgroupCommonOperation.java
deleted file mode 100644
index 7465645..0000000
--- a/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/CgroupCommonOperation.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.cluster.cgroup;
-
-import java.io.IOException;
-import java.util.Set;
-
-public interface CgroupCommonOperation {
-
- public void addTask(int taskid) throws IOException;
-
- public Set<Integer> getTasks() throws IOException;
-
- public void addProcs(int pid) throws IOException;
-
- public Set<Integer> getPids() throws IOException;
-
- public void setNotifyOnRelease(boolean flag) throws IOException;
-
- public boolean getNotifyOnRelease() throws IOException;
-
- public void setReleaseAgent(String command) throws IOException;
-
- public String getReleaseAgent() throws IOException;
-
- public void setCgroupCloneChildren(boolean flag) throws IOException;
-
- public boolean getCgroupCloneChildren() throws IOException;
-
- public void setEventControl(String eventFd, String controlFd, String... args) throws IOException;
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/CgroupCoreFactory.java
----------------------------------------------------------------------
diff --git a/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/CgroupCoreFactory.java b/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/CgroupCoreFactory.java
deleted file mode 100644
index a719f91..0000000
--- a/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/CgroupCoreFactory.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.cluster.cgroup;
-
-import io.gearpump.cluster.cgroup.core.CgroupCore;
-import io.gearpump.cluster.cgroup.core.CpuCore;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-public class CgroupCoreFactory {
-
- public static Map<ResourceType, CgroupCore> getInstance(Set<ResourceType> types, String dir) {
- Map<ResourceType, CgroupCore> result = new HashMap<ResourceType, CgroupCore>();
- for (ResourceType type : types) {
- switch (type) {
- case cpu:
- result.put(ResourceType.cpu, new CpuCore(dir));
- break;
- default:
- break;
- }
- }
- return result;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/CgroupOperation.java
----------------------------------------------------------------------
diff --git a/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/CgroupOperation.java b/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/CgroupOperation.java
deleted file mode 100644
index a3d830a..0000000
--- a/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/CgroupOperation.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.cluster.cgroup;
-
-import java.io.IOException;
-import java.util.List;
-import java.util.Set;
-
-public interface CgroupOperation {
-
- public List<Hierarchy> getHierarchies();
-
- public Set<CGroupResource> getCGroupResources();
-
- public boolean enabled(ResourceType subsystem);
-
- public Hierarchy busy(ResourceType subsystem);
-
- public Hierarchy mounted(Hierarchy hierarchy);
-
- public void mount(Hierarchy hierarchy) throws IOException;
-
- public void umount(Hierarchy hierarchy) throws IOException;
-
- public void create(CgroupCommon cgroup) throws SecurityException;
-
- public void delete(CgroupCommon cgroup) throws IOException;
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/CgroupUtils.java
----------------------------------------------------------------------
diff --git a/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/CgroupUtils.java b/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/CgroupUtils.java
deleted file mode 100644
index 0a7f97c..0000000
--- a/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/CgroupUtils.java
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.cluster.cgroup;
-
-import io.gearpump.cluster.utils.SystemOperation;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.*;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-public class CgroupUtils {
-
- public static final Logger LOG = LoggerFactory.getLogger(CgroupUtils.class);
-
- public static void deleteDir(String dir) {
- try {
- String cmd = "rmdir " + dir;
- SystemOperation.exec(cmd);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- LOG.error("rm " + dir + " fail!", e);
- }
- }
-
- public static boolean fileExists(String dir) {
- File file = new File(dir);
- return file.exists();
- }
-
- public static boolean dirExists(String dir) {
- File file = new File(dir);
- return file.isDirectory();
- }
-
- public static Set<ResourceType> analyse(String str) {
- Set<ResourceType> result = new HashSet<ResourceType>();
- String[] subSystems = str.split(",");
- for (String subSystem : subSystems) {
- ResourceType type = ResourceType.getResourceType(subSystem);
- if (type != null)
- result.add(type);
- }
- return result;
- }
-
- public static String reAnalyse(Set<ResourceType> subSystems) {
- StringBuilder sb = new StringBuilder();
- if (subSystems.size() == 0)
- return sb.toString();
- for (ResourceType type : subSystems) {
- sb.append(type.name()).append(",");
- }
- return sb.toString().substring(0, sb.length() - 1);
- }
-
- public static boolean enabled() {
- return CgroupUtils.fileExists(Constants.CGROUP_STATUS_FILE);
- }
-
- public static List<String> readFileByLine(String fileDir) throws IOException {
- List<String> result = new ArrayList<String>();
- FileReader fileReader = null;
- BufferedReader reader = null;
- try {
- File file = new File(fileDir);
- fileReader = new FileReader(file);
- reader = new BufferedReader(fileReader);
- String tempString = null;
- while ((tempString = reader.readLine()) != null) {
- result.add(tempString);
- }
- } finally {
- CgroupUtils.close(fileReader, reader);
- }
- return result;
- }
-
- public static void writeFileByLine(String fileDir, List<String> strings) throws IOException {
- FileWriter writer = null;
- BufferedWriter bw = null;
- try {
- File file = new File(fileDir);
- if (!file.exists()) {
- LOG.error(fileDir + " is no existed");
- return;
- }
- writer = new FileWriter(file, true);
- bw = new BufferedWriter(writer);
- for (String string : strings) {
- bw.write(string);
- bw.newLine();
- bw.flush();
- }
- } finally {
- CgroupUtils.close(writer, bw);
- }
- }
-
- public static void writeFileByLine(String fileDir, String string) throws IOException {
- FileWriter writer = null;
- BufferedWriter bw = null;
- try {
- File file = new File(fileDir);
- if (!file.exists()) {
- LOG.error(fileDir + " is no existed");
- return;
- }
- writer = new FileWriter(file, true);
- bw = new BufferedWriter(writer);
- bw.write(string);
- bw.newLine();
- bw.flush();
- } finally {
- CgroupUtils.close(writer, bw);
- }
- }
-
- public static void close(FileReader reader, BufferedReader br) {
- try {
- if (reader != null)
- reader.close();
- if (br != null)
- br.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
-
- }
- }
-
- public static void close(FileWriter writer, BufferedWriter bw) {
- try {
- if (writer != null)
- writer.close();
- if (bw != null)
- bw.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
-
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/Constants.java
----------------------------------------------------------------------
diff --git a/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/Constants.java b/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/Constants.java
deleted file mode 100644
index 80e12be..0000000
--- a/experiments/cgroup/src/main/java/io/gearpump/cluster/cgroup/Constants.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.cluster.cgroup;
-
-public class Constants {
-
- public static final String CGROUP_STATUS_FILE = "/proc/cgroups";
-
- public static final String MOUNT_STATUS_FILE = "/proc/mounts";
-
- public static String getDir(String dir, String constant) {
- return dir + constant;
- }
-}
[08/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/task/TaskControlMessage.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/task/TaskControlMessage.scala b/streaming/src/main/scala/io/gearpump/streaming/task/TaskControlMessage.scala
deleted file mode 100644
index d89387a..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/task/TaskControlMessage.scala
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.task
-
-import io.gearpump.TimeStamp
-import io.gearpump.streaming.ProcessorId
-
-/*
- * Initial AckRequest
- */
-case class InitialAckRequest(taskId: TaskId, sessionId: Int)
-
-/*
- Here the sessionId filed is used to distinguish messages
- between different replays after the application restart
- */
-case class AckRequest(taskId: TaskId, seq: Short, sessionId: Int)
-
-/**
- * Ack back to sender task actor.
- *
- * @param seq The seq field represents the expected number of received messages and the
- * actualReceivedNum field means the actual received number since start.
- */
-case class Ack(taskId: TaskId, seq: Short, actualReceivedNum: Short, sessionId: Int)
-
-sealed trait ClockEvent
-
-case class UpdateClock(taskId: TaskId, time: TimeStamp) extends ClockEvent
-
-object GetLatestMinClock extends ClockEvent
-
-case class GetUpstreamMinClock(taskId: TaskId) extends ClockEvent
-
-case class UpstreamMinClock(latestMinClock: TimeStamp)
-
-case class LatestMinClock(clock: TimeStamp)
-
-case class ReportCheckpointClock(taskId: TaskId, clock: TimeStamp)
-
-case object GetCheckpointClock
-
-case class CheckpointClock(clock: Option[TimeStamp])
-
-case object GetStartClock
-
-case class StartClock(clock: TimeStamp)
-
-/** Probe the latency between two upstream to downstream tasks. */
-case class LatencyProbe(timestamp: Long)
-
-case class SendMessageLoss()
-
-case object GetDAG
-
-case class CheckProcessorDeath(processorId: ProcessorId)
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/task/TaskId.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/task/TaskId.scala b/streaming/src/main/scala/io/gearpump/streaming/task/TaskId.scala
deleted file mode 100644
index 66c3c52..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/task/TaskId.scala
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.task
-
-import io.gearpump.streaming._
-
-case class TaskId(processorId: ProcessorId, index: TaskIndex)
-
-object TaskId {
- def toLong(id: TaskId): Long = (id.processorId.toLong << 32) + id.index
- def fromLong(id: Long): TaskId = TaskId(((id >> 32) & 0xFFFFFFFF).toInt, (id & 0xFFFFFFFF).toInt)
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/task/TaskMessageSerializer.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/task/TaskMessageSerializer.scala b/streaming/src/main/scala/io/gearpump/streaming/task/TaskMessageSerializer.scala
deleted file mode 100644
index 500f8b3..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/task/TaskMessageSerializer.scala
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.task
-
-import java.io.{DataInput, DataOutput}
-
-trait TaskMessageSerializer[T] {
- def write(dataOutput: DataOutput, obj: T)
-
- def read(dataInput: DataInput): T
-
- def getLength(obj: T): Int
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/task/TaskUtil.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/task/TaskUtil.scala b/streaming/src/main/scala/io/gearpump/streaming/task/TaskUtil.scala
deleted file mode 100644
index 040fc2e..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/task/TaskUtil.scala
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.task
-
-object TaskUtil {
-
- /**
- * Resolves a classname to a Task class.
- *
- * @param className the class name to resolve
- * @return resolved class
- */
- def loadClass(className: String): Class[_ <: Task] = {
- val loader = Thread.currentThread().getContextClassLoader()
- loader.loadClass(className).asSubclass(classOf[Task])
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/task/TaskWrapper.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/task/TaskWrapper.scala b/streaming/src/main/scala/io/gearpump/streaming/task/TaskWrapper.scala
deleted file mode 100644
index e7e883c..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/task/TaskWrapper.scala
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.task
-
-import scala.concurrent.duration.FiniteDuration
-
-import akka.actor.Actor._
-import akka.actor.{ActorRef, ActorSystem, Cancellable, Props}
-import org.slf4j.Logger
-
-import io.gearpump.cluster.UserConfig
-import io.gearpump.util.LogUtil
-import io.gearpump.{Message, TimeStamp}
-
-/**
- * This provides TaskContext for user defined tasks
- *
- * @param taskClass task class
- * @param context context class
- * @param userConf user config
- */
-class TaskWrapper(
- val taskId: TaskId, taskClass: Class[_ <: Task], context: TaskContextData,
- userConf: UserConfig) extends TaskContext with TaskInterface {
-
- private val LOG = LogUtil.getLogger(taskClass, task = taskId)
-
- private var actor: TaskActor = null
-
- private var task: Option[Task] = None
-
- def setTaskActor(actor: TaskActor): Unit = this.actor = actor
-
- override def appId: Int = context.appId
-
- override def appName: String = context.appName
-
- override def executorId: Int = context.executorId
-
- override def parallelism: Int = context.parallelism
-
- override def appMaster: ActorRef = context.appMaster
-
- override def output(msg: Message): Unit = actor.output(msg)
-
- /**
- * See [[io.gearpump.streaming.task.TaskActor]] output(arrayIndex: Int, msg: Message): Unit
- *
- * @param index, not same as ProcessorId
- */
- def output(index: Int, msg: Message): Unit = actor.output(index, msg)
-
- /**
- * Use with caution, output unmanaged message to target tasks
- *
- * @param msg message to output
- * @param tasks the tasks to output to
- */
- def outputUnManaged(msg: AnyRef, tasks: TaskId*): Unit = {
- actor.transport(msg, tasks: _*)
- }
-
- override def self: ActorRef = actor.context.self
-
- override def sender: ActorRef = actor.context.sender()
-
- def system: ActorSystem = actor.context.system
-
- override def actorOf(props: Props): ActorRef = actor.context.actorOf(props)
-
- override def actorOf(props: Props, name: String): ActorRef = actor.context.actorOf(props, name)
-
- override def onStart(startTime: StartTime): Unit = {
- if (None != task) {
- LOG.error(s"Task.onStart should not be called multiple times... ${task.getClass}")
- }
- val constructor = taskClass.getConstructor(classOf[TaskContext], classOf[UserConfig])
- task = Some(constructor.newInstance(this, userConf))
- task.foreach(_.onStart(startTime))
- }
-
- override def onNext(msg: Message): Unit = task.foreach(_.onNext(msg))
-
- override def onStop(): Unit = {
- task.foreach(_.onStop())
- task = None
- }
-
- override def receiveUnManagedMessage: Receive = {
- task.map(_.receiveUnManagedMessage).getOrElse(defaultMessageHandler)
- }
-
- override def upstreamMinClock: TimeStamp = {
- actor.getUpstreamMinClock
- }
-
- def schedule(initialDelay: FiniteDuration, interval: FiniteDuration)(f: => Unit): Cancellable = {
- val dispatcher = actor.context.system.dispatcher
- actor.context.system.scheduler.schedule(initialDelay, interval)(f)(dispatcher)
- }
-
- def scheduleOnce(initialDelay: FiniteDuration)(f: => Unit): Cancellable = {
- val dispatcher = actor.context.system.dispatcher
- actor.context.system.scheduler.scheduleOnce(initialDelay)(f)(dispatcher)
- }
-
- private def defaultMessageHandler: Receive = {
- case msg =>
- LOG.error("Failed! Received unknown message " + "taskId: " + taskId + ", " + msg.toString)
- }
-
- /**
- * Logger is environment dependant, it should be provided by
- * containing environment.
- */
- override def logger: Logger = LOG
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/transaction/api/CheckpointStore.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/transaction/api/CheckpointStore.scala b/streaming/src/main/scala/io/gearpump/streaming/transaction/api/CheckpointStore.scala
deleted file mode 100644
index f3894ea..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/transaction/api/CheckpointStore.scala
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.transaction.api
-
-import io.gearpump.TimeStamp
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.task.TaskContext
-
-/**
- * CheckpointStore persistently stores mapping of timestamp to checkpoint
- * it's possible that two checkpoints have the same timestamp
- * CheckpointStore needs to handle this either during write or read
- */
-trait CheckpointStore {
-
- def persist(timeStamp: TimeStamp, checkpoint: Array[Byte]): Unit
-
- def recover(timestamp: TimeStamp): Option[Array[Byte]]
-
- def close(): Unit
-}
-
-trait CheckpointStoreFactory extends java.io.Serializable {
- def getCheckpointStore(conf: UserConfig, taskContext: TaskContext): CheckpointStore
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/transaction/api/MessageDecoder.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/transaction/api/MessageDecoder.scala b/streaming/src/main/scala/io/gearpump/streaming/transaction/api/MessageDecoder.scala
deleted file mode 100644
index 7039b71..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/transaction/api/MessageDecoder.scala
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.transaction.api
-
-import io.gearpump.Message
-
-/**
- * MessageDecoder decodes raw bytes to Message It is usually written by end user and
- * passed into TimeReplayableSource
- */
-trait MessageDecoder extends java.io.Serializable {
- def fromBytes(bytes: Array[Byte]): Message
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/transaction/api/OffsetManager.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/transaction/api/OffsetManager.scala b/streaming/src/main/scala/io/gearpump/streaming/transaction/api/OffsetManager.scala
deleted file mode 100644
index 412ddcc..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/transaction/api/OffsetManager.scala
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.transaction.api
-
-import scala.util.Try
-
-import io.gearpump.{Message, TimeStamp}
-
-/**
- * Filters offsets and store the mapping from timestamp to offset
- */
-trait MessageFilter {
- def filter(messageAndOffset: (Message, Long)): Option[Message]
-}
-
-/**
- * Resolves timestamp to offset by look up the underlying storage
- */
-trait OffsetTimeStampResolver {
- def resolveOffset(time: TimeStamp): Try[Long]
-}
-
-/**
- * Manages message's offset on TimeReplayableSource and timestamp
- */
-trait OffsetManager extends MessageFilter with OffsetTimeStampResolver {
- def close(): Unit
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/transaction/api/OffsetStorage.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/transaction/api/OffsetStorage.scala b/streaming/src/main/scala/io/gearpump/streaming/transaction/api/OffsetStorage.scala
deleted file mode 100644
index fa7161c..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/transaction/api/OffsetStorage.scala
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.transaction.api
-
-import scala.util.Try
-
-import io.gearpump.TimeStamp
-
-object OffsetStorage {
-
- /**
- * StorageEmpty means no data has been stored
- */
- case object StorageEmpty extends Throwable
-
- /**
- * Overflow means the looked up time is
- * larger than the maximum stored TimeStamp
- */
- case class Overflow(maxTimestamp: Array[Byte]) extends Throwable
-
- /**
- * Underflow means the looked up time is
- * smaller than the minimum stored TimeStamp
- */
- case class Underflow(minTimestamp: Array[Byte]) extends Throwable
-}
-
-/**
- * OffsetStorage stores the mapping from TimeStamp to Offset
- */
-trait OffsetStorage {
- /**
- * Tries to look up the time in the OffsetStorage return the corresponding Offset if the time is
- * in the range of stored TimeStamps or one of the failure info (StorageEmpty, Overflow,
- * Underflow)
- *
- * @param time the time to look for
- * @return the corresponding offset if the time is in the range, otherwise failure
- */
- def lookUp(time: TimeStamp): Try[Array[Byte]]
-
- def append(time: TimeStamp, offset: Array[Byte]): Unit
-
- def close(): Unit
-}
-
-trait OffsetStorageFactory extends java.io.Serializable {
- def getOffsetStorage(dir: String): OffsetStorage
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/transaction/api/TimeReplayableSource.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/transaction/api/TimeReplayableSource.scala b/streaming/src/main/scala/io/gearpump/streaming/transaction/api/TimeReplayableSource.scala
deleted file mode 100644
index 50711ee..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/transaction/api/TimeReplayableSource.scala
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.transaction.api
-
-import io.gearpump.streaming.source.DataSource
-
-/**
- * AT-LEAST-ONCE API. Represents a data source which allow replaying.
- *
- * Subclass should be able to replay messages on recovery from the time
- * when an application crashed.
- */
-trait TimeReplayableSource extends DataSource
-
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/transaction/api/TimeStampFilter.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/transaction/api/TimeStampFilter.scala b/streaming/src/main/scala/io/gearpump/streaming/transaction/api/TimeStampFilter.scala
deleted file mode 100644
index 7c34e1a..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/transaction/api/TimeStampFilter.scala
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.transaction.api
-
-import io.gearpump.{Message, TimeStamp}
-
-/**
- * TimeStampFilter filters out messages that are obsolete.
- */
-trait TimeStampFilter extends java.io.Serializable {
- def filter(msg: Message, predicate: TimeStamp): Option[Message]
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/io/gearpump/streaming/util/ActorPathUtil.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/io/gearpump/streaming/util/ActorPathUtil.scala b/streaming/src/main/scala/io/gearpump/streaming/util/ActorPathUtil.scala
deleted file mode 100644
index c2ac32a..0000000
--- a/streaming/src/main/scala/io/gearpump/streaming/util/ActorPathUtil.scala
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.util
-
-import akka.actor.{ActorPath, ActorRef}
-
-import io.gearpump.streaming.task.TaskId
-
-object ActorPathUtil {
-
- def executorActorName(executorId: Int): String = executorId.toString
-
- def taskActorName(taskId: TaskId): String = {
- s"processor_${taskId.processorId}_task_${taskId.index}"
- }
-
- def taskActorPath(appMaster: ActorRef, executorId: Int, taskId: TaskId): ActorPath = {
- val executorManager = appMaster.path.child(executorManagerActorName)
- val executor = executorManager.child(executorActorName(executorId))
- val task = executor.child(taskActorName(taskId))
- task
- }
-
- def executorManagerActorName: String = "executors"
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/ClusterMessage.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/ClusterMessage.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/ClusterMessage.scala
new file mode 100644
index 0000000..4b801a2
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/ClusterMessage.scala
@@ -0,0 +1,85 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming
+
+import scala.language.existentials
+
+import akka.actor.ActorRef
+
+import org.apache.gearpump.TimeStamp
+import org.apache.gearpump.cluster.appmaster.WorkerInfo
+import org.apache.gearpump.cluster.scheduler.Resource
+import org.apache.gearpump.streaming.appmaster.TaskRegistry.TaskLocations
+import org.apache.gearpump.streaming.task.{Subscriber, TaskId}
+import org.apache.gearpump.transport.HostPort
+
+object AppMasterToExecutor {
+ case class LaunchTasks(
+ taskId: List[TaskId], dagVersion: Int, processorDescription: ProcessorDescription,
+ subscribers: List[Subscriber])
+
+ case object TasksLaunched
+
+ /**
+ * dagVersion, life, and subscribers will be changed on target task list.
+ */
+ case class ChangeTasks(
+ taskId: List[TaskId], dagVersion: Int, life: LifeTime, subscribers: List[Subscriber])
+
+ case class TasksChanged(taskIds: List[TaskId])
+
+ case class ChangeTask(
+ taskId: TaskId, dagVersion: Int, life: LifeTime, subscribers: List[Subscriber])
+
+ case class TaskChanged(taskId: TaskId, dagVersion: Int)
+
+ case class StartTask(taskId: TaskId)
+
+ case class StopTask(taskId: TaskId)
+
+ case class TaskLocationsReady(taskLocations: TaskLocations, dagVersion: Int)
+
+ case class TaskLocationsReceived(dagVersion: Int, executorId: ExecutorId)
+
+ case class TaskLocationsRejected(
+ dagVersion: Int, executorId: ExecutorId, reason: String, ex: Throwable)
+
+ case class StartAllTasks(dagVersion: Int)
+
+ case class StartDynamicDag(dagVersion: Int)
+ case class TaskRegistered(taskId: TaskId, sessionId: Int, startClock: TimeStamp)
+ case class TaskRejected(taskId: TaskId)
+
+ case object RestartClockService
+ class MsgLostException extends Exception
+}
+
+object ExecutorToAppMaster {
+ case class RegisterExecutor(
+ executor: ActorRef, executorId: Int, resource: Resource, worker : WorkerInfo)
+
+ case class RegisterTask(taskId: TaskId, executorId: Int, task: HostPort)
+ case class UnRegisterTask(taskId: TaskId, executorId: Int)
+
+ case class MessageLoss(executorId: Int, taskId: TaskId, cause: String)
+}
+
+object AppMasterToMaster {
+ case class StallingTasks(tasks: List[TaskId])
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/Constants.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/Constants.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/Constants.scala
new file mode 100644
index 0000000..445f26c
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/Constants.scala
@@ -0,0 +1,36 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming
+
+object Constants {
+
+ val GEARPUMP_STREAMING_OPERATOR = "gearpump.streaming.dsl.operator"
+ val GEARPUMP_STREAMING_SOURCE = "gearpump.streaming.dsl.source"
+ val GEARPUMP_STREAMING_SINK = "gearpump.streaming.dsl.sink"
+ val GEARPUMP_STREAMING_GROUPBY_FUNCTION = "gearpump.streaming.dsl.groupby-function"
+
+ val GEARPUMP_STREAMING_LOCALITIES = "gearpump.streaming.localities"
+
+ val GEARPUMP_STREAMING_REGISTER_TASK_TIMEOUT_MS = "gearpump.streaming.register-task-timeout-ms"
+
+ val GEARPUMP_STREAMING_MAX_PENDING_MESSAGE_COUNT =
+ "gearpump.streaming.max-pending-message-count-per-connection"
+
+ val GEARPUMP_STREAMING_ACK_ONCE_EVERY_MESSAGE_COUNT =
+ "gearpump.streaming.ack-once-every-message-count"
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/DAG.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/DAG.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/DAG.scala
new file mode 100644
index 0000000..4a94ad3
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/DAG.scala
@@ -0,0 +1,62 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming
+
+import org.apache.gearpump.partitioner.PartitionerDescription
+import org.apache.gearpump.streaming.task.TaskId
+import org.apache.gearpump.util.Graph
+
+/**
+ * DAG is wrapper for [[org.apache.gearpump.util.Graph]] for streaming applications.
+ */
+case class DAG(version: Int, processors : Map[ProcessorId, ProcessorDescription],
+ graph : Graph[ProcessorId, PartitionerDescription])
+ extends Serializable {
+
+ def isEmpty: Boolean = {
+ processors.isEmpty
+ }
+
+ def taskCount: Int = {
+ processors.foldLeft(0) { (count, task) =>
+ count + task._2.parallelism
+ }
+ }
+
+ def tasks: List[TaskId] = {
+ processors.flatMap { pair =>
+ val (processorId, processor) = pair
+ (0 until processor.parallelism).map(TaskId(processorId, _))
+ }.toList
+ }
+}
+
+object DAG {
+ def apply(graph: Graph[ProcessorDescription, PartitionerDescription], version: Int = 0): DAG = {
+ val processors = graph.vertices.map { processorDescription =>
+ (processorDescription.id, processorDescription)
+ }.toMap
+ val dag = graph.mapVertex { processor =>
+ processor.id
+ }
+ new DAG(version, processors, dag)
+ }
+
+ def empty: DAG = apply(Graph.empty[ProcessorDescription, PartitionerDescription])
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/MessageSerializer.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/MessageSerializer.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/MessageSerializer.scala
new file mode 100644
index 0000000..20e2529
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/MessageSerializer.scala
@@ -0,0 +1,108 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming
+
+import java.io.{DataInput, DataOutput}
+
+import org.apache.gearpump.streaming.task._
+
+class TaskIdSerializer extends TaskMessageSerializer[TaskId] {
+ override def getLength(obj: TaskId): Int = 8
+
+ override def write(dataOutput: DataOutput, obj: TaskId): Unit = {
+ dataOutput.writeInt(obj.processorId)
+ dataOutput.writeInt(obj.index)
+ }
+
+ override def read(dataInput: DataInput): TaskId = {
+ val processorId = dataInput.readInt()
+ val index = dataInput.readInt()
+ new TaskId(processorId, index)
+ }
+}
+
+class AckSerializer extends TaskMessageSerializer[Ack] {
+ val taskIdSerializer = new TaskIdSerializer
+
+ override def getLength(obj: Ack): Int = taskIdSerializer.getLength(obj.taskId) + 8
+
+ override def write(dataOutput: DataOutput, obj: Ack): Unit = {
+ taskIdSerializer.write(dataOutput, obj.taskId)
+ dataOutput.writeShort(obj.seq)
+ dataOutput.writeShort(obj.actualReceivedNum)
+ dataOutput.writeInt(obj.sessionId)
+ }
+
+ override def read(dataInput: DataInput): Ack = {
+ val taskId = taskIdSerializer.read(dataInput)
+ val seq = dataInput.readShort()
+ val actualReceivedNum = dataInput.readShort()
+ val sessionId = dataInput.readInt()
+ Ack(taskId, seq, actualReceivedNum, sessionId)
+ }
+}
+
+class InitialAckRequestSerializer extends TaskMessageSerializer[InitialAckRequest] {
+ val taskIdSerialzer = new TaskIdSerializer()
+
+ override def getLength(obj: InitialAckRequest): Int = taskIdSerialzer.getLength(obj.taskId) + 4
+
+ override def write(dataOutput: DataOutput, obj: InitialAckRequest): Unit = {
+ taskIdSerialzer.write(dataOutput, obj.taskId)
+ dataOutput.writeInt(obj.sessionId)
+ }
+
+ override def read(dataInput: DataInput): InitialAckRequest = {
+ val taskId = taskIdSerialzer.read(dataInput)
+ val sessionId = dataInput.readInt()
+ InitialAckRequest(taskId, sessionId)
+ }
+}
+
+class AckRequestSerializer extends TaskMessageSerializer[AckRequest] {
+ val taskIdSerializer = new TaskIdSerializer
+
+ override def getLength(obj: AckRequest): Int = taskIdSerializer.getLength(obj.taskId) + 6
+
+ override def write(dataOutput: DataOutput, obj: AckRequest): Unit = {
+ taskIdSerializer.write(dataOutput, obj.taskId)
+ dataOutput.writeShort(obj.seq)
+ dataOutput.writeInt(obj.sessionId)
+ }
+
+ override def read(dataInput: DataInput): AckRequest = {
+ val taskId = taskIdSerializer.read(dataInput)
+ val seq = dataInput.readShort()
+ val sessionId = dataInput.readInt()
+ AckRequest(taskId, seq, sessionId)
+ }
+}
+
+class LatencyProbeSerializer extends TaskMessageSerializer[LatencyProbe] {
+ override def getLength(obj: LatencyProbe): Int = 8
+
+ override def write(dataOutput: DataOutput, obj: LatencyProbe): Unit = {
+ dataOutput.writeLong(obj.timestamp)
+ }
+
+ override def read(dataInput: DataInput): LatencyProbe = {
+ val timestamp = dataInput.readLong()
+ LatencyProbe(timestamp)
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/StreamApplication.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/StreamApplication.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/StreamApplication.scala
new file mode 100644
index 0000000..66ec873
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/StreamApplication.scala
@@ -0,0 +1,171 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming
+
+import scala.language.implicitConversions
+import scala.reflect.ClassTag
+
+import akka.actor.ActorSystem
+
+import org.apache.gearpump.TimeStamp
+import org.apache.gearpump.cluster._
+import org.apache.gearpump.partitioner.{HashPartitioner, Partitioner, PartitionerDescription, PartitionerObject}
+import org.apache.gearpump.streaming.appmaster.AppMaster
+import org.apache.gearpump.streaming.task.Task
+import org.apache.gearpump.util.{Graph, LogUtil, ReferenceEqual}
+
+/**
+ * Processor is the blueprint for tasks.
+ */
+trait Processor[+T <: Task] extends ReferenceEqual {
+
+ /**
+ * How many tasks you want to use for this processor.
+ */
+ def parallelism: Int
+
+ /**
+ * The custom [[org.apache.gearpump.cluster.UserConfig]], it is used to
+ * initialize a task in runtime.
+ */
+ def taskConf: UserConfig
+
+ /**
+ * Some description text for this processor.
+ */
+ def description: String
+
+ /**
+ * The task class, should be a subtype of Task.
+ *
+ * Each runtime instance of this class is a task.
+ */
+ def taskClass: Class[_ <: Task]
+}
+
+object Processor {
+ def ProcessorToProcessorDescription(id: ProcessorId, processor: Processor[_ <: Task])
+ : ProcessorDescription = {
+ import processor._
+ ProcessorDescription(id, taskClass.getName, parallelism, description, taskConf)
+ }
+
+ def apply[T<: Task](
+ parallelism : Int, description: String = "",
+ taskConf: UserConfig = UserConfig.empty)(implicit classtag: ClassTag[T])
+ : DefaultProcessor[T] = {
+ new DefaultProcessor[T](parallelism, description, taskConf,
+ classtag.runtimeClass.asInstanceOf[Class[T]])
+ }
+
+ def apply[T<: Task](
+ taskClazz: Class[T], parallelism : Int, description: String, taskConf: UserConfig)
+ : DefaultProcessor[T] = {
+ new DefaultProcessor[T](parallelism, description, taskConf, taskClazz)
+ }
+
+ case class DefaultProcessor[T<: Task](
+ parallelism : Int, description: String, taskConf: UserConfig, taskClass: Class[T])
+ extends Processor[T] {
+
+ def withParallelism(parallel: Int): DefaultProcessor[T] = {
+ new DefaultProcessor[T](parallel, description, taskConf, taskClass)
+ }
+
+ def withDescription(desc: String): DefaultProcessor[T] = {
+ new DefaultProcessor[T](parallelism, desc, taskConf, taskClass)
+ }
+
+ def withConfig(conf: UserConfig): DefaultProcessor[T] = {
+ new DefaultProcessor[T](parallelism, description, conf, taskClass)
+ }
+ }
+}
+
+/**
+ * Each processor has a LifeTime.
+ *
+ * When input message's timestamp is beyond current processor's lifetime,
+ * then it will not be processed by this processor.
+ */
+case class LifeTime(birth: TimeStamp, death: TimeStamp) {
+ def contains(timestamp: TimeStamp): Boolean = {
+ timestamp >= birth && timestamp < death
+ }
+
+ def cross(another: LifeTime): LifeTime = {
+ LifeTime(Math.max(birth, another.birth), Math.min(death, another.death))
+ }
+}
+
+object LifeTime {
+ val Immortal = LifeTime(0L, Long.MaxValue)
+}
+
+/**
+ * Represent a streaming application
+ */
+class StreamApplication(
+ override val name: String, val inputUserConfig: UserConfig,
+ val dag: Graph[ProcessorDescription, PartitionerDescription])
+ extends Application {
+
+ require(!dag.hasDuplicatedEdge(), "Graph should not have duplicated edges")
+
+ override def appMaster: Class[_ <: ApplicationMaster] = classOf[AppMaster]
+ override def userConfig(implicit system: ActorSystem): UserConfig = {
+ inputUserConfig.withValue(StreamApplication.DAG, dag)
+ }
+}
+
+case class ProcessorDescription(
+ id: ProcessorId,
+ taskClass: String,
+ parallelism : Int,
+ description: String = "",
+ taskConf: UserConfig = null,
+ life: LifeTime = LifeTime.Immortal,
+ jar: AppJar = null) extends ReferenceEqual
+
+object StreamApplication {
+
+ private val hashPartitioner = new HashPartitioner()
+ private val LOG = LogUtil.getLogger(getClass)
+
+ def apply[T <: Processor[Task], P <: Partitioner](
+ name: String, dag: Graph[T, P], userConfig: UserConfig): StreamApplication = {
+ import org.apache.gearpump.streaming.Processor._
+
+ if (dag.hasCycle()) {
+ LOG.warn(s"Detected cycles in DAG of application $name!")
+ }
+
+ val indices = dag.topologicalOrderWithCirclesIterator.toList.zipWithIndex.toMap
+ val graph = dag.mapVertex { processor =>
+ val updatedProcessor = ProcessorToProcessorDescription(indices(processor), processor)
+ updatedProcessor
+ }.mapEdge { (node1, edge, node2) =>
+ PartitionerDescription(new PartitionerObject(
+ Option(edge).getOrElse(StreamApplication.hashPartitioner)))
+ }
+ new StreamApplication(name, userConfig, graph)
+ }
+
+ val DAG = "DAG"
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/AppMaster.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/AppMaster.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/AppMaster.scala
new file mode 100644
index 0000000..7c08b9b
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/AppMaster.scala
@@ -0,0 +1,362 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.appmaster
+
+import java.lang.management.ManagementFactory
+
+import akka.actor._
+import org.apache.gearpump._
+import org.apache.gearpump.cluster.ClientToMaster.{GetLastFailure, GetStallingTasks, QueryHistoryMetrics, ShutdownApplication}
+import org.apache.gearpump.cluster.MasterToAppMaster.{AppMasterDataDetailRequest, ReplayFromTimestampWindowTrailingEdge}
+import org.apache.gearpump.cluster.MasterToClient.{HistoryMetrics, HistoryMetricsItem, LastFailure}
+import org.apache.gearpump.cluster._
+import org.apache.gearpump.cluster.worker.WorkerId
+import org.apache.gearpump.metrics.Metrics.ReportMetrics
+import org.apache.gearpump.metrics.{JvmMetricsSet, Metrics, MetricsReporterService}
+import org.apache.gearpump.partitioner.PartitionerDescription
+import org.apache.gearpump.streaming.ExecutorToAppMaster.{MessageLoss, RegisterExecutor, RegisterTask, UnRegisterTask}
+import org.apache.gearpump.streaming._
+import org.apache.gearpump.streaming.appmaster.AppMaster._
+import org.apache.gearpump.streaming.appmaster.DagManager.{GetLatestDAG, LatestDAG, ReplaceProcessor}
+import org.apache.gearpump.streaming.appmaster.ExecutorManager.{ExecutorInfo, GetExecutorInfo}
+import org.apache.gearpump.streaming.appmaster.TaskManager.{FailedToRecover, GetTaskList, TaskList}
+import org.apache.gearpump.streaming.executor.Executor.{ExecutorConfig, ExecutorSummary, GetExecutorSummary, QueryExecutorConfig}
+import org.apache.gearpump.streaming.storage.InMemoryAppStoreOnMaster
+import org.apache.gearpump.streaming.task._
+import org.apache.gearpump.streaming.util.ActorPathUtil
+import org.apache.gearpump.util.Constants.{APPMASTER_DEFAULT_EXECUTOR_ID, _}
+import org.apache.gearpump.util.HistoryMetricsService.HistoryMetricsConfig
+import org.apache.gearpump.util._
+import org.slf4j.Logger
+
+import scala.concurrent.Future
+
+/**
+ * AppMaster is the head of a streaming application.
+ *
+ * It contains:
+ * 1. ExecutorManager to manage all executors.
+ * 2. TaskManager to manage all tasks,
+ * 3. ClockService to track the global clock for this streaming application.
+ * 4. Scheduler to decide which a task should be scheduled to.
+ */
+class AppMaster(appContext: AppMasterContext, app: AppDescription) extends ApplicationMaster {
+ import app.userConfig
+ import appContext.{appId, masterProxy, username}
+
+ private implicit val actorSystem = context.system
+ private implicit val timeOut = FUTURE_TIMEOUT
+
+ import akka.pattern.ask
+ private implicit val dispatcher = context.dispatcher
+
+ private val startTime: TimeStamp = System.currentTimeMillis()
+
+ private val LOG: Logger = LogUtil.getLogger(getClass, app = appId)
+ LOG.info(s"AppMaster[$appId] is launched by $username, app: $app xxxxxxxxxxxxxxxxx")
+ LOG.info(s"AppMaster actor path: ${ActorUtil.getFullPath(context.system, self.path)}")
+
+ private val address = ActorUtil.getFullPath(context.system, self.path)
+
+ private val store = new InMemoryAppStoreOnMaster(appId, appContext.masterProxy)
+ private val dagManager = context.actorOf(Props(new DagManager(appContext.appId, userConfig, store,
+ Some(getUpdatedDAG()))))
+
+ private var taskManager: Option[ActorRef] = None
+ private var clockService: Option[ActorRef] = None
+ private val systemConfig = context.system.settings.config
+ private var lastFailure = LastFailure(0L, null)
+
+ private val appMasterBrief = ExecutorBrief(APPMASTER_DEFAULT_EXECUTOR_ID,
+ self.path.toString,
+ Option(appContext.workerInfo).map(_.workerId).getOrElse(WorkerId.unspecified), "active")
+
+ private val getHistoryMetricsConfig = HistoryMetricsConfig(systemConfig)
+
+ private val metricsEnabled = systemConfig.getBoolean(GEARPUMP_METRIC_ENABLED)
+
+ private val userDir = System.getProperty("user.dir")
+ private val logFile = LogUtil.applicationLogDir(actorSystem.settings.config)
+
+ private val appMasterExecutorSummary = ExecutorSummary(
+ APPMASTER_DEFAULT_EXECUTOR_ID,
+ Option(appContext.workerInfo).map(_.workerId).getOrElse(WorkerId.unspecified),
+ self.path.toString,
+ logFile.getAbsolutePath,
+ status = "Active",
+ taskCount = 0,
+ tasks = Map.empty[ProcessorId, List[TaskId]],
+ jvmName = ManagementFactory.getRuntimeMXBean().getName()
+ )
+
+ private val historyMetricsService = if (metricsEnabled) {
+ // Registers jvm metrics
+ Metrics(context.system).register(new JvmMetricsSet(
+ s"app${appId}.executor${APPMASTER_DEFAULT_EXECUTOR_ID}"))
+
+ val historyMetricsService = context.actorOf(Props(new HistoryMetricsService(
+ s"app$appId", getHistoryMetricsConfig)))
+
+ val metricsReportService = context.actorOf(Props(
+ new MetricsReporterService(Metrics(context.system))))
+ historyMetricsService.tell(ReportMetrics, metricsReportService)
+
+ Some(historyMetricsService)
+ } else {
+ None
+ }
+
+ private val executorManager: ActorRef =
+ context.actorOf(ExecutorManager.props(userConfig, appContext, app.clusterConfig, app.name),
+ ActorPathUtil.executorManagerActorName)
+
+ for (dag <- getDAG) {
+ clockService = Some(context.actorOf(Props(new ClockService(dag, store))))
+ val jarScheduler = new JarScheduler(appId, app.name, systemConfig, context)
+
+ taskManager = Some(context.actorOf(Props(new TaskManager(appContext.appId, dagManager,
+ jarScheduler, executorManager, clockService.get, self, app.name))))
+ }
+
+ override def receive: Receive = {
+ taskMessageHandler orElse
+ executorMessageHandler orElse
+ recover orElse
+ appMasterService orElse
+ ActorUtil.defaultMsgHandler(self)
+ }
+
+ /** Handles messages from Tasks */
+ def taskMessageHandler: Receive = {
+ case clock: ClockEvent =>
+ taskManager.foreach(_ forward clock)
+ case register: RegisterTask =>
+ taskManager.foreach(_ forward register)
+ case unRegister: UnRegisterTask =>
+ taskManager.foreach(_ forward unRegister)
+ // Checks whether this processor dead, if it is, then we should remove it from clockService.
+ clockService.foreach(_ forward CheckProcessorDeath(unRegister.taskId.processorId))
+ case replay: ReplayFromTimestampWindowTrailingEdge =>
+ taskManager.foreach(_ forward replay)
+ case messageLoss: MessageLoss =>
+ lastFailure = LastFailure(System.currentTimeMillis(), messageLoss.cause)
+ taskManager.foreach(_ forward messageLoss)
+ case lookupTask: LookupTaskActorRef =>
+ taskManager.foreach(_ forward lookupTask)
+ case checkpoint: ReportCheckpointClock =>
+ clockService.foreach(_ forward checkpoint)
+ case GetDAG =>
+ val task = sender
+ getDAG.foreach {
+ dag => task ! dag
+ }
+ case GetCheckpointClock =>
+ clockService.foreach(_ forward GetCheckpointClock)
+ }
+
+ /** Handles messages from Executors */
+ def executorMessageHandler: Receive = {
+ case register: RegisterExecutor =>
+ executorManager forward register
+ case ReportMetrics =>
+ historyMetricsService.foreach(_ forward ReportMetrics)
+ }
+
+ /** Handles messages from AppMaster */
+ def appMasterService: Receive = {
+ case appMasterDataDetailRequest: AppMasterDataDetailRequest =>
+ LOG.debug(s"AppMaster got AppMasterDataDetailRequest for $appId ")
+
+ val executorsFuture = executorBrief
+ val clockFuture = getMinClock
+ val taskFuture = getTaskList
+ val dagFuture = getDAG
+
+ val appMasterDataDetail = for {
+ executors <- executorsFuture
+ clock <- clockFuture
+ tasks <- taskFuture
+ dag <- dagFuture
+ } yield {
+ val graph = dag.graph
+
+ val executorToTasks = tasks.tasks.groupBy(_._2).mapValues {
+ _.keys.toList
+ }
+
+ val processors = dag.processors.map { kv =>
+ val processor = kv._2
+ import processor._
+ val tasks = executorToTasks.map { kv =>
+ (kv._1, TaskCount(kv._2.count(_.processorId == id)))
+ }.filter(_._2.count != 0)
+ (id,
+ ProcessorSummary(id, taskClass, parallelism, description, taskConf, life,
+ tasks.keys.toList, tasks))
+ }
+
+ StreamAppMasterSummary(
+ appId = appId,
+ appName = app.name,
+ actorPath = address,
+ clock = clock,
+ status = MasterToAppMaster.AppMasterActive,
+ startTime = startTime,
+ uptime = System.currentTimeMillis() - startTime,
+ user = username,
+ homeDirectory = userDir,
+ logFile = logFile.getAbsolutePath,
+ processors = processors,
+ processorLevels = graph.vertexHierarchyLevelMap(),
+ dag = graph.mapEdge { (node1, edge, node2) =>
+ edge.partitionerFactory.name
+ },
+ executors = executors,
+ historyMetricsConfig = getHistoryMetricsConfig
+ )
+ }
+
+ val client = sender()
+
+ appMasterDataDetail.map { appData =>
+ client ! appData
+ }
+ // TODO: WebSocket is buggy and disabled.
+ // case appMasterMetricsRequest: AppMasterMetricsRequest =>
+ // val client = sender()
+ // actorSystem.eventStream.subscribe(client, classOf[MetricType])
+ case query: QueryHistoryMetrics =>
+ if (historyMetricsService.isEmpty) {
+ // Returns empty metrics so that we don't hang the UI
+ sender ! HistoryMetrics(query.path, List.empty[HistoryMetricsItem])
+ } else {
+ historyMetricsService.get forward query
+ }
+ case getStalling: GetStallingTasks =>
+ clockService.foreach(_ forward getStalling)
+ case replaceDAG: ReplaceProcessor =>
+ dagManager forward replaceDAG
+ case GetLastFailure(_) =>
+ sender ! lastFailure
+ case get@GetExecutorSummary(executorId) =>
+ val client = sender
+ if (executorId == APPMASTER_DEFAULT_EXECUTOR_ID) {
+ client ! appMasterExecutorSummary
+ } else {
+ ActorUtil.askActor[Map[ExecutorId, ExecutorInfo]](executorManager, GetExecutorInfo)
+ .map { map =>
+ map.get(executorId).foreach { executor =>
+ executor.executor.tell(get, client)
+ }
+ }
+ }
+ case query@QueryExecutorConfig(executorId) =>
+ val client = sender
+ if (executorId == -1) {
+ val systemConfig = context.system.settings.config
+ sender ! ExecutorConfig(ClusterConfig.filterOutDefaultConfig(systemConfig))
+ } else {
+ ActorUtil.askActor[Map[ExecutorId, ExecutorInfo]](executorManager, GetExecutorInfo)
+ .map { map =>
+ map.get(executorId).foreach { executor =>
+ executor.executor.tell(query, client)
+ }
+ }
+ }
+ }
+
+ /** Error handling */
+ def recover: Receive = {
+ case FailedToRecover(errorMsg) =>
+ if (context.children.toList.contains(sender())) {
+ LOG.error(errorMsg)
+ masterProxy ! ShutdownApplication(appId)
+ }
+ case AllocateResourceTimeOut =>
+ LOG.error(s"Failed to allocate resource in time, shutdown application $appId")
+ masterProxy ! ShutdownApplication(appId)
+ context.stop(self)
+ }
+
+ private def getMinClock: Future[TimeStamp] = {
+ clockService match {
+ case Some(clockService) =>
+ (clockService ? GetLatestMinClock).asInstanceOf[Future[LatestMinClock]].map(_.clock)
+ case None =>
+ Future.failed(new ServiceNotAvailableException("clock service not ready"))
+ }
+ }
+
+ private def executorBrief: Future[List[ExecutorBrief]] = {
+ ActorUtil.askActor[Map[ExecutorId, ExecutorInfo]](executorManager, GetExecutorInfo)
+ .map { infos =>
+ infos.values.map { info =>
+ ExecutorBrief(info.executorId,
+ info.executor.path.toSerializationFormat,
+ info.worker.workerId,
+ "active")
+ }.toList :+ appMasterBrief
+ }
+ }
+
+ private def getTaskList: Future[TaskList] = {
+ taskManager match {
+ case Some(taskManager) =>
+ (taskManager ? GetTaskList).asInstanceOf[Future[TaskList]]
+ case None =>
+ Future.failed(new ServiceNotAvailableException("task manager not ready"))
+ }
+ }
+
+ private def getDAG: Future[DAG] = {
+ (dagManager ? GetLatestDAG).asInstanceOf[Future[LatestDAG]].map(_.dag)
+ }
+
+ private def getUpdatedDAG(): DAG = {
+ val dag = DAG(userConfig.getValue[Graph[ProcessorDescription,
+ PartitionerDescription]](StreamApplication.DAG).get)
+ val updated = dag.processors.map { idAndProcessor =>
+ val (id, oldProcessor) = idAndProcessor
+ val newProcessor = if (oldProcessor.jar == null) {
+ oldProcessor.copy(jar = appContext.appJar.getOrElse(null))
+ } else {
+ oldProcessor
+ }
+ (id, newProcessor)
+ }
+ DAG(dag.version, updated, dag.graph)
+ }
+}
+
+object AppMaster {
+
+ /** Master node doesn't return resource in time */
+ case object AllocateResourceTimeOut
+
+ /** Query task ActorRef by providing the taskId */
+ case class LookupTaskActorRef(taskId: TaskId)
+
+ case class TaskActorRef(task: ActorRef)
+
+ class ServiceNotAvailableException(reason: String) extends Exception(reason)
+
+ case class ExecutorBrief(
+ executorId: ExecutorId, executor: String, workerId: WorkerId, status: String)
+
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/ClockService.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/ClockService.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/ClockService.scala
new file mode 100644
index 0000000..458fded
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/ClockService.scala
@@ -0,0 +1,447 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.appmaster
+
+import java.util
+import java.util.Date
+import java.util.concurrent.TimeUnit
+
+import akka.actor.{Actor, Cancellable, Stash}
+import io.gearpump.google.common.primitives.Longs
+import org.apache.gearpump.TimeStamp
+import org.apache.gearpump.cluster.ClientToMaster.GetStallingTasks
+import org.apache.gearpump.streaming.AppMasterToMaster.StallingTasks
+import org.apache.gearpump.streaming._
+import org.apache.gearpump.streaming.appmaster.ClockService.HealthChecker.ClockValue
+import org.apache.gearpump.streaming.appmaster.ClockService._
+import org.apache.gearpump.streaming.storage.AppDataStore
+import org.apache.gearpump.streaming.task._
+import org.apache.gearpump.util.LogUtil
+import org.slf4j.Logger
+
+import scala.concurrent.Future
+import scala.concurrent.duration.FiniteDuration
+import scala.language.implicitConversions
+
+/**
+ * Maintains a global view of message timestamp in the application
+ */
+class ClockService(private var dag: DAG, store: AppDataStore) extends Actor with Stash {
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+
+ import context.dispatcher
+
+ private val healthChecker = new HealthChecker(stallingThresholdSeconds = 60)
+ private var healthCheckScheduler: Cancellable = null
+ private var snapshotScheduler: Cancellable = null
+
+ override def receive: Receive = null
+
+ override def preStart(): Unit = {
+ LOG.info("Initializing Clock service, get snapshotted StartClock ....")
+ store.get(START_CLOCK).asInstanceOf[Future[TimeStamp]].map { clock =>
+ val startClock = Option(clock).getOrElse(0L)
+
+ minCheckpointClock = Some(startClock)
+
+ // Recover the application by restarting from last persisted startClock.
+ // Only messge after startClock will be replayed.
+ self ! StoredStartClock(startClock)
+ LOG.info(s"Start Clock Retrieved, starting ClockService, startClock: $startClock")
+ }
+
+ context.become(waitForStartClock)
+ }
+
+ override def postStop(): Unit = {
+ Option(healthCheckScheduler).map(_.cancel)
+ Option(snapshotScheduler).map(_.cancel)
+ }
+
+ // Keep track of clock value of all processors.
+ private var clocks = Map.empty[ProcessorId, ProcessorClock]
+
+ // Each process can have multiple upstream processors. This keep track of the upstream clocks.
+ private var upstreamClocks = Map.empty[ProcessorId, Array[ProcessorClock]]
+
+ // We use Array instead of List for Performance consideration
+ private var processorClocks = Array.empty[ProcessorClock]
+
+ private var checkpointClocks: Map[TaskId, Vector[TimeStamp]] = null
+
+ private var minCheckpointClock: Option[TimeStamp] = None
+
+ private def checkpointEnabled(processor: ProcessorDescription): Boolean = {
+ val taskConf = processor.taskConf
+ taskConf != null && taskConf.getBoolean("state.checkpoint.enable") == Some(true)
+ }
+
+ private def resetCheckpointClocks(dag: DAG, startClock: TimeStamp): Unit = {
+ this.checkpointClocks = dag.processors.filter(startClock < _._2.life.death)
+ .filter { case (_, processor) =>
+ checkpointEnabled(processor)
+ }.flatMap { case (id, processor) =>
+ (0 until processor.parallelism).map(TaskId(id, _) -> Vector.empty[TimeStamp])
+ }
+ if (this.checkpointClocks.isEmpty) {
+ minCheckpointClock = None
+ }
+ }
+
+ private def initDag(startClock: TimeStamp): Unit = {
+ recoverDag(this.dag, startClock)
+ }
+
+ private def recoverDag(dag: DAG, startClock: TimeStamp): Unit = {
+ this.clocks = dag.processors.filter(startClock < _._2.life.death).
+ map { pair =>
+ val (processorId, processor) = pair
+ val parallelism = processor.parallelism
+ val clock = new ProcessorClock(processorId, processor.life, parallelism)
+ clock.init(startClock)
+ (processorId, clock)
+ }
+
+ this.upstreamClocks = clocks.map { pair =>
+ val (processorId, processor) = pair
+
+ val upstreams = dag.graph.incomingEdgesOf(processorId).map(_._1)
+ val upstreamClocks = upstreams.flatMap(clocks.get(_))
+ (processorId, upstreamClocks.toArray)
+ }
+
+ this.processorClocks = clocks.toArray.map(_._2)
+
+ resetCheckpointClocks(dag, startClock)
+ }
+
+ private def dynamicDAG(dag: DAG, startClock: TimeStamp): Unit = {
+ val newClocks = dag.processors.filter(startClock < _._2.life.death).
+ map { pair =>
+ val (processorId, processor) = pair
+ val parallelism = processor.parallelism
+
+ val clock = if (clocks.contains(processor.id)) {
+ clocks(processorId).copy(life = processor.life)
+ } else {
+ new ProcessorClock(processorId, processor.life, parallelism)
+ }
+ (processorId, clock)
+ }
+
+ this.clocks = newClocks
+
+ this.upstreamClocks = newClocks.map { pair =>
+ val (processorId, processor) = pair
+
+ val upstreams = dag.graph.incomingEdgesOf(processorId).map(_._1)
+ val upstreamClocks = upstreams.flatMap(newClocks.get(_))
+ (processorId, upstreamClocks.toArray)
+ }
+
+ // Inits the clock of all processors.
+ newClocks.map { pair =>
+ val (processorId, processorClock) = pair
+ val upstreamClock = getUpStreamMinClock(processorId)
+ val birth = processorClock.life.birth
+
+ if (dag.graph.inDegreeOf(processorId) == 0) {
+ processorClock.init(Longs.max(birth, startClock))
+ } else {
+ processorClock.init(upstreamClock)
+ }
+ }
+
+ this.processorClocks = clocks.toArray.map(_._2)
+
+ resetCheckpointClocks(dag, startClock)
+ }
+
+ def waitForStartClock: Receive = {
+ case StoredStartClock(startClock) =>
+ initDag(startClock)
+
+ import context.dispatcher
+
+ // Period report current clock
+ healthCheckScheduler = context.system.scheduler.schedule(
+ new FiniteDuration(5, TimeUnit.SECONDS),
+ new FiniteDuration(60, TimeUnit.SECONDS), self, HealthCheck)
+
+ // Period snpashot latest min startclock to external storage
+ snapshotScheduler = context.system.scheduler.schedule(new FiniteDuration(5, TimeUnit.SECONDS),
+ new FiniteDuration(5, TimeUnit.SECONDS), self, SnapshotStartClock)
+
+ unstashAll()
+ context.become(clockService)
+
+ case _ =>
+ stash()
+ }
+
+ private def getUpStreamMinClock(processorId: ProcessorId): TimeStamp = {
+ val clocks = upstreamClocks.get(processorId)
+ if (clocks.isDefined) {
+ if (clocks.get == null || clocks.get.length == 0) {
+ Long.MaxValue
+ } else {
+ ProcessorClocks.minClock(clocks.get)
+ }
+ } else {
+ Long.MaxValue
+ }
+ }
+
+ def clockService: Receive = {
+ case GetUpstreamMinClock(task) =>
+ sender ! UpstreamMinClock(getUpStreamMinClock(task.processorId))
+
+ case update@UpdateClock(task, clock) =>
+ val upstreamMinClock = getUpStreamMinClock(task.processorId)
+
+ val processorClock = clocks.get(task.processorId)
+ if (processorClock.isDefined) {
+ processorClock.get.updateMinClock(task.index, clock)
+ } else {
+ LOG.error(s"Cannot updateClock for task $task")
+ }
+ sender ! UpstreamMinClock(upstreamMinClock)
+
+ case GetLatestMinClock =>
+ sender ! LatestMinClock(minClock)
+
+ case GetStartClock =>
+ sender ! StartClock(getStartClock)
+
+ case deathCheck: CheckProcessorDeath =>
+ val processorId = deathCheck.processorId
+ val processorClock = clocks.get(processorId)
+ if (processorClock.isDefined) {
+ val life = processorClock.get.life
+ if (processorClock.get.min >= life.death) {
+
+ LOG.info(s"Removing $processorId from clock service...")
+ removeProcessor(processorId)
+ } else {
+ LOG.info(s"Unsuccessfully in removing $processorId from clock service...," +
+ s" min: ${processorClock.get.min}, life: $life")
+ }
+ }
+ case HealthCheck =>
+ selfCheck()
+
+ case SnapshotStartClock =>
+ snapshotStartClock()
+
+ case ReportCheckpointClock(task, time) =>
+ updateCheckpointClocks(task, time)
+
+ case GetCheckpointClock =>
+ sender ! CheckpointClock(minCheckpointClock)
+
+ case getStalling: GetStallingTasks =>
+ sender ! StallingTasks(healthChecker.getReport.stallingTasks)
+
+ case ChangeToNewDAG(dag) =>
+ if (dag.version > this.dag.version) {
+ // Transits to a new dag version
+ this.dag = dag
+ dynamicDAG(dag, getStartClock)
+ } else {
+ // Restarts current dag.
+ recoverDag(dag, getStartClock)
+ }
+ LOG.info(s"Change to new DAG(dag = ${dag.version}), send back ChangeToNewDAGSuccess")
+ sender ! ChangeToNewDAGSuccess(clocks.map { pair =>
+ val (id, clock) = pair
+ (id, clock.min)
+ })
+ }
+
+ private def removeProcessor(processorId: ProcessorId): Unit = {
+ clocks = clocks - processorId
+ processorClocks = processorClocks.filter(_.processorId != processorId)
+
+ upstreamClocks = upstreamClocks.map { pair =>
+ val (id, upstreams) = pair
+ val updatedUpstream = upstreams.filter(_.processorId != processorId)
+ (id, updatedUpstream)
+ }
+
+ upstreamClocks = upstreamClocks - processorId
+
+ // Removes dead processor from checkpoints.
+ checkpointClocks = checkpointClocks.filter { kv =>
+ val (taskId, processor) = kv
+ taskId.processorId != processorId
+ }
+ }
+
+ private def minClock: TimeStamp = {
+ ProcessorClocks.minClock(processorClocks)
+ }
+
+ def selfCheck(): Unit = {
+ val minTimestamp = minClock
+
+ if (Long.MaxValue == minTimestamp) {
+ processorClocks.foreach { clock =>
+ LOG.info(s"Processor ${clock.processorId} Clock: min: ${clock.min}, " +
+ s"taskClocks: " + clock.taskClocks.mkString(","))
+ }
+ }
+
+ healthChecker.check(minTimestamp, clocks, dag, System.currentTimeMillis())
+ }
+
+ private def getStartClock: TimeStamp = {
+ minCheckpointClock.getOrElse(minClock)
+ }
+
+ private def snapshotStartClock(): Unit = {
+ store.put(START_CLOCK, getStartClock)
+ }
+
+ private def updateCheckpointClocks(task: TaskId, time: TimeStamp): Unit = {
+ val clocks = checkpointClocks(task) :+ time
+ checkpointClocks += task -> clocks
+
+ if (checkpointClocks.forall(_._2.contains(time))) {
+ minCheckpointClock = Some(time)
+ LOG.info(s"minCheckpointTime $minCheckpointClock")
+
+ checkpointClocks = checkpointClocks.mapValues(_.dropWhile(_ <= time))
+ }
+ }
+}
+
+object ClockService {
+ val START_CLOCK = "startClock"
+
+ case object HealthCheck
+
+ class ProcessorClock(val processorId: ProcessorId, val life: LifeTime, val parallism: Int,
+ private var _min: TimeStamp = 0L, private var _taskClocks: Array[TimeStamp] = null) {
+
+ def copy(life: LifeTime): ProcessorClock = {
+ new ProcessorClock(processorId, life, parallism, _min, _taskClocks)
+ }
+
+ def min: TimeStamp = _min
+ def taskClocks: Array[TimeStamp] = _taskClocks
+
+ def init(startClock: TimeStamp): Unit = {
+ if (taskClocks == null) {
+ this._min = startClock
+ this._taskClocks = new Array(parallism)
+ util.Arrays.fill(taskClocks, startClock)
+ }
+ }
+
+ def updateMinClock(taskIndex: Int, clock: TimeStamp): Unit = {
+ taskClocks(taskIndex) = clock
+ _min = Longs.min(taskClocks: _*)
+ }
+ }
+
+ case object SnapshotStartClock
+
+ case class Report(stallingTasks: List[TaskId])
+
+ /**
+ * Check whether the clock is advancing normally
+ */
+ class HealthChecker(stallingThresholdSeconds: Int) {
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+
+ private var minClock: ClockValue = null
+ private val stallingThresholdMilliseconds = stallingThresholdSeconds * 1000
+ // 60 seconds
+ private var stallingTasks = Array.empty[TaskId]
+
+ /** Check for stalling tasks */
+ def check(
+ currentMinClock: TimeStamp, processorClocks: Map[ProcessorId, ProcessorClock],
+ dag: DAG, now: TimeStamp): Unit = {
+ var isClockStalling = false
+ if (null == minClock || currentMinClock > minClock.appClock) {
+ minClock = ClockValue(systemClock = now, appClock = currentMinClock)
+ } else {
+ // Clock not advancing
+ if (now > minClock.systemClock + stallingThresholdMilliseconds) {
+ LOG.warn(s"Clock has not advanced for ${(now - minClock.systemClock) / 1000} seconds " +
+ s"since ${minClock.prettyPrint}...")
+ isClockStalling = true
+ }
+ }
+
+ if (isClockStalling) {
+ val processorId = dag.graph.topologicalOrderWithCirclesIterator.toList.find { processorId =>
+ val clock = processorClocks.get(processorId)
+ if (clock.isDefined) {
+ clock.get.min == minClock.appClock
+ } else {
+ false
+ }
+ }
+
+ processorId.foreach { processorId =>
+ val processorClock = processorClocks(processorId)
+ val taskClocks = processorClock.taskClocks
+ stallingTasks = taskClocks.zipWithIndex.filter(_._1 == minClock.appClock).
+ map(pair => TaskId(processorId, pair._2))
+ }
+ LOG.info(s"Stalling Tasks: ${stallingTasks.mkString(",")}")
+ } else {
+ stallingTasks = Array.empty[TaskId]
+ }
+ }
+
+ def getReport: Report = {
+ Report(stallingTasks.toList)
+ }
+ }
+
+ object HealthChecker {
+ case class ClockValue(systemClock: TimeStamp, appClock: TimeStamp) {
+ def prettyPrint: String = {
+ "(system clock: " + new Date(systemClock).toString + ", app clock: " + appClock + ")"
+ }
+ }
+ }
+
+ object ProcessorClocks {
+
+ // Get the Min clock of all processors
+ def minClock(clock: Array[ProcessorClock]): TimeStamp = {
+ var i = 0
+ var min = if (clock.length == 0) 0L else clock(0).min
+ while (i < clock.length) {
+ min = Math.min(min, clock(i).min)
+ i += 1
+ }
+ min
+ }
+ }
+
+ case class ChangeToNewDAG(dag: DAG)
+ case class ChangeToNewDAGSuccess(clocks: Map[ProcessorId, TimeStamp])
+
+ case class StoredStartClock(clock: TimeStamp)
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/DagManager.scala
----------------------------------------------------------------------
diff --git a/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/DagManager.scala b/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/DagManager.scala
new file mode 100644
index 0000000..3341d4f
--- /dev/null
+++ b/streaming/src/main/scala/org/apache/gearpump/streaming/appmaster/DagManager.scala
@@ -0,0 +1,181 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.appmaster
+
+import akka.actor.{Actor, ActorRef, Stash}
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.partitioner.PartitionerDescription
+import org.apache.gearpump.streaming._
+import org.apache.gearpump.streaming.appmaster.DagManager._
+import org.apache.gearpump.streaming.storage.AppDataStore
+import org.apache.gearpump.streaming.task.Subscriber
+import org.apache.gearpump.util.{Graph, LogUtil}
+import org.slf4j.Logger
+
+import scala.concurrent.Future
+
+/**
+ * Handles dag modification and other stuff related with DAG
+ *
+ * DagManager maintains multiple version of DAGs. For each version, the DAG is immutable.
+ * For operations like modifying a processor, it will create a new version of DAG.
+ */
+class DagManager(appId: Int, userConfig: UserConfig, store: AppDataStore, dag: Option[DAG])
+ extends Actor with Stash {
+
+ import context.dispatcher
+ private val LOG: Logger = LogUtil.getLogger(getClass, app = appId)
+ private val NOT_INITIALIZED = -1
+
+ private var dags = List.empty[DAG]
+ private var maxProcessorId = -1
+ private implicit val system = context.system
+
+ private var watchers = List.empty[ActorRef]
+
+ override def receive: Receive = null
+
+ override def preStart(): Unit = {
+ LOG.info("Initializing Dag Service, get stored Dag ....")
+ store.get(StreamApplication.DAG).asInstanceOf[Future[DAG]].map { storedDag =>
+ if (storedDag != null) {
+ dags :+= storedDag
+ } else {
+ dags :+= dag.getOrElse(DAG(userConfig.getValue[Graph[ProcessorDescription,
+ PartitionerDescription]](StreamApplication.DAG).get))
+ }
+ maxProcessorId = {
+ val keys = dags.head.processors.keys
+ if (keys.size == 0) {
+ 0
+ } else {
+ keys.max
+ }
+ }
+ self ! DagInitiated
+ }
+ context.become(waitForDagInitiate)
+ }
+
+ def waitForDagInitiate: Receive = {
+ case DagInitiated =>
+ unstashAll()
+ context.become(dagService)
+ case _ =>
+ stash()
+ }
+
+ private def nextProcessorId: ProcessorId = {
+ maxProcessorId += 1
+ maxProcessorId
+ }
+
+ private def taskLaunchData(dag: DAG, processorId: Int, context: AnyRef): TaskLaunchData = {
+ val processorDescription = dag.processors(processorId)
+ val subscribers = Subscriber.of(processorId, dag)
+ TaskLaunchData(processorDescription, subscribers, context)
+ }
+
+ def dagService: Receive = {
+ case GetLatestDAG =>
+ // Get the latest version of DAG.
+ sender ! LatestDAG(dags.last)
+ case GetTaskLaunchData(version, processorId, context) =>
+ // Task information like Processor class, downstream subscriber processors and etc.
+ dags.find(_.version == version).foreach { dag =>
+ LOG.info(s"Get task launcher data for processor: $processorId, dagVersion: $version")
+ sender ! taskLaunchData(dag, processorId, context)
+ }
+ case ReplaceProcessor(oldProcessorId, inputNewProcessor) =>
+ // Replace a processor with new implementation. The upstream processors and downstream
+ // processors are NOT changed.
+ var newProcessor = inputNewProcessor.copy(id = nextProcessorId)
+ if (inputNewProcessor.jar == null) {
+ val oldJar = dags.last.processors.get(oldProcessorId).get
+ newProcessor = newProcessor.copy(jar = oldJar.jar)
+ }
+ if (dags.length > 1) {
+ sender ! DAGOperationFailed(
+ "We are in the process of handling previous dynamic dag change")
+ } else {
+ val oldDAG = dags.last
+ val newVersion = oldDAG.version + 1
+ val newDAG = replaceDAG(oldDAG, oldProcessorId, newProcessor, newVersion)
+ dags :+= newDAG
+
+ LOG.info(s"ReplaceProcessor old: $oldProcessorId, new: $newProcessor")
+ LOG.info(s"new DAG: $newDAG")
+ watchers.foreach(_ ! LatestDAG(newDAG))
+ sender ! DAGOperationSuccess
+ }
+
+ case WatchChange(watcher) =>
+ // Checks whether there are modifications for this DAG.
+ if (!this.watchers.contains(watcher)) {
+ this.watchers :+= watcher
+ }
+
+ case NewDAGDeployed(dagVersion) =>
+ // Means dynamic Dag transition completed, and the new DAG version has been successfully
+ // deployed. The obsolete dag versions will be removed.
+ if (dagVersion != NOT_INITIALIZED) {
+ dags = dags.filter(_.version == dagVersion)
+ store.put(StreamApplication.DAG, dags.last)
+ }
+ }
+
+ private def replaceDAG(
+ dag: DAG, oldProcessorId: ProcessorId, newProcessor: ProcessorDescription, newVersion: Int)
+ : DAG = {
+ val oldProcessorLife = LifeTime(dag.processors(oldProcessorId).life.birth,
+ newProcessor.life.birth)
+
+ val newProcessorMap = dag.processors ++
+ Map(oldProcessorId -> dag.processors(oldProcessorId).copy(life = oldProcessorLife),
+ newProcessor.id -> newProcessor)
+
+ val newGraph = dag.graph.subGraph(oldProcessorId).
+ replaceVertex(oldProcessorId, newProcessor.id).addGraph(dag.graph)
+ new DAG(newVersion, newProcessorMap, newGraph)
+ }
+}
+
+object DagManager {
+ case object DagInitiated
+
+ case class WatchChange(watcher: ActorRef)
+
+ case object GetLatestDAG
+ case class LatestDAG(dag: DAG)
+
+ case class GetTaskLaunchData(dagVersion: Int, processorId: Int, context: AnyRef = null)
+ case class TaskLaunchData(processorDescription : ProcessorDescription,
+ subscribers: List[Subscriber], context: AnyRef = null)
+
+ sealed trait DAGOperation
+
+ case class ReplaceProcessor(oldProcessorId: ProcessorId,
+ newProcessorDescription: ProcessorDescription) extends DAGOperation
+
+ sealed trait DAGOperationResult
+ case object DAGOperationSuccess extends DAGOperationResult
+ case class DAGOperationFailed(reason: String) extends DAGOperationResult
+
+ case class NewDAGDeployed(dagVersion: Int)
+}
\ No newline at end of file
[42/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/util/ActorSystemBooter.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/util/ActorSystemBooter.scala b/core/src/main/scala/org/apache/gearpump/util/ActorSystemBooter.scala
new file mode 100644
index 0000000..674445a
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/util/ActorSystemBooter.scala
@@ -0,0 +1,152 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.util
+
+import java.util.concurrent.{TimeUnit, TimeoutException}
+import scala.concurrent.Await
+import scala.concurrent.duration.Duration
+import scala.util.{Failure, Success, Try}
+
+import akka.actor._
+import com.typesafe.config.Config
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.ClusterConfig
+import org.apache.gearpump.util.LogUtil.ProcessType
+
+/**
+ * ActorSystemBooter start a new JVM process to boot an actor system.
+ * All executors are started by ActorSystemBooter
+ *
+ * It send the system address to "report back actor"
+ */
+class ActorSystemBooter(config: Config) {
+ import org.apache.gearpump.util.ActorSystemBooter._
+
+ def boot(name: String, reportBackActor: String): ActorSystem = {
+ val system = ActorSystem(name, config)
+ // Daemon path: http://{system}@{ip}:{port}/daemon
+ system.actorOf(Props(classOf[Daemon], name, reportBackActor), "daemon")
+ system
+ }
+}
+
+object ActorSystemBooter {
+
+ def apply(config: Config): ActorSystemBooter = new ActorSystemBooter(config)
+
+ def main(args: Array[String]) {
+ val name = args(0)
+ val reportBack = args(1)
+ val config = ClusterConfig.default()
+
+ LogUtil.loadConfiguration(config, ProcessType.APPLICATION)
+
+ val debugPort = Option(System.getProperty(Constants.GEARPUMP_REMOTE_DEBUG_PORT))
+ debugPort.foreach { port =>
+ val LOG: Logger = LogUtil.getLogger(ActorSystemBooter.getClass)
+ LOG.info("==========================================")
+ LOG.info("Remote debug port: " + port)
+ LOG.info("==========================================")
+ }
+
+ val system = apply(config).boot(name, reportBack)
+
+ Runtime.getRuntime().addShutdownHook(new Thread() {
+ override def run(): Unit = {
+ val LOG: Logger = LogUtil.getLogger(ActorSystemBooter.getClass)
+ LOG.info("Maybe we have received a SIGINT signal from parent process, " +
+ "start to cleanup resources....")
+ system.terminate()
+ }
+ })
+
+ Await.result(system.whenTerminated, Duration.Inf)
+ }
+
+ case class BindLifeCycle(actor: ActorRef)
+ case class CreateActor(prop: Props, name: String)
+ case class ActorCreated(actor: ActorRef, name: String)
+ case class CreateActorFailed(name: String, reason: Throwable)
+
+ case class RegisterActorSystem(systemPath: String)
+
+ /**
+ * This actor system will watch for parent,
+ * If parent dies, this will also die
+ */
+ case class ActorSystemRegistered(bindLifeWith: ActorRef)
+ case class RegisterActorSystemFailed(reason: Throwable)
+
+ object RegisterActorSystemTimeOut
+
+ class Daemon(val name: String, reportBack: String) extends Actor {
+ val LOG: Logger = LogUtil.getLogger(getClass, context = name)
+
+ val username = Option(System.getProperty(Constants.GEARPUMP_USERNAME)).getOrElse("not_defined")
+ LOG.info(s"RegisterActorSystem to ${reportBack}, current user: $username")
+
+ val reportBackActor = context.actorSelection(reportBack)
+ reportBackActor ! RegisterActorSystem(ActorUtil.getSystemAddress(context.system).toString)
+
+ implicit val executionContext = context.dispatcher
+ val timeout = context.system.scheduler.scheduleOnce(Duration(25, TimeUnit.SECONDS),
+ self, RegisterActorSystemFailed(new TimeoutException))
+
+ context.become(waitForRegisterResult)
+
+ def receive: Receive = null
+
+ def waitForRegisterResult: Receive = {
+ case ActorSystemRegistered(parent) =>
+ timeout.cancel()
+ context.watch(parent)
+ context.become(waitCommand)
+ case RegisterActorSystemFailed(ex) =>
+ LOG.error("RegisterActorSystemFailed", ex)
+ timeout.cancel()
+ context.stop(self)
+ }
+
+ def waitCommand: Receive = {
+ case BindLifeCycle(actor) =>
+ LOG.info(s"ActorSystem $name Binding life cycle with actor: $actor")
+ context.watch(actor)
+ case create@CreateActor(props: Props, name: String) =>
+ LOG.info(s"creating actor $name")
+ val actor = Try(context.actorOf(props, name))
+ actor match {
+ case Success(actor) =>
+ sender ! ActorCreated(actor, name)
+ case Failure(e) =>
+ sender ! CreateActorFailed(props.clazz.getName, e)
+ }
+ case PoisonPill =>
+ context.stop(self)
+ case Terminated(actor) =>
+ LOG.info(s"System $name Watched actor is terminated $actor")
+ context.stop(self)
+ }
+
+ override def postStop(): Unit = {
+ LOG.info(s"ActorSystem $name is shutting down...")
+ context.system.terminate()
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/util/ActorUtil.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/util/ActorUtil.scala b/core/src/main/scala/org/apache/gearpump/util/ActorUtil.scala
new file mode 100644
index 0000000..b10163f
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/util/ActorUtil.scala
@@ -0,0 +1,131 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.util
+
+import org.apache.gearpump.cluster.worker.WorkerId
+
+import scala.concurrent.{ExecutionContext, Future}
+
+import akka.actor.Actor.Receive
+import akka.actor._
+import akka.pattern.ask
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.AppMasterToMaster.GetAllWorkers
+import org.apache.gearpump.cluster.ClientToMaster.{ResolveAppId, ResolveWorkerId}
+import org.apache.gearpump.cluster.MasterToAppMaster.WorkerList
+import org.apache.gearpump.cluster.MasterToClient.{ResolveAppIdResult, ResolveWorkerIdResult}
+import org.apache.gearpump.cluster.appmaster.ExecutorSystemScheduler.{ExecutorSystemJvmConfig, StartExecutorSystems}
+import org.apache.gearpump.cluster.scheduler.{Relaxation, Resource, ResourceRequest}
+import org.apache.gearpump.transport.HostPort
+
+object ActorUtil {
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+
+ def getSystemAddress(system: ActorSystem): Address = {
+ system.asInstanceOf[ExtendedActorSystem].provider.getDefaultAddress
+ }
+
+ def getFullPath(system: ActorSystem, path: ActorPath): String = {
+ path.toStringWithAddress(getSystemAddress(system))
+ }
+
+ def getHostname(actor: ActorRef): String = {
+ val path = actor.path
+ path.address.host.getOrElse("localhost")
+ }
+
+ def defaultMsgHandler(actor: ActorRef): Receive = {
+ case msg: Any =>
+ LOG.error(s"Cannot find a matching message, ${msg.getClass.toString}, forwarded from $actor")
+ }
+
+ def printActorSystemTree(system: ActorSystem): Unit = {
+ val extendedSystem = system.asInstanceOf[ExtendedActorSystem]
+ val clazz = system.getClass
+ val m = clazz.getDeclaredMethod("printTree")
+ m.setAccessible(true)
+ LOG.info(m.invoke(system).asInstanceOf[String])
+ }
+
+ /** Checks whether a actor is child actor by simply examining name */
+ // TODO: fix this, we should also check the path to root besides name
+ def isChildActorPath(parent: ActorRef, child: ActorRef): Boolean = {
+ if (null != child) {
+ parent.path.name == child.path.parent.name
+ } else {
+ false
+ }
+ }
+
+ def actorNameForExecutor(appId: Int, executorId: Int): String = "app" + appId + "-executor" +
+ executorId
+
+ // TODO: Currently we explicitly require the master contacts to be started with this path pattern
+ // akka.tcp://$MASTER@${master.host}:${master.port}/user/$MASTER
+ def getMasterActorPath(master: HostPort): ActorPath = {
+ import org.apache.gearpump.util.Constants.MASTER
+ ActorPath.fromString(s"akka.tcp://$MASTER@${master.host}:${master.port}/user/$MASTER")
+ }
+
+ def launchExecutorOnEachWorker(master: ActorRef, executorJvmConfig: ExecutorSystemJvmConfig,
+ sender: ActorRef)(implicit executor: scala.concurrent.ExecutionContext): Unit = {
+ implicit val timeout = Constants.FUTURE_TIMEOUT
+
+ (master ? GetAllWorkers).asInstanceOf[Future[WorkerList]].map { list =>
+ val resources = list.workers.map {
+ workerId => ResourceRequest(Resource(1), workerId, relaxation = Relaxation.SPECIFICWORKER)
+ }.toArray
+
+ master.tell(StartExecutorSystems(resources, executorJvmConfig), sender)
+ }
+ }
+
+ def askAppMaster[T](master: ActorRef, appId: Int, msg: Any)(implicit ex: ExecutionContext)
+ : Future[T] = {
+ implicit val timeout = Constants.FUTURE_TIMEOUT
+ val appmaster = askActor[ResolveAppIdResult](master, ResolveAppId(appId)).flatMap { result =>
+ if (result.appMaster.isSuccess) {
+ Future.successful(result.appMaster.get)
+ } else {
+ Future.failed(result.appMaster.failed.get)
+ }
+ }
+ appmaster.flatMap(askActor[T](_, msg))
+ }
+
+ def askWorker[T](master: ActorRef, workerId: WorkerId, msg: Any)(implicit ex: ExecutionContext)
+ : Future[T] = {
+ implicit val timeout = Constants.FUTURE_TIMEOUT
+ val worker = askActor[ResolveWorkerIdResult](master, ResolveWorkerId(workerId))
+ .flatMap { result =>
+ if (result.worker.isSuccess) {
+ Future.successful(result.worker.get)
+ } else {
+ Future.failed(result.worker.failed.get)
+ }
+ }
+ worker.flatMap(askActor[T](_, msg))
+ }
+
+ def askActor[T](actor: ActorRef, msg: Any)(implicit ex: ExecutionContext): Future[T] = {
+ implicit val timeout = Constants.FUTURE_TIMEOUT
+ (actor ? msg).asInstanceOf[Future[T]]
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/util/AkkaApp.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/util/AkkaApp.scala b/core/src/main/scala/org/apache/gearpump/util/AkkaApp.scala
new file mode 100644
index 0000000..6060368
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/util/AkkaApp.scala
@@ -0,0 +1,45 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.util
+
+import scala.util.Try
+
+import org.apache.gearpump.cluster.ClusterConfig
+
+/**
+ * A Main class helper to load Akka configuration automatically.
+ */
+trait AkkaApp {
+
+ type Config = com.typesafe.config.Config
+
+ def main(akkaConf: Config, args: Array[String]): Unit
+
+ def help(): Unit
+
+ protected def akkaConfig: Config = {
+ ClusterConfig.default()
+ }
+
+ def main(args: Array[String]): Unit = {
+ Try {
+ main(akkaConfig, args)
+ }.failed.foreach { ex => help(); throw ex }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/util/Constants.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/util/Constants.scala b/core/src/main/scala/org/apache/gearpump/util/Constants.scala
new file mode 100644
index 0000000..dba5a1f
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/util/Constants.scala
@@ -0,0 +1,177 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.util
+
+import java.util.concurrent.TimeUnit
+
+import org.apache.gearpump.partitioner._
+
+object Constants {
+ val MASTER_WATCHER = "masterwatcher"
+ val SINGLETON_MANAGER = "singleton"
+
+ val MASTER_CONFIG = "gearpump-master"
+ val WORKER_CONFIG = "gearpump-worker"
+ val UI_CONFIG = "gearpump-ui"
+ val LINUX_CONFIG = "gearpump-linux" // linux or Mac
+
+ val MASTER = "master"
+ val WORKER = "worker"
+
+ val GEARPUMP_WORKER_SLOTS = "gearpump.worker.slots"
+ val GEARPUMP_EXECUTOR_PROCESS_LAUNCHER = "gearpump.worker.executor-process-launcher"
+ val GEARPUMP_SCHEDULING_SCHEDULER = "gearpump.scheduling.scheduler-class"
+ val GEARPUMP_SCHEDULING_REQUEST = "gearpump.scheduling.requests"
+ val GEARPUMP_TRANSPORT_SERIALIZER = "gearpump.transport.serializer"
+ val GEARPUMP_SERIALIZER_POOL = "gearpump.serialization-framework"
+ val GEARPUMP_SERIALIZERS = "gearpump.serializers"
+ val GEARPUMP_TASK_DISPATCHER = "gearpump.task-dispatcher"
+ val GEARPUMP_CLUSTER_MASTERS = "gearpump.cluster.masters"
+ val GEARPUMP_MASTERCLIENT_TIMEOUT = "gearpump.masterclient.timeout"
+ val GEARPUMP_CLUSTER_EXECUTOR_WORKER_SHARE_SAME_PROCESS =
+ "gearpump.worker.executor-share-same-jvm-as-worker"
+
+ val GEARPUMP_HOME = "gearpump.home"
+ val GEARPUMP_FULL_SCALA_VERSION = "gearpump.binary-version-with-scala-version"
+ val GEARPUMP_HOSTNAME = "gearpump.hostname"
+ val GEARPUMP_APPMASTER_ARGS = "gearpump.appmaster.vmargs"
+ val GEARPUMP_APPMASTER_EXTRA_CLASSPATH = "gearpump.appmaster.extraClasspath"
+ val GEARPUMP_EXECUTOR_ARGS = "gearpump.executor.vmargs"
+ val GEARPUMP_EXECUTOR_EXTRA_CLASSPATH = "gearpump.executor.extraClasspath"
+ val GEARPUMP_LOG_DAEMON_DIR = "gearpump.log.daemon.dir"
+ val GEARPUMP_LOG_APPLICATION_DIR = "gearpump.log.application.dir"
+ val HADOOP_CONF = "hadoopConf"
+
+ // Id used to identity Master JVM process in low level resource manager like YARN.
+ // In YARN, it means the container Id.
+ val GEARPUMP_MASTER_RESOURCE_MANAGER_CONTAINER_ID =
+ "gearpump.master-resource-manager-container-id"
+
+ // Id used to identity Worker JVM process in low level resource manager like YARN.
+ // In YARN, it means the container Id.
+ val GEARPUMP_WORKER_RESOURCE_MANAGER_CONTAINER_ID =
+ "gearpump.worker-resource-manager-container-id"
+
+ // true or false
+ val GEARPUMP_REMOTE_DEBUG_EXECUTOR_JVM = "gearpump.remote-debug-executor-jvm"
+ val GEARPUMP_REMOTE_DEBUG_PORT = "gearpump.remote-debug-port"
+
+ // Whether to turn on GC log, true or false
+ val GEARPUMP_VERBOSE_GC = "gearpump.verbose-gc"
+
+ // The time out for Future, like ask.
+ // !Important! This global timeout setting will also impact the UI
+ // responsive time if set to too big. Please make sure you have
+ // enough justification to change this global setting, otherwise
+ // please use your local timeout setting instead.
+ val FUTURE_TIMEOUT = akka.util.Timeout(15, TimeUnit.SECONDS)
+
+ val GEARPUMP_START_EXECUTOR_SYSTEM_TIMEOUT_MS = "gearpump.start-executor-system-timeout-ms"
+
+ val APPMASTER_DEFAULT_EXECUTOR_ID = -1
+
+ val NETTY_BUFFER_SIZE = "gearpump.netty.buffer-size"
+ val NETTY_MAX_RETRIES = "gearpump.netty.max-retries"
+ val NETTY_BASE_SLEEP_MS = "gearpump.netty.base-sleep-ms"
+ val NETTY_MAX_SLEEP_MS = "gearpump.netty.max-sleep-ms"
+ val NETTY_MESSAGE_BATCH_SIZE = "gearpump.netty.message-batch-size"
+ val NETTY_FLUSH_CHECK_INTERVAL = "gearpump.netty.flush-check-interval"
+ val NETTY_TCP_HOSTNAME = "akka.remote.netty.tcp.hostname"
+ val NETTY_DISPATCHER = "gearpump.netty.dispatcher"
+
+ val GEARPUMP_USERNAME = "gearpump.username"
+ val GEARPUMP_APPLICATION_ID = "gearpump.applicationId"
+ val GEARPUMP_MASTER_STARTTIME = "gearpump.master.starttime"
+ val GEARPUMP_EXECUTOR_ID = "gearpump.executorId"
+ // Application jar property
+ val GEARPUMP_APP_JAR = "gearpump.app.jar"
+ val GEARPUMP_APP_NAME_PREFIX = "gearpump.app.name.prefix"
+
+ // Where the jar is stored at. It can be a HDFS, or a local disk.
+ val GEARPUMP_APP_JAR_STORE_ROOT_PATH = "gearpump.jarstore.rootpath"
+
+ // Uses java property -Dgearpump.config.file=xxx.conf to set customized configuration
+ // Otherwise application.conf in classpath will be loaded
+ val GEARPUMP_CUSTOM_CONFIG_FILE = "gearpump.config.file"
+
+ // Metrics related
+ val GEARPUMP_METRIC_ENABLED = "gearpump.metrics.enabled"
+ val GEARPUMP_METRIC_SAMPLE_RATE = "gearpump.metrics.sample-rate"
+ val GEARPUMP_METRIC_REPORT_INTERVAL = "gearpump.metrics.report-interval-ms"
+ val GEARPUMP_METRIC_GRAPHITE_HOST = "gearpump.metrics.graphite.host"
+ val GEARPUMP_METRIC_GRAPHITE_PORT = "gearpump.metrics.graphite.port"
+ val GEARPUMP_METRIC_REPORTER = "gearpump.metrics.reporter"
+
+ // Retains at max @RETAIN_HISTORY_HOURS history data
+ val GEARPUMP_METRIC_RETAIN_HISTORY_DATA_HOURS = "gearpump.metrics.retainHistoryData.hours"
+
+ // Time interval between two history data points.
+ val GEARPUMP_RETAIN_HISTORY_DATA_INTERVAL_MS = "gearpump.metrics.retainHistoryData.intervalMs"
+
+ // Retains at max @RETAIN_LATEST_SECONDS recent data points
+ val GEARPUMP_RETAIN_RECENT_DATA_SECONDS = "gearpump.metrics.retainRecentData.seconds"
+
+ // time interval between two recent data points.
+ val GEARPUMP_RETAIN_RECENT_DATA_INTERVAL_MS = "gearpump.metrics.retainRecentData.intervalMs"
+
+ // AppMaster will max wait this time until it declare the resource cannot be allocated,
+ // and shutdown itself
+ val GEARPUMP_RESOURCE_ALLOCATION_TIMEOUT = "gearpump.resource-allocation-timeout-seconds"
+
+ // Service related
+ val GEARPUMP_SERVICE_HTTP = "gearpump.services.http"
+ val GEARPUMP_SERVICE_HOST = "gearpump.services.host"
+ val GEARPUMP_SERVICE_SUPERVISOR_PATH = "gearpump.services.supervisor-actor-path"
+ val GEARPUMP_SERVICE_RENDER_CONFIG_CONCISE = "gearpump.services.config-render-option-concise"
+
+ // The partitioners provided by Gearpump
+ val BUILTIN_PARTITIONERS = Array(
+ classOf[BroadcastPartitioner],
+ classOf[CoLocationPartitioner],
+ classOf[HashPartitioner],
+ classOf[ShuffleGroupingPartitioner],
+ classOf[ShufflePartitioner])
+
+ // Security related
+ val GEARPUMP_KEYTAB_FILE = "gearpump.keytab.file"
+ val GEARPUMP_KERBEROS_PRINCIPAL = "gearpump.kerberos.principal"
+
+ val GEARPUMP_METRICS_MAX_LIMIT = "gearpump.metrics.akka.max-limit-on-query"
+ val GEARPUMP_METRICS_AGGREGATORS = "gearpump.metrics.akka.metrics-aggregator-class"
+
+ val GEARPUMP_UI_SECURITY = "gearpump.ui-security"
+ val GEARPUMP_UI_SECURITY_AUTHENTICATION_ENABLED = "gearpump.ui-security.authentication-enabled"
+ val GEARPUMP_UI_AUTHENTICATOR_CLASS = "gearpump.ui-security.authenticator"
+ // OAuth Authentication Factory for UI server.
+ val GEARPUMP_UI_OAUTH2_AUTHENTICATOR_ENABLED = "gearpump.ui-security.oauth2-authenticator-enabled"
+ val GEARPUMP_UI_OAUTH2_AUTHENTICATORS = "gearpump.ui-security.oauth2-authenticators"
+ val GEARPUMP_UI_OAUTH2_AUTHENTICATOR_CLASS = "class"
+ val GEARPUMP_UI_OAUTH2_AUTHENTICATOR_CALLBACK = "callback"
+ val GEARPUMP_UI_OAUTH2_AUTHENTICATOR_CLIENT_ID = "clientid"
+ val GEARPUMP_UI_OAUTH2_AUTHENTICATOR_CLIENT_SECRET = "clientsecret"
+ val GEARPUMP_UI_OAUTH2_AUTHENTICATOR_DEFAULT_USER_ROLE = "default-userrole"
+ val GEARPUMP_UI_OAUTH2_AUTHENTICATOR_AUTHORIZATION_CODE = "code"
+ val GEARPUMP_UI_OAUTH2_AUTHENTICATOR_ACCESS_TOKEN = "accesstoken"
+
+ val PREFER_IPV4 = "java.net.preferIPv4Stack"
+
+ val APPLICATION_EXECUTOR_NUMBER = "gearpump.application.executor-num"
+
+ val AKKA_SCHEDULER_TICK_DURATION = "akka.scheduler.tick-duration"
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/util/FileUtils.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/util/FileUtils.scala b/core/src/main/scala/org/apache/gearpump/util/FileUtils.scala
new file mode 100644
index 0000000..d13f514
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/util/FileUtils.scala
@@ -0,0 +1,53 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.util
+
+import java.io.{File, IOException}
+import java.nio.charset.Charset
+
+import io.gearpump.google.common.io.Files
+
+object FileUtils {
+ private val UTF8 = Charset.forName("UTF-8")
+
+ def write(file: File, str: String): Unit = {
+ Files.write(str, file, UTF8)
+ }
+
+ def read(file: File): String = {
+ Files.asCharSource(file, UTF8).read()
+ }
+
+ def writeByteArrayToFile(file: File, bytes: Array[Byte]): Unit = {
+ Files.write(bytes, file)
+ }
+
+ def readFileToByteArray(file: File): Array[Byte] = {
+ Files.toByteArray(file)
+ }
+
+ /** recursively making all parent directories including itself */
+ def forceMkdir(directory: File): Unit = {
+ if (directory.exists() && directory.isFile) {
+ throw new IOException(s"Failed to create directory ${directory.toString}, it already exist")
+ }
+ Files.createParentDirs(directory)
+ val result = directory.mkdir()
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/util/Graph.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/util/Graph.scala b/core/src/main/scala/org/apache/gearpump/util/Graph.scala
new file mode 100644
index 0000000..6bb58b8
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/util/Graph.scala
@@ -0,0 +1,496 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.util
+import scala.annotation.tailrec
+import scala.collection.mutable
+import scala.language.implicitConversions
+
+/**
+ * Generic mutable Graph libraries.
+ */
+class Graph[N, E](vertexList: List[N], edgeList: List[(N, E, N)]) extends Serializable {
+
+ private val _vertices = mutable.Set.empty[N]
+ private val _edges = mutable.Set.empty[(N, E, N)]
+
+ // This is used to ensure the output of this Graph is always stable
+ // Like method vertices(), or edges()
+ private var _indexs = Map.empty[Any, Int]
+ private var _nextIndex = 0
+ private def nextId: Int = {
+ val result = _nextIndex
+ _nextIndex += 1
+ result
+ }
+
+ private def init(): Unit = {
+ Option(vertexList).getOrElse(List.empty[N]).foreach(addVertex(_))
+ Option(edgeList).getOrElse(List.empty[(N, E, N)]).foreach(addEdge(_))
+ }
+
+ init()
+
+ /**
+ * Add a vertex
+ * Current Graph is changed.
+ */
+ def addVertex(vertex: N): Unit = {
+ val result = _vertices.add(vertex)
+ if (result) {
+ _indexs += vertex -> nextId
+ }
+ }
+
+ /**
+ * Add a edge
+ * Current Graph is changed.
+ */
+ def addEdge(edge: (N, E, N)): Unit = {
+ val result = _edges.add(edge)
+ if (result) {
+ _indexs += edge -> nextId
+ }
+ }
+
+ /**
+ * return all vertices.
+ * The result is stable
+ */
+ def vertices: List[N] = {
+ // Sorts the vertex so that we can keep the order for mapVertex
+ _vertices.toList.sortBy(_indexs(_))
+ }
+
+ /**
+ * out degree
+ */
+ def outDegreeOf(node: N): Int = {
+ edges.count(_._1 == node)
+ }
+
+ /**
+ * in degree
+ */
+ def inDegreeOf(node: N): Int = {
+ edges.count(_._3 == node)
+ }
+
+ /**
+ * out going edges.
+ */
+ def outgoingEdgesOf(node: N): List[(N, E, N)] = {
+ edges.filter(_._1 == node)
+ }
+
+ /**
+ * incoming edges.
+ */
+ def incomingEdgesOf(node: N): List[(N, E, N)] = {
+ edges.filter(_._3 == node)
+ }
+
+ /**
+ * Remove vertex
+ * Current Graph is changed.
+ */
+ def removeVertex(node: N): Unit = {
+ _vertices.remove(node)
+ _indexs -= node
+ val toBeRemoved = incomingEdgesOf(node) ++ outgoingEdgesOf(node)
+ toBeRemoved.foreach(removeEdge(_))
+ }
+
+ /**
+ * Remove edge
+ * Current Graph is changed.
+ */
+ private def removeEdge(edge: (N, E, N)): Unit = {
+ _indexs -= edge
+ _edges.remove(edge)
+ }
+
+ /**
+ * add edge
+ * Current Graph is changed.
+ */
+ def addEdge(node1: N, edge: E, node2: N): Unit = {
+ addVertex(node1)
+ addVertex(node2)
+ addEdge((node1, edge, node2))
+ }
+
+ /**
+ * Map a graph to a new graph, with vertex converted to a new type
+ * Current Graph is not changed.
+ */
+ def mapVertex[NewNode](fun: N => NewNode): Graph[NewNode, E] = {
+ val vertexes = vertices.map(node => (node, fun(node)))
+
+ val vertexMap: Map[N, NewNode] = vertexes.toMap
+
+ val newEdges = edges.map { edge =>
+ (vertexMap(edge._1), edge._2, vertexMap(edge._3))
+ }
+ new Graph(vertexes.map(_._2), newEdges)
+ }
+
+ /**
+ * Map a graph to a new graph, with edge converted to new type
+ * Current graph is not changed.
+ */
+ def mapEdge[NewEdge](fun: (N, E, N) => NewEdge): Graph[N, NewEdge] = {
+ val newEdges = edges.map { edge =>
+ (edge._1, fun(edge._1, edge._2, edge._3), edge._3)
+ }
+ new Graph(vertices, newEdges)
+ }
+
+ /**
+ * edges connected to node
+ */
+ def edgesOf(node: N): List[(N, E, N)] = {
+ (incomingEdgesOf(node) ++ outgoingEdgesOf(node)).toSet[(N, E, N)].toList.sortBy(_indexs(_))
+ }
+
+ /**
+ * all edges
+ */
+ def edges: List[(N, E, N)] = {
+ _edges.toList.sortBy(_indexs(_))
+ }
+
+ /**
+ * Add another graph
+ * Current graph is changed.
+ */
+ def addGraph(other: Graph[N, E]): Graph[N, E] = {
+ (vertices ++ other.vertices).foreach(addVertex(_))
+ (edges ++ other.edges).foreach(edge => addEdge(edge._1, edge._2, edge._3))
+ this
+ }
+
+ /**
+ * clone the graph
+ */
+ def copy: Graph[N, E] = {
+ new Graph(vertices, edges)
+ }
+
+ /**
+ * check empty
+ */
+ def isEmpty: Boolean = {
+ val vertexCount = vertices.size
+ val edgeCount = edges.length
+ if (vertexCount + edgeCount == 0) {
+ true
+ } else {
+ false
+ }
+ }
+
+ /**
+ * sub-graph which contains current node and all neighbour
+ * nodes and edges.
+ */
+ def subGraph(node: N): Graph[N, E] = {
+ val newGraph = Graph.empty[N, E]
+ for (edge <- edgesOf(node)) {
+ newGraph.addEdge(edge._1, edge._2, edge._3)
+ }
+ newGraph
+ }
+
+ /**
+ * replace vertex, the current Graph is mutated.
+ */
+ def replaceVertex(node: N, newNode: N): Graph[N, E] = {
+ for (edge <- incomingEdgesOf(node)) {
+ addEdge(edge._1, edge._2, newNode)
+ }
+
+ for (edge <- outgoingEdgesOf(node)) {
+ addEdge(newNode, edge._2, edge._3)
+ }
+ removeVertex(node)
+ this
+ }
+
+ private def removeZeroInDegree: List[N] = {
+ val toBeRemoved = vertices.filter(inDegreeOf(_) == 0).sortBy(_indexs(_))
+ toBeRemoved.foreach(removeVertex(_))
+ toBeRemoved
+ }
+
+ /**
+ * Return an iterator of vertex in topological order
+ * The node returned by Iterator is stable sorted.
+ */
+ def topologicalOrderIterator: Iterator[N] = {
+ val newGraph = copy
+ var output = List.empty[N]
+
+ while (!newGraph.isEmpty) {
+ output ++= newGraph.removeZeroInDegree
+ }
+ output.iterator
+ }
+
+ /**
+ * Return all circles in graph.
+ *
+ * The reference of this algorithm is:
+ * https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm
+ */
+ private def findCircles: mutable.MutableList[mutable.MutableList[N]] = {
+ val inStack = mutable.Map.empty[N, Boolean]
+ val stack = mutable.Stack[N]()
+ val indexMap = mutable.Map.empty[N, Int]
+ val lowLink = mutable.Map.empty[N, Int]
+ var index = 0
+
+ val circles = mutable.MutableList.empty[mutable.MutableList[N]]
+
+ def tarjan(node: N): Unit = {
+ indexMap(node) = index
+ lowLink(node) = index
+ index += 1
+ inStack(node) = true
+ stack.push(node)
+
+ outgoingEdgesOf(node).foreach {
+ edge => {
+ if (!indexMap.contains(edge._3)) {
+ tarjan(edge._3)
+ if (lowLink.get(edge._3).get < lowLink.get(node).get) {
+ lowLink(node) = lowLink(edge._3)
+ }
+ } else {
+ if (inStack.get(edge._3).get && (indexMap.get(edge._3).get < lowLink.get(node).get)) {
+ lowLink(node) = indexMap(edge._3)
+ }
+ }
+ }
+ }
+
+ if (indexMap.get(node).get == lowLink.get(node).get) {
+ val circle = mutable.MutableList.empty[N]
+ var n = node
+ do {
+ n = stack.pop()
+ inStack(n) = false
+ circle += n
+ } while (n != node)
+ circles += circle
+ }
+ }
+
+ vertices.foreach {
+ node => {
+ if (!indexMap.contains(node)) tarjan(node)
+ }
+ }
+
+ circles
+ }
+
+ /**
+ * Return an iterator of vertex in topological order of graph with circles
+ * The node returned by Iterator is stable sorted.
+ *
+ * The reference of this algorithm is:
+ * http://www.drdobbs.com/database/topological-sorting/184410262
+ */
+ def topologicalOrderWithCirclesIterator: Iterator[N] = {
+ val circles = findCircles
+ val newGraph = Graph.empty[mutable.MutableList[N], E]
+ circles.foreach {
+ circle => {
+ newGraph.addVertex(circle)
+ }
+ }
+
+ for (circle1 <- circles; circle2 <- circles; if circle1 != circle2) yield {
+ for (node1 <- circle1; node2 <- circle2) yield {
+ var edges = outgoingEdgesOf(node1)
+ for (edge <- edges; if edge._3 == node2) yield {
+ newGraph.addEdge(circle1, edge._2, circle2)
+ }
+
+ edges = outgoingEdgesOf(node2)
+ for (edge <- edges; if edge._3 == node1) yield {
+ newGraph.addEdge(circle2, edge._2, circle1)
+ }
+ }
+ }
+
+ val topo = newGraph.topologicalOrderIterator
+ topo.flatMap(_.sortBy(_indexs(_)).iterator)
+ }
+
+ /**
+ * check whether there is a loop
+ */
+ def hasCycle(): Boolean = {
+ @tailrec
+ def detectCycle(graph: Graph[N, E]): Boolean = {
+ if (graph.edges.isEmpty) {
+ false
+ } else if (graph.vertices.nonEmpty && !graph.vertices.exists(graph.inDegreeOf(_) == 0)) {
+ true
+ } else {
+ graph.removeZeroInDegree
+ detectCycle(graph)
+ }
+ }
+
+ detectCycle(copy)
+ }
+
+ /**
+ * Check whether there are two edges connecting two nodes.
+ */
+ def hasDuplicatedEdge(): Boolean = {
+ edges.groupBy(edge => (edge._1, edge._3)).values.exists(_.size > 1)
+ }
+
+ /**
+ * Generate a level map for each vertex withholding:
+ * {{{
+ * if vertex A -> B, then level(A) -> level(B)
+ * }}}
+ */
+ def vertexHierarchyLevelMap(): Map[N, Int] = {
+ val newGraph = copy
+ var output = Map.empty[N, Int]
+ var level = 0
+ while (!newGraph.isEmpty) {
+ output ++= newGraph.removeZeroInDegree.map((_, level)).toMap
+ level += 1
+ }
+ output
+ }
+
+ override def toString: String = {
+ Map("vertices" -> vertices.mkString(","),
+ "edges" -> edges.mkString(",")).toString()
+ }
+}
+
+object Graph {
+
+ /**
+ * Example:
+ *
+ * {{{
+ * Graph(1 ~ 2 ~> 4 ~ 5 ~> 7, 8~9~>55, 11)
+ * Will create a graph with:
+ * nodes:
+ * 1, 4, 7, 8, 55, 11
+ * edge:
+ * 2: (1->4)
+ * 5: (4->7)
+ * 9: (8->55)
+ * }}}
+ */
+ def apply[N, E](elems: Path[_ <: N, _ <: E]*): Graph[N, E] = {
+ val graph = empty[N, E]
+ elems.foreach { path =>
+ path.updategraph(graph)
+ }
+ graph
+ }
+
+ def apply[N, E](vertices: List[N], edges: List[(N, E, N)]): Graph[N, E] = {
+ new Graph(vertices, edges)
+ }
+
+ def unapply[N, E](graph: Graph[N, E]): Option[(List[N], List[(N, E, N)])] = {
+ Some((graph.vertices, graph.edges))
+ }
+
+ def empty[N, E]: Graph[N, E] = {
+ new Graph(List.empty[N], List.empty[(N, E, N)])
+ }
+
+ class Path[N, + E](path: List[Either[N, E]]) {
+
+ def ~[Edge >: E](edge: Edge): Path[N, Edge] = {
+ new Path(path :+ Right(edge))
+ }
+
+ def ~>[Node >: N](node: Node): Path[Node, E] = {
+ new Path(path :+ Left(node))
+ }
+
+ def to[Node >: N, Edge >: E](node: Node, edge: Edge): Path[Node, Edge] = {
+ this ~ edge ~> node
+ }
+
+ private[Graph] def updategraph[Node >: N, Edge >: E](graph: Graph[Node, Edge]): Unit = {
+ val nodeEdgePair: Tuple2[Option[N], Option[E]] = (None, None)
+ path.foldLeft(nodeEdgePair) { (pair, either) =>
+ val (lastNode, lastEdge) = pair
+ either match {
+ case Left(node) =>
+ graph.addVertex(node)
+ if (lastNode.isDefined) {
+ graph.addEdge(lastNode.get, lastEdge.getOrElse(null.asInstanceOf[Edge]), node)
+ }
+ (Some(node), None)
+ case Right(edge) =>
+ (lastNode, Some(edge))
+ }
+ }
+ }
+ }
+
+ object Path {
+ implicit def anyToPath[N, E](any: N): Path[N, E] = Node(any)
+ }
+
+ implicit class Node[N, E](self: N) extends Path[N, E](List(Left(self))) {
+
+ override def ~[Edge](edge: Edge): Path[N, Edge] = {
+ new Path(List(Left(self), Right(edge)))
+ }
+
+ override def ~>[Node >: N](node: Node): Path[Node, E] = {
+ new NodeList(List(self, node))
+ }
+
+ override def to[Node >: N, Edge >: E](node: Node, edge: Edge): Path[Node, Edge] = {
+ this ~ edge ~> node
+ }
+ }
+
+ class NodeList[N, E](nodes: List[N]) extends Path[N, E](nodes.map(Left(_))) {
+ override def ~[Edge](edge: Edge): Path[N, Edge] = {
+ new Path(nodes.map(Left(_)) :+ Right(edge))
+ }
+
+ override def ~>[Node >: N](node: Node): Path[Node, E] = {
+ new NodeList(nodes :+ node)
+ }
+
+ override def to[Node >: N, Edge >: E](node: Node, edge: Edge): Path[Node, Edge] = {
+ this ~ edge ~> node
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/util/HistoryMetricsService.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/util/HistoryMetricsService.scala b/core/src/main/scala/org/apache/gearpump/util/HistoryMetricsService.scala
new file mode 100644
index 0000000..549c34f
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/util/HistoryMetricsService.scala
@@ -0,0 +1,404 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.util
+
+import java.util
+import scala.collection.mutable.ListBuffer
+
+import akka.actor.Actor
+import com.typesafe.config.Config
+import org.slf4j.Logger
+
+import org.apache.gearpump.TimeStamp
+import org.apache.gearpump.cluster.ClientToMaster.{QueryHistoryMetrics, ReadOption}
+import org.apache.gearpump.cluster.MasterToClient.{HistoryMetrics, HistoryMetricsItem}
+import org.apache.gearpump.metrics.Metrics._
+import org.apache.gearpump.metrics.MetricsAggregator
+import org.apache.gearpump.util.Constants._
+import org.apache.gearpump.util.HistoryMetricsService.{DummyMetricsAggregator, HistoryMetricsConfig, HistoryMetricsStore, SkipAllAggregator}
+
+/**
+ *
+ * Metrics service to serve history metrics data
+ *
+ * For simplicity, HistoryMetricsService will maintain 72 hours coarse-grained data
+ * for last 72 hours, and fine-grained data for past 5 min.
+ *
+ * For the coarse-grained data of past 72 hours, one or two sample point will be stored
+ * for each hour.
+ *
+ * For fine-grained data in last 5 min, there will be 1 sample point per 15 seconds.
+ */
+class HistoryMetricsService(name: String, config: HistoryMetricsConfig) extends Actor {
+ private val LOG: Logger = LogUtil.getLogger(getClass, name = name)
+ private var metricsStore = Map.empty[String, HistoryMetricsStore]
+ private val systemConfig = context.system.settings.config
+
+ def receive: Receive = metricHandler orElse commandHandler
+ def metricHandler: Receive = {
+ case ReportMetrics =>
+ sender ! DemandMoreMetrics(self)
+ case metrics: MetricType =>
+ val name = metrics.name
+ if (metricsStore.contains(name)) {
+ metricsStore(name).add(metrics)
+ } else {
+ val store = HistoryMetricsStore(name, metrics, config)
+ metricsStore += name -> store
+ store.add(metrics)
+ }
+ }
+
+ private def toRegularExpression(input: String): String = {
+ "^" + input.flatMap {
+ case '*' => ".*"
+ case '?' => "."
+ case char if "()[]$^.{}|\\".contains(char) => "\\" + char
+ case other => s"$other"
+ } + ".*$"
+ }
+
+ private def fetchMetricsHistory(pathPattern: String, readOption: ReadOption.ReadOption)
+ : List[HistoryMetricsItem] = {
+
+ val result = new ListBuffer[HistoryMetricsItem]
+
+ val regex = toRegularExpression(pathPattern).r.pattern
+
+ val iter = metricsStore.iterator
+ while (iter.hasNext) {
+ val (name, store) = iter.next()
+
+ val matcher = regex.matcher(name)
+ if (matcher.matches()) {
+ readOption match {
+ case ReadOption.ReadLatest =>
+ result.append(store.readLatest: _*)
+ case ReadOption.ReadRecent =>
+ result.append(store.readRecent: _*)
+ case ReadOption.ReadHistory =>
+ result.append(store.readHistory: _*)
+ case _ =>
+ // Skip all other options.
+ }
+ }
+ }
+ result.toList
+ }
+
+ val dummyAggregator = new DummyMetricsAggregator
+ private var aggregators: Map[String, MetricsAggregator] = Map.empty[String, MetricsAggregator]
+
+ import scala.collection.JavaConverters._
+ private val validAggregators: Set[String] = {
+ val rootConfig = systemConfig.getConfig(Constants.GEARPUMP_METRICS_AGGREGATORS).root.unwrapped
+ rootConfig.keySet().asScala.toSet
+ }
+
+ def commandHandler: Receive = {
+ // Path accept syntax ? *, ? will match one char, * will match at least one char
+ case QueryHistoryMetrics(inputPath, readOption, aggregatorClazz, options) =>
+
+ val aggregator = {
+ if (aggregatorClazz == null || aggregatorClazz.isEmpty) {
+ dummyAggregator
+ } else if (aggregators.contains(aggregatorClazz)) {
+ aggregators(aggregatorClazz)
+ } else if (validAggregators.contains(aggregatorClazz)) {
+ val clazz = Class.forName(aggregatorClazz)
+ val constructor = clazz.getConstructor(classOf[Config])
+ val aggregator = constructor.newInstance(systemConfig).asInstanceOf[MetricsAggregator]
+ aggregators += aggregatorClazz -> aggregator
+ aggregator
+ } else {
+ LOG.error(s"Aggregator $aggregatorClazz is not in the white list ${validAggregators}, " +
+ s"we will drop all messages. Please see config at ${GEARPUMP_METRICS_AGGREGATORS}")
+ val skipAll = new SkipAllAggregator
+ aggregators += aggregatorClazz -> new SkipAllAggregator
+ skipAll
+ }
+ }
+
+ val metrics = fetchMetricsHistory(inputPath, readOption).iterator
+ sender ! HistoryMetrics(inputPath, aggregator.aggregate(options, metrics))
+ }
+}
+
+object HistoryMetricsService {
+
+ trait MetricsStore {
+ def add(inputMetrics: MetricType): Unit
+
+ def read: List[HistoryMetricsItem]
+
+ /**
+ * read latest inserted records
+ * @return
+ */
+ def readLatest: List[HistoryMetricsItem]
+ }
+
+ trait HistoryMetricsStore {
+ def add(inputMetrics: MetricType): Unit
+
+ /**
+ * read latest inserted records
+ * @return
+ */
+ def readLatest: List[HistoryMetricsItem]
+
+ def readRecent: List[HistoryMetricsItem]
+
+ def readHistory: List[HistoryMetricsItem]
+ }
+
+ class DummyHistoryMetricsStore extends HistoryMetricsStore {
+
+ val empty = List.empty[HistoryMetricsItem]
+
+ override def add(inputMetrics: MetricType): Unit = Unit
+
+ override def readRecent: List[HistoryMetricsItem] = empty
+
+ /**
+ * read latest inserted records
+ * @return
+ */
+ override def readLatest: List[HistoryMetricsItem] = empty
+
+ override def readHistory: List[HistoryMetricsItem] = empty
+ }
+
+ object HistoryMetricsStore {
+ def apply(name: String, metric: MetricType, config: HistoryMetricsConfig)
+ : HistoryMetricsStore = {
+ metric match {
+ case histogram: Histogram => new HistogramMetricsStore(config)
+ case meter: Meter => new MeterMetricsStore(config)
+ case counter: Counter => new CounterMetricsStore(config)
+ case gauge: Gauge => new GaugeMetricsStore(config)
+ case _ => new DummyHistoryMetricsStore // other metrics are not supported
+ }
+ }
+ }
+
+ /**
+ * Metrics store to store history data points
+ * For each time point, we will store single data point.
+ *
+ * @param retainCount how many data points to retain, old data will be removed
+ * @param retainIntervalMs time interval between two data points.
+ */
+ class SingleValueMetricsStore(retainCount: Int, retainIntervalMs: Long) extends MetricsStore {
+
+ private val queue = new util.ArrayDeque[HistoryMetricsItem]()
+ private var latest = List.empty[HistoryMetricsItem]
+
+ // End of the time window we are tracking
+ private var endTime = 0L
+
+ override def add(inputMetrics: MetricType): Unit = {
+ add(inputMetrics, System.currentTimeMillis())
+ }
+
+ def add(inputMetrics: MetricType, now: TimeStamp): Unit = {
+
+ val metrics = HistoryMetricsItem(now, inputMetrics)
+ latest = List(metrics)
+
+ if (now >= endTime) {
+ queue.addFirst(metrics)
+ endTime = (now / retainIntervalMs + 1) * retainIntervalMs
+
+ // Removes old data
+ if (queue.size() > retainCount) {
+ queue.removeLast()
+ }
+ }
+ }
+
+ def read: List[HistoryMetricsItem] = {
+ val result = new ListBuffer[HistoryMetricsItem]
+ import scala.collection.JavaConverters._
+ queue.iterator().asScala.foreach(result.prepend(_))
+ result.toList
+ }
+
+ override def readLatest: List[HistoryMetricsItem] = {
+ latest
+ }
+ }
+
+ /**
+ * Config for how long to keep history metrics data.
+ *
+ * @param retainHistoryDataHours Retain at max @RETAIN_HISTORY_HOURS history data(unit hour)
+ * @param retainHistoryDataIntervalMs time interval between two history data points.(unit: ms)
+ * @param retainRecentDataSeconds Retain at max @RETAIN_LATEST_SECONDS
+ * recent data points(unit: seconds)
+ * @param retainRecentDataIntervalMs Retain at max @RETAIN_LATEST_SECONDS recent
+ * data points(unit: ms)
+ */
+ case class HistoryMetricsConfig(
+ retainHistoryDataHours: Int,
+ retainHistoryDataIntervalMs: Int,
+ retainRecentDataSeconds: Int,
+ retainRecentDataIntervalMs: Int)
+
+ object HistoryMetricsConfig {
+ def apply(config: Config): HistoryMetricsConfig = {
+ val historyHour = config.getInt(GEARPUMP_METRIC_RETAIN_HISTORY_DATA_HOURS)
+ val historyInterval = config.getInt(GEARPUMP_RETAIN_HISTORY_DATA_INTERVAL_MS)
+
+ val recentSeconds = config.getInt(GEARPUMP_RETAIN_RECENT_DATA_SECONDS)
+ val recentInterval = config.getInt(GEARPUMP_RETAIN_RECENT_DATA_INTERVAL_MS)
+ HistoryMetricsConfig(historyHour, historyInterval, recentSeconds, recentInterval)
+ }
+ }
+
+ class HistogramMetricsStore(config: HistoryMetricsConfig) extends HistoryMetricsStore {
+
+ private val history = new SingleValueMetricsStore(
+ config.retainHistoryDataHours * 3600 * 1000 / config.retainHistoryDataIntervalMs,
+ config.retainHistoryDataIntervalMs)
+
+ private val recent = new SingleValueMetricsStore(
+ config.retainRecentDataSeconds * 1000 / config.retainRecentDataIntervalMs,
+ config.retainRecentDataIntervalMs)
+
+ override def add(inputMetrics: MetricType): Unit = {
+ recent.add(inputMetrics)
+ history.add(inputMetrics)
+ }
+
+ override def readRecent: List[HistoryMetricsItem] = {
+ recent.read
+ }
+
+ override def readHistory: List[HistoryMetricsItem] = {
+ history.read
+ }
+
+ override def readLatest: List[HistoryMetricsItem] = {
+ recent.readLatest
+ }
+ }
+
+ class MeterMetricsStore(config: HistoryMetricsConfig) extends HistoryMetricsStore {
+
+ private val history = new SingleValueMetricsStore(
+ config.retainHistoryDataHours * 3600 * 1000 / config.retainHistoryDataIntervalMs,
+ config.retainHistoryDataIntervalMs)
+
+ private val recent = new SingleValueMetricsStore(
+ config.retainRecentDataSeconds * 1000 / config.retainRecentDataIntervalMs,
+ config.retainRecentDataIntervalMs)
+
+ override def add(inputMetrics: MetricType): Unit = {
+ recent.add(inputMetrics)
+ history.add(inputMetrics)
+ }
+
+ override def readRecent: List[HistoryMetricsItem] = {
+ recent.read
+ }
+
+ override def readHistory: List[HistoryMetricsItem] = {
+ history.read
+ }
+
+ override def readLatest: List[HistoryMetricsItem] = {
+ recent.readLatest
+ }
+ }
+
+ class CounterMetricsStore(config: HistoryMetricsConfig) extends HistoryMetricsStore {
+
+ private val history = new SingleValueMetricsStore(
+ config.retainHistoryDataHours * 3600 * 1000 / config.retainHistoryDataIntervalMs,
+ config.retainHistoryDataIntervalMs)
+
+ private val recent = new SingleValueMetricsStore(
+ config.retainRecentDataSeconds * 1000 / config.retainRecentDataIntervalMs,
+ config.retainRecentDataIntervalMs)
+
+ override def add(inputMetrics: MetricType): Unit = {
+ history.add(inputMetrics)
+ recent.add(inputMetrics)
+ }
+
+ override def readRecent: List[HistoryMetricsItem] = {
+ recent.read
+ }
+
+ override def readHistory: List[HistoryMetricsItem] = {
+ history.read
+ }
+
+ override def readLatest: List[HistoryMetricsItem] = {
+ recent.readLatest
+ }
+ }
+
+ class GaugeMetricsStore(config: HistoryMetricsConfig) extends HistoryMetricsStore {
+
+ private val compartor = (left: HistoryMetricsItem, right: HistoryMetricsItem) =>
+ left.value.asInstanceOf[Gauge].value > right.value.asInstanceOf[Gauge].value
+
+ private val history = new SingleValueMetricsStore(
+ config.retainHistoryDataHours * 3600 * 1000 / config.retainHistoryDataIntervalMs,
+ config.retainHistoryDataIntervalMs)
+
+ private val recent = new SingleValueMetricsStore(
+ config.retainRecentDataSeconds * 1000 / config.retainRecentDataIntervalMs,
+ config.retainRecentDataIntervalMs)
+
+ override def add(inputMetrics: MetricType): Unit = {
+ recent.add(inputMetrics)
+ history.add(inputMetrics)
+ }
+
+ override def readRecent: List[HistoryMetricsItem] = {
+ recent.read
+ }
+
+ override def readHistory: List[HistoryMetricsItem] = {
+ history.read
+ }
+
+ override def readLatest: List[HistoryMetricsItem] = {
+ recent.readLatest
+ }
+ }
+
+ class DummyMetricsAggregator extends MetricsAggregator {
+ def aggregate(options: Map[String, String], inputs: Iterator[HistoryMetricsItem])
+ : List[HistoryMetricsItem] = {
+ inputs.toList
+ }
+ }
+
+ class SkipAllAggregator extends MetricsAggregator {
+ private val empty = List.empty[HistoryMetricsItem]
+ def aggregate(options: Map[String, String], inputs: Iterator[HistoryMetricsItem])
+ : List[HistoryMetricsItem] = {
+ empty
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/util/LogUtil.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/util/LogUtil.scala b/core/src/main/scala/org/apache/gearpump/util/LogUtil.scala
new file mode 100644
index 0000000..225f796
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/util/LogUtil.scala
@@ -0,0 +1,125 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.util
+
+import java.io.File
+import java.net.InetAddress
+import java.util.Properties
+import scala.util.Try
+
+import com.typesafe.config.Config
+import org.apache.log4j.PropertyConfigurator
+import org.slf4j.{Logger, LoggerFactory}
+
+object LogUtil {
+ object ProcessType extends Enumeration {
+ type ProcessType = Value
+ val MASTER, WORKER, LOCAL, APPLICATION, UI = Value
+ }
+
+ def getLogger[T](
+ clazz: Class[T], context: String = null, master: Any = null, worker: Any = null,
+ executor: Any = null, task: Any = null, app: Any = null, name: String = null): Logger = {
+ var env = ""
+
+ if (null != context) {
+ env += context
+ }
+ if (null != master) {
+ env += "master" + master
+ }
+ if (null != worker) {
+ env += "worker" + worker
+ }
+
+ if (null != app) {
+ env += "app" + app
+ }
+
+ if (null != executor) {
+ env += "exec" + executor
+ }
+ if (null != task) {
+ env += task
+ }
+ if (null != name) {
+ env += name
+ }
+
+ if (!env.isEmpty) {
+ LoggerFactory.getLogger(clazz.getSimpleName + "@" + env)
+ } else {
+ LoggerFactory.getLogger(clazz.getSimpleName)
+ }
+ }
+
+ /** Custom the log file locations by reading config from system properties */
+ def loadConfiguration(config: Config, processType: ProcessType.ProcessType): Unit = {
+ // Set log file name
+ val propName = s"gearpump.${processType.toString.toLowerCase}.log.file"
+ val props = loadConfiguration
+
+ props.setProperty("gearpump.log.file", "${" + propName + "}")
+
+ props.setProperty("JVM_NAME", jvmName)
+
+ processType match {
+ case ProcessType.APPLICATION =>
+ props.setProperty("log4j.rootAppender", "${gearpump.application.logger}")
+ props.setProperty("gearpump.application.log.rootdir",
+ applicationLogDir(config).getAbsolutePath)
+ case _ =>
+ props.setProperty("log4j.rootAppender", "${gearpump.root.logger}")
+ props.setProperty("gearpump.log.dir", daemonLogDir(config).getAbsolutePath)
+ }
+
+ PropertyConfigurator.configure(props)
+ }
+
+ def daemonLogDir(config: Config): File = {
+ val dir = config.getString(Constants.GEARPUMP_LOG_DAEMON_DIR)
+ new File(dir)
+ }
+
+ def verboseLogToConsole(): Unit = {
+ val props = loadConfiguration
+ props.setProperty("log4j.rootLogger", "DEBUG,console")
+ PropertyConfigurator.configure(props)
+ }
+
+ def loadConfiguration: Properties = {
+ val props = new Properties()
+ val log4jConfStream = getClass().getClassLoader.getResourceAsStream("log4j.properties")
+ if (log4jConfStream != null) {
+ props.load(log4jConfStream)
+ }
+ log4jConfStream.close()
+ props
+ }
+
+ private def jvmName: String = {
+ val hostname = Try(InetAddress.getLocalHost.getHostName).getOrElse("local")
+ java.lang.management.ManagementFactory.getRuntimeMXBean().getName()
+ }
+
+ def applicationLogDir(config: Config): File = {
+ val appLogDir = config.getString(Constants.GEARPUMP_LOG_APPLICATION_DIR)
+ new File(appLogDir)
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/util/ProcessLogRedirector.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/util/ProcessLogRedirector.scala b/core/src/main/scala/org/apache/gearpump/util/ProcessLogRedirector.scala
new file mode 100644
index 0000000..e6d79e4
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/util/ProcessLogRedirector.scala
@@ -0,0 +1,53 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.util
+
+import java.io.{Closeable, Flushable}
+import scala.sys.process.ProcessLogger
+
+import org.slf4j.LoggerFactory
+
+/** Redirect the console output to parent process */
+class ProcessLogRedirector extends ProcessLogger with Closeable with Flushable with ConsoleOutput {
+ private val LOG = LoggerFactory.getLogger("redirect")
+
+ // We only capture the first 1K chars
+ private final val LENGTH = 1000
+ private var _error: String = ""
+ private var _output: String = ""
+
+ def error: String = _error
+ def output: String = _output
+
+ def out(s: => String): Unit = {
+ if (_output.length <= LENGTH) {
+ _output += "\n" + s
+ }
+ LOG.info(s)
+ }
+ def err(s: => String): Unit = {
+ if (_error.length <= LENGTH) {
+ _error += "\n" + s
+ }
+ LOG.error(s)
+ }
+ def buffer[T](f: => T): T = f
+ def close(): Unit = Unit
+ def flush(): Unit = Unit
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/util/ReferenceEqual.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/util/ReferenceEqual.scala b/core/src/main/scala/org/apache/gearpump/util/ReferenceEqual.scala
new file mode 100644
index 0000000..69e0d4c
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/util/ReferenceEqual.scala
@@ -0,0 +1,33 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.util
+
+/**
+ * Check equal using reference-equal.
+ */
+trait ReferenceEqual extends AnyRef {
+
+ override def equals(other: Any): Boolean = {
+ this.eq(other.asInstanceOf[AnyRef])
+ }
+
+ override def hashCode(): Int = {
+ super.hashCode()
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/util/RestartPolicy.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/util/RestartPolicy.scala b/core/src/main/scala/org/apache/gearpump/util/RestartPolicy.scala
new file mode 100644
index 0000000..97d6dd0
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/util/RestartPolicy.scala
@@ -0,0 +1,41 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.util
+
+import scala.concurrent.duration.Duration
+
+import akka.actor.ChildRestartStats
+
+/**
+ * When one executor or task fails, Gearpump will try to start. However, if it fails after
+ * multiple retries, then we abort.
+ *
+ * @param maxNrOfRetries The number of times is allowed to be restarted, negative value means no
+ * limit, if the limit is exceeded the policy will not allow to restart
+ * @param withinTimeRange Duration of the time window for maxNrOfRetries.
+ * Duration.Inf means no window
+ */
+class RestartPolicy(maxNrOfRetries: Int, withinTimeRange: Duration) {
+ private val status = new ChildRestartStats(null, 0, 0L)
+ private val retriesWindow = (Some(maxNrOfRetries), Some(withinTimeRange.toMillis.toInt))
+
+ def allowRestart: Boolean = {
+ status.requestRestartPermission(retriesWindow)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/util/RichProcess.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/util/RichProcess.scala b/core/src/main/scala/org/apache/gearpump/util/RichProcess.scala
new file mode 100644
index 0000000..1729d32
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/util/RichProcess.scala
@@ -0,0 +1,33 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.util
+
+import scala.sys.process.Process
+
+trait ConsoleOutput {
+ def output: String
+ def error: String
+}
+
+/** Extends Process by providing a additional logger: ConsoleOutput interface. */
+class RichProcess(process: Process, _logger: ConsoleOutput) extends Process {
+ def exitValue(): scala.Int = process.exitValue()
+ def destroy(): scala.Unit = process.destroy()
+ def logger: ConsoleOutput = _logger
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/util/TimeOutScheduler.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/util/TimeOutScheduler.scala b/core/src/main/scala/org/apache/gearpump/util/TimeOutScheduler.scala
new file mode 100644
index 0000000..0e2e27c
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/util/TimeOutScheduler.scala
@@ -0,0 +1,43 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.util
+
+import java.util.concurrent.TimeUnit
+import scala.concurrent.duration._
+
+import akka.actor.{Actor, ActorRef}
+import akka.pattern.ask
+
+/** A helper util to send a message to remote actor and notify callback when timeout */
+trait TimeOutScheduler {
+ this: Actor =>
+ import context.dispatcher
+
+ def sendMsgWithTimeOutCallBack(
+ target: ActorRef, msg: AnyRef, milliSeconds: Long, timeOutHandler: => Unit): Unit = {
+ val result = target.ask(msg)(FiniteDuration(milliSeconds, TimeUnit.MILLISECONDS))
+ result onSuccess {
+ case msg =>
+ self ! msg
+ }
+ result onFailure {
+ case _ => timeOutHandler
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/main/scala/org/apache/gearpump/util/Util.scala
----------------------------------------------------------------------
diff --git a/core/src/main/scala/org/apache/gearpump/util/Util.scala b/core/src/main/scala/org/apache/gearpump/util/Util.scala
new file mode 100644
index 0000000..19bd5a8
--- /dev/null
+++ b/core/src/main/scala/org/apache/gearpump/util/Util.scala
@@ -0,0 +1,181 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.util
+
+import java.io.{BufferedReader, File, FileInputStream, InputStreamReader}
+import java.net.{ServerSocket, URI}
+import scala.concurrent.forkjoin.ThreadLocalRandom
+import scala.sys.process.Process
+import scala.util.{Failure, Success, Try}
+
+import com.typesafe.config.{Config, ConfigFactory}
+
+import org.apache.gearpump.cluster.AppJar
+import org.apache.gearpump.jarstore.JarStoreService
+import org.apache.gearpump.transport.HostPort
+
+object Util {
+ val LOG = LogUtil.getLogger(getClass)
+ private val defaultUri = new URI("file:///")
+ private val appNamePattern = "^[a-zA-Z_][a-zA-Z0-9_]+$".r.pattern
+
+ def validApplicationName(appName: String): Boolean = {
+ appNamePattern.matcher(appName).matches()
+ }
+
+ def getCurrentClassPath: Array[String] = {
+ val classpath = System.getProperty("java.class.path")
+ val classpathList = classpath.split(File.pathSeparator)
+ classpathList
+ }
+
+ def version: String = {
+ val home = System.getProperty(Constants.GEARPUMP_HOME)
+ val version = Try {
+ val versionFile = new FileInputStream(new File(home, "VERSION"))
+ val reader = new BufferedReader(new InputStreamReader(versionFile))
+ val version = reader.readLine().replace("version:=", "")
+ versionFile.close()
+ version
+ }
+ version match {
+ case Success(version) =>
+ version
+ case Failure(ex) =>
+ LOG.error("failed to read VERSION file, " + ex.getMessage)
+ "Unknown-Version"
+ }
+ }
+
+ def startProcess(options: Array[String], classPath: Array[String], mainClass: String,
+ arguments: Array[String]): RichProcess = {
+ val java = System.getProperty("java.home") + "/bin/java"
+ val command = List(java) ++ options ++
+ List("-cp", classPath.mkString(File.pathSeparator), mainClass) ++ arguments
+ LOG.info(s"Starting executor process java $mainClass ${arguments.mkString(" ")} " +
+ s"\n ${options.mkString(" ")}")
+ val logger = new ProcessLogRedirector()
+ val process = Process(command).run(logger)
+ new RichProcess(process, logger)
+ }
+
+ /**
+ * hostList format: host1:port1,host2:port2,host3:port3...
+ */
+ def parseHostList(hostList: String): List[HostPort] = {
+ val masters = hostList.trim.split(",").map { address =>
+ val hostAndPort = address.split(":")
+ HostPort(hostAndPort(0), hostAndPort(1).toInt)
+ }
+ masters.toList
+ }
+
+ def resolvePath(path: String): String = {
+ val uri = new URI(path)
+ if (uri.getScheme == null && uri.getFragment == null) {
+ val absolutePath = new File(path).getCanonicalPath.replaceAll("\\\\", "/")
+ "file://" + absolutePath
+ } else {
+ path
+ }
+ }
+
+ def isLocalPath(path: String): Boolean = {
+ val uri = new URI(path)
+ val scheme = uri.getScheme
+ val authority = uri.getAuthority
+ if (scheme == null && authority == null) {
+ true
+ } else if (scheme == defaultUri.getScheme) {
+ true
+ } else {
+ false
+ }
+ }
+
+ def randInt(): Int = {
+ Math.abs(ThreadLocalRandom.current.nextInt())
+ }
+
+ def findFreePort(): Try[Int] = {
+ Try {
+ val socket = new ServerSocket(0)
+ socket.setReuseAddress(true)
+ val port = socket.getLocalPort()
+ socket.close
+ port
+ }
+ }
+
+ def uploadJar(jarFile: File, jarStoreService: JarStoreService): AppJar = {
+ val remotePath = jarStoreService.copyFromLocal(jarFile)
+ AppJar(jarFile.getName, remotePath)
+ }
+
+ /**
+ * This util can be used to filter out configuration from specific origin
+ *
+ * For example, if you want to filter out configuration from reference.conf
+ * Then you can use like this:
+ *
+ * filterOutOrigin(config, "reference.conf")
+ */
+ import scala.collection.JavaConverters._
+ def filterOutOrigin(config: Config, originFile: String): Config = {
+ config.entrySet().asScala.foldLeft(ConfigFactory.empty()) { (config, entry) =>
+ val key = entry.getKey
+ val value = entry.getValue
+ val origin = value.origin()
+ if (origin.resource() == originFile) {
+ config
+ } else {
+ config.withValue(key, value)
+ }
+ }
+ }
+
+ case class JvmSetting(vmargs: Array[String], classPath: Array[String])
+
+ case class AppJvmSettings(appMater: JvmSetting, executor: JvmSetting)
+
+ /** Get an effective AppJvmSettings from Config */
+ def resolveJvmSetting(conf: Config): AppJvmSettings = {
+
+ import org.apache.gearpump.util.Constants._
+
+ val appMasterVMArgs = Try(conf.getString(GEARPUMP_APPMASTER_ARGS).split("\\s+")
+ .filter(_.nonEmpty)).toOption
+ val executorVMArgs = Try(conf.getString(GEARPUMP_EXECUTOR_ARGS).split("\\s+")
+ .filter(_.nonEmpty)).toOption
+
+ val appMasterClassPath = Try(
+ conf.getString(GEARPUMP_APPMASTER_EXTRA_CLASSPATH)
+ .split("[;:]").filter(_.nonEmpty)).toOption
+
+ val executorClassPath = Try(
+ conf.getString(GEARPUMP_EXECUTOR_EXTRA_CLASSPATH)
+ .split(File.pathSeparator).filter(_.nonEmpty)).toOption
+
+ AppJvmSettings(
+ JvmSetting(appMasterVMArgs.getOrElse(Array.empty[String]),
+ appMasterClassPath.getOrElse(Array.empty[String])),
+ JvmSetting(executorVMArgs
+ .getOrElse(Array.empty[String]), executorClassPath.getOrElse(Array.empty[String])))
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/resources/log4j.properties
----------------------------------------------------------------------
diff --git a/core/src/test/resources/log4j.properties b/core/src/test/resources/log4j.properties
index 0faadd9..fb5f594 100644
--- a/core/src/test/resources/log4j.properties
+++ b/core/src/test/resources/log4j.properties
@@ -80,7 +80,7 @@ log4j.appender.RFA.MaxBackupIndex=30
#
# Hadoop Filesystem Rolling File Appender, similar to RFA but writing to Hadoop Filesystem instead of local disk.
#
-log4j.appender.HDFSRFA=io.gearpump.util.HadoopFSLogAppender
+log4j.appender.HDFSRFA=org.apache.gearpump.util.HadoopFSLogAppender
log4j.appender.HDFSRFA.File=${gearpump.log.dir}/${gearpump.log.file}
# Logfile size and and 30 backups
@@ -103,7 +103,7 @@ log4j.appender.console.layout.ConversionPattern=[%p] [%d{MM/dd/yyyy HH:mm:ss.SSS
#
# Application Log Appender
#
-log4j.appender.ALA=io.gearpump.util.HadoopFSLogAppender
+log4j.appender.ALA=org.apache.gearpump.util.HadoopFSLogAppender
log4j.appender.ALA.File=${gearpump.application.log.dir}/${gearpump.application.log.file}
# Logfile size and and 30 backups
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/resources/test.conf
----------------------------------------------------------------------
diff --git a/core/src/test/resources/test.conf b/core/src/test/resources/test.conf
index ac18c88..58e5ef1 100644
--- a/core/src/test/resources/test.conf
+++ b/core/src/test/resources/test.conf
@@ -14,7 +14,7 @@ gearpump {
application.executor-num = 1
- worker.executor-process-launcher = "io.gearpump.cluster.worker.DefaultExecutorProcessLauncher"
+ worker.executor-process-launcher = "org.apache.gearpump.cluster.worker.DefaultExecutorProcessLauncher"
cluster {
masters = []
@@ -22,9 +22,9 @@ gearpump {
streaming.register-task-timeout-ms = 5000
- transport.serializer = "io.gearpump.transport.MockTransportSerializer"
+ transport.serializer = "org.apache.gearpump.transport.MockTransportSerializer"
- serialization-framework = "io.gearpump.serializer.FastKryoSerializationFramework"
+ serialization-framework = "org.apache.gearpump.serializer.FastKryoSerializationFramework"
}
## Configurations only visible on Linux or Mac..
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/io/gearpump/TestProbeUtil.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/io/gearpump/TestProbeUtil.scala b/core/src/test/scala/io/gearpump/TestProbeUtil.scala
deleted file mode 100644
index e7181db..0000000
--- a/core/src/test/scala/io/gearpump/TestProbeUtil.scala
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump
-
-import scala.language.implicitConversions
-
-import akka.actor.{Actor, Props, Terminated}
-import akka.testkit.TestProbe
-
-object TestProbeUtil {
- implicit def toProps(probe: TestProbe): Props = {
- Props(new Actor {
- val probeRef = probe.ref
- context.watch(probeRef)
- def receive: Receive = {
- case Terminated(probeRef) => context.stop(self)
- case x => probeRef.forward(x)
- }
- })
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/io/gearpump/cluster/MasterHarness.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/io/gearpump/cluster/MasterHarness.scala b/core/src/test/scala/io/gearpump/cluster/MasterHarness.scala
deleted file mode 100644
index b1ca357..0000000
--- a/core/src/test/scala/io/gearpump/cluster/MasterHarness.scala
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster
-
-import java.io.File
-import java.net.{InetSocketAddress, Socket, SocketTimeoutException, URLClassLoader, UnknownHostException}
-import java.util.Properties
-import java.util.concurrent.{Executors, TimeUnit}
-import scala.collection.JavaConverters._
-import scala.concurrent.duration.Duration
-import scala.concurrent.{Await, ExecutionContext}
-
-import akka.actor.{Actor, ActorSystem, Address, Props}
-import akka.testkit.TestProbe
-import com.typesafe.config.{Config, ConfigFactory, ConfigParseOptions, ConfigValueFactory}
-
-import io.gearpump.cluster.MasterHarness.MockMaster
-import io.gearpump.util.Constants._
-import io.gearpump.util.{ActorUtil, FileUtils, LogUtil}
-
-trait MasterHarness {
- private val LOG = LogUtil.getLogger(getClass)
-
- implicit val pool = MasterHarness.cachedPool
-
- private var system: ActorSystem = null
- private var systemAddress: Address = null
- private var host: String = null
- private var port: Int = 0
- private var masterProperties = new Properties()
- val PROCESS_BOOT_TIME = Duration(25, TimeUnit.SECONDS)
-
- def getActorSystem: ActorSystem = system
- def getHost: String = host
- def getPort: Int = port
-
- protected def config: Config
-
- def startActorSystem(): Unit = {
- val systemConfig = config
- system = ActorSystem(MASTER, systemConfig)
- systemAddress = ActorUtil.getSystemAddress(system)
- host = systemAddress.host.get
- port = systemAddress.port.get
-
- masterProperties.put(s"${GEARPUMP_CLUSTER_MASTERS}.0", s"$getHost:$getPort")
- masterProperties.put(s"${GEARPUMP_HOSTNAME}", s"$getHost")
-
- LOG.info(s"Actor system is started, $host, $port")
- }
-
- def shutdownActorSystem(): Unit = {
- system.terminate()
- Await.result(system.whenTerminated, Duration.Inf)
- LOG.info(s"Actor system is stopped, $host, $port")
- }
-
- def convertTestConf(host: String, port: Int): File = {
- val test = ConfigFactory.parseResourcesAnySyntax("test.conf",
- ConfigParseOptions.defaults.setAllowMissing(true))
-
- val newConf = test.withValue(GEARPUMP_CLUSTER_MASTERS,
- ConfigValueFactory.fromAnyRef(Array(s"$host:$port").toList.asJava))
-
- val confFile = File.createTempFile("main", ".conf")
- val serialized = newConf.root().render()
- FileUtils.write(confFile, serialized)
- confFile
- }
-
- def createMockMaster(): TestProbe = {
- val masterReceiver = TestProbe()(system)
- val master = system.actorOf(Props(classOf[MockMaster], masterReceiver), MASTER)
- masterReceiver
- }
-
- def isPortUsed(host: String, port: Int): Boolean = {
-
- var isPortUsed = true
- val socket = new Socket()
- try {
- socket.setReuseAddress(true)
- socket.connect(new InetSocketAddress(host, port), 1000)
- socket.isConnected
- } catch {
- case ex: SocketTimeoutException =>
- isPortUsed = false
- case ex: UnknownHostException =>
- isPortUsed = false
- case ex: Throwable =>
- // For other case, we think the port has been occupied.
- isPortUsed = true
- } finally {
- socket.close()
- }
- isPortUsed
- }
-
- def getContextClassPath: Array[String] = {
- val contextLoader = Thread.currentThread().getContextClassLoader()
-
- val urlLoader = if (!contextLoader.isInstanceOf[URLClassLoader]) {
- contextLoader.getParent.asInstanceOf[URLClassLoader]
- } else {
- contextLoader.asInstanceOf[URLClassLoader]
- }
-
- val urls = urlLoader.getURLs()
- val classPath = urls.map { url =>
- new File(url.getPath()).toString
- }
- classPath
- }
-
- /**
- * Remove trailing $
- */
- def getMainClassName(mainObj: Any): String = {
- mainObj.getClass.getName.dropRight(1)
- }
-
- def getMasterListOption(): Array[String] = {
- masterProperties.asScala.toList.map { kv =>
- s"-D${kv._1}=${kv._2}"
- }.toArray
- }
-
- def masterConfig: Config = {
- ConfigFactory.parseProperties(masterProperties).withFallback(system.settings.config)
- }
-}
-
-object MasterHarness {
-
- val cachedPool = ExecutionContext.fromExecutorService(Executors.newCachedThreadPool())
-
- class MockMaster(receiver: TestProbe) extends Actor {
- def receive: Receive = {
- case msg => {
- receiver.ref forward msg
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/core/src/test/scala/io/gearpump/cluster/TestUtil.scala
----------------------------------------------------------------------
diff --git a/core/src/test/scala/io/gearpump/cluster/TestUtil.scala b/core/src/test/scala/io/gearpump/cluster/TestUtil.scala
deleted file mode 100644
index dce4902..0000000
--- a/core/src/test/scala/io/gearpump/cluster/TestUtil.scala
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.cluster
-
-import akka.actor._
-
-object TestUtil {
- val DEFAULT_CONFIG = ClusterConfig.default("test.conf")
- val MASTER_CONFIG = ClusterConfig.master("test.conf")
- val UI_CONFIG = ClusterConfig.ui("test.conf")
-
- class DummyAppMaster(context: AppMasterContext, app: AppDescription) extends ApplicationMaster {
- context.masterProxy !(context, app)
-
- def receive: Receive = null
- }
-
- val dummyApp: AppDescription =
- AppDescription("dummy", classOf[DummyAppMaster].getName, UserConfig.empty)
-}
\ No newline at end of file
[32/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/fsio/src/main/scala/org/apache/gearpump/streaming/examples/fsio/SequenceFileIO.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/fsio/src/main/scala/org/apache/gearpump/streaming/examples/fsio/SequenceFileIO.scala b/examples/streaming/fsio/src/main/scala/org/apache/gearpump/streaming/examples/fsio/SequenceFileIO.scala
new file mode 100644
index 0000000..5c75904
--- /dev/null
+++ b/examples/streaming/fsio/src/main/scala/org/apache/gearpump/streaming/examples/fsio/SequenceFileIO.scala
@@ -0,0 +1,67 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.examples.fsio
+
+import org.apache.hadoop.conf.Configuration
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.cluster.client.ClientContext
+import org.apache.gearpump.cluster.main.{ArgumentsParser, CLIOption, ParseResult}
+import org.apache.gearpump.partitioner.ShufflePartitioner
+import org.apache.gearpump.streaming.examples.fsio.HadoopConfig._
+import org.apache.gearpump.streaming.{Processor, StreamApplication}
+import org.apache.gearpump.util.Graph._
+import org.apache.gearpump.util.{AkkaApp, Graph, LogUtil}
+
+object SequenceFileIO extends AkkaApp with ArgumentsParser {
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+
+ override val options: Array[(String, CLIOption[Any])] = Array(
+ "source" -> CLIOption[Int]("<sequence file reader number>", required = false,
+ defaultValue = Some(1)),
+ "sink" -> CLIOption[Int]("<sequence file writer number>", required = false,
+ defaultValue = Some(1)),
+ "input" -> CLIOption[String]("<input file path>", required = true),
+ "output" -> CLIOption[String]("<output file directory>", required = true)
+ )
+
+ def application(config: ParseResult): StreamApplication = {
+ val spoutNum = config.getInt("source")
+ val boltNum = config.getInt("sink")
+ val input = config.getString("input")
+ val output = config.getString("output")
+ val appConfig = UserConfig.empty.withString(SeqFileStreamProducer.INPUT_PATH, input)
+ .withString(SeqFileStreamProcessor.OUTPUT_PATH, output)
+ val hadoopConfig = appConfig.withHadoopConf(new Configuration())
+ val partitioner = new ShufflePartitioner()
+ val streamProducer = Processor[SeqFileStreamProducer](spoutNum)
+ val streamProcessor = Processor[SeqFileStreamProcessor](boltNum)
+
+ val app = StreamApplication("SequenceFileIO",
+ Graph(streamProducer ~ partitioner ~> streamProcessor), hadoopConfig)
+ app
+ }
+
+ override def main(akkaConf: Config, args: Array[String]): Unit = {
+ val config = parse(args)
+ val context = ClientContext(akkaConf)
+ val appId = context.submit(application(config))
+ context.close()
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/fsio/src/test/scala/io/gearpump/streaming/examples/fsio/HadoopConfigSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/fsio/src/test/scala/io/gearpump/streaming/examples/fsio/HadoopConfigSpec.scala b/examples/streaming/fsio/src/test/scala/io/gearpump/streaming/examples/fsio/HadoopConfigSpec.scala
deleted file mode 100644
index e5dbe0b..0000000
--- a/examples/streaming/fsio/src/test/scala/io/gearpump/streaming/examples/fsio/HadoopConfigSpec.scala
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.examples.fsio
-
-import org.apache.hadoop.conf.Configuration
-import org.scalatest.{Matchers, WordSpec}
-
-import io.gearpump.cluster.UserConfig
-
-class HadoopConfigSpec extends WordSpec with Matchers {
-
- "HadoopConfig" should {
- "serialize and deserialze hadoop configuration properly" in {
- val hadoopConf = new Configuration()
- val key = "test_key"
- val value = "test_value"
- hadoopConf.set(key, value)
-
- val user = UserConfig.empty
-
- import io.gearpump.streaming.examples.fsio.HadoopConfig._
- assert(user.withHadoopConf(hadoopConf).hadoopConf.get(key) == value)
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/fsio/src/test/scala/io/gearpump/streaming/examples/fsio/SeqFileStreamProcessorSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/fsio/src/test/scala/io/gearpump/streaming/examples/fsio/SeqFileStreamProcessorSpec.scala b/examples/streaming/fsio/src/test/scala/io/gearpump/streaming/examples/fsio/SeqFileStreamProcessorSpec.scala
deleted file mode 100644
index bb0d26b..0000000
--- a/examples/streaming/fsio/src/test/scala/io/gearpump/streaming/examples/fsio/SeqFileStreamProcessorSpec.scala
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.examples.fsio
-
-import java.io.File
-import scala.collection.mutable.ArrayBuffer
-
-import akka.actor.ActorSystem
-import akka.testkit.TestProbe
-import org.apache.hadoop.conf.Configuration
-import org.apache.hadoop.fs.{FileSystem, Path}
-import org.apache.hadoop.io.SequenceFile.Reader
-import org.apache.hadoop.io.{SequenceFile, Text}
-import org.mockito.Mockito._
-import org.scalacheck.Gen
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{BeforeAndAfter, Matchers, PropSpec}
-
-import io.gearpump.Message
-import io.gearpump.cluster.{TestUtil, UserConfig}
-import io.gearpump.streaming.task.{StartTime, TaskId}
-import io.gearpump.streaming.{MockUtil, Processor}
-class SeqFileStreamProcessorSpec
- extends PropSpec with PropertyChecks with Matchers with BeforeAndAfter {
-
- val kvPairs = new ArrayBuffer[(String, String)]
- val outputDirectory = "SeqFileStreamProcessor_Test"
- val sequenceFilePath = new Path(outputDirectory + File.separator + TaskId(0, 0))
- val hadoopConf = new Configuration()
- val fs = FileSystem.get(hadoopConf)
- val textClass = new Text().getClass
- val _key = new Text()
- val _value = new Text()
-
- val kvGenerator = for {
- key <- Gen.alphaStr
- value <- Gen.alphaStr
- } yield (key, value)
-
- before {
- implicit val system1 = ActorSystem("SeqFileStreamProcessor", TestUtil.DEFAULT_CONFIG)
- val system2 = ActorSystem("Reporter", TestUtil.DEFAULT_CONFIG)
- val watcher = TestProbe()(system1)
- val conf = HadoopConfig(UserConfig.empty.withString(SeqFileStreamProcessor.OUTPUT_PATH,
- outputDirectory)).withHadoopConf(new Configuration())
- val context = MockUtil.mockTaskContext
-
- val processorDescription =
- Processor.ProcessorToProcessorDescription(id = 0, Processor[SeqFileStreamProcessor](1))
-
- val taskId = TaskId(0, 0)
- when(context.taskId).thenReturn(taskId)
-
- val processor = new SeqFileStreamProcessor(context, conf)
- processor.onStart(StartTime(0))
-
- forAll(kvGenerator) { kv =>
- val (key, value) = kv
- kvPairs.append((key, value))
- processor.onNext(Message(key + "++" + value))
- }
- processor.onStop()
- }
-
- property("SeqFileStreamProcessor should write the key-value pairs to a sequence file") {
- val reader = new SequenceFile.Reader(hadoopConf, Reader.file(sequenceFilePath))
- kvPairs.foreach { kv =>
- val (key, value) = kv
- if (value.length > 0 && reader.next(_key, _value)) {
- assert(_key.toString == key && _value.toString == value)
- }
- }
- reader.close()
- }
-
- after {
- fs.deleteOnExit(new Path(outputDirectory))
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/fsio/src/test/scala/io/gearpump/streaming/examples/fsio/SeqFileStreamProducerSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/fsio/src/test/scala/io/gearpump/streaming/examples/fsio/SeqFileStreamProducerSpec.scala b/examples/streaming/fsio/src/test/scala/io/gearpump/streaming/examples/fsio/SeqFileStreamProducerSpec.scala
deleted file mode 100644
index 04dafa7..0000000
--- a/examples/streaming/fsio/src/test/scala/io/gearpump/streaming/examples/fsio/SeqFileStreamProducerSpec.scala
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.examples.fsio
-
-import scala.collection.mutable.ArrayBuffer
-
-import org.apache.hadoop.conf.Configuration
-import org.apache.hadoop.fs.{FileSystem, Path}
-import org.apache.hadoop.io.SequenceFile.Writer
-import org.apache.hadoop.io.{SequenceFile, Text}
-import org.mockito.Mockito._
-import org.scalacheck.Gen
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{BeforeAndAfter, Matchers, PropSpec}
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.MockUtil
-import io.gearpump.streaming.MockUtil._
-import io.gearpump.streaming.task.StartTime
-
-class SeqFileStreamProducerSpec
- extends PropSpec with PropertyChecks with Matchers with BeforeAndAfter {
-
- val kvPairs = new ArrayBuffer[(String, String)]
- val inputFile = "SeqFileStreamProducer_Test"
- val sequenceFilePath = new Path(inputFile)
- val hadoopConf = new Configuration()
- val fs = FileSystem.get(hadoopConf)
- val textClass = new Text().getClass
- val _key = new Text()
- val _value = new Text()
-
- val kvGenerator = for {
- key <- Gen.alphaStr
- value <- Gen.alphaStr
- } yield (key, value)
-
- before {
- fs.deleteOnExit(sequenceFilePath)
- val writer = SequenceFile.createWriter(hadoopConf, Writer.file(sequenceFilePath),
- Writer.keyClass(textClass), Writer.valueClass(textClass))
- forAll(kvGenerator) { kv =>
- _key.set(kv._1)
- _value.set(kv._2)
- kvPairs.append((kv._1, kv._2))
- writer.append(_key, _value)
- }
- writer.close()
- }
-
- property("SeqFileStreamProducer should read the key-value pairs from " +
- "a sequence file and deliver them") {
-
- val conf = HadoopConfig(UserConfig.empty.withString(SeqFileStreamProducer.INPUT_PATH,
- inputFile)).withHadoopConf(new Configuration())
-
- val context = MockUtil.mockTaskContext
-
- val producer = new SeqFileStreamProducer(context, conf)
- producer.onStart(StartTime(0))
- producer.onNext(Message("start"))
-
- val expected = kvPairs.map(kv => kv._1 + "++" + kv._2).toSet
- verify(context).output(argMatch[Message](msg =>
- expected.contains(msg.msg.asInstanceOf[String])))
- }
-
- after {
- fs.deleteOnExit(sequenceFilePath)
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/fsio/src/test/scala/io/gearpump/streaming/examples/fsio/SequenceFileIOSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/fsio/src/test/scala/io/gearpump/streaming/examples/fsio/SequenceFileIOSpec.scala b/examples/streaming/fsio/src/test/scala/io/gearpump/streaming/examples/fsio/SequenceFileIOSpec.scala
deleted file mode 100644
index efb5e44..0000000
--- a/examples/streaming/fsio/src/test/scala/io/gearpump/streaming/examples/fsio/SequenceFileIOSpec.scala
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.fsio
-
-import scala.concurrent.Future
-import scala.util.{Success, Try}
-
-import com.typesafe.config.Config
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{BeforeAndAfterAll, Matchers, PropSpec}
-
-import io.gearpump.cluster.ClientToMaster.SubmitApplication
-import io.gearpump.cluster.MasterToClient.SubmitApplicationResult
-import io.gearpump.cluster.{MasterHarness, TestUtil}
-
-class SequenceFileIOSpec
- extends PropSpec with PropertyChecks with Matchers with BeforeAndAfterAll with MasterHarness {
-
- override def beforeAll {
- startActorSystem()
- }
-
- override def afterAll {
- shutdownActorSystem()
- }
-
- override def config: Config = TestUtil.DEFAULT_CONFIG
-
- property("SequenceFileIO should succeed to submit application with required arguments") {
- val requiredArgs = Array(
- "-input", "/tmp/input",
- "-output", "/tmp/output"
- )
- val optionalArgs = Array(
- "-source", "1",
- "-sink", "1"
- )
- val validArgs = {
- Table(
- ("requiredArgs", "optionalArgs"),
- (requiredArgs, optionalArgs)
- )
- }
- val masterReceiver = createMockMaster()
- forAll(validArgs) { (requiredArgs: Array[String], optionalArgs: Array[String]) =>
- val args = requiredArgs ++ optionalArgs
-
- Future {
- SequenceFileIO.main(masterConfig, args)
- }
- masterReceiver.expectMsgType[SubmitApplication](PROCESS_BOOT_TIME)
- masterReceiver.reply(SubmitApplicationResult(Success(0)))
- }
-
- val invalidArgs = {
- Table(
- ("requiredArgs", "optionalArgs"),
- (requiredArgs.take(0), optionalArgs),
- (requiredArgs.take(2), optionalArgs)
- )
- }
- forAll(invalidArgs) { (requiredArgs: Array[String], optionalArgs: Array[String]) =>
- val args = optionalArgs
- assert(Try(SequenceFileIO.main(args)).isFailure, "missing required arguments, print usage")
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/fsio/src/test/scala/org/apache/gearpump/streaming/examples/fsio/HadoopConfigSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/fsio/src/test/scala/org/apache/gearpump/streaming/examples/fsio/HadoopConfigSpec.scala b/examples/streaming/fsio/src/test/scala/org/apache/gearpump/streaming/examples/fsio/HadoopConfigSpec.scala
new file mode 100644
index 0000000..cf1bea8
--- /dev/null
+++ b/examples/streaming/fsio/src/test/scala/org/apache/gearpump/streaming/examples/fsio/HadoopConfigSpec.scala
@@ -0,0 +1,40 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.examples.fsio
+
+import org.apache.hadoop.conf.Configuration
+import org.scalatest.{Matchers, WordSpec}
+
+import org.apache.gearpump.cluster.UserConfig
+
+class HadoopConfigSpec extends WordSpec with Matchers {
+
+ "HadoopConfig" should {
+ "serialize and deserialze hadoop configuration properly" in {
+ val hadoopConf = new Configuration()
+ val key = "test_key"
+ val value = "test_value"
+ hadoopConf.set(key, value)
+
+ val user = UserConfig.empty
+
+ import org.apache.gearpump.streaming.examples.fsio.HadoopConfig._
+ assert(user.withHadoopConf(hadoopConf).hadoopConf.get(key) == value)
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/fsio/src/test/scala/org/apache/gearpump/streaming/examples/fsio/SeqFileStreamProcessorSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/fsio/src/test/scala/org/apache/gearpump/streaming/examples/fsio/SeqFileStreamProcessorSpec.scala b/examples/streaming/fsio/src/test/scala/org/apache/gearpump/streaming/examples/fsio/SeqFileStreamProcessorSpec.scala
new file mode 100644
index 0000000..7831b14
--- /dev/null
+++ b/examples/streaming/fsio/src/test/scala/org/apache/gearpump/streaming/examples/fsio/SeqFileStreamProcessorSpec.scala
@@ -0,0 +1,94 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.examples.fsio
+
+import java.io.File
+import scala.collection.mutable.ArrayBuffer
+
+import akka.actor.ActorSystem
+import akka.testkit.TestProbe
+import org.apache.hadoop.conf.Configuration
+import org.apache.hadoop.fs.{FileSystem, Path}
+import org.apache.hadoop.io.SequenceFile.Reader
+import org.apache.hadoop.io.{SequenceFile, Text}
+import org.mockito.Mockito._
+import org.scalacheck.Gen
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{BeforeAndAfter, Matchers, PropSpec}
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.{TestUtil, UserConfig}
+import org.apache.gearpump.streaming.task.{StartTime, TaskId}
+import org.apache.gearpump.streaming.{MockUtil, Processor}
+class SeqFileStreamProcessorSpec
+ extends PropSpec with PropertyChecks with Matchers with BeforeAndAfter {
+
+ val kvPairs = new ArrayBuffer[(String, String)]
+ val outputDirectory = "SeqFileStreamProcessor_Test"
+ val sequenceFilePath = new Path(outputDirectory + File.separator + TaskId(0, 0))
+ val hadoopConf = new Configuration()
+ val fs = FileSystem.get(hadoopConf)
+ val textClass = new Text().getClass
+ val _key = new Text()
+ val _value = new Text()
+
+ val kvGenerator = for {
+ key <- Gen.alphaStr
+ value <- Gen.alphaStr
+ } yield (key, value)
+
+ before {
+ implicit val system1 = ActorSystem("SeqFileStreamProcessor", TestUtil.DEFAULT_CONFIG)
+ val system2 = ActorSystem("Reporter", TestUtil.DEFAULT_CONFIG)
+ val watcher = TestProbe()(system1)
+ val conf = HadoopConfig(UserConfig.empty.withString(SeqFileStreamProcessor.OUTPUT_PATH,
+ outputDirectory)).withHadoopConf(new Configuration())
+ val context = MockUtil.mockTaskContext
+
+ val processorDescription =
+ Processor.ProcessorToProcessorDescription(id = 0, Processor[SeqFileStreamProcessor](1))
+
+ val taskId = TaskId(0, 0)
+ when(context.taskId).thenReturn(taskId)
+
+ val processor = new SeqFileStreamProcessor(context, conf)
+ processor.onStart(StartTime(0))
+
+ forAll(kvGenerator) { kv =>
+ val (key, value) = kv
+ kvPairs.append((key, value))
+ processor.onNext(Message(key + "++" + value))
+ }
+ processor.onStop()
+ }
+
+ property("SeqFileStreamProcessor should write the key-value pairs to a sequence file") {
+ val reader = new SequenceFile.Reader(hadoopConf, Reader.file(sequenceFilePath))
+ kvPairs.foreach { kv =>
+ val (key, value) = kv
+ if (value.length > 0 && reader.next(_key, _value)) {
+ assert(_key.toString == key && _value.toString == value)
+ }
+ }
+ reader.close()
+ }
+
+ after {
+ fs.deleteOnExit(new Path(outputDirectory))
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/fsio/src/test/scala/org/apache/gearpump/streaming/examples/fsio/SeqFileStreamProducerSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/fsio/src/test/scala/org/apache/gearpump/streaming/examples/fsio/SeqFileStreamProducerSpec.scala b/examples/streaming/fsio/src/test/scala/org/apache/gearpump/streaming/examples/fsio/SeqFileStreamProducerSpec.scala
new file mode 100644
index 0000000..ad27e63
--- /dev/null
+++ b/examples/streaming/fsio/src/test/scala/org/apache/gearpump/streaming/examples/fsio/SeqFileStreamProducerSpec.scala
@@ -0,0 +1,87 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.examples.fsio
+
+import scala.collection.mutable.ArrayBuffer
+
+import org.apache.hadoop.conf.Configuration
+import org.apache.hadoop.fs.{FileSystem, Path}
+import org.apache.hadoop.io.SequenceFile.Writer
+import org.apache.hadoop.io.{SequenceFile, Text}
+import org.mockito.Mockito._
+import org.scalacheck.Gen
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{BeforeAndAfter, Matchers, PropSpec}
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.MockUtil
+import org.apache.gearpump.streaming.MockUtil._
+import org.apache.gearpump.streaming.task.StartTime
+
+class SeqFileStreamProducerSpec
+ extends PropSpec with PropertyChecks with Matchers with BeforeAndAfter {
+
+ val kvPairs = new ArrayBuffer[(String, String)]
+ val inputFile = "SeqFileStreamProducer_Test"
+ val sequenceFilePath = new Path(inputFile)
+ val hadoopConf = new Configuration()
+ val fs = FileSystem.get(hadoopConf)
+ val textClass = new Text().getClass
+ val _key = new Text()
+ val _value = new Text()
+
+ val kvGenerator = for {
+ key <- Gen.alphaStr
+ value <- Gen.alphaStr
+ } yield (key, value)
+
+ before {
+ fs.deleteOnExit(sequenceFilePath)
+ val writer = SequenceFile.createWriter(hadoopConf, Writer.file(sequenceFilePath),
+ Writer.keyClass(textClass), Writer.valueClass(textClass))
+ forAll(kvGenerator) { kv =>
+ _key.set(kv._1)
+ _value.set(kv._2)
+ kvPairs.append((kv._1, kv._2))
+ writer.append(_key, _value)
+ }
+ writer.close()
+ }
+
+ property("SeqFileStreamProducer should read the key-value pairs from " +
+ "a sequence file and deliver them") {
+
+ val conf = HadoopConfig(UserConfig.empty.withString(SeqFileStreamProducer.INPUT_PATH,
+ inputFile)).withHadoopConf(new Configuration())
+
+ val context = MockUtil.mockTaskContext
+
+ val producer = new SeqFileStreamProducer(context, conf)
+ producer.onStart(StartTime(0))
+ producer.onNext(Message("start"))
+
+ val expected = kvPairs.map(kv => kv._1 + "++" + kv._2).toSet
+ verify(context).output(argMatch[Message](msg =>
+ expected.contains(msg.msg.asInstanceOf[String])))
+ }
+
+ after {
+ fs.deleteOnExit(sequenceFilePath)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/fsio/src/test/scala/org/apache/gearpump/streaming/examples/fsio/SequenceFileIOSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/fsio/src/test/scala/org/apache/gearpump/streaming/examples/fsio/SequenceFileIOSpec.scala b/examples/streaming/fsio/src/test/scala/org/apache/gearpump/streaming/examples/fsio/SequenceFileIOSpec.scala
new file mode 100644
index 0000000..ba65802
--- /dev/null
+++ b/examples/streaming/fsio/src/test/scala/org/apache/gearpump/streaming/examples/fsio/SequenceFileIOSpec.scala
@@ -0,0 +1,83 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.fsio
+
+import scala.concurrent.Future
+import scala.util.{Success, Try}
+
+import com.typesafe.config.Config
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{BeforeAndAfterAll, Matchers, PropSpec}
+
+import org.apache.gearpump.cluster.ClientToMaster.SubmitApplication
+import org.apache.gearpump.cluster.MasterToClient.SubmitApplicationResult
+import org.apache.gearpump.cluster.{MasterHarness, TestUtil}
+
+class SequenceFileIOSpec
+ extends PropSpec with PropertyChecks with Matchers with BeforeAndAfterAll with MasterHarness {
+
+ override def beforeAll {
+ startActorSystem()
+ }
+
+ override def afterAll {
+ shutdownActorSystem()
+ }
+
+ override def config: Config = TestUtil.DEFAULT_CONFIG
+
+ property("SequenceFileIO should succeed to submit application with required arguments") {
+ val requiredArgs = Array(
+ "-input", "/tmp/input",
+ "-output", "/tmp/output"
+ )
+ val optionalArgs = Array(
+ "-source", "1",
+ "-sink", "1"
+ )
+ val validArgs = {
+ Table(
+ ("requiredArgs", "optionalArgs"),
+ (requiredArgs, optionalArgs)
+ )
+ }
+ val masterReceiver = createMockMaster()
+ forAll(validArgs) { (requiredArgs: Array[String], optionalArgs: Array[String]) =>
+ val args = requiredArgs ++ optionalArgs
+
+ Future {
+ SequenceFileIO.main(masterConfig, args)
+ }
+ masterReceiver.expectMsgType[SubmitApplication](PROCESS_BOOT_TIME)
+ masterReceiver.reply(SubmitApplicationResult(Success(0)))
+ }
+
+ val invalidArgs = {
+ Table(
+ ("requiredArgs", "optionalArgs"),
+ (requiredArgs.take(0), optionalArgs),
+ (requiredArgs.take(2), optionalArgs)
+ )
+ }
+ forAll(invalidArgs) { (requiredArgs: Array[String], optionalArgs: Array[String]) =>
+ val args = optionalArgs
+ assert(Try(SequenceFileIO.main(args)).isFailure, "missing required arguments, print usage")
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/kafka/README.md
----------------------------------------------------------------------
diff --git a/examples/streaming/kafka/README.md b/examples/streaming/kafka/README.md
index bac7101..587271c 100644
--- a/examples/streaming/kafka/README.md
+++ b/examples/streaming/kafka/README.md
@@ -81,7 +81,7 @@ Change directory into gearpump root, build gearpump with `sbt pack` and launch a
Finally, let's run the KafkaWordCount example.
```bash
- ./target/pack/bin/gear app -jar ./examples/target/$SCALA_VERSION_MAJOR/gearpump-examples-assembly-$VERSION.jar io.gearpump.streaming.examples.kafka.wordcount.KafkaWordCount
+ ./target/pack/bin/gear app -jar ./examples/target/$SCALA_VERSION_MAJOR/gearpump-examples-assembly-$VERSION.jar org.apache.gearpump.streaming.examples.kafka.wordcount.KafkaWordCount
```
One more step is to verify that we've succeeded in producing data to Kafka.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/kafka/src/main/scala/io/gearpump/streaming/examples/kafka/KafkaReadWrite.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/kafka/src/main/scala/io/gearpump/streaming/examples/kafka/KafkaReadWrite.scala b/examples/streaming/kafka/src/main/scala/io/gearpump/streaming/examples/kafka/KafkaReadWrite.scala
deleted file mode 100644
index 35b6594..0000000
--- a/examples/streaming/kafka/src/main/scala/io/gearpump/streaming/examples/kafka/KafkaReadWrite.scala
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.kafka
-
-import akka.actor.ActorSystem
-import org.slf4j.Logger
-
-import io.gearpump.cluster.UserConfig
-import io.gearpump.cluster.client.ClientContext
-import io.gearpump.cluster.main.{ArgumentsParser, CLIOption, ParseResult}
-import io.gearpump.partitioner.ShufflePartitioner
-import io.gearpump.streaming.StreamApplication
-import io.gearpump.streaming.kafka.{KafkaSink, KafkaSource, KafkaStorageFactory}
-import io.gearpump.streaming.sink.DataSinkProcessor
-import io.gearpump.streaming.source.DataSourceProcessor
-import io.gearpump.util.Graph._
-import io.gearpump.util.{AkkaApp, Graph, LogUtil}
-
-object KafkaReadWrite extends AkkaApp with ArgumentsParser {
- private val LOG: Logger = LogUtil.getLogger(getClass)
-
- override val options: Array[(String, CLIOption[Any])] = Array(
- "source" -> CLIOption[Int]("<hom many kafka producer tasks>", required = false,
- defaultValue = Some(1)),
- "sink" -> CLIOption[Int]("<hom many kafka processor tasks>", required = false,
- defaultValue = Some(1)),
- "zookeeperConnect" -> CLIOption[String]("<zookeeper connect string>", required = false,
- defaultValue = Some("localhost:2181")),
- "brokerList" -> CLIOption[String]("<broker server list string>", required = false,
- defaultValue = Some("localhost:9092")),
- "sourceTopic" -> CLIOption[String]("<kafka source topic>", required = false,
- defaultValue = Some("topic1")),
- "sinkTopic" -> CLIOption[String]("<kafka sink topic>", required = false,
- defaultValue = Some("topic2"))
- )
-
- def application(config: ParseResult, system: ActorSystem): StreamApplication = {
- implicit val actorSystem = system
- val sourceNum = config.getInt("source")
- val sinkNum = config.getInt("sink")
- val zookeeperConnect = config.getString("zookeeperConnect")
- val brokerList = config.getString("brokerList")
- val sourceTopic = config.getString("sourceTopic")
- val sinkTopic = config.getString("sinkTopic")
-
- val appConfig = UserConfig.empty
- val offsetStorageFactory = new KafkaStorageFactory(zookeeperConnect, brokerList)
- val source = new KafkaSource(sourceTopic, zookeeperConnect, offsetStorageFactory)
- val sourceProcessor = DataSourceProcessor(source, sourceNum)
- val sink = new KafkaSink(sinkTopic, brokerList)
- val sinkProcessor = DataSinkProcessor(sink, sinkNum)
- val partitioner = new ShufflePartitioner
- val computation = sourceProcessor ~ partitioner ~> sinkProcessor
- val app = StreamApplication("KafkaReadWrite", Graph(computation), appConfig)
- app
- }
-
- override def main(akkaConf: Config, args: Array[String]): Unit = {
- val config = parse(args)
- val context = ClientContext(akkaConf)
- val appId = context.submit(application(config, context.system))
- context.close()
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/kafka/src/main/scala/io/gearpump/streaming/examples/kafka/wordcount/KafkaWordCount.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/kafka/src/main/scala/io/gearpump/streaming/examples/kafka/wordcount/KafkaWordCount.scala b/examples/streaming/kafka/src/main/scala/io/gearpump/streaming/examples/kafka/wordcount/KafkaWordCount.scala
deleted file mode 100644
index 6955bcc..0000000
--- a/examples/streaming/kafka/src/main/scala/io/gearpump/streaming/examples/kafka/wordcount/KafkaWordCount.scala
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.kafka.wordcount
-
-import akka.actor.ActorSystem
-import kafka.api.OffsetRequest
-import org.slf4j.Logger
-
-import io.gearpump.cluster.UserConfig
-import io.gearpump.cluster.client.ClientContext
-import io.gearpump.cluster.main.{ArgumentsParser, CLIOption, ParseResult}
-import io.gearpump.partitioner.HashPartitioner
-import io.gearpump.streaming.kafka.lib.KafkaSourceConfig
-import io.gearpump.streaming.kafka.{KafkaSink, KafkaSource, KafkaStorageFactory}
-import io.gearpump.streaming.sink.DataSinkProcessor
-import io.gearpump.streaming.source.DataSourceProcessor
-import io.gearpump.streaming.{Processor, StreamApplication}
-import io.gearpump.util.Graph._
-import io.gearpump.util.{AkkaApp, Graph, LogUtil}
-
-object KafkaWordCount extends AkkaApp with ArgumentsParser {
- private val LOG: Logger = LogUtil.getLogger(getClass)
-
- override val options: Array[(String, CLIOption[Any])] = Array(
- "source" -> CLIOption[Int]("<how many kafka source tasks>", required = false,
- defaultValue = Some(1)),
- "split" -> CLIOption[Int]("<how many split tasks>", required = false, defaultValue = Some(1)),
- "sum" -> CLIOption[Int]("<how many sum tasks>", required = false, defaultValue = Some(1)),
- "sink" -> CLIOption[Int]("<how many kafka sink tasks>", required = false,
- defaultValue = Some(1))
- )
-
- def application(config: ParseResult, system: ActorSystem): StreamApplication = {
- implicit val actorSystem = system
- val sourceNum = config.getInt("source")
- val splitNum = config.getInt("split")
- val sumNum = config.getInt("sum")
- val sinkNum = config.getInt("sink")
-
- val appConfig = UserConfig.empty
- val offsetStorageFactory = new KafkaStorageFactory("localhost:2181", "localhost:9092")
- val kafkaSourceConfig = new KafkaSourceConfig()
- .withConsumerTopics("topic1").withConsumerStartOffset(OffsetRequest.LatestTime)
- val source = new KafkaSource(kafkaSourceConfig, offsetStorageFactory)
- val sourceProcessor = DataSourceProcessor(source, sourceNum)
- val split = Processor[Split](splitNum)
- val sum = Processor[Sum](sumNum)
- val sink = new KafkaSink("topic2", "localhost:9092")
- val sinkProcessor = DataSinkProcessor(sink, sinkNum)
- val partitioner = new HashPartitioner
- val computation = sourceProcessor ~ partitioner ~> split ~ partitioner ~>
- sum ~ partitioner ~> sinkProcessor
- val app = StreamApplication("KafkaWordCount", Graph(computation), appConfig)
- app
- }
-
- override def main(akkaConf: Config, args: Array[String]): Unit = {
- val config = parse(args)
- val context = ClientContext(akkaConf)
- val appId = context.submit(application(config, context.system))
- context.close()
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/kafka/src/main/scala/io/gearpump/streaming/examples/kafka/wordcount/Split.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/kafka/src/main/scala/io/gearpump/streaming/examples/kafka/wordcount/Split.scala b/examples/streaming/kafka/src/main/scala/io/gearpump/streaming/examples/kafka/wordcount/Split.scala
deleted file mode 100644
index b46d170..0000000
--- a/examples/streaming/kafka/src/main/scala/io/gearpump/streaming/examples/kafka/wordcount/Split.scala
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.kafka.wordcount
-
-import com.twitter.bijection.Injection
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.task.{StartTime, Task, TaskContext}
-
-class Split(taskContext: TaskContext, conf: UserConfig) extends Task(taskContext, conf) {
- import taskContext.output
-
- override def onStart(startTime: StartTime): Unit = {
- }
-
- override def onNext(msg: Message): Unit = {
- Injection.invert[String, Array[Byte]](msg.msg.asInstanceOf[Array[Byte]])
- .foreach(_.split("\\s+").foreach(
- word => output(new Message(word, msg.timestamp))))
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/kafka/src/main/scala/io/gearpump/streaming/examples/kafka/wordcount/Sum.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/kafka/src/main/scala/io/gearpump/streaming/examples/kafka/wordcount/Sum.scala b/examples/streaming/kafka/src/main/scala/io/gearpump/streaming/examples/kafka/wordcount/Sum.scala
deleted file mode 100644
index 9c67733..0000000
--- a/examples/streaming/kafka/src/main/scala/io/gearpump/streaming/examples/kafka/wordcount/Sum.scala
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.kafka.wordcount
-
-import com.twitter.bijection.Injection
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.task.{StartTime, Task, TaskContext}
-
-class Sum(taskContext: TaskContext, conf: UserConfig) extends Task(taskContext, conf) {
- import taskContext.output
-
- private[wordcount] var wordcount = Map.empty[String, Long]
-
- override def onStart(startTime: StartTime): Unit = {}
-
- override def onNext(message: Message): Unit = {
- val word = message.msg.asInstanceOf[String]
- val count = wordcount.getOrElse(word, 0L) + 1
- wordcount += word -> count
- output(new Message(
- Injection[String, Array[Byte]](word) ->
- Injection[Long, Array[Byte]](count),
- message.timestamp))
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/kafka/src/main/scala/org/apache/gearpump/streaming/examples/kafka/KafkaReadWrite.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/kafka/src/main/scala/org/apache/gearpump/streaming/examples/kafka/KafkaReadWrite.scala b/examples/streaming/kafka/src/main/scala/org/apache/gearpump/streaming/examples/kafka/KafkaReadWrite.scala
new file mode 100644
index 0000000..364544b
--- /dev/null
+++ b/examples/streaming/kafka/src/main/scala/org/apache/gearpump/streaming/examples/kafka/KafkaReadWrite.scala
@@ -0,0 +1,80 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.kafka
+
+import akka.actor.ActorSystem
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.cluster.client.ClientContext
+import org.apache.gearpump.cluster.main.{ArgumentsParser, CLIOption, ParseResult}
+import org.apache.gearpump.partitioner.ShufflePartitioner
+import org.apache.gearpump.streaming.StreamApplication
+import org.apache.gearpump.streaming.kafka.{KafkaSink, KafkaSource, KafkaStorageFactory}
+import org.apache.gearpump.streaming.sink.DataSinkProcessor
+import org.apache.gearpump.streaming.source.DataSourceProcessor
+import org.apache.gearpump.util.Graph._
+import org.apache.gearpump.util.{AkkaApp, Graph, LogUtil}
+
+object KafkaReadWrite extends AkkaApp with ArgumentsParser {
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+
+ override val options: Array[(String, CLIOption[Any])] = Array(
+ "source" -> CLIOption[Int]("<hom many kafka producer tasks>", required = false,
+ defaultValue = Some(1)),
+ "sink" -> CLIOption[Int]("<hom many kafka processor tasks>", required = false,
+ defaultValue = Some(1)),
+ "zookeeperConnect" -> CLIOption[String]("<zookeeper connect string>", required = false,
+ defaultValue = Some("localhost:2181")),
+ "brokerList" -> CLIOption[String]("<broker server list string>", required = false,
+ defaultValue = Some("localhost:9092")),
+ "sourceTopic" -> CLIOption[String]("<kafka source topic>", required = false,
+ defaultValue = Some("topic1")),
+ "sinkTopic" -> CLIOption[String]("<kafka sink topic>", required = false,
+ defaultValue = Some("topic2"))
+ )
+
+ def application(config: ParseResult, system: ActorSystem): StreamApplication = {
+ implicit val actorSystem = system
+ val sourceNum = config.getInt("source")
+ val sinkNum = config.getInt("sink")
+ val zookeeperConnect = config.getString("zookeeperConnect")
+ val brokerList = config.getString("brokerList")
+ val sourceTopic = config.getString("sourceTopic")
+ val sinkTopic = config.getString("sinkTopic")
+
+ val appConfig = UserConfig.empty
+ val offsetStorageFactory = new KafkaStorageFactory(zookeeperConnect, brokerList)
+ val source = new KafkaSource(sourceTopic, zookeeperConnect, offsetStorageFactory)
+ val sourceProcessor = DataSourceProcessor(source, sourceNum)
+ val sink = new KafkaSink(sinkTopic, brokerList)
+ val sinkProcessor = DataSinkProcessor(sink, sinkNum)
+ val partitioner = new ShufflePartitioner
+ val computation = sourceProcessor ~ partitioner ~> sinkProcessor
+ val app = StreamApplication("KafkaReadWrite", Graph(computation), appConfig)
+ app
+ }
+
+ override def main(akkaConf: Config, args: Array[String]): Unit = {
+ val config = parse(args)
+ val context = ClientContext(akkaConf)
+ val appId = context.submit(application(config, context.system))
+ context.close()
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/kafka/src/main/scala/org/apache/gearpump/streaming/examples/kafka/wordcount/KafkaWordCount.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/kafka/src/main/scala/org/apache/gearpump/streaming/examples/kafka/wordcount/KafkaWordCount.scala b/examples/streaming/kafka/src/main/scala/org/apache/gearpump/streaming/examples/kafka/wordcount/KafkaWordCount.scala
new file mode 100644
index 0000000..5ef1e67
--- /dev/null
+++ b/examples/streaming/kafka/src/main/scala/org/apache/gearpump/streaming/examples/kafka/wordcount/KafkaWordCount.scala
@@ -0,0 +1,79 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.kafka.wordcount
+
+import akka.actor.ActorSystem
+import kafka.api.OffsetRequest
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.cluster.client.ClientContext
+import org.apache.gearpump.cluster.main.{ArgumentsParser, CLIOption, ParseResult}
+import org.apache.gearpump.partitioner.HashPartitioner
+import org.apache.gearpump.streaming.kafka.lib.KafkaSourceConfig
+import org.apache.gearpump.streaming.kafka.{KafkaSink, KafkaSource, KafkaStorageFactory}
+import org.apache.gearpump.streaming.sink.DataSinkProcessor
+import org.apache.gearpump.streaming.source.DataSourceProcessor
+import org.apache.gearpump.streaming.{Processor, StreamApplication}
+import org.apache.gearpump.util.Graph._
+import org.apache.gearpump.util.{AkkaApp, Graph, LogUtil}
+
+object KafkaWordCount extends AkkaApp with ArgumentsParser {
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+
+ override val options: Array[(String, CLIOption[Any])] = Array(
+ "source" -> CLIOption[Int]("<how many kafka source tasks>", required = false,
+ defaultValue = Some(1)),
+ "split" -> CLIOption[Int]("<how many split tasks>", required = false, defaultValue = Some(1)),
+ "sum" -> CLIOption[Int]("<how many sum tasks>", required = false, defaultValue = Some(1)),
+ "sink" -> CLIOption[Int]("<how many kafka sink tasks>", required = false,
+ defaultValue = Some(1))
+ )
+
+ def application(config: ParseResult, system: ActorSystem): StreamApplication = {
+ implicit val actorSystem = system
+ val sourceNum = config.getInt("source")
+ val splitNum = config.getInt("split")
+ val sumNum = config.getInt("sum")
+ val sinkNum = config.getInt("sink")
+
+ val appConfig = UserConfig.empty
+ val offsetStorageFactory = new KafkaStorageFactory("localhost:2181", "localhost:9092")
+ val kafkaSourceConfig = new KafkaSourceConfig()
+ .withConsumerTopics("topic1").withConsumerStartOffset(OffsetRequest.LatestTime)
+ val source = new KafkaSource(kafkaSourceConfig, offsetStorageFactory)
+ val sourceProcessor = DataSourceProcessor(source, sourceNum)
+ val split = Processor[Split](splitNum)
+ val sum = Processor[Sum](sumNum)
+ val sink = new KafkaSink("topic2", "localhost:9092")
+ val sinkProcessor = DataSinkProcessor(sink, sinkNum)
+ val partitioner = new HashPartitioner
+ val computation = sourceProcessor ~ partitioner ~> split ~ partitioner ~>
+ sum ~ partitioner ~> sinkProcessor
+ val app = StreamApplication("KafkaWordCount", Graph(computation), appConfig)
+ app
+ }
+
+ override def main(akkaConf: Config, args: Array[String]): Unit = {
+ val config = parse(args)
+ val context = ClientContext(akkaConf)
+ val appId = context.submit(application(config, context.system))
+ context.close()
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/kafka/src/main/scala/org/apache/gearpump/streaming/examples/kafka/wordcount/Split.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/kafka/src/main/scala/org/apache/gearpump/streaming/examples/kafka/wordcount/Split.scala b/examples/streaming/kafka/src/main/scala/org/apache/gearpump/streaming/examples/kafka/wordcount/Split.scala
new file mode 100644
index 0000000..a95f596
--- /dev/null
+++ b/examples/streaming/kafka/src/main/scala/org/apache/gearpump/streaming/examples/kafka/wordcount/Split.scala
@@ -0,0 +1,38 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.kafka.wordcount
+
+import com.twitter.bijection.Injection
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.task.{StartTime, Task, TaskContext}
+
+class Split(taskContext: TaskContext, conf: UserConfig) extends Task(taskContext, conf) {
+ import taskContext.output
+
+ override def onStart(startTime: StartTime): Unit = {
+ }
+
+ override def onNext(msg: Message): Unit = {
+ Injection.invert[String, Array[Byte]](msg.msg.asInstanceOf[Array[Byte]])
+ .foreach(_.split("\\s+").foreach(
+ word => output(new Message(word, msg.timestamp))))
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/kafka/src/main/scala/org/apache/gearpump/streaming/examples/kafka/wordcount/Sum.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/kafka/src/main/scala/org/apache/gearpump/streaming/examples/kafka/wordcount/Sum.scala b/examples/streaming/kafka/src/main/scala/org/apache/gearpump/streaming/examples/kafka/wordcount/Sum.scala
new file mode 100644
index 0000000..9930b92
--- /dev/null
+++ b/examples/streaming/kafka/src/main/scala/org/apache/gearpump/streaming/examples/kafka/wordcount/Sum.scala
@@ -0,0 +1,43 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.kafka.wordcount
+
+import com.twitter.bijection.Injection
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.task.{StartTime, Task, TaskContext}
+
+class Sum(taskContext: TaskContext, conf: UserConfig) extends Task(taskContext, conf) {
+ import taskContext.output
+
+ private[wordcount] var wordcount = Map.empty[String, Long]
+
+ override def onStart(startTime: StartTime): Unit = {}
+
+ override def onNext(message: Message): Unit = {
+ val word = message.msg.asInstanceOf[String]
+ val count = wordcount.getOrElse(word, 0L) + 1
+ wordcount += word -> count
+ output(new Message(
+ Injection[String, Array[Byte]](word) ->
+ Injection[Long, Array[Byte]](count),
+ message.timestamp))
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/kafka/src/test/scala/io/gearpump/streaming/examples/kafka/wordcount/KafkaWordCountSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/kafka/src/test/scala/io/gearpump/streaming/examples/kafka/wordcount/KafkaWordCountSpec.scala b/examples/streaming/kafka/src/test/scala/io/gearpump/streaming/examples/kafka/wordcount/KafkaWordCountSpec.scala
deleted file mode 100644
index 35f7a62..0000000
--- a/examples/streaming/kafka/src/test/scala/io/gearpump/streaming/examples/kafka/wordcount/KafkaWordCountSpec.scala
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.kafka.wordcount
-
-import scala.concurrent.Future
-import scala.util.Success
-
-import com.typesafe.config.Config
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{BeforeAndAfter, Matchers, PropSpec}
-
-import io.gearpump.cluster.ClientToMaster.SubmitApplication
-import io.gearpump.cluster.MasterToClient.SubmitApplicationResult
-import io.gearpump.cluster.{MasterHarness, TestUtil}
-
-class KafkaWordCountSpec
- extends PropSpec with PropertyChecks with Matchers with BeforeAndAfter with MasterHarness {
-
- before {
- startActorSystem()
- }
-
- after {
- shutdownActorSystem()
- }
-
- override def config: Config = TestUtil.DEFAULT_CONFIG
-
- property("KafkaWordCount should succeed to submit application with required arguments") {
- val requiredArgs = Array.empty[String]
- val optionalArgs = Array(
- "-source", "1",
- "-split", "1",
- "-sum", "1",
- "-sink", "1")
-
- val args = {
- Table(
- ("requiredArgs", "optionalArgs"),
- (requiredArgs, optionalArgs)
- )
- }
- val masterReceiver = createMockMaster()
- forAll(args) { (requiredArgs: Array[String], optionalArgs: Array[String]) =>
- val args = requiredArgs ++ optionalArgs
-
- Future {
- KafkaWordCount.main(masterConfig, args)
- }
-
- masterReceiver.expectMsgType[SubmitApplication](PROCESS_BOOT_TIME)
- masterReceiver.reply(SubmitApplicationResult(Success(0)))
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/kafka/src/test/scala/io/gearpump/streaming/examples/kafka/wordcount/SplitSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/kafka/src/test/scala/io/gearpump/streaming/examples/kafka/wordcount/SplitSpec.scala b/examples/streaming/kafka/src/test/scala/io/gearpump/streaming/examples/kafka/wordcount/SplitSpec.scala
deleted file mode 100644
index 2cc6a16..0000000
--- a/examples/streaming/kafka/src/test/scala/io/gearpump/streaming/examples/kafka/wordcount/SplitSpec.scala
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.examples.kafka.wordcount
-
-import com.twitter.bijection.Injection
-import org.mockito.Matchers._
-import org.mockito.Mockito._
-import org.scalatest._
-import org.scalatest.mock.MockitoSugar
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.task.TaskContext
-
-class SplitSpec extends FlatSpec with Matchers with MockitoSugar {
-
- it should "split should split the text and deliver to next task" in {
- val taskContext = mock[TaskContext]
- val split = new Split(taskContext, UserConfig.empty)
-
- val msg = "this is a test message"
- split.onNext(Message(Injection[String, Array[Byte]](msg)))
- verify(taskContext, times(msg.split(" ").length)).output(anyObject[Message])
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/kafka/src/test/scala/io/gearpump/streaming/examples/kafka/wordcount/SumSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/kafka/src/test/scala/io/gearpump/streaming/examples/kafka/wordcount/SumSpec.scala b/examples/streaming/kafka/src/test/scala/io/gearpump/streaming/examples/kafka/wordcount/SumSpec.scala
deleted file mode 100644
index 4dcb9d7..0000000
--- a/examples/streaming/kafka/src/test/scala/io/gearpump/streaming/examples/kafka/wordcount/SumSpec.scala
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * 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.
- */
-package io.gearpump.streaming.examples.kafka.wordcount
-
-import scala.collection.mutable
-
-import org.mockito.Matchers._
-import org.mockito.Mockito._
-import org.scalacheck.Gen
-import org.scalatest.{FlatSpec, Matchers}
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.MockUtil
-import io.gearpump.streaming.task.StartTime
-
-class SumSpec extends FlatSpec with Matchers {
-
- it should "sum should calculate the frequency of the word correctly" in {
-
- val stringGenerator = Gen.alphaStr
- val expectedWordCountMap: mutable.HashMap[String, Long] = new mutable.HashMap[String, Long]()
-
- val taskContext = MockUtil.mockTaskContext
-
- val sum = new Sum(taskContext, UserConfig.empty)
- sum.onStart(StartTime(0))
- val str = "once two two three three three"
-
- var totalWordCount = 0
- stringGenerator.map { word =>
- totalWordCount += 1
- expectedWordCountMap.put(word, expectedWordCountMap.getOrElse(word, 0L) + 1)
- sum.onNext(Message(word))
- }
- verify(taskContext, times(totalWordCount)).output(anyObject[Message])
-
- expectedWordCountMap.foreach { wordCount =>
- val (word, count) = wordCount
- assert(count == sum.wordcount.get(word).get)
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/kafka/src/test/scala/org/apache/gearpump/streaming/examples/kafka/wordcount/KafkaWordCountSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/kafka/src/test/scala/org/apache/gearpump/streaming/examples/kafka/wordcount/KafkaWordCountSpec.scala b/examples/streaming/kafka/src/test/scala/org/apache/gearpump/streaming/examples/kafka/wordcount/KafkaWordCountSpec.scala
new file mode 100644
index 0000000..c4c422d
--- /dev/null
+++ b/examples/streaming/kafka/src/test/scala/org/apache/gearpump/streaming/examples/kafka/wordcount/KafkaWordCountSpec.scala
@@ -0,0 +1,71 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.kafka.wordcount
+
+import scala.concurrent.Future
+import scala.util.Success
+
+import com.typesafe.config.Config
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{BeforeAndAfter, Matchers, PropSpec}
+
+import org.apache.gearpump.cluster.ClientToMaster.SubmitApplication
+import org.apache.gearpump.cluster.MasterToClient.SubmitApplicationResult
+import org.apache.gearpump.cluster.{MasterHarness, TestUtil}
+
+class KafkaWordCountSpec
+ extends PropSpec with PropertyChecks with Matchers with BeforeAndAfter with MasterHarness {
+
+ before {
+ startActorSystem()
+ }
+
+ after {
+ shutdownActorSystem()
+ }
+
+ override def config: Config = TestUtil.DEFAULT_CONFIG
+
+ property("KafkaWordCount should succeed to submit application with required arguments") {
+ val requiredArgs = Array.empty[String]
+ val optionalArgs = Array(
+ "-source", "1",
+ "-split", "1",
+ "-sum", "1",
+ "-sink", "1")
+
+ val args = {
+ Table(
+ ("requiredArgs", "optionalArgs"),
+ (requiredArgs, optionalArgs)
+ )
+ }
+ val masterReceiver = createMockMaster()
+ forAll(args) { (requiredArgs: Array[String], optionalArgs: Array[String]) =>
+ val args = requiredArgs ++ optionalArgs
+
+ Future {
+ KafkaWordCount.main(masterConfig, args)
+ }
+
+ masterReceiver.expectMsgType[SubmitApplication](PROCESS_BOOT_TIME)
+ masterReceiver.reply(SubmitApplicationResult(Success(0)))
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/kafka/src/test/scala/org/apache/gearpump/streaming/examples/kafka/wordcount/SplitSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/kafka/src/test/scala/org/apache/gearpump/streaming/examples/kafka/wordcount/SplitSpec.scala b/examples/streaming/kafka/src/test/scala/org/apache/gearpump/streaming/examples/kafka/wordcount/SplitSpec.scala
new file mode 100644
index 0000000..893d06d
--- /dev/null
+++ b/examples/streaming/kafka/src/test/scala/org/apache/gearpump/streaming/examples/kafka/wordcount/SplitSpec.scala
@@ -0,0 +1,40 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.examples.kafka.wordcount
+
+import com.twitter.bijection.Injection
+import org.mockito.Matchers._
+import org.mockito.Mockito._
+import org.scalatest._
+import org.scalatest.mock.MockitoSugar
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.task.TaskContext
+
+class SplitSpec extends FlatSpec with Matchers with MockitoSugar {
+
+ it should "split should split the text and deliver to next task" in {
+ val taskContext = mock[TaskContext]
+ val split = new Split(taskContext, UserConfig.empty)
+
+ val msg = "this is a test message"
+ split.onNext(Message(Injection[String, Array[Byte]](msg)))
+ verify(taskContext, times(msg.split(" ").length)).output(anyObject[Message])
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/kafka/src/test/scala/org/apache/gearpump/streaming/examples/kafka/wordcount/SumSpec.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/kafka/src/test/scala/org/apache/gearpump/streaming/examples/kafka/wordcount/SumSpec.scala b/examples/streaming/kafka/src/test/scala/org/apache/gearpump/streaming/examples/kafka/wordcount/SumSpec.scala
new file mode 100644
index 0000000..3538ece
--- /dev/null
+++ b/examples/streaming/kafka/src/test/scala/org/apache/gearpump/streaming/examples/kafka/wordcount/SumSpec.scala
@@ -0,0 +1,58 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.examples.kafka.wordcount
+
+import scala.collection.mutable
+
+import org.mockito.Matchers._
+import org.mockito.Mockito._
+import org.scalacheck.Gen
+import org.scalatest.{FlatSpec, Matchers}
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.MockUtil
+import org.apache.gearpump.streaming.task.StartTime
+
+class SumSpec extends FlatSpec with Matchers {
+
+ it should "sum should calculate the frequency of the word correctly" in {
+
+ val stringGenerator = Gen.alphaStr
+ val expectedWordCountMap: mutable.HashMap[String, Long] = new mutable.HashMap[String, Long]()
+
+ val taskContext = MockUtil.mockTaskContext
+
+ val sum = new Sum(taskContext, UserConfig.empty)
+ sum.onStart(StartTime(0))
+ val str = "once two two three three three"
+
+ var totalWordCount = 0
+ stringGenerator.map { word =>
+ totalWordCount += 1
+ expectedWordCountMap.put(word, expectedWordCountMap.getOrElse(word, 0L) + 1)
+ sum.onNext(Message(word))
+ }
+ verify(taskContext, times(totalWordCount)).output(anyObject[Message])
+
+ expectedWordCountMap.foreach { wordCount =>
+ val (word, count) = wordCount
+ assert(count == sum.wordcount.get(word).get)
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/sol/README.md
----------------------------------------------------------------------
diff --git a/examples/streaming/sol/README.md b/examples/streaming/sol/README.md
index a8b10b3..d9c8eab 100644
--- a/examples/streaming/sol/README.md
+++ b/examples/streaming/sol/README.md
@@ -14,5 +14,5 @@ The original code comes from: https://github.com/yahoo/storm-perf-test
<B>Example:</B>
```
-bin/gear app -jar examples/gearpump-examples-assembly-$VERSION.jar io.gearpump.streaming.examples.sol.SOL
+bin/gear app -jar examples/gearpump-examples-assembly-$VERSION.jar org.apache.gearpump.streaming.examples.sol.SOL
```
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/sol/src/main/scala/io/gearpump/streaming/examples/sol/SOL.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/sol/src/main/scala/io/gearpump/streaming/examples/sol/SOL.scala b/examples/streaming/sol/src/main/scala/io/gearpump/streaming/examples/sol/SOL.scala
deleted file mode 100644
index 10c190c..0000000
--- a/examples/streaming/sol/src/main/scala/io/gearpump/streaming/examples/sol/SOL.scala
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.sol
-
-import org.slf4j.Logger
-
-import io.gearpump.cluster.UserConfig
-import io.gearpump.cluster.client.ClientContext
-import io.gearpump.cluster.main.{ArgumentsParser, CLIOption, ParseResult}
-import io.gearpump.partitioner.ShufflePartitioner
-import io.gearpump.streaming.{Processor, StreamApplication}
-import io.gearpump.util.Graph._
-import io.gearpump.util.{AkkaApp, Graph, LogUtil}
-
-object SOL extends AkkaApp with ArgumentsParser {
- private val LOG: Logger = LogUtil.getLogger(getClass)
-
- override val options: Array[(String, CLIOption[Any])] = Array(
- "streamProducer" -> CLIOption[Int]("<stream producer number>", required = false,
- defaultValue = Some(1)),
- "streamProcessor" -> CLIOption[Int]("<stream processor number>", required = false,
- defaultValue = Some(1)),
- "bytesPerMessage" -> CLIOption[Int]("<size of each message>", required = false,
- defaultValue = Some(100)),
- "stages" -> CLIOption[Int]("<how many stages to run>", required = false,
- defaultValue = Some(2)))
-
- def application(config: ParseResult): StreamApplication = {
- val spoutNum = config.getInt("streamProducer")
- val boltNum = config.getInt("streamProcessor")
- val bytesPerMessage = config.getInt("bytesPerMessage")
- val stages = config.getInt("stages")
- val appConfig = UserConfig.empty.withInt(SOLStreamProducer.BYTES_PER_MESSAGE, bytesPerMessage)
- val partitioner = new ShufflePartitioner()
- val streamProducer = Processor[SOLStreamProducer](spoutNum)
- val streamProcessor = Processor[SOLStreamProcessor](boltNum)
- var computation = streamProducer ~ partitioner ~> streamProcessor
- computation = 0.until(stages - 2).foldLeft(computation) { (c, id) =>
- c ~ partitioner ~> streamProcessor.copy()
- }
- val dag = Graph(computation)
- val app = StreamApplication("sol", dag, appConfig)
- app
- }
-
- override def main(akkaConf: Config, args: Array[String]): Unit = {
- val config = parse(args)
- val context = ClientContext(akkaConf)
- val appId = context.submit(application(config))
- context.close()
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/sol/src/main/scala/io/gearpump/streaming/examples/sol/SOLStreamProcessor.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/sol/src/main/scala/io/gearpump/streaming/examples/sol/SOLStreamProcessor.scala b/examples/streaming/sol/src/main/scala/io/gearpump/streaming/examples/sol/SOLStreamProcessor.scala
deleted file mode 100644
index de1054f..0000000
--- a/examples/streaming/sol/src/main/scala/io/gearpump/streaming/examples/sol/SOLStreamProcessor.scala
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.sol
-
-import java.util.concurrent.TimeUnit
-import scala.concurrent.duration.FiniteDuration
-
-import akka.actor.Cancellable
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.task.{StartTime, Task, TaskContext}
-
-class SOLStreamProcessor(taskContext: TaskContext, conf: UserConfig)
- extends Task(taskContext, conf) {
- import taskContext.output
-
- val taskConf = taskContext
-
- private var msgCount: Long = 0
- private var scheduler: Cancellable = null
- private var snapShotWordCount: Long = 0
- private var snapShotTime: Long = 0
-
- override def onStart(startTime: StartTime): Unit = {
- scheduler = taskContext.schedule(new FiniteDuration(5, TimeUnit.SECONDS),
- new FiniteDuration(5, TimeUnit.SECONDS))(reportWordCount())
- snapShotTime = System.currentTimeMillis()
- }
-
- override def onNext(msg: Message): Unit = {
- output(msg)
- msgCount = msgCount + 1
- }
-
- override def onStop(): Unit = {
- if (scheduler != null) {
- scheduler.cancel()
- }
- }
-
- def reportWordCount(): Unit = {
- val current: Long = System.currentTimeMillis()
- LOG.info(s"Task ${taskConf.taskId} " +
- s"Throughput: ${(msgCount - snapShotWordCount, (current - snapShotTime) / 1000)} " +
- s"(words, second)")
- snapShotWordCount = msgCount
- snapShotTime = current
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/sol/src/main/scala/io/gearpump/streaming/examples/sol/SOLStreamProducer.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/sol/src/main/scala/io/gearpump/streaming/examples/sol/SOLStreamProducer.scala b/examples/streaming/sol/src/main/scala/io/gearpump/streaming/examples/sol/SOLStreamProducer.scala
deleted file mode 100644
index 5c0f3be..0000000
--- a/examples/streaming/sol/src/main/scala/io/gearpump/streaming/examples/sol/SOLStreamProducer.scala
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.examples.sol
-
-import java.util.Random
-
-import io.gearpump.Message
-import io.gearpump.cluster.UserConfig
-import io.gearpump.streaming.examples.sol.SOLStreamProducer._
-import io.gearpump.streaming.task.{StartTime, Task, TaskContext}
-
-class SOLStreamProducer(taskContext: TaskContext, conf: UserConfig)
- extends Task(taskContext, conf) {
-
- import taskContext.output
-
- private val sizeInBytes = conf.getInt(SOLStreamProducer.BYTES_PER_MESSAGE)
- .getOrElse(DEFAULT_MESSAGE_SIZE)
- private var messages: Array[String] = null
- private var rand: Random = null
- private var messageCount: Long = 0
-
- override def onStart(startTime: StartTime): Unit = {
- prepareRandomMessage
- self ! Start
- }
-
- private def prepareRandomMessage = {
- rand = new Random()
- val differentMessages = 100
- messages = new Array(differentMessages)
-
- 0.until(differentMessages).map { index =>
- val sb = new StringBuilder(sizeInBytes)
- // Even though java encodes strings in UCS2, the serialized version sent by the tuples
- // is UTF8, so it should be a single byte
- 0.until(sizeInBytes).foldLeft(sb) { (sb, j) =>
- sb.append(rand.nextInt(9))
- }
- messages(index) = sb.toString()
- }
- }
-
- override def onNext(msg: Message): Unit = {
- val message = messages(rand.nextInt(messages.length))
- output(new Message(message, System.currentTimeMillis()))
- messageCount = messageCount + 1L
- self ! messageSourceMinClock
- }
-
- // messageSourceMinClock represent the min clock of the message source
- private def messageSourceMinClock: Message = {
- Message("tick", System.currentTimeMillis())
- }
-}
-
-object SOLStreamProducer {
- val DEFAULT_MESSAGE_SIZE = 100
- // Bytes
- val BYTES_PER_MESSAGE = "bytesPerMessage"
- val Start = Message("start")
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/examples/streaming/sol/src/main/scala/org/apache/gearpump/streaming/examples/sol/SOL.scala
----------------------------------------------------------------------
diff --git a/examples/streaming/sol/src/main/scala/org/apache/gearpump/streaming/examples/sol/SOL.scala b/examples/streaming/sol/src/main/scala/org/apache/gearpump/streaming/examples/sol/SOL.scala
new file mode 100644
index 0000000..fb80ad3
--- /dev/null
+++ b/examples/streaming/sol/src/main/scala/org/apache/gearpump/streaming/examples/sol/SOL.scala
@@ -0,0 +1,68 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.examples.sol
+
+import org.slf4j.Logger
+
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.cluster.client.ClientContext
+import org.apache.gearpump.cluster.main.{ArgumentsParser, CLIOption, ParseResult}
+import org.apache.gearpump.partitioner.ShufflePartitioner
+import org.apache.gearpump.streaming.{Processor, StreamApplication}
+import org.apache.gearpump.util.Graph._
+import org.apache.gearpump.util.{AkkaApp, Graph, LogUtil}
+
+object SOL extends AkkaApp with ArgumentsParser {
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+
+ override val options: Array[(String, CLIOption[Any])] = Array(
+ "streamProducer" -> CLIOption[Int]("<stream producer number>", required = false,
+ defaultValue = Some(1)),
+ "streamProcessor" -> CLIOption[Int]("<stream processor number>", required = false,
+ defaultValue = Some(1)),
+ "bytesPerMessage" -> CLIOption[Int]("<size of each message>", required = false,
+ defaultValue = Some(100)),
+ "stages" -> CLIOption[Int]("<how many stages to run>", required = false,
+ defaultValue = Some(2)))
+
+ def application(config: ParseResult): StreamApplication = {
+ val spoutNum = config.getInt("streamProducer")
+ val boltNum = config.getInt("streamProcessor")
+ val bytesPerMessage = config.getInt("bytesPerMessage")
+ val stages = config.getInt("stages")
+ val appConfig = UserConfig.empty.withInt(SOLStreamProducer.BYTES_PER_MESSAGE, bytesPerMessage)
+ val partitioner = new ShufflePartitioner()
+ val streamProducer = Processor[SOLStreamProducer](spoutNum)
+ val streamProcessor = Processor[SOLStreamProcessor](boltNum)
+ var computation = streamProducer ~ partitioner ~> streamProcessor
+ computation = 0.until(stages - 2).foldLeft(computation) { (c, id) =>
+ c ~ partitioner ~> streamProcessor.copy()
+ }
+ val dag = Graph(computation)
+ val app = StreamApplication("sol", dag, appConfig)
+ app
+ }
+
+ override def main(akkaConf: Config, args: Array[String]): Unit = {
+ val config = parse(args)
+ val context = ClientContext(akkaConf)
+ val appId = context.submit(application(config))
+ context.close()
+ }
+}
[18/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/KafkaSource.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/KafkaSource.scala b/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/KafkaSource.scala
new file mode 100644
index 0000000..339711b
--- /dev/null
+++ b/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/KafkaSource.scala
@@ -0,0 +1,195 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.kafka
+
+import java.util.Properties
+import scala.collection.mutable.ArrayBuffer
+import scala.util.{Failure, Success}
+
+import kafka.common.TopicAndPartition
+import org.slf4j.Logger
+
+import org.apache.gearpump.streaming.kafka.lib.consumer.{FetchThread, KafkaMessage}
+import org.apache.gearpump.streaming.kafka.lib.{DefaultMessageDecoder, KafkaOffsetManager, KafkaSourceConfig, KafkaUtil}
+import org.apache.gearpump.streaming.source.DefaultTimeStampFilter
+import org.apache.gearpump.streaming.task.TaskContext
+import org.apache.gearpump.streaming.transaction.api.OffsetStorage.StorageEmpty
+import org.apache.gearpump.streaming.transaction.api._
+import org.apache.gearpump.util.LogUtil
+import org.apache.gearpump.{Message, TimeStamp}
+
+object KafkaSource {
+ private val LOG: Logger = LogUtil.getLogger(classOf[KafkaSource])
+}
+
+/**
+ * Kafka source connectors that pulls a batch of messages (`kafka.consumer.emit.batch.size`)
+ * from multiple Kafka TopicAndPartition in a round-robin way.
+ *
+ * This is a TimeReplayableSource which is able to replay messages given a start time.
+ * Each kafka message is tagged with a timestamp by
+ * [[org.apache.gearpump.streaming.transaction.api.MessageDecoder]] and the (offset, timestamp)
+ * mapping is stored to a [[org.apache.gearpump.streaming.transaction.api.OffsetStorage]].
+ * On recovery, we could retrieve the previously stored offset from the
+ * [[org.apache.gearpump.streaming.transaction.api.OffsetStorage]] by timestamp and start to read
+ * from there.
+ *
+ * kafka message is wrapped into gearpump [[org.apache.gearpump.Message]] and further filtered by a
+ * [[org.apache.gearpump.streaming.transaction.api.TimeStampFilter]]
+ * such that obsolete messages are dropped.
+ *
+ * @param config kafka source config
+ * @param offsetStorageFactory factory to build [[OffsetStorage]]
+ * @param messageDecoder decodes [[org.apache.gearpump.Message]] from raw bytes
+ * @param timestampFilter filters out message based on timestamp
+ * @param fetchThread fetches messages and puts on a in-memory queue
+ * @param offsetManagers manages offset-to-timestamp storage for each kafka.common.TopicAndPartition
+ */
+class KafkaSource(
+ config: KafkaSourceConfig,
+ offsetStorageFactory: OffsetStorageFactory,
+ messageDecoder: MessageDecoder = new DefaultMessageDecoder,
+ timestampFilter: TimeStampFilter = new DefaultTimeStampFilter,
+ private var fetchThread: Option[FetchThread] = None,
+ private var offsetManagers: Map[TopicAndPartition, KafkaOffsetManager] = {
+ Map.empty[TopicAndPartition, KafkaOffsetManager]
+ }) extends TimeReplayableSource {
+ import org.apache.gearpump.streaming.kafka.KafkaSource._
+
+ private var startTime: Option[TimeStamp] = None
+
+ /**
+ * Constructs a Kafka Source by...
+ *
+ * @param topics comma-separated string of topics
+ * @param properties kafka consumer config
+ * @param offsetStorageFactory org.apache.gearpump.streaming.transaction.api.OffsetStorageFactory
+ * that creates [[org.apache.gearpump.streaming.transaction.api.OffsetStorage]]
+ *
+ */
+ def this(topics: String, properties: Properties, offsetStorageFactory: OffsetStorageFactory) = {
+ this(KafkaSourceConfig(properties).withConsumerTopics(topics), offsetStorageFactory)
+ }
+ /**
+ * Constructs a Kafka Source by...
+ *
+ * @param topics comma-separated string of topics
+ * @param properties kafka consumer config
+ * @param offsetStorageFactory org.apache.gearpump.streaming.transaction.api.OffsetStorageFactory
+ * that creates [[org.apache.gearpump.streaming.transaction.api.OffsetStorage]]
+ * @param messageDecoder decodes [[org.apache.gearpump.Message]] from raw bytes
+ * @param timestampFilter filters out message based on timestamp
+ */
+ def this(topics: String, properties: Properties, offsetStorageFactory: OffsetStorageFactory,
+ messageDecoder: MessageDecoder, timestampFilter: TimeStampFilter) = {
+ this(KafkaSourceConfig(properties)
+ .withConsumerTopics(topics), offsetStorageFactory,
+ messageDecoder, timestampFilter)
+ }
+
+ /**
+ * Constructs a Kafka Source by...
+ *
+ * @param topics comma-separated string of topics
+ * @param zkConnect kafka consumer config `zookeeper.connect`
+ * @param offsetStorageFactory org.apache.gearpump.streaming.transaction.api.OffsetStorageFactory
+ * that creates [[org.apache.gearpump.streaming.transaction.api.OffsetStorage]]
+ */
+ def this(topics: String, zkConnect: String, offsetStorageFactory: OffsetStorageFactory) =
+ this(topics, KafkaUtil.buildConsumerConfig(zkConnect), offsetStorageFactory)
+
+ /**
+ * Constructs a Kafka Source by...
+ *
+ * @param topics comma-separated string of topics
+ * @param zkConnect kafka consumer config `zookeeper.connect`
+ * @param offsetStorageFactory org.apache.gearpump.streaming.transaction.api.OffsetStorageFactory
+ * that creates [[org.apache.gearpump.streaming.transaction.api.OffsetStorage]]
+ * @param messageDecoder decodes [[org.apache.gearpump.Message]] from raw bytes
+ * @param timestampFilter filters out message based on timestamp
+ */
+ def this(topics: String, zkConnect: String, offsetStorageFactory: OffsetStorageFactory,
+ messageDecoder: MessageDecoder,
+ timestampFilter: TimeStampFilter) = {
+ this(topics, KafkaUtil.buildConsumerConfig(zkConnect), offsetStorageFactory,
+ messageDecoder, timestampFilter)
+ }
+
+ LOG.debug(s"assigned ${offsetManagers.keySet}")
+
+ private[kafka] def setStartTime(startTime: Option[TimeStamp]): Unit = {
+ this.startTime = startTime
+ fetchThread.foreach { fetch =>
+ this.startTime.foreach { time =>
+ offsetManagers.foreach { case (tp, offsetManager) =>
+ offsetManager.resolveOffset(time) match {
+ case Success(offset) =>
+ LOG.debug(s"set start offset to $offset for $tp")
+ fetch.setStartOffset(tp, offset)
+ case Failure(StorageEmpty) =>
+ LOG.debug(s"no previous TimeStamp stored")
+ case Failure(e) => throw e
+ }
+ }
+ }
+ fetch.setDaemon(true)
+ fetch.start()
+ }
+ }
+
+ override def open(context: TaskContext, startTime: TimeStamp): Unit = {
+ import context.{appId, appName, parallelism, taskId}
+
+ val topics = config.getConsumerTopics
+ val grouper = config.getGrouper
+ val consumerConfig = config.consumerConfig
+ val topicAndPartitions = grouper.group(parallelism, taskId.index,
+ KafkaUtil.getTopicAndPartitions(KafkaUtil.connectZookeeper(consumerConfig)(), topics))
+ this.fetchThread = Some(FetchThread(topicAndPartitions, config.getFetchThreshold,
+ config.getFetchSleepMS, config.getConsumerStartOffset, consumerConfig))
+ this.offsetManagers = topicAndPartitions.map { tp =>
+ val storageTopic = s"app${appId}_${appName}_${tp.topic}_${tp.partition}"
+ val storage = offsetStorageFactory.getOffsetStorage(storageTopic)
+ tp -> new KafkaOffsetManager(storage)
+ }.toMap
+
+ setStartTime(Option(startTime))
+ }
+
+ override def read(): Message = {
+ fetchThread.flatMap(_.poll.flatMap(filterMessage)).orNull
+ }
+
+ private def filterMessage(kafkaMsg: KafkaMessage): Option[Message] = {
+ val msgOpt = offsetManagers(kafkaMsg.topicAndPartition)
+ .filter(messageDecoder.fromBytes(kafkaMsg.msg) -> kafkaMsg.offset)
+ msgOpt.flatMap { msg =>
+ startTime match {
+ case None =>
+ Some(msg)
+ case Some(time) =>
+ timestampFilter.filter(msg, time)
+ }
+ }
+ }
+
+ override def close(): Unit = {
+ offsetManagers.foreach(_._2.close())
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/KafkaStorage.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/KafkaStorage.scala b/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/KafkaStorage.scala
new file mode 100644
index 0000000..8748999
--- /dev/null
+++ b/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/KafkaStorage.scala
@@ -0,0 +1,148 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.kafka
+
+import java.util.Properties
+import scala.collection.mutable
+import scala.util.{Failure, Success, Try}
+
+import com.twitter.bijection.Injection
+import kafka.api.OffsetRequest
+import kafka.consumer.ConsumerConfig
+import org.I0Itec.zkclient.ZkClient
+import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord}
+import org.apache.kafka.common.serialization.ByteArraySerializer
+import org.slf4j.Logger
+
+import org.apache.gearpump.TimeStamp
+import org.apache.gearpump.streaming.kafka.lib.KafkaUtil
+import org.apache.gearpump.streaming.kafka.lib.consumer.KafkaConsumer
+import org.apache.gearpump.streaming.transaction.api.OffsetStorage.{Overflow, StorageEmpty, Underflow}
+import org.apache.gearpump.streaming.transaction.api.{OffsetStorage, OffsetStorageFactory}
+import org.apache.gearpump.util.LogUtil
+
+/**
+ * Factory that builds [[KafkaStorage]]
+ *
+ * @param consumerProps kafka consumer config
+ * @param producerProps kafka producer config
+ */
+class KafkaStorageFactory(consumerProps: Properties, producerProps: Properties)
+ extends OffsetStorageFactory {
+
+ /**
+ * Creates consumer config properties with `zookeeper.connect` set to zkConnect
+ * and producer config properties with `bootstrap.servers` set to bootstrapServers
+ *
+ * @param zkConnect kafka consumer config `zookeeper.connect`
+ * @param bootstrapServers kafka producer config `bootstrap.servers`
+ */
+ def this(zkConnect: String, bootstrapServers: String) =
+ this(KafkaUtil.buildConsumerConfig(zkConnect), KafkaUtil.buildProducerConfig(bootstrapServers))
+
+ override def getOffsetStorage(dir: String): OffsetStorage = {
+ val topic = dir
+ val consumerConfig = new ConsumerConfig(consumerProps)
+ val getConsumer = () => KafkaConsumer(topic, 0, OffsetRequest.EarliestTime, consumerConfig)
+ new KafkaStorage(topic, KafkaUtil.createKafkaProducer[Array[Byte], Array[Byte]](
+ producerProps, new ByteArraySerializer, new ByteArraySerializer),
+ getConsumer(), KafkaUtil.connectZookeeper(consumerConfig)())
+ }
+}
+
+object KafkaStorage {
+ private val LOG: Logger = LogUtil.getLogger(classOf[KafkaStorage])
+}
+
+/**
+ * Stores offset-timestamp mapping to kafka
+ *
+ * @param topic kafka store topic
+ * @param producer kafka producer
+ * @param getConsumer function to get kafka consumer
+ * @param connectZk function to connect zookeeper
+ */
+class KafkaStorage private[kafka](
+ topic: String,
+ producer: KafkaProducer[Array[Byte], Array[Byte]],
+ getConsumer: => KafkaConsumer,
+ connectZk: => ZkClient)
+ extends OffsetStorage {
+
+ private lazy val consumer = getConsumer
+
+ private val dataByTime: List[(TimeStamp, Array[Byte])] = {
+ if (KafkaUtil.topicExists(connectZk, topic)) {
+ load(consumer)
+ } else {
+ List.empty[(TimeStamp, Array[Byte])]
+ }
+ }
+
+ /**
+ * Offsets with timestamp less than `time` have already been processed by the system
+ * so we look up the storage for the first offset with timestamp large equal than `time`
+ * on replay.
+ *
+ * @param time the timestamp to look up for the earliest unprocessed offset
+ * @return the earliest unprocessed offset if `time` is in the range, otherwise failure
+ */
+ override def lookUp(time: TimeStamp): Try[Array[Byte]] = {
+ if (dataByTime.isEmpty) {
+ Failure(StorageEmpty)
+ } else {
+ val min = dataByTime.head
+ val max = dataByTime.last
+ if (time < min._1) {
+ Failure(Underflow(min._2))
+ } else if (time > max._1) {
+ Failure(Overflow(max._2))
+ } else {
+ Success(dataByTime.find(_._1 >= time).get._2)
+ }
+ }
+ }
+
+ override def append(time: TimeStamp, offset: Array[Byte]): Unit = {
+ val message = new ProducerRecord[Array[Byte], Array[Byte]](
+ topic, 0, Injection[Long, Array[Byte]](time), offset)
+ producer.send(message)
+ }
+
+ override def close(): Unit = {
+ producer.close()
+ KafkaUtil.deleteTopic(connectZk, topic)
+ }
+
+ private[kafka] def load(consumer: KafkaConsumer): List[(TimeStamp, Array[Byte])] = {
+ var messagesBuilder = new mutable.ArrayBuilder.ofRef[(TimeStamp, Array[Byte])]
+ while (consumer.hasNext) {
+ val kafkaMsg = consumer.next
+ kafkaMsg.key.map { k =>
+ Injection.invert[TimeStamp, Array[Byte]](k) match {
+ case Success(time) =>
+ messagesBuilder += (time -> kafkaMsg.msg)
+ case Failure(e) => throw e
+ }
+ } orElse (throw new RuntimeException("offset key should not be null"))
+ }
+ consumer.close()
+ messagesBuilder.result().toList
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/dsl/KafkaDSLSink.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/dsl/KafkaDSLSink.scala b/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/dsl/KafkaDSLSink.scala
new file mode 100644
index 0000000..5f48b43
--- /dev/null
+++ b/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/dsl/KafkaDSLSink.scala
@@ -0,0 +1,53 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.kafka.dsl
+
+import java.util.Properties
+
+import org.apache.gearpump.cluster.UserConfig
+import org.apache.gearpump.streaming.dsl
+import org.apache.gearpump.streaming.kafka.KafkaSink
+
+class KafkaDSLSink[T](stream: dsl.Stream[T]) {
+
+ /** Create a Kafka DSL Sink */
+ def writeToKafka(
+ topic: String,
+ bootstrapServers: String,
+ parallism: Int,
+ description: String): dsl.Stream[T] = {
+ stream.sink(new KafkaSink(topic, bootstrapServers), parallism, UserConfig.empty, description)
+ }
+
+ def writeToKafka(
+ topic: String,
+ properties: Properties,
+ parallism: Int,
+ description: String): dsl.Stream[T] = {
+ stream.sink(new KafkaSink(topic, properties), parallism, UserConfig.empty, description)
+ }
+}
+
+object KafkaDSLSink {
+
+ import scala.language.implicitConversions
+
+ implicit def streamToKafkaDSLSink[T](stream: dsl.Stream[T]): KafkaDSLSink[T] = {
+ new KafkaDSLSink[T](stream)
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/dsl/KafkaDSLUtil.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/dsl/KafkaDSLUtil.scala b/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/dsl/KafkaDSLUtil.scala
new file mode 100644
index 0000000..0275966
--- /dev/null
+++ b/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/dsl/KafkaDSLUtil.scala
@@ -0,0 +1,88 @@
+/*
+ * 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.
+ */
+package org.apache.gearpump.streaming.kafka.dsl
+
+import java.util.Properties
+
+import org.apache.gearpump.streaming.dsl
+import org.apache.gearpump.streaming.dsl.StreamApp
+import org.apache.gearpump.streaming.kafka.KafkaSource
+import org.apache.gearpump.streaming.kafka.lib.{DefaultMessageDecoder, KafkaSourceConfig}
+import org.apache.gearpump.streaming.transaction.api.{MessageDecoder, OffsetStorageFactory, TimeStampFilter}
+
+object KafkaDSLUtil {
+ def createStream[T](
+ app: StreamApp,
+ parallelism: Int,
+ description: String,
+ kafkaConfig: KafkaSourceConfig,
+ offsetStorageFactory: OffsetStorageFactory,
+ messageDecoder: MessageDecoder = new DefaultMessageDecoder): dsl.Stream[T] = {
+ app.source[T](new KafkaSource(kafkaConfig, offsetStorageFactory, messageDecoder),
+ parallelism, description)
+ }
+
+ def createStream[T](
+ app: StreamApp,
+ parallelism: Int,
+ description: String,
+ topics: String,
+ zkConnect: String,
+ offsetStorageFactory: OffsetStorageFactory): dsl.Stream[T] = {
+ app.source[T](new KafkaSource(topics, zkConnect, offsetStorageFactory),
+ parallelism, description)
+ }
+
+ def createStream[T](
+ app: StreamApp,
+ parallelism: Int,
+ description: String,
+ topics: String,
+ zkConnect: String,
+ offsetStorageFactory: OffsetStorageFactory,
+ messageDecoder: MessageDecoder,
+ timestampFilter: TimeStampFilter): dsl.Stream[T] = {
+ app.source[T](new KafkaSource(topics, zkConnect, offsetStorageFactory,
+ messageDecoder, timestampFilter), parallelism, description)
+ }
+
+ def createStream[T](
+ app: StreamApp,
+ parallelism: Int,
+ description: String,
+ topics: String,
+ properties: Properties,
+ offsetStorageFactory: OffsetStorageFactory): dsl.Stream[T] = {
+ app.source[T](new KafkaSource(topics, properties, offsetStorageFactory),
+ parallelism, description)
+ }
+
+ def createStream[T](
+ app: StreamApp,
+ topics: String,
+ parallelism: Int,
+ description: String,
+ properties: Properties,
+ offsetStorageFactory: OffsetStorageFactory,
+ messageDecoder: MessageDecoder,
+ timestampFilter: TimeStampFilter): dsl.Stream[T] = {
+ app.source[T](new KafkaSource(topics, properties, offsetStorageFactory,
+ messageDecoder, timestampFilter), parallelism, description)
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/DefaultMessageDecoder.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/DefaultMessageDecoder.scala b/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/DefaultMessageDecoder.scala
new file mode 100644
index 0000000..ea7e8d1
--- /dev/null
+++ b/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/DefaultMessageDecoder.scala
@@ -0,0 +1,41 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.kafka.lib
+
+import scala.util.{Failure, Success}
+
+import com.twitter.bijection.Injection
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.streaming.transaction.api.MessageDecoder
+
+class DefaultMessageDecoder extends MessageDecoder {
+ override def fromBytes(bytes: Array[Byte]): Message = {
+ Message(bytes, System.currentTimeMillis())
+ }
+}
+
+class StringMessageDecoder extends MessageDecoder {
+ override def fromBytes(bytes: Array[Byte]): Message = {
+ Injection.invert[String, Array[Byte]](bytes) match {
+ case Success(s) => Message(s, System.currentTimeMillis())
+ case Failure(e) => throw e
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/KafkaOffsetManager.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/KafkaOffsetManager.scala b/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/KafkaOffsetManager.scala
new file mode 100644
index 0000000..88f509b
--- /dev/null
+++ b/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/KafkaOffsetManager.scala
@@ -0,0 +1,66 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.kafka.lib
+
+import scala.util.{Failure, Success, Try}
+
+import com.twitter.bijection.Injection
+import org.slf4j.Logger
+
+import org.apache.gearpump._
+import org.apache.gearpump.streaming.transaction.api.OffsetStorage.{Overflow, StorageEmpty, Underflow}
+import org.apache.gearpump.streaming.transaction.api.{OffsetManager, OffsetStorage}
+import org.apache.gearpump.util.LogUtil
+
+object KafkaOffsetManager {
+ private val LOG: Logger = LogUtil.getLogger(classOf[KafkaOffsetManager])
+}
+
+private[kafka] class KafkaOffsetManager(storage: OffsetStorage) extends OffsetManager {
+ import org.apache.gearpump.streaming.kafka.lib.KafkaOffsetManager._
+
+ var maxTime: TimeStamp = 0L
+
+ override def filter(messageAndOffset: (Message, Long)): Option[Message] = {
+ val (message, offset) = messageAndOffset
+ if (message.timestamp > maxTime) {
+ maxTime = message.timestamp
+ storage.append(maxTime, Injection[Long, Array[Byte]](offset))
+ }
+ Some(message)
+ }
+
+ override def resolveOffset(time: TimeStamp): Try[Long] = {
+ storage.lookUp(time) match {
+ case Success(offset) => Injection.invert[Long, Array[Byte]](offset)
+ case Failure(Overflow(max)) =>
+ LOG.warn(s"start time larger than the max stored TimeStamp; set to max offset")
+ Injection.invert[Long, Array[Byte]](max)
+ case Failure(Underflow(min)) =>
+ LOG.warn(s"start time less than the min stored TimeStamp; set to min offset")
+ Injection.invert[Long, Array[Byte]](min)
+ case Failure(StorageEmpty) => Failure(StorageEmpty)
+ case Failure(e) => throw e
+ }
+ }
+
+ override def close(): Unit = {
+ storage.close()
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/KafkaSourceConfig.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/KafkaSourceConfig.scala b/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/KafkaSourceConfig.scala
new file mode 100644
index 0000000..ade414e
--- /dev/null
+++ b/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/KafkaSourceConfig.scala
@@ -0,0 +1,178 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.kafka.lib
+
+import java.util.Properties
+
+import kafka.api.OffsetRequest
+import kafka.consumer.ConsumerConfig
+import org.slf4j.Logger
+
+import org.apache.gearpump.streaming.kafka.lib.grouper.{KafkaDefaultGrouper, KafkaGrouper}
+import org.apache.gearpump.util.LogUtil
+
+object KafkaSourceConfig {
+
+ val NAME = "kafka_config"
+
+ val ZOOKEEPER_CONNECT = "zookeeper.connect"
+ val GROUP_ID = "group.id"
+ val CONSUMER_START_OFFSET = "kafka.consumer.start.offset"
+ val CONSUMER_TOPICS = "kafka.consumer.topics"
+ val FETCH_THRESHOLD = "kafka.consumer.fetch.threshold"
+ val FETCH_SLEEP_MS = "kafka.consumer.fetch.sleep.ms"
+ val GROUPER_CLASS = "kafka.grouper.class"
+
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+
+ def apply(consumerProps: Properties): KafkaSourceConfig = new KafkaSourceConfig(consumerProps)
+}
+
+/**
+ * Extends kafka.consumer.ConsumerConfig with specific config needed by
+ * [[org.apache.gearpump.streaming.kafka.KafkaSource]]
+ *
+ * @param consumerProps kafka consumer config
+ */
+class KafkaSourceConfig(val consumerProps: Properties = new Properties)
+ extends java.io.Serializable {
+ import org.apache.gearpump.streaming.kafka.lib.KafkaSourceConfig._
+
+ if (!consumerProps.containsKey(ZOOKEEPER_CONNECT)) {
+ consumerProps.setProperty(ZOOKEEPER_CONNECT, "localhost:2181")
+ }
+
+ if (!consumerProps.containsKey(GROUP_ID)) {
+ consumerProps.setProperty(GROUP_ID, "gearpump")
+ }
+
+ def consumerConfig: ConsumerConfig = new ConsumerConfig(consumerProps)
+
+ /**
+ * Set kafka consumer topics, seperated by comma.
+ *
+ * @param topics comma-separated string
+ * @return new KafkaConfig based on this but with
+ * [[org.apache.gearpump.streaming.kafka.lib.KafkaSourceConfig#CONSUMER_TOPICS]]
+ * set to given value
+ */
+ def withConsumerTopics(topics: String): KafkaSourceConfig = {
+ consumerProps.setProperty(CONSUMER_TOPICS, topics)
+ KafkaSourceConfig(consumerProps)
+ }
+
+ /**
+ * Returns a list of kafka consumer topics
+ */
+ def getConsumerTopics: List[String] = {
+ Option(consumerProps.getProperty(CONSUMER_TOPICS)).getOrElse("topic1").split(",").toList
+ }
+
+ /**
+ * Sets the sleep interval if there are no more message or message buffer is full.
+ *
+ * Consumer.FetchThread will sleep for a while if no more messages or
+ * the incoming queue size is above the
+ * [[org.apache.gearpump.streaming.kafka.lib.KafkaSourceConfig#FETCH_THRESHOLD]]
+ *
+ * @param sleepMS sleep interval in milliseconds
+ * @return new KafkaConfig based on this but with
+ * [[org.apache.gearpump.streaming.kafka.lib.KafkaSourceConfig#FETCH_SLEEP_MS]]
+ * set to given value
+ */
+ def withFetchSleepMS(sleepMS: Int): KafkaSourceConfig = {
+ consumerProps.setProperty(FETCH_SLEEP_MS, s"$sleepMS")
+ KafkaSourceConfig(consumerProps)
+ }
+
+ /**
+ * Gets the sleep interval
+ *
+ * Consumer.FetchThread sleeps for a while if no more messages or
+ * the incoming queue is full (size is bigger than the
+ * [[org.apache.gearpump.streaming.kafka.lib.KafkaSourceConfig#FETCH_THRESHOLD]])
+ *
+ * @return sleep interval in milliseconds
+ */
+ def getFetchSleepMS: Int = {
+ Option(consumerProps.getProperty(FETCH_SLEEP_MS)).getOrElse("100").toInt
+ }
+
+ /**
+ * Sets the batch size we use for one fetch.
+ *
+ * Consumer.FetchThread stops fetching new messages if its incoming queue
+ * size is above the threshold and starts again when the queue size is below it
+ *
+ * @param threshold queue size
+ * @return new KafkaConfig based on this but with
+ * [[org.apache.gearpump.streaming.kafka.lib.KafkaSourceConfig#FETCH_THRESHOLD]]
+ * set to give value
+ */
+ def withFetchThreshold(threshold: Int): KafkaSourceConfig = {
+ consumerProps.setProperty(FETCH_THRESHOLD, s"$threshold")
+ KafkaSourceConfig(consumerProps)
+ }
+
+ /**
+ * Returns fetch batch size.
+ *
+ * Consumer.FetchThread stops fetching new messages if
+ * its incoming queue size is above the threshold and starts again when the queue size is below it
+ *
+ * @return fetch threshold
+ */
+ def getFetchThreshold: Int = {
+ Option(consumerProps.getProperty(FETCH_THRESHOLD)).getOrElse("10000").toInt
+ }
+
+ /**
+ * Sets [[org.apache.gearpump.streaming.kafka.lib.grouper.KafkaGrouper]], which
+ * defines how kafka.common.TopicAndPartitions are mapped to source tasks.
+ *
+ * @param className name of the factory class
+ * @return new KafkaConfig based on this but with
+ * [[org.apache.gearpump.streaming.kafka.lib.KafkaSourceConfig#GROUPER_CLASS]]
+ * set to given value
+ */
+ def withGrouper(className: String): KafkaSourceConfig = {
+ consumerProps.setProperty(GROUPER_CLASS, className)
+ KafkaSourceConfig(consumerProps)
+ }
+
+ /**
+ * Returns [[org.apache.gearpump.streaming.kafka.lib.grouper.KafkaGrouper]] instance, which
+ * defines how kafka.common.TopicAndPartitions are mapped to source tasks
+ */
+ def getGrouper: KafkaGrouper = {
+ Class.forName(Option(consumerProps.getProperty(GROUPER_CLASS))
+ .getOrElse(classOf[KafkaDefaultGrouper].getName)).newInstance().asInstanceOf[KafkaGrouper]
+ }
+
+ def withConsumerStartOffset(earliestOrLatest: Long): KafkaSourceConfig = {
+ consumerProps.setProperty(CONSUMER_START_OFFSET, s"$earliestOrLatest")
+ KafkaSourceConfig(consumerProps)
+ }
+
+ def getConsumerStartOffset: Long = {
+ Option(consumerProps.getProperty(CONSUMER_START_OFFSET))
+ .getOrElse(s"${OffsetRequest.EarliestTime}").toLong
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/KafkaUtil.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/KafkaUtil.scala b/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/KafkaUtil.scala
new file mode 100644
index 0000000..e8cf574
--- /dev/null
+++ b/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/KafkaUtil.scala
@@ -0,0 +1,167 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.kafka.lib
+
+import java.io.InputStream
+import java.util.Properties
+
+import kafka.admin.AdminUtils
+import kafka.cluster.Broker
+import kafka.common.TopicAndPartition
+import kafka.consumer.ConsumerConfig
+import kafka.utils.{ZKStringSerializer, ZkUtils}
+import org.I0Itec.zkclient.ZkClient
+import org.apache.kafka.clients.producer.{KafkaProducer, ProducerConfig}
+import org.apache.kafka.common.serialization.Serializer
+import org.slf4j.Logger
+
+import org.apache.gearpump.util.LogUtil
+
+object KafkaUtil {
+ private val LOG: Logger = LogUtil.getLogger(getClass)
+
+ def getBroker(connectZk: => ZkClient, topic: String, partition: Int): Broker = {
+ val zkClient = connectZk
+ try {
+ val leader = ZkUtils.getLeaderForPartition(zkClient, topic, partition)
+ .getOrElse(throw new RuntimeException(
+ s"leader not available for TopicAndPartition($topic, $partition)"))
+ ZkUtils.getBrokerInfo(zkClient, leader)
+ .getOrElse(throw new RuntimeException(s"broker info not found for leader $leader"))
+ } catch {
+ case e: Exception =>
+ LOG.error(e.getMessage)
+ throw e
+ } finally {
+ zkClient.close()
+ }
+ }
+
+ def getTopicAndPartitions(connectZk: => ZkClient, consumerTopics: List[String])
+ : Array[TopicAndPartition] = {
+ val zkClient = connectZk
+ try {
+ ZkUtils.getPartitionsForTopics(zkClient, consumerTopics).flatMap {
+ case (topic, partitions) => partitions.map(TopicAndPartition(topic, _))
+ }.toArray
+ } catch {
+ case e: Exception =>
+ LOG.error(e.getMessage)
+ throw e
+ } finally {
+ zkClient.close()
+ }
+ }
+
+ def topicExists(connectZk: => ZkClient, topic: String): Boolean = {
+ val zkClient = connectZk
+ try {
+ AdminUtils.topicExists(zkClient, topic)
+ } catch {
+ case e: Exception =>
+ LOG.error(e.getMessage)
+ throw e
+ } finally {
+ zkClient.close()
+ }
+ }
+
+ /**
+ * create a new kafka topic
+ * return true if topic already exists, and false otherwise
+ */
+ def createTopic(connectZk: => ZkClient, topic: String, partitions: Int, replicas: Int)
+ : Boolean = {
+ val zkClient = connectZk
+ try {
+ if (AdminUtils.topicExists(zkClient, topic)) {
+ LOG.info(s"topic $topic exists")
+ true
+ } else {
+ AdminUtils.createTopic(zkClient, topic, partitions, replicas)
+ LOG.info(s"created topic $topic")
+ false
+ }
+ } catch {
+ case e: Exception =>
+ LOG.error(e.getMessage)
+ throw e
+ } finally {
+ zkClient.close()
+ }
+ }
+
+ def deleteTopic(connectZk: => ZkClient, topic: String): Unit = {
+ val zkClient = connectZk
+ try {
+ AdminUtils.deleteTopic(zkClient, topic)
+ } catch {
+ case e: Exception =>
+ LOG.error(e.getMessage)
+ } finally {
+ zkClient.close()
+ }
+ }
+
+ def connectZookeeper(config: ConsumerConfig): () => ZkClient = {
+ val zookeeperConnect = config.zkConnect
+ val sessionTimeout = config.zkSessionTimeoutMs
+ val connectionTimeout = config.zkConnectionTimeoutMs
+ () => new ZkClient(zookeeperConnect, sessionTimeout, connectionTimeout, ZKStringSerializer)
+ }
+
+ def loadProperties(filename: String): Properties = {
+ val props = new Properties()
+ var propStream: InputStream = null
+ try {
+ propStream = getClass.getClassLoader.getResourceAsStream(filename)
+ props.load(propStream)
+ } catch {
+ case e: Exception =>
+ LOG.error(s"$filename not found")
+ } finally {
+ if (propStream != null) {
+ propStream.close()
+ }
+ }
+ props
+ }
+
+ def createKafkaProducer[K, V](properties: Properties,
+ keySerializer: Serializer[K],
+ valueSerializer: Serializer[V]): KafkaProducer[K, V] = {
+ if (properties.getProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG) == null) {
+ properties.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092")
+ }
+ new KafkaProducer[K, V](properties, keySerializer, valueSerializer)
+ }
+
+ def buildProducerConfig(bootstrapServers: String): Properties = {
+ val properties = new Properties()
+ properties.setProperty("bootstrap.servers", bootstrapServers)
+ properties
+ }
+
+ def buildConsumerConfig(zkConnect: String): Properties = {
+ val properties = new Properties()
+ properties.setProperty("zookeeper.connect", zkConnect)
+ properties.setProperty("group.id", "gearpump")
+ properties
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/consumer/ExponentialBackoffSleeper.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/consumer/ExponentialBackoffSleeper.scala b/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/consumer/ExponentialBackoffSleeper.scala
new file mode 100644
index 0000000..ce17f5a
--- /dev/null
+++ b/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/consumer/ExponentialBackoffSleeper.scala
@@ -0,0 +1,55 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.kafka.lib.consumer
+
+/**
+ * someone sleeps for exponentially increasing duration each time
+ * until the cap
+ *
+ * @param backOffMultiplier The factor by which the duration increases.
+ * @param initialDurationMs Time in milliseconds for initial sleep.
+ * @param maximumDurationMs Cap up to which we will increase the duration.
+ */
+private[consumer] class ExponentialBackoffSleeper(
+ backOffMultiplier: Double = 2.0,
+ initialDurationMs: Long = 100,
+ maximumDurationMs: Long = 10000) {
+
+ require(backOffMultiplier > 1.0, "backOffMultiplier must be greater than 1")
+ require(initialDurationMs > 0, "initialDurationMs must be positive")
+ require(maximumDurationMs >= initialDurationMs, "maximumDurationMs must be >= initialDurationMs")
+
+ private var sleepDuration = initialDurationMs
+
+ def reset(): Unit = {
+ sleepDuration = initialDurationMs
+ }
+
+ def sleep(): Unit = {
+ Thread.sleep(sleepDuration)
+ setNextSleepDuration()
+ }
+
+ def getSleepDuration: Long = sleepDuration
+
+ def setNextSleepDuration(): Unit = {
+ val next = (sleepDuration * backOffMultiplier).asInstanceOf[Long]
+ sleepDuration = math.min(math.max(initialDurationMs, next), maximumDurationMs)
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/consumer/FetchThread.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/consumer/FetchThread.scala b/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/consumer/FetchThread.scala
new file mode 100644
index 0000000..8550207
--- /dev/null
+++ b/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/consumer/FetchThread.scala
@@ -0,0 +1,139 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.kafka.lib.consumer
+
+import java.nio.channels.ClosedByInterruptException
+import java.util.concurrent.LinkedBlockingQueue
+
+import kafka.common.TopicAndPartition
+import kafka.consumer.ConsumerConfig
+import org.slf4j.Logger
+
+import org.apache.gearpump.util.LogUtil
+
+object FetchThread {
+ private val LOG: Logger = LogUtil.getLogger(classOf[FetchThread])
+
+ def apply(topicAndPartitions: Array[TopicAndPartition],
+ fetchThreshold: Int,
+ fetchSleepMS: Long,
+ startOffsetTime: Long,
+ consumerConfig: ConsumerConfig): FetchThread = {
+ val createConsumer = (tp: TopicAndPartition) =>
+ KafkaConsumer(tp.topic, tp.partition, startOffsetTime, consumerConfig)
+
+ val incomingQueue = new LinkedBlockingQueue[KafkaMessage]()
+ new FetchThread(topicAndPartitions, createConsumer, incomingQueue, fetchThreshold, fetchSleepMS)
+ }
+}
+
+/**
+ * A thread to fetch messages from multiple kafka org.apache.kafka.TopicAndPartition and puts them
+ * onto a queue, which is asynchronously polled by a consumer
+ *
+ * @param createConsumer given a org.apache.kafka.TopicAndPartition, create a
+ * [[org.apache.gearpump.streaming.kafka.lib.consumer.KafkaConsumer]] to
+ * connect to it
+ * @param incomingQueue a queue to buffer incoming messages
+ * @param fetchThreshold above which thread should stop fetching messages
+ * @param fetchSleepMS interval to sleep when no more messages or hitting fetchThreshold
+ */
+private[kafka] class FetchThread(topicAndPartitions: Array[TopicAndPartition],
+ createConsumer: TopicAndPartition => KafkaConsumer,
+ incomingQueue: LinkedBlockingQueue[KafkaMessage],
+ fetchThreshold: Int,
+ fetchSleepMS: Long) extends Thread {
+ import org.apache.gearpump.streaming.kafka.lib.consumer.FetchThread._
+
+ private var consumers: Map[TopicAndPartition, KafkaConsumer] = createAllConsumers
+
+ def setStartOffset(tp: TopicAndPartition, startOffset: Long): Unit = {
+ consumers(tp).setStartOffset(startOffset)
+ }
+
+ def poll: Option[KafkaMessage] = {
+ Option(incomingQueue.poll())
+ }
+
+ override def run(): Unit = {
+ try {
+ var nextOffsets = Map.empty[TopicAndPartition, Long]
+ var reset = false
+ val sleeper = new ExponentialBackoffSleeper(
+ backOffMultiplier = 2.0,
+ initialDurationMs = 100L,
+ maximumDurationMs = 10000L)
+ while (!Thread.currentThread().isInterrupted) {
+ try {
+ if (reset) {
+ nextOffsets = consumers.mapValues(_.getNextOffset)
+ resetConsumers(nextOffsets)
+ reset = false
+ }
+ val hasMoreMessages = fetchMessage
+ sleeper.reset()
+ if (!hasMoreMessages) {
+ Thread.sleep(fetchSleepMS)
+ }
+ } catch {
+ case exception: Exception =>
+ LOG.warn(s"resetting consumers due to $exception")
+ reset = true
+ sleeper.sleep()
+ }
+ }
+ } catch {
+ case e: InterruptedException => LOG.info("fetch thread got interrupted exception")
+ case e: ClosedByInterruptException => LOG.info("fetch thread closed by interrupt exception")
+ } finally {
+ consumers.values.foreach(_.close())
+ }
+ }
+
+ /**
+ * fetch message from each TopicAndPartition in a round-robin way
+ */
+ def fetchMessage: Boolean = {
+ consumers.foldLeft(false) { (hasNext, tpAndConsumer) =>
+ val (_, consumer) = tpAndConsumer
+ if (incomingQueue.size < fetchThreshold) {
+ if (consumer.hasNext) {
+ incomingQueue.put(consumer.next())
+ true
+ } else {
+ hasNext
+ }
+ } else {
+ true
+ }
+ }
+ }
+
+ private def createAllConsumers: Map[TopicAndPartition, KafkaConsumer] = {
+ topicAndPartitions.map(tp => tp -> createConsumer(tp)).toMap
+ }
+
+ private def resetConsumers(nextOffsets: Map[TopicAndPartition, Long]): Unit = {
+ consumers.values.foreach(_.close())
+ consumers = createAllConsumers
+ consumers.foreach { case (tp, consumer) =>
+ consumer.setStartOffset(nextOffsets(tp))
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/consumer/KafkaConsumer.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/consumer/KafkaConsumer.scala b/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/consumer/KafkaConsumer.scala
new file mode 100644
index 0000000..55c327b
--- /dev/null
+++ b/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/consumer/KafkaConsumer.scala
@@ -0,0 +1,103 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.kafka.lib.consumer
+
+import kafka.api.{FetchRequestBuilder, OffsetRequest}
+import kafka.common.ErrorMapping._
+import kafka.common.TopicAndPartition
+import kafka.consumer.{ConsumerConfig, SimpleConsumer}
+import kafka.message.MessageAndOffset
+import kafka.utils.Utils
+
+import org.apache.gearpump.streaming.kafka.lib.KafkaUtil
+
+object KafkaConsumer {
+ def apply(topic: String, partition: Int, startOffsetTime: Long, config: ConsumerConfig)
+ : KafkaConsumer = {
+ val connectZk = KafkaUtil.connectZookeeper(config)
+ val broker = KafkaUtil.getBroker(connectZk(), topic, partition)
+ val soTimeout = config.socketTimeoutMs
+ val soBufferSize = config.socketReceiveBufferBytes
+ val fetchSize = config.fetchMessageMaxBytes
+ val clientId = config.clientId
+ val consumer = new SimpleConsumer(broker.host, broker.port, soTimeout, soBufferSize, clientId)
+ val getIterator = (offset: Long) => {
+ val request = new FetchRequestBuilder()
+ .addFetch(topic, partition, offset, fetchSize)
+ .build()
+
+ val response = consumer.fetch(request)
+ response.errorCode(topic, partition) match {
+ case NoError => response.messageSet(topic, partition).iterator
+ case error => throw exceptionFor(error)
+ }
+ }
+ new KafkaConsumer(consumer, topic, partition, getIterator, startOffsetTime)
+ }
+}
+
+/**
+ * uses kafka kafka.consumer.SimpleConsumer to consume and iterate over
+ * messages from a kafka kafka.common.TopicAndPartition.
+ */
+class KafkaConsumer(consumer: SimpleConsumer,
+ topic: String,
+ partition: Int,
+ getIterator: (Long) => Iterator[MessageAndOffset],
+ startOffsetTime: Long = OffsetRequest.EarliestTime) {
+ private val earliestOffset = consumer
+ .earliestOrLatestOffset(TopicAndPartition(topic, partition), startOffsetTime, -1)
+ private var nextOffset: Long = earliestOffset
+ private var iterator: Iterator[MessageAndOffset] = getIterator(nextOffset)
+
+ def setStartOffset(startOffset: Long): Unit = {
+ nextOffset = startOffset
+ iterator = getIterator(nextOffset)
+ }
+
+ def next(): KafkaMessage = {
+ val mo = iterator.next()
+ val message = mo.message
+
+ nextOffset = mo.nextOffset
+
+ val offset = mo.offset
+ val payload = Utils.readBytes(message.payload)
+ new KafkaMessage(topic, partition, offset, Option(message.key).map(Utils.readBytes), payload)
+ }
+
+ def hasNext: Boolean = {
+ @annotation.tailrec
+ def hasNextHelper(iter: Iterator[MessageAndOffset], newIterator: Boolean): Boolean = {
+ if (iter.hasNext) true
+ else if (newIterator) false
+ else {
+ iterator = getIterator(nextOffset)
+ hasNextHelper(iterator, newIterator = true)
+ }
+ }
+ hasNextHelper(iterator, newIterator = false)
+ }
+
+ def getNextOffset: Long = nextOffset
+
+ def close(): Unit = {
+ consumer.close()
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/consumer/KafkaMessage.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/consumer/KafkaMessage.scala b/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/consumer/KafkaMessage.scala
new file mode 100644
index 0000000..e0813d9
--- /dev/null
+++ b/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/consumer/KafkaMessage.scala
@@ -0,0 +1,38 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.kafka.lib.consumer
+
+import kafka.common.TopicAndPartition
+
+/**
+ * wrapper over messages from kafka
+ * @param topicAndPartition where message comes from
+ * @param offset message offset on kafka queue
+ * @param key message key, could be None
+ * @param msg message payload
+ */
+case class KafkaMessage(topicAndPartition: TopicAndPartition, offset: Long,
+ key: Option[Array[Byte]], msg: Array[Byte]) {
+
+ def this(topic: String, partition: Int, offset: Long,
+ key: Option[Array[Byte]], msg: Array[Byte]) = {
+ this(TopicAndPartition(topic, partition), offset, key, msg)
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/grouper/KafkaDefaultGrouper.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/grouper/KafkaDefaultGrouper.scala b/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/grouper/KafkaDefaultGrouper.scala
new file mode 100644
index 0000000..b34bf09
--- /dev/null
+++ b/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/grouper/KafkaDefaultGrouper.scala
@@ -0,0 +1,38 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.kafka.lib.grouper
+
+import kafka.common.TopicAndPartition
+
+/**
+ * default grouper groups TopicAndPartitions among StreamProducers by partitions
+ *
+ * e.g. given 2 topics (topicA with 2 partitions and topicB with 3 partitions) and
+ * 2 streamProducers (streamProducer0 and streamProducer1)
+ *
+ * streamProducer0 gets (topicA, partition1), (topicB, partition1) and (topicA, partition3)
+ * streamProducer1 gets (topicA, partition2), (topicB, partition2)
+ */
+class KafkaDefaultGrouper extends KafkaGrouper {
+ def group(taskNum: Int, taskIndex: Int, topicAndPartitions: Array[TopicAndPartition])
+ : Array[TopicAndPartition] = {
+ topicAndPartitions.indices.filter(_ % taskNum == taskIndex)
+ .map(i => topicAndPartitions(i)).toArray
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/grouper/KafkaGrouper.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/grouper/KafkaGrouper.scala b/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/grouper/KafkaGrouper.scala
new file mode 100644
index 0000000..e2f5203
--- /dev/null
+++ b/external/kafka/src/main/scala/org/apache/gearpump/streaming/kafka/lib/grouper/KafkaGrouper.scala
@@ -0,0 +1,30 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.kafka.lib.grouper
+
+import kafka.common.TopicAndPartition
+
+/**
+ * this class dispatches kafka kafka.common.TopicAndPartition to gearpump tasks
+ */
+trait KafkaGrouper {
+ def group(taskNum: Int, taskIndex: Int, topicAndPartitions: Array[TopicAndPartition])
+ : Array[TopicAndPartition]
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/test/scala/io/gearpump/streaming/kafka/KafkaSinkSpec.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/test/scala/io/gearpump/streaming/kafka/KafkaSinkSpec.scala b/external/kafka/src/test/scala/io/gearpump/streaming/kafka/KafkaSinkSpec.scala
deleted file mode 100644
index 2b00414..0000000
--- a/external/kafka/src/test/scala/io/gearpump/streaming/kafka/KafkaSinkSpec.scala
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.kafka
-
-import com.twitter.bijection.Injection
-import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord}
-import org.mockito.Mockito._
-import org.scalacheck.Gen
-import org.scalatest.mock.MockitoSugar
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{Matchers, PropSpec}
-
-import io.gearpump.Message
-import io.gearpump.streaming.MockUtil
-
-class KafkaSinkSpec extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
-
- val dataGen = for {
- topic <- Gen.alphaStr
- key <- Gen.alphaStr
- msg <- Gen.alphaStr
- } yield (topic, Injection[String, Array[Byte]](key), Injection[String, Array[Byte]](msg))
-
- property("KafkaSink write should send producer record") {
- forAll(dataGen) {
- (data: (String, Array[Byte], Array[Byte])) =>
- val producer = mock[KafkaProducer[Array[Byte], Array[Byte]]]
- val (topic, key, msg) = data
- val kafkaSink = new KafkaSink(() => producer, topic)
- kafkaSink.write(Message((key, msg)))
- verify(producer).send(MockUtil.argMatch[ProducerRecord[Array[Byte], Array[Byte]]](
- r => r.topic == topic && (r.key sameElements key) && (r.value sameElements msg)))
- kafkaSink.write(Message(msg))
- verify(producer).send(MockUtil.argMatch[ProducerRecord[Array[Byte], Array[Byte]]](
- r => r.topic() == topic && (r.key == null) && (r.value() sameElements msg)
- ))
- kafkaSink.close()
- }
- }
-
- property("KafkaSink close should close kafka producer") {
- val producer = mock[KafkaProducer[Array[Byte], Array[Byte]]]
- val kafkaSink = new KafkaSink(() => producer, "topic")
- kafkaSink.close()
- verify(producer).close()
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/test/scala/io/gearpump/streaming/kafka/KafkaSourceSpec.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/test/scala/io/gearpump/streaming/kafka/KafkaSourceSpec.scala b/external/kafka/src/test/scala/io/gearpump/streaming/kafka/KafkaSourceSpec.scala
deleted file mode 100644
index 7c804f7..0000000
--- a/external/kafka/src/test/scala/io/gearpump/streaming/kafka/KafkaSourceSpec.scala
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.kafka
-
-import scala.util.{Failure, Success}
-
-import com.twitter.bijection.Injection
-import kafka.common.TopicAndPartition
-import org.mockito.Matchers._
-import org.mockito.Mockito._
-import org.scalacheck.Gen
-import org.scalatest.mock.MockitoSugar
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{Matchers, PropSpec}
-
-import io.gearpump.Message
-import io.gearpump.streaming.kafka.lib.consumer.{FetchThread, KafkaMessage}
-import io.gearpump.streaming.kafka.lib.{KafkaOffsetManager, KafkaSourceConfig}
-import io.gearpump.streaming.transaction.api.OffsetStorage.StorageEmpty
-import io.gearpump.streaming.transaction.api.{MessageDecoder, OffsetStorageFactory, TimeStampFilter}
-
-class KafkaSourceSpec extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
-
- val startTimeGen = Gen.choose[Long](0L, 1000L)
- val offsetGen = Gen.choose[Long](0L, 1000L)
-
- property("KafkaSource open sets consumer to earliest offset") {
- val topicAndPartition = mock[TopicAndPartition]
- val fetchThread = mock[FetchThread]
- val offsetManager = mock[KafkaOffsetManager]
- val messageDecoder = mock[MessageDecoder]
- val timestampFilter = mock[TimeStampFilter]
- val offsetStorageFactory = mock[OffsetStorageFactory]
- val kafkaConfig = mock[KafkaSourceConfig]
- val kafkaSource = new KafkaSource(kafkaConfig, offsetStorageFactory, messageDecoder,
- timestampFilter, Some(fetchThread), Map(topicAndPartition -> offsetManager))
-
- kafkaSource.setStartTime(None)
-
- verify(fetchThread).start()
- verify(fetchThread, never()).setStartOffset(anyObject[TopicAndPartition](), anyLong())
- }
-
- property("KafkaSource open should not set consumer start offset if offset storage is empty") {
- forAll(startTimeGen) { (startTime: Long) =>
- val offsetManager = mock[KafkaOffsetManager]
- val topicAndPartition = mock[TopicAndPartition]
- val fetchThread = mock[FetchThread]
- val messageDecoder = mock[MessageDecoder]
- val timestampFilter = mock[TimeStampFilter]
- val offsetStorageFactory = mock[OffsetStorageFactory]
- val kafkaConfig = mock[KafkaSourceConfig]
- val source = new KafkaSource(kafkaConfig, offsetStorageFactory, messageDecoder,
- timestampFilter, Some(fetchThread), Map(topicAndPartition -> offsetManager))
-
- when(offsetManager.resolveOffset(startTime)).thenReturn(Failure(StorageEmpty))
-
- source.setStartTime(Some(startTime))
- verify(fetchThread, never()).setStartOffset(anyObject[TopicAndPartition](), anyLong())
- verify(fetchThread).start()
-
- when(offsetManager.resolveOffset(startTime)).thenReturn(Failure(new RuntimeException))
- intercept[RuntimeException] {
- source.setStartTime(Some(startTime))
- }
- source.close()
- }
- }
-
- property("KafkaSource open should set consumer start offset if offset storage is not empty") {
- forAll(startTimeGen, offsetGen) {
- (startTime: Long, offset: Long) =>
- val offsetManager = mock[KafkaOffsetManager]
- val topicAndPartition = mock[TopicAndPartition]
- val fetchThread = mock[FetchThread]
- val messageDecoder = mock[MessageDecoder]
- val timestampFilter = mock[TimeStampFilter]
- val offsetStorageFactory = mock[OffsetStorageFactory]
- val kafkaConfig = mock[KafkaSourceConfig]
- val source = new KafkaSource(kafkaConfig, offsetStorageFactory, messageDecoder,
- timestampFilter, Some(fetchThread), Map(topicAndPartition -> offsetManager))
-
- when(offsetManager.resolveOffset(startTime)).thenReturn(Success(offset))
-
- source.setStartTime(Some(startTime))
- verify(fetchThread).setStartOffset(topicAndPartition, offset)
- verify(fetchThread).start()
-
- when(offsetManager.resolveOffset(startTime)).thenReturn(Failure(new RuntimeException))
- intercept[RuntimeException] {
- source.setStartTime(Some(startTime))
- }
- source.close()
- }
- }
-
- property("KafkaSource read should return number of messages in best effort") {
- val kafkaMsgGen = for {
- topic <- Gen.alphaStr
- partition <- Gen.choose[Int](0, 1000)
- offset <- Gen.choose[Long](0L, 1000L)
- key = None
- msg <- Gen.alphaStr.map(Injection[String, Array[Byte]])
- } yield KafkaMessage(TopicAndPartition(topic, partition), offset, key, msg)
- val msgQueueGen = Gen.containerOf[Array, KafkaMessage](kafkaMsgGen)
- forAll(msgQueueGen) {
- (msgQueue: Array[KafkaMessage]) =>
- val offsetManager = mock[KafkaOffsetManager]
- val fetchThread = mock[FetchThread]
- val messageDecoder = mock[MessageDecoder]
-
- val timestampFilter = mock[TimeStampFilter]
- val offsetStorageFactory = mock[OffsetStorageFactory]
- val kafkaConfig = mock[KafkaSourceConfig]
- val offsetManagers = msgQueue.map(_.topicAndPartition -> offsetManager).toMap
-
- val source = new KafkaSource(kafkaConfig, offsetStorageFactory, messageDecoder,
- timestampFilter, Some(fetchThread), offsetManagers)
-
- if (msgQueue.isEmpty) {
- when(fetchThread.poll).thenReturn(None)
- source.read() shouldBe null
- } else {
- msgQueue.indices.foreach { i =>
- val message = Message(msgQueue(i).msg)
- when(fetchThread.poll).thenReturn(Option(msgQueue(i)))
- when(messageDecoder.fromBytes(anyObject[Array[Byte]])).thenReturn(message)
- when(offsetManager.filter(anyObject[(Message, Long)])).thenReturn(Some(message))
- when(timestampFilter.filter(anyObject[Message], anyLong())).thenReturn(Some(message))
-
- source.read shouldBe message
- }
- }
- source.close()
- }
- }
-
- property("KafkaSource close should close all offset managers") {
- val offsetManager = mock[KafkaOffsetManager]
- val topicAndPartition = mock[TopicAndPartition]
- val fetchThread = mock[FetchThread]
- val timestampFilter = mock[TimeStampFilter]
- val messageDecoder = mock[MessageDecoder]
- val offsetStorageFactory = mock[OffsetStorageFactory]
- val kafkaConfig = mock[KafkaSourceConfig]
- val source = new KafkaSource(kafkaConfig, offsetStorageFactory, messageDecoder,
- timestampFilter, Some(fetchThread), Map(topicAndPartition -> offsetManager))
- source.close()
- verify(offsetManager).close()
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/test/scala/io/gearpump/streaming/kafka/lib/DefaultMessageDecoderSpec.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/test/scala/io/gearpump/streaming/kafka/lib/DefaultMessageDecoderSpec.scala b/external/kafka/src/test/scala/io/gearpump/streaming/kafka/lib/DefaultMessageDecoderSpec.scala
deleted file mode 100644
index f3b5425..0000000
--- a/external/kafka/src/test/scala/io/gearpump/streaming/kafka/lib/DefaultMessageDecoderSpec.scala
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.kafka.lib
-
-import com.twitter.bijection.Injection
-import org.scalacheck.Gen
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{Matchers, PropSpec}
-
-class DefaultMessageDecoderSpec extends PropSpec with PropertyChecks with Matchers {
- property("DefaultMessageDecoder should keep the original bytes data in Message") {
- val decoder = new DefaultMessageDecoder()
- forAll(Gen.alphaStr) { (s: String) =>
- val bytes = Injection[String, Array[Byte]](s)
- decoder.fromBytes(bytes).msg shouldBe bytes
- }
- }
-}
-
-class StringMessageDecoderSpec extends PropSpec with PropertyChecks with Matchers {
- property("StringMessageDecoder should decode original bytes data into string") {
- val decoder = new StringMessageDecoder()
- forAll(Gen.alphaStr) { (s: String) =>
- val bytes = Injection[String, Array[Byte]](s)
- decoder.fromBytes(bytes).msg shouldBe s
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/test/scala/io/gearpump/streaming/kafka/lib/KafkaOffsetManagerSpec.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/test/scala/io/gearpump/streaming/kafka/lib/KafkaOffsetManagerSpec.scala b/external/kafka/src/test/scala/io/gearpump/streaming/kafka/lib/KafkaOffsetManagerSpec.scala
deleted file mode 100644
index c762b06..0000000
--- a/external/kafka/src/test/scala/io/gearpump/streaming/kafka/lib/KafkaOffsetManagerSpec.scala
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.kafka.lib
-
-import scala.util.{Failure, Success}
-
-import com.twitter.bijection.Injection
-import org.mockito.Mockito._
-import org.scalacheck.Gen
-import org.scalatest.mock.MockitoSugar
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{Matchers, PropSpec}
-
-import io.gearpump.Message
-import io.gearpump.streaming.transaction.api.OffsetStorage
-import io.gearpump.streaming.transaction.api.OffsetStorage.{Overflow, StorageEmpty, Underflow}
-
-class KafkaOffsetManagerSpec extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
-
- val timeStampGen = Gen.choose[Long](0L, 1000L)
- val messageGen = for {
- msg <- Gen.alphaStr
- time <- timeStampGen
- } yield Message(msg, time)
-
- val messageAndOffsetsGen = Gen.listOf[Message](messageGen).map(_.zipWithIndex)
-
- property("KafkaOffsetManager should append offset to storage in monotonically" +
- " increasing time order") {
- forAll(messageAndOffsetsGen) { (messageAndOffsets: List[(Message, Int)]) =>
- val offsetStorage = mock[OffsetStorage]
- val offsetManager = new KafkaOffsetManager(offsetStorage)
- messageAndOffsets.foldLeft(0L) { (max, messageAndOffset) =>
- val (message, offset) = messageAndOffset
- offsetManager.filter((message, offset.toLong)) shouldBe Option(message)
- if (message.timestamp > max) {
- val newMax = message.timestamp
- verify(offsetStorage).append(newMax, Injection[Long, Array[Byte]](offset.toLong))
- newMax
- } else {
- verifyZeroInteractions(offsetStorage)
- max
- }
- }
- offsetManager.close()
- }
- }
-
- val minTimeStampGen = Gen.choose[Long](0L, 500L)
- val maxTimeStampGen = Gen.choose[Long](500L, 1000L)
- property("KafkaOffsetManager resolveOffset should " +
- "report StorageEmpty failure when storage is empty") {
- forAll(timeStampGen) { (time: Long) =>
- val offsetStorage = mock[OffsetStorage]
- val offsetManager = new KafkaOffsetManager(offsetStorage)
- when(offsetStorage.lookUp(time)).thenReturn(Failure(StorageEmpty))
- offsetManager.resolveOffset(time) shouldBe Failure(StorageEmpty)
-
- doThrow(new RuntimeException).when(offsetStorage).lookUp(time)
- intercept[RuntimeException] {
- offsetManager.resolveOffset(time)
- }
- offsetManager.close()
- }
- }
-
- val offsetGen = Gen.choose[Long](0L, 1000L)
- property("KafkaOffsetManager resolveOffset should return a valid" +
- " offset when storage is not empty") {
- forAll(timeStampGen, minTimeStampGen, maxTimeStampGen, offsetGen) {
- (time: Long, min: Long, max: Long, offset: Long) =>
- val offsetStorage = mock[OffsetStorage]
- val offsetManager = new KafkaOffsetManager(offsetStorage)
- if (time < min) {
- when(offsetStorage.lookUp(time)).thenReturn(Failure(
- Underflow(Injection[Long, Array[Byte]](min))))
- offsetManager.resolveOffset(time) shouldBe Success(min)
- } else if (time > max) {
- when(offsetStorage.lookUp(time)).thenReturn(Failure(
- Overflow(Injection[Long, Array[Byte]](max))))
- offsetManager.resolveOffset(time) shouldBe Success(max)
- } else {
- when(offsetStorage.lookUp(time)).thenReturn(Success(Injection[Long, Array[Byte]](offset)))
- offsetManager.resolveOffset(time) shouldBe Success(offset)
- }
-
- doThrow(new RuntimeException).when(offsetStorage).lookUp(time)
- intercept[RuntimeException] {
- offsetManager.resolveOffset(time)
- }
- offsetManager.close()
- }
- }
-
- property("KafkaOffsetManager close should close offset storage") {
- val offsetStorage = mock[OffsetStorage]
- val offsetManager = new KafkaOffsetManager(offsetStorage)
- offsetManager.close()
- verify(offsetStorage).close()
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/test/scala/io/gearpump/streaming/kafka/lib/KafkaStorageSpec.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/test/scala/io/gearpump/streaming/kafka/lib/KafkaStorageSpec.scala b/external/kafka/src/test/scala/io/gearpump/streaming/kafka/lib/KafkaStorageSpec.scala
deleted file mode 100644
index af23c12..0000000
--- a/external/kafka/src/test/scala/io/gearpump/streaming/kafka/lib/KafkaStorageSpec.scala
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.kafka.lib
-
-// TODO: Fix the UT failure!
-
-// class KafkaStorageSpec extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
-// val minTimeGen = Gen.choose[Long](1L, 500L)
-// val maxTimeGen = Gen.choose[Long](500L, 999L)
-//
-// property("KafkaStorage lookup time should report StorageEmpty if storage is empty") {
-// forAll { (time: Long, topic: String) =>
-// val producer = mock[KafkaProducer[Array[Byte], Array[Byte]]]
-// val getConsumer = () => mock[KafkaConsumer]
-// val connectZk = () => mock[ZkClient]
-// val storage = new KafkaStorage(topic, topicExists = false, producer, getConsumer(),
-// connectZk())
-// storage.lookUp(time) shouldBe Failure(StorageEmpty)
-// }
-// }
-//
-// property("KafkaStorage lookup time should return data or report failure if storage not empty") {
-// forAll(minTimeGen, maxTimeGen, Gen.alphaStr) {(minTime: Long, maxTime: Long, topic: String) =>
-// val timeAndOffsets = minTime.to(maxTime).zipWithIndex.map { case (time, index) =>
-// val offset = index.toLong
-// time -> offset
-// }
-// val timeAndOffsetsMap = timeAndOffsets.toMap
-// val data = timeAndOffsets.map {
-// case (time, offset) =>
-// new KafkaMessage(topic, 0, offset.toLong, Some(Injection[Long, Array[Byte]](time)),
-// Injection[Long, Array[Byte]](offset))
-// }.toList
-//
-// val producer = mock[KafkaProducer[Array[Byte], Array[Byte]]]
-// val consumer = mock[KafkaConsumer]
-// val getConsumer = () => consumer
-// val connectZk = () => mock[ZkClient]
-//
-// val hasNexts = List.fill(data.tail.size)(true) :+ false
-// when(consumer.hasNext).thenReturn(true, hasNexts:_*)
-// when(consumer.next).thenReturn(data.head, data.tail:_*)
-//
-// val storage = new KafkaStorage(topic, topicExists = true, producer,
-// getConsumer(), connectZk())
-// forAll(Gen.choose[Long](minTime, maxTime)) {
-// time =>
-// storage.lookUp(time) match {
-// case Success(array) =>
-// array should equal (Injection[Long, Array[Byte]](timeAndOffsetsMap(time)))
-// case Failure(e) => fail("time in range should return Success with value")
-// }
-// }
-//
-// forAll(Gen.choose[Long](0L, minTime - 1)) {
-// time =>
-// storage.lookUp(time) match {
-// case Failure(e) => e shouldBe a [Underflow]
-// e.asInstanceOf[Underflow].min should equal
-// (Injection[Long, Array[Byte]](timeAndOffsetsMap(minTime)))
-// case Success(_) => fail("time less than min should return Underflow failure")
-// }
-// }
-//
-// forAll(Gen.choose[Long](maxTime + 1, 1000L)) {
-// time =>
-// storage.lookUp(time) match {
-// case Failure(e) => e shouldBe a [Overflow]
-// e.asInstanceOf[Overflow].max should equal
-// (Injection[Long, Array[Byte]](timeAndOffsetsMap(maxTime)))
-// case Success(_) => fail("time larger than max should return Overflow failure")
-// }
-// }
-// }
-// }
-//
-// property("KafkaStorage append should send data to Kafka") {
-// forAll(Gen.chooseNum[Long](1, 1000), Gen.chooseNum[Long](0, 1000),
-// Gen.alphaStr, Gen.oneOf(true, false)) {
-// (time: Long, offset: Long, topic: String, topicExists: Boolean) =>
-// val producer = mock[KafkaProducer[Array[Byte], Array[Byte]]]
-// val getConsumer = () => mock[KafkaConsumer]
-// val connectZk = () => mock[ZkClient]
-// val storage = new KafkaStorage(topic, topicExists, producer, getConsumer(), connectZk())
-// val offsetBytes = Injection[Long, Array[Byte]](offset)
-// storage.append(time, offsetBytes)
-// verify(producer).send(anyObject[ProducerRecord[Array[Byte], Array[Byte]]]())
-// }
-// }
-//
-// val topicAndPartitionGen = for {
-// topic <- Gen.alphaStr
-// partition <- Gen.choose[Int](0, 100)
-// } yield TopicAndPartition(topic, partition)
-// property("KafkaStorage should load data from Kafka") {
-// val kafkaMsgGen = for {
-// timestamp <- Gen.choose[Long](1L, 1000L)
-// offset <- Gen.choose[Long](0L, 1000L)
-// } yield (timestamp, Injection[Long, Array[Byte]](offset))
-// val msgListGen = Gen.listOf[(Long, Array[Byte])](kafkaMsgGen)
-//
-// val topicExistsGen = Gen.oneOf(true, false)
-//
-// forAll(topicAndPartitionGen, msgListGen) {
-// (topicAndPartition: TopicAndPartition, msgList: List[(Long, Array[Byte])]) =>
-// val producer= mock[KafkaProducer[Array[Byte], Array[Byte]]]
-// val consumer = mock[KafkaConsumer]
-// val getConsumer = () => consumer
-// val connectZk = () => mock[ZkClient]
-// val kafkaStorage = new KafkaStorage(topicAndPartition.topic,
-// topicExists = true, producer, getConsumer(), connectZk())
-// msgList match {
-// case Nil =>
-// when(consumer.hasNext).thenReturn(false)
-// case list =>
-// val hasNexts = List.fill(list.tail.size)(true) :+ false
-// val kafkaMsgList = list.zipWithIndex.map { case ((timestamp, bytes), index) =>
-// KafkaMessage(topicAndPartition, index.toLong,
-// Some(Injection[Long, Array[Byte]](timestamp)), bytes)
-// }
-// when(consumer.hasNext).thenReturn(true, hasNexts: _*)
-// when(consumer.next).thenReturn(kafkaMsgList.head, kafkaMsgList.tail: _*)
-// }
-// kafkaStorage.load(consumer) shouldBe msgList
-// }
-// }
-//
-// property("KafkaStorage should not get consumer when topic doesn't exist") {
-// forAll(Gen.alphaStr) { (topic: String) =>
-// val producer = mock[KafkaProducer[Array[Byte], Array[Byte]]]
-// val getConsumer = mock[() => KafkaConsumer]
-// val connectZk = () => mock[ZkClient]
-// val kafkaStorage = new KafkaStorage(topic,
-// topicExists = false, producer, getConsumer(), connectZk())
-// verify(getConsumer, never()).apply()
-// kafkaStorage.close()
-// }
-// }
-//
-// property("KafkaStorage should fail to load invalid KafkaMessage") {
-// val invalidKafkaMsgGen = for {
-// tp <- topicAndPartitionGen
-// offset <- Gen.choose[Long](1L, 1000L)
-// timestamp <- Gen.oneOf(Some(Injection[ByteBuffer, Array[Byte]](ByteBuffer.allocate(0))),
-// None)
-// msg <- Gen.alphaStr.map(Injection[String, Array[Byte]])
-// } yield KafkaMessage(tp, offset, timestamp, msg)
-// forAll(invalidKafkaMsgGen) { (invalidKafkaMsg: KafkaMessage) =>
-// val consumer = mock[KafkaConsumer]
-// val getConsumer = () => consumer
-// val producer = mock[KafkaProducer[Array[Byte], Array[Byte]]]
-// val connectZk = () => mock[ZkClient]
-// val kafkaStorage = new KafkaStorage(invalidKafkaMsg.topicAndPartition.topic,
-// topicExists = true, producer, getConsumer(), connectZk())
-// when(consumer.hasNext).thenReturn(true, false)
-// when(consumer.next).thenReturn(invalidKafkaMsg, invalidKafkaMsg)
-// Try(kafkaStorage.load(consumer)).isFailure shouldBe true
-// }
-// }
-//
-// property("KafkaStorage close should close kafka producer and delete topic") {
-// val producer = mock[KafkaProducer[Array[Byte], Array[Byte]]]
-// val getConsumer = () => mock[KafkaConsumer]
-// val zkClient = mock[ZkClient]
-// val connectZk = () => zkClient
-// val kafkaStorage = new KafkaStorage("topic", false, producer, getConsumer(), connectZk())
-// kafkaStorage.close()
-// verify(producer).close()
-// verify(zkClient).createPersistent(anyString(), anyString())
-// }
-// }
[17/49] incubator-gearpump git commit: fix GEARPUMP-118 change
package name to org.apache
Posted by ma...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/test/scala/io/gearpump/streaming/kafka/lib/KafkaUtilSpec.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/test/scala/io/gearpump/streaming/kafka/lib/KafkaUtilSpec.scala b/external/kafka/src/test/scala/io/gearpump/streaming/kafka/lib/KafkaUtilSpec.scala
deleted file mode 100644
index 7447308..0000000
--- a/external/kafka/src/test/scala/io/gearpump/streaming/kafka/lib/KafkaUtilSpec.scala
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.kafka.lib
-
-import kafka.common.TopicAndPartition
-import kafka.server.{KafkaConfig => KafkaServerConfig}
-import kafka.utils.{TestUtils, TestZKUtils}
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{BeforeAndAfterEach, Matchers, PropSpec}
-
-import io.gearpump.streaming.kafka.lib.grouper.KafkaGrouper
-import io.gearpump.streaming.kafka.util.KafkaServerHarness
-
-class KafkaUtilSpec
- extends PropSpec with PropertyChecks with BeforeAndAfterEach
- with Matchers with KafkaServerHarness {
-
- val numServers = 1
- override val configs: List[KafkaServerConfig] =
- for (props <- TestUtils.createBrokerConfigs(numServers, enableControlledShutdown = false))
- yield new KafkaServerConfig(props) {
- override val zkConnect = TestZKUtils.zookeeperConnect
- override val numPartitions = 4
- }
-
- override def beforeEach(): Unit = {
- super.setUp()
- }
-
- override def afterEach(): Unit = {
- super.tearDown()
- }
-
- import io.gearpump.streaming.kafka.lib.KafkaUtil._
-
- property("KafkaUtil should be able to create topic") {
- val args = {
- Table(
- ("topic", "partitions", "replicas"),
- (TestUtils.tempTopic, 1, numServers),
- (TestUtils.tempTopic, 2, numServers + 1),
- ("", 1, numServers),
- (TestUtils.tempTopic, 0, numServers),
- (TestUtils.tempTopic, 1, 0)
- )
- }
- forAll(args) {
- (topic: String, partitions: Int, replicas: Int) =>
- if (topic.nonEmpty && partitions > 0 && replicas > 0 && replicas <= numServers) {
- createTopic(connectZk(), topic, partitions, replicas) shouldBe false
- createTopic(connectZk(), topic, partitions, replicas) shouldBe true
- } else {
- intercept[RuntimeException] {
- createTopic(connectZk(), topic, partitions, replicas)
- }
- }
- }
- }
-
- property("KafkaUtil should be able to get broker info") {
- val brokerList = getBrokerList
- val partitions = 2
- val replicas = numServers
- val topic = TestUtils.tempTopic()
- intercept[RuntimeException] {
- getBroker(connectZk(), topic, partitions)
- }
- val partitionsToBrokers = createTopicUntilLeaderIsElected(topic, partitions, replicas)
- 0.until(partitions).foreach { part =>
- val hostPorts = brokerList(partitionsToBrokers(part).get).split(":")
- val broker = getBroker(connectZk(), topic, part)
-
- broker.host shouldBe hostPorts(0)
- broker.port.toString shouldBe hostPorts(1)
- }
- }
-
- property("KafkaUtil should be able to get TopicAndPartitions info and group with KafkaGrouper") {
- val grouper: KafkaGrouper = new KafkaGrouper {
- override def group(taskNum: Int, taskIndex: Int, topicAndPartitions: Array[TopicAndPartition])
- : Array[TopicAndPartition] = {
- topicAndPartitions
- }
- }
- val topicNum = 3
- val topics = List.fill(topicNum)(TestUtils.tempTopic())
- topics.foreach(t => createTopicUntilLeaderIsElected(t, partitions = 1, replicas = 1))
- KafkaUtil.getTopicAndPartitions(connectZk(), topics).toSet shouldBe
- topics.map(t => TopicAndPartition(t, 0)).toSet
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/test/scala/io/gearpump/streaming/kafka/lib/consumer/ExponentialBackoffSleeperSpec.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/test/scala/io/gearpump/streaming/kafka/lib/consumer/ExponentialBackoffSleeperSpec.scala b/external/kafka/src/test/scala/io/gearpump/streaming/kafka/lib/consumer/ExponentialBackoffSleeperSpec.scala
deleted file mode 100644
index 3983874..0000000
--- a/external/kafka/src/test/scala/io/gearpump/streaming/kafka/lib/consumer/ExponentialBackoffSleeperSpec.scala
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.kafka.lib.consumer
-
-import org.scalatest.{Matchers, WordSpec}
-
-class ExponentialBackoffSleeperSpec extends WordSpec with Matchers {
-
- "ExponentialBackOffSleeper" should {
- "sleep for increasing duration" in {
- val sleeper = new ExponentialBackoffSleeper(
- backOffMultiplier = 2.0,
- initialDurationMs = 100,
- maximumDurationMs = 10000
- )
- sleeper.getSleepDuration shouldBe 100
- sleeper.setNextSleepDuration()
- sleeper.getSleepDuration shouldBe 200
- sleeper.setNextSleepDuration()
- sleeper.getSleepDuration shouldBe 400
- sleeper.setNextSleepDuration()
- sleeper.getSleepDuration shouldBe 800
- }
-
- "sleep for no more than maximum duration" in {
- val sleeper = new ExponentialBackoffSleeper(
- backOffMultiplier = 2.0,
- initialDurationMs = 6400,
- maximumDurationMs = 10000
- )
- sleeper.getSleepDuration shouldBe 6400
- sleeper.setNextSleepDuration()
- sleeper.getSleepDuration shouldBe 10000
- sleeper.setNextSleepDuration()
- sleeper.getSleepDuration shouldBe 10000
- }
-
- "sleep for initial duration after reset" in {
- val sleeper = new ExponentialBackoffSleeper(
- backOffMultiplier = 2.0,
- initialDurationMs = 100,
- maximumDurationMs = 10000
- )
- sleeper.getSleepDuration shouldBe 100
- sleeper.setNextSleepDuration()
- sleeper.getSleepDuration shouldBe 200
- sleeper.reset()
- sleeper.getSleepDuration shouldBe 100
- }
- }
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/test/scala/io/gearpump/streaming/kafka/lib/consumer/FetchThreadSpec.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/test/scala/io/gearpump/streaming/kafka/lib/consumer/FetchThreadSpec.scala b/external/kafka/src/test/scala/io/gearpump/streaming/kafka/lib/consumer/FetchThreadSpec.scala
deleted file mode 100644
index d955dfa..0000000
--- a/external/kafka/src/test/scala/io/gearpump/streaming/kafka/lib/consumer/FetchThreadSpec.scala
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.kafka.lib.consumer
-
-import java.util.concurrent.LinkedBlockingQueue
-
-import kafka.common.TopicAndPartition
-import org.mockito.Mockito._
-import org.scalacheck.Gen
-import org.scalatest.mock.MockitoSugar
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{Matchers, PropSpec}
-
-class FetchThreadSpec extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
-
- val nonNegativeGen = Gen.choose[Int](0, 1000)
- val positiveGen = Gen.choose[Int](1, 1000)
- val startOffsetGen = Gen.choose[Long](0L, 1000L)
- property("FetchThread should set startOffset to iterators") {
- forAll(nonNegativeGen, nonNegativeGen, startOffsetGen) {
- (fetchThreshold: Int, fetchSleepMS: Int, startOffset: Long) =>
- val topicAndPartition = mock[TopicAndPartition]
- val consumer = mock[KafkaConsumer]
- val createConsumer = (tp: TopicAndPartition) => consumer
- val incomingQueue = new LinkedBlockingQueue[KafkaMessage]()
- val fetchThread = new FetchThread(Array(topicAndPartition), createConsumer,
- incomingQueue, fetchThreshold, fetchSleepMS)
- fetchThread.setStartOffset(topicAndPartition, startOffset)
- verify(consumer).setStartOffset(startOffset)
- }
- }
-
- val topicAndPartitionGen = for {
- topic <- Gen.alphaStr
- partition <- Gen.choose[Int](0, Int.MaxValue)
- } yield TopicAndPartition(topic, partition)
- property("FetchThread should only fetchMessage when the number " +
- "of messages in queue is below the threshold") {
- forAll(positiveGen, nonNegativeGen, nonNegativeGen, startOffsetGen, topicAndPartitionGen) {
- (messageNum: Int, fetchThreshold: Int, fetchSleepMS: Int,
- startOffset: Long, topicAndPartition: TopicAndPartition) =>
- val message = mock[KafkaMessage]
- val consumer = mock[KafkaConsumer]
- val createConsumer = (tp: TopicAndPartition) => consumer
- when(consumer.hasNext).thenReturn(true)
- when(consumer.next).thenReturn(message)
- val incomingQueue = new LinkedBlockingQueue[KafkaMessage]()
- val fetchThread = new FetchThread(Array(topicAndPartition), createConsumer,
- incomingQueue, fetchThreshold, fetchSleepMS)
-
- 0.until(messageNum) foreach { _ =>
- fetchThread.fetchMessage
- }
-
- incomingQueue.size() shouldBe Math.min(messageNum, fetchThreshold)
- }
- }
-
- property("FetchThread poll should try to retrieve and remove the head of incoming queue") {
- val topicAndPartition = mock[TopicAndPartition]
- val consumer = mock[KafkaConsumer]
- val createConsumer = (tp: TopicAndPartition) => consumer
- val kafkaMsg = mock[KafkaMessage]
- val incomingQueue = new LinkedBlockingQueue[KafkaMessage]()
- incomingQueue.put(kafkaMsg)
- val fetchThread = new FetchThread(Array(topicAndPartition), createConsumer, incomingQueue, 0, 0)
- fetchThread.poll shouldBe Some(kafkaMsg)
- fetchThread.poll shouldBe None
- }
-
- val tpAndHasNextGen = for {
- tp <- topicAndPartitionGen
- hasNext <- Gen.oneOf(true, false)
- } yield (tp, hasNext)
-
- val tpHasNextMapGen = Gen.listOf[(TopicAndPartition, Boolean)](tpAndHasNextGen)
- .map(_.toMap) suchThat (_.nonEmpty)
-
- property("FetchThread fetchMessage should return false when there are no more messages " +
- "from any TopicAndPartition") {
- forAll(tpHasNextMapGen, nonNegativeGen) {
- (tpHasNextMap: Map[TopicAndPartition, Boolean], fetchSleepMS: Int) =>
- val createConsumer = (tp: TopicAndPartition) => {
- val consumer = mock[KafkaConsumer]
- val kafkaMsg = mock[KafkaMessage]
- val hasNext = tpHasNextMap(tp)
- when(consumer.hasNext).thenReturn(hasNext)
- when(consumer.next).thenReturn(kafkaMsg)
- consumer
- }
- val incomingQueue = new LinkedBlockingQueue[KafkaMessage]()
- val fetchThread = new FetchThread(tpHasNextMap.keys.toArray,
- createConsumer, incomingQueue, tpHasNextMap.size + 1, fetchSleepMS)
- fetchThread.fetchMessage shouldBe tpHasNextMap.values.reduce(_ || _)
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/test/scala/io/gearpump/streaming/kafka/lib/consumer/KafkaConsumerSpec.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/test/scala/io/gearpump/streaming/kafka/lib/consumer/KafkaConsumerSpec.scala b/external/kafka/src/test/scala/io/gearpump/streaming/kafka/lib/consumer/KafkaConsumerSpec.scala
deleted file mode 100644
index 524fc9b..0000000
--- a/external/kafka/src/test/scala/io/gearpump/streaming/kafka/lib/consumer/KafkaConsumerSpec.scala
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.kafka.lib.consumer
-
-import com.twitter.bijection.Injection
-import kafka.api.OffsetRequest
-import kafka.common.TopicAndPartition
-import kafka.consumer.SimpleConsumer
-import kafka.message.{Message, MessageAndOffset}
-import org.mockito.Mockito._
-import org.scalacheck.Gen
-import org.scalatest.mock.MockitoSugar
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{Matchers, PropSpec}
-
-class KafkaConsumerSpec extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
- val messageGen = Gen.alphaStr map (msg => new Message(Injection[String, Array[Byte]](msg)))
- val messageNumGen = Gen.choose[Int](0, 1000)
- val topicAndPartitionGen = for {
- topic <- Gen.alphaStr
- partition <- Gen.choose[Int](0, Int.MaxValue)
- } yield (topic, partition)
-
- property("KafkaConsumer should iterate MessageAndOffset calling hasNext and next") {
- forAll(messageGen, messageNumGen, topicAndPartitionGen) {
- (message: Message, num: Int, topicAndPartition: (String, Int)) =>
- val (topic, partition) = topicAndPartition
- val consumer = mock[SimpleConsumer]
- when(consumer.earliestOrLatestOffset(TopicAndPartition(topic, partition),
- OffsetRequest.EarliestTime, -1)).thenReturn(0)
- val iterator = 0.until(num).map(index => MessageAndOffset(message, index.toLong)).iterator
- val getIterator = (offset: Long) => iterator
- val kafkaConsumer = new KafkaConsumer(consumer, topic, partition, getIterator)
- 0.until(num).foreach { i =>
- kafkaConsumer.hasNext shouldBe true
- val kafkaMessage = kafkaConsumer.next
- kafkaMessage.offset shouldBe i.toLong
- kafkaMessage.key shouldBe None
- }
- kafkaConsumer.hasNext shouldBe false
- }
- }
-
- val startOffsetGen = Gen.choose[Long](1L, 1000L)
- property("KafkaConsumer setStartOffset should reset internal iterator") {
- forAll(topicAndPartitionGen, startOffsetGen) {
- (topicAndPartition: (String, Int), startOffset: Long) =>
- val (topic, partition) = topicAndPartition
- val consumer = mock[SimpleConsumer]
- val getIterator = mock[Long => Iterator[MessageAndOffset]]
- when(consumer.earliestOrLatestOffset(TopicAndPartition(topic, partition),
- OffsetRequest.EarliestTime, -1)).thenReturn(0)
- val kafkaConsumer = new KafkaConsumer(consumer, topic, partition, getIterator)
- kafkaConsumer.setStartOffset(startOffset)
- verify(getIterator).apply(startOffset)
- }
- }
-
- property("KafkaConsumer close should close SimpleConsumer") {
- forAll(topicAndPartitionGen) {
- (topicAndPartition: (String, Int)) =>
- val (topic, partition) = topicAndPartition
- val consumer = mock[SimpleConsumer]
- when(consumer.earliestOrLatestOffset(TopicAndPartition(topic, partition),
- OffsetRequest.EarliestTime, -1)).thenReturn(0)
- val getIterator = mock[Long => Iterator[MessageAndOffset]]
- val kafkaConsumer = new KafkaConsumer(consumer, topic, partition, getIterator)
- kafkaConsumer.close()
- verify(consumer).close()
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/test/scala/io/gearpump/streaming/kafka/lib/grouper/KafkaDefaultGrouperSpec.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/test/scala/io/gearpump/streaming/kafka/lib/grouper/KafkaDefaultGrouperSpec.scala b/external/kafka/src/test/scala/io/gearpump/streaming/kafka/lib/grouper/KafkaDefaultGrouperSpec.scala
deleted file mode 100644
index 46067ab..0000000
--- a/external/kafka/src/test/scala/io/gearpump/streaming/kafka/lib/grouper/KafkaDefaultGrouperSpec.scala
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.kafka.lib.grouper
-
-import kafka.common.TopicAndPartition
-import org.scalacheck.Gen
-import org.scalatest.prop.PropertyChecks
-import org.scalatest.{Matchers, PropSpec}
-
-class KafkaDefaultGrouperSpec extends PropSpec with PropertyChecks with Matchers {
- property("KafkaDefaultGrouper should group TopicAndPartitions in a round-robin way") {
- forAll(Gen.posNum[Int], Gen.posNum[Int], Gen.posNum[Int]) {
- (topicNum: Int, partitionNum: Int, taskNum: Int) => {
- val topicAndPartitions = for {
- t <- 0.until(topicNum)
- p <- 0.until(partitionNum)
- } yield TopicAndPartition("topic" + t, p)
- 0.until(taskNum).foreach { taskIndex =>
- val grouper = new KafkaDefaultGrouper
- grouper.group(taskNum, taskIndex, topicAndPartitions.toArray).forall(
- tp => topicAndPartitions.indexOf(tp) % taskNum == taskIndex)
- }
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/test/scala/io/gearpump/streaming/kafka/util/KafkaServerHarness.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/test/scala/io/gearpump/streaming/kafka/util/KafkaServerHarness.scala b/external/kafka/src/test/scala/io/gearpump/streaming/kafka/util/KafkaServerHarness.scala
deleted file mode 100644
index ad315fe..0000000
--- a/external/kafka/src/test/scala/io/gearpump/streaming/kafka/util/KafkaServerHarness.scala
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.kafka.util
-
-import java.util.Properties
-
-import kafka.admin.AdminUtils
-import kafka.common.KafkaException
-import kafka.server.{KafkaConfig => KafkaServerConfig, KafkaServer}
-import kafka.utils.{TestUtils, Utils}
-
-trait KafkaServerHarness extends ZookeeperHarness {
- val configs: List[KafkaServerConfig]
- private var servers: List[KafkaServer] = null
- private var brokerList: String = null
-
- def getServers: List[KafkaServer] = servers
- def getBrokerList: Array[String] = brokerList.split(",")
-
- override def setUp() {
- super.setUp
- if (configs.size <= 0) {
- throw new KafkaException("Must supply at least one server config.")
- }
- brokerList = TestUtils.getBrokerListStrFromConfigs(configs)
- servers = configs.map(TestUtils.createServer(_))
- }
-
- override def tearDown() {
- servers.map(server => server.shutdown())
- servers.map(server => server.config.logDirs.map(Utils.rm(_)))
- super.tearDown
- }
-
- def createTopicUntilLeaderIsElected(
- topic: String, partitions: Int, replicas: Int, timeout: Long = 10000)
- : Map[Int, Option[Int]] = {
- val zkClient = connectZk()
- try {
- // Creates topic
- AdminUtils.createTopic(zkClient, topic, partitions, replicas, new Properties)
- // Waits until the update metadata request for new topic reaches all servers
- (0 until partitions).map { case i =>
- TestUtils.waitUntilMetadataIsPropagated(servers, topic, i, timeout)
- i -> TestUtils.waitUntilLeaderIsElectedOrChanged(zkClient, topic, i, timeout)
- }.toMap
- } catch {
- case e: Exception => throw e
- } finally {
- zkClient.close()
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/test/scala/io/gearpump/streaming/kafka/util/ZookeeperHarness.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/test/scala/io/gearpump/streaming/kafka/util/ZookeeperHarness.scala b/external/kafka/src/test/scala/io/gearpump/streaming/kafka/util/ZookeeperHarness.scala
deleted file mode 100644
index 45fe760..0000000
--- a/external/kafka/src/test/scala/io/gearpump/streaming/kafka/util/ZookeeperHarness.scala
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.kafka.util
-
-import kafka.utils.{TestZKUtils, Utils, ZKStringSerializer}
-import kafka.zk.EmbeddedZookeeper
-import org.I0Itec.zkclient.ZkClient
-
-trait ZookeeperHarness {
- val zkConnect: String = TestZKUtils.zookeeperConnect
- val zkConnectionTimeout = 60000
- val zkSessionTimeout = 60000
- private var zookeeper: EmbeddedZookeeper = null
-
- def getZookeeper: EmbeddedZookeeper = zookeeper
- def connectZk: () => ZkClient = () => {
- new ZkClient(zkConnect, zkSessionTimeout, zkConnectionTimeout, ZKStringSerializer)
- }
-
- def setUp() {
- zookeeper = new EmbeddedZookeeper(zkConnect)
- }
-
- def tearDown() {
- Utils.swallow(zookeeper.shutdown())
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/KafkaSinkSpec.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/KafkaSinkSpec.scala b/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/KafkaSinkSpec.scala
new file mode 100644
index 0000000..2f8a533
--- /dev/null
+++ b/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/KafkaSinkSpec.scala
@@ -0,0 +1,63 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.kafka
+
+import com.twitter.bijection.Injection
+import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord}
+import org.mockito.Mockito._
+import org.scalacheck.Gen
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{Matchers, PropSpec}
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.streaming.MockUtil
+
+class KafkaSinkSpec extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
+
+ val dataGen = for {
+ topic <- Gen.alphaStr
+ key <- Gen.alphaStr
+ msg <- Gen.alphaStr
+ } yield (topic, Injection[String, Array[Byte]](key), Injection[String, Array[Byte]](msg))
+
+ property("KafkaSink write should send producer record") {
+ forAll(dataGen) {
+ (data: (String, Array[Byte], Array[Byte])) =>
+ val producer = mock[KafkaProducer[Array[Byte], Array[Byte]]]
+ val (topic, key, msg) = data
+ val kafkaSink = new KafkaSink(() => producer, topic)
+ kafkaSink.write(Message((key, msg)))
+ verify(producer).send(MockUtil.argMatch[ProducerRecord[Array[Byte], Array[Byte]]](
+ r => r.topic == topic && (r.key sameElements key) && (r.value sameElements msg)))
+ kafkaSink.write(Message(msg))
+ verify(producer).send(MockUtil.argMatch[ProducerRecord[Array[Byte], Array[Byte]]](
+ r => r.topic() == topic && (r.key == null) && (r.value() sameElements msg)
+ ))
+ kafkaSink.close()
+ }
+ }
+
+ property("KafkaSink close should close kafka producer") {
+ val producer = mock[KafkaProducer[Array[Byte], Array[Byte]]]
+ val kafkaSink = new KafkaSink(() => producer, "topic")
+ kafkaSink.close()
+ verify(producer).close()
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/KafkaSourceSpec.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/KafkaSourceSpec.scala b/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/KafkaSourceSpec.scala
new file mode 100644
index 0000000..8055d00
--- /dev/null
+++ b/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/KafkaSourceSpec.scala
@@ -0,0 +1,167 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.kafka
+
+import scala.util.{Failure, Success}
+
+import com.twitter.bijection.Injection
+import kafka.common.TopicAndPartition
+import org.mockito.Matchers._
+import org.mockito.Mockito._
+import org.scalacheck.Gen
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{Matchers, PropSpec}
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.streaming.kafka.lib.consumer.{FetchThread, KafkaMessage}
+import org.apache.gearpump.streaming.kafka.lib.{KafkaOffsetManager, KafkaSourceConfig}
+import org.apache.gearpump.streaming.transaction.api.OffsetStorage.StorageEmpty
+import org.apache.gearpump.streaming.transaction.api.{MessageDecoder, OffsetStorageFactory, TimeStampFilter}
+
+class KafkaSourceSpec extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
+
+ val startTimeGen = Gen.choose[Long](0L, 1000L)
+ val offsetGen = Gen.choose[Long](0L, 1000L)
+
+ property("KafkaSource open sets consumer to earliest offset") {
+ val topicAndPartition = mock[TopicAndPartition]
+ val fetchThread = mock[FetchThread]
+ val offsetManager = mock[KafkaOffsetManager]
+ val messageDecoder = mock[MessageDecoder]
+ val timestampFilter = mock[TimeStampFilter]
+ val offsetStorageFactory = mock[OffsetStorageFactory]
+ val kafkaConfig = mock[KafkaSourceConfig]
+ val kafkaSource = new KafkaSource(kafkaConfig, offsetStorageFactory, messageDecoder,
+ timestampFilter, Some(fetchThread), Map(topicAndPartition -> offsetManager))
+
+ kafkaSource.setStartTime(None)
+
+ verify(fetchThread).start()
+ verify(fetchThread, never()).setStartOffset(anyObject[TopicAndPartition](), anyLong())
+ }
+
+ property("KafkaSource open should not set consumer start offset if offset storage is empty") {
+ forAll(startTimeGen) { (startTime: Long) =>
+ val offsetManager = mock[KafkaOffsetManager]
+ val topicAndPartition = mock[TopicAndPartition]
+ val fetchThread = mock[FetchThread]
+ val messageDecoder = mock[MessageDecoder]
+ val timestampFilter = mock[TimeStampFilter]
+ val offsetStorageFactory = mock[OffsetStorageFactory]
+ val kafkaConfig = mock[KafkaSourceConfig]
+ val source = new KafkaSource(kafkaConfig, offsetStorageFactory, messageDecoder,
+ timestampFilter, Some(fetchThread), Map(topicAndPartition -> offsetManager))
+
+ when(offsetManager.resolveOffset(startTime)).thenReturn(Failure(StorageEmpty))
+
+ source.setStartTime(Some(startTime))
+ verify(fetchThread, never()).setStartOffset(anyObject[TopicAndPartition](), anyLong())
+ verify(fetchThread).start()
+
+ when(offsetManager.resolveOffset(startTime)).thenReturn(Failure(new RuntimeException))
+ intercept[RuntimeException] {
+ source.setStartTime(Some(startTime))
+ }
+ source.close()
+ }
+ }
+
+ property("KafkaSource open should set consumer start offset if offset storage is not empty") {
+ forAll(startTimeGen, offsetGen) {
+ (startTime: Long, offset: Long) =>
+ val offsetManager = mock[KafkaOffsetManager]
+ val topicAndPartition = mock[TopicAndPartition]
+ val fetchThread = mock[FetchThread]
+ val messageDecoder = mock[MessageDecoder]
+ val timestampFilter = mock[TimeStampFilter]
+ val offsetStorageFactory = mock[OffsetStorageFactory]
+ val kafkaConfig = mock[KafkaSourceConfig]
+ val source = new KafkaSource(kafkaConfig, offsetStorageFactory, messageDecoder,
+ timestampFilter, Some(fetchThread), Map(topicAndPartition -> offsetManager))
+
+ when(offsetManager.resolveOffset(startTime)).thenReturn(Success(offset))
+
+ source.setStartTime(Some(startTime))
+ verify(fetchThread).setStartOffset(topicAndPartition, offset)
+ verify(fetchThread).start()
+
+ when(offsetManager.resolveOffset(startTime)).thenReturn(Failure(new RuntimeException))
+ intercept[RuntimeException] {
+ source.setStartTime(Some(startTime))
+ }
+ source.close()
+ }
+ }
+
+ property("KafkaSource read should return number of messages in best effort") {
+ val kafkaMsgGen = for {
+ topic <- Gen.alphaStr
+ partition <- Gen.choose[Int](0, 1000)
+ offset <- Gen.choose[Long](0L, 1000L)
+ key = None
+ msg <- Gen.alphaStr.map(Injection[String, Array[Byte]])
+ } yield KafkaMessage(TopicAndPartition(topic, partition), offset, key, msg)
+ val msgQueueGen = Gen.containerOf[Array, KafkaMessage](kafkaMsgGen)
+ forAll(msgQueueGen) {
+ (msgQueue: Array[KafkaMessage]) =>
+ val offsetManager = mock[KafkaOffsetManager]
+ val fetchThread = mock[FetchThread]
+ val messageDecoder = mock[MessageDecoder]
+
+ val timestampFilter = mock[TimeStampFilter]
+ val offsetStorageFactory = mock[OffsetStorageFactory]
+ val kafkaConfig = mock[KafkaSourceConfig]
+ val offsetManagers = msgQueue.map(_.topicAndPartition -> offsetManager).toMap
+
+ val source = new KafkaSource(kafkaConfig, offsetStorageFactory, messageDecoder,
+ timestampFilter, Some(fetchThread), offsetManagers)
+
+ if (msgQueue.isEmpty) {
+ when(fetchThread.poll).thenReturn(None)
+ source.read() shouldBe null
+ } else {
+ msgQueue.indices.foreach { i =>
+ val message = Message(msgQueue(i).msg)
+ when(fetchThread.poll).thenReturn(Option(msgQueue(i)))
+ when(messageDecoder.fromBytes(anyObject[Array[Byte]])).thenReturn(message)
+ when(offsetManager.filter(anyObject[(Message, Long)])).thenReturn(Some(message))
+ when(timestampFilter.filter(anyObject[Message], anyLong())).thenReturn(Some(message))
+
+ source.read shouldBe message
+ }
+ }
+ source.close()
+ }
+ }
+
+ property("KafkaSource close should close all offset managers") {
+ val offsetManager = mock[KafkaOffsetManager]
+ val topicAndPartition = mock[TopicAndPartition]
+ val fetchThread = mock[FetchThread]
+ val timestampFilter = mock[TimeStampFilter]
+ val messageDecoder = mock[MessageDecoder]
+ val offsetStorageFactory = mock[OffsetStorageFactory]
+ val kafkaConfig = mock[KafkaSourceConfig]
+ val source = new KafkaSource(kafkaConfig, offsetStorageFactory, messageDecoder,
+ timestampFilter, Some(fetchThread), Map(topicAndPartition -> offsetManager))
+ source.close()
+ verify(offsetManager).close()
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/lib/DefaultMessageDecoderSpec.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/lib/DefaultMessageDecoderSpec.scala b/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/lib/DefaultMessageDecoderSpec.scala
new file mode 100644
index 0000000..e243eab
--- /dev/null
+++ b/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/lib/DefaultMessageDecoderSpec.scala
@@ -0,0 +1,44 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.kafka.lib
+
+import com.twitter.bijection.Injection
+import org.scalacheck.Gen
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{Matchers, PropSpec}
+
+class DefaultMessageDecoderSpec extends PropSpec with PropertyChecks with Matchers {
+ property("DefaultMessageDecoder should keep the original bytes data in Message") {
+ val decoder = new DefaultMessageDecoder()
+ forAll(Gen.alphaStr) { (s: String) =>
+ val bytes = Injection[String, Array[Byte]](s)
+ decoder.fromBytes(bytes).msg shouldBe bytes
+ }
+ }
+}
+
+class StringMessageDecoderSpec extends PropSpec with PropertyChecks with Matchers {
+ property("StringMessageDecoder should decode original bytes data into string") {
+ val decoder = new StringMessageDecoder()
+ forAll(Gen.alphaStr) { (s: String) =>
+ val bytes = Injection[String, Array[Byte]](s)
+ decoder.fromBytes(bytes).msg shouldBe s
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/lib/KafkaOffsetManagerSpec.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/lib/KafkaOffsetManagerSpec.scala b/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/lib/KafkaOffsetManagerSpec.scala
new file mode 100644
index 0000000..987d975
--- /dev/null
+++ b/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/lib/KafkaOffsetManagerSpec.scala
@@ -0,0 +1,117 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.kafka.lib
+
+import scala.util.{Failure, Success}
+
+import com.twitter.bijection.Injection
+import org.mockito.Mockito._
+import org.scalacheck.Gen
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{Matchers, PropSpec}
+
+import org.apache.gearpump.Message
+import org.apache.gearpump.streaming.transaction.api.OffsetStorage
+import org.apache.gearpump.streaming.transaction.api.OffsetStorage.{Overflow, StorageEmpty, Underflow}
+
+class KafkaOffsetManagerSpec extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
+
+ val timeStampGen = Gen.choose[Long](0L, 1000L)
+ val messageGen = for {
+ msg <- Gen.alphaStr
+ time <- timeStampGen
+ } yield Message(msg, time)
+
+ val messageAndOffsetsGen = Gen.listOf[Message](messageGen).map(_.zipWithIndex)
+
+ property("KafkaOffsetManager should append offset to storage in monotonically" +
+ " increasing time order") {
+ forAll(messageAndOffsetsGen) { (messageAndOffsets: List[(Message, Int)]) =>
+ val offsetStorage = mock[OffsetStorage]
+ val offsetManager = new KafkaOffsetManager(offsetStorage)
+ messageAndOffsets.foldLeft(0L) { (max, messageAndOffset) =>
+ val (message, offset) = messageAndOffset
+ offsetManager.filter((message, offset.toLong)) shouldBe Option(message)
+ if (message.timestamp > max) {
+ val newMax = message.timestamp
+ verify(offsetStorage).append(newMax, Injection[Long, Array[Byte]](offset.toLong))
+ newMax
+ } else {
+ verifyZeroInteractions(offsetStorage)
+ max
+ }
+ }
+ offsetManager.close()
+ }
+ }
+
+ val minTimeStampGen = Gen.choose[Long](0L, 500L)
+ val maxTimeStampGen = Gen.choose[Long](500L, 1000L)
+ property("KafkaOffsetManager resolveOffset should " +
+ "report StorageEmpty failure when storage is empty") {
+ forAll(timeStampGen) { (time: Long) =>
+ val offsetStorage = mock[OffsetStorage]
+ val offsetManager = new KafkaOffsetManager(offsetStorage)
+ when(offsetStorage.lookUp(time)).thenReturn(Failure(StorageEmpty))
+ offsetManager.resolveOffset(time) shouldBe Failure(StorageEmpty)
+
+ doThrow(new RuntimeException).when(offsetStorage).lookUp(time)
+ intercept[RuntimeException] {
+ offsetManager.resolveOffset(time)
+ }
+ offsetManager.close()
+ }
+ }
+
+ val offsetGen = Gen.choose[Long](0L, 1000L)
+ property("KafkaOffsetManager resolveOffset should return a valid" +
+ " offset when storage is not empty") {
+ forAll(timeStampGen, minTimeStampGen, maxTimeStampGen, offsetGen) {
+ (time: Long, min: Long, max: Long, offset: Long) =>
+ val offsetStorage = mock[OffsetStorage]
+ val offsetManager = new KafkaOffsetManager(offsetStorage)
+ if (time < min) {
+ when(offsetStorage.lookUp(time)).thenReturn(Failure(
+ Underflow(Injection[Long, Array[Byte]](min))))
+ offsetManager.resolveOffset(time) shouldBe Success(min)
+ } else if (time > max) {
+ when(offsetStorage.lookUp(time)).thenReturn(Failure(
+ Overflow(Injection[Long, Array[Byte]](max))))
+ offsetManager.resolveOffset(time) shouldBe Success(max)
+ } else {
+ when(offsetStorage.lookUp(time)).thenReturn(Success(Injection[Long, Array[Byte]](offset)))
+ offsetManager.resolveOffset(time) shouldBe Success(offset)
+ }
+
+ doThrow(new RuntimeException).when(offsetStorage).lookUp(time)
+ intercept[RuntimeException] {
+ offsetManager.resolveOffset(time)
+ }
+ offsetManager.close()
+ }
+ }
+
+ property("KafkaOffsetManager close should close offset storage") {
+ val offsetStorage = mock[OffsetStorage]
+ val offsetManager = new KafkaOffsetManager(offsetStorage)
+ offsetManager.close()
+ verify(offsetStorage).close()
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/lib/KafkaStorageSpec.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/lib/KafkaStorageSpec.scala b/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/lib/KafkaStorageSpec.scala
new file mode 100644
index 0000000..6e4a1c4
--- /dev/null
+++ b/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/lib/KafkaStorageSpec.scala
@@ -0,0 +1,187 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.kafka.lib
+
+// TODO: Fix the UT failure!
+
+// class KafkaStorageSpec extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
+// val minTimeGen = Gen.choose[Long](1L, 500L)
+// val maxTimeGen = Gen.choose[Long](500L, 999L)
+//
+// property("KafkaStorage lookup time should report StorageEmpty if storage is empty") {
+// forAll { (time: Long, topic: String) =>
+// val producer = mock[KafkaProducer[Array[Byte], Array[Byte]]]
+// val getConsumer = () => mock[KafkaConsumer]
+// val connectZk = () => mock[ZkClient]
+// val storage = new KafkaStorage(topic, topicExists = false, producer, getConsumer(),
+// connectZk())
+// storage.lookUp(time) shouldBe Failure(StorageEmpty)
+// }
+// }
+//
+// property("KafkaStorage lookup time should return data or report failure if storage not empty") {
+// forAll(minTimeGen, maxTimeGen, Gen.alphaStr) {(minTime: Long, maxTime: Long, topic: String) =>
+// val timeAndOffsets = minTime.to(maxTime).zipWithIndex.map { case (time, index) =>
+// val offset = index.toLong
+// time -> offset
+// }
+// val timeAndOffsetsMap = timeAndOffsets.toMap
+// val data = timeAndOffsets.map {
+// case (time, offset) =>
+// new KafkaMessage(topic, 0, offset.toLong, Some(Injection[Long, Array[Byte]](time)),
+// Injection[Long, Array[Byte]](offset))
+// }.toList
+//
+// val producer = mock[KafkaProducer[Array[Byte], Array[Byte]]]
+// val consumer = mock[KafkaConsumer]
+// val getConsumer = () => consumer
+// val connectZk = () => mock[ZkClient]
+//
+// val hasNexts = List.fill(data.tail.size)(true) :+ false
+// when(consumer.hasNext).thenReturn(true, hasNexts:_*)
+// when(consumer.next).thenReturn(data.head, data.tail:_*)
+//
+// val storage = new KafkaStorage(topic, topicExists = true, producer,
+// getConsumer(), connectZk())
+// forAll(Gen.choose[Long](minTime, maxTime)) {
+// time =>
+// storage.lookUp(time) match {
+// case Success(array) =>
+// array should equal (Injection[Long, Array[Byte]](timeAndOffsetsMap(time)))
+// case Failure(e) => fail("time in range should return Success with value")
+// }
+// }
+//
+// forAll(Gen.choose[Long](0L, minTime - 1)) {
+// time =>
+// storage.lookUp(time) match {
+// case Failure(e) => e shouldBe a [Underflow]
+// e.asInstanceOf[Underflow].min should equal
+// (Injection[Long, Array[Byte]](timeAndOffsetsMap(minTime)))
+// case Success(_) => fail("time less than min should return Underflow failure")
+// }
+// }
+//
+// forAll(Gen.choose[Long](maxTime + 1, 1000L)) {
+// time =>
+// storage.lookUp(time) match {
+// case Failure(e) => e shouldBe a [Overflow]
+// e.asInstanceOf[Overflow].max should equal
+// (Injection[Long, Array[Byte]](timeAndOffsetsMap(maxTime)))
+// case Success(_) => fail("time larger than max should return Overflow failure")
+// }
+// }
+// }
+// }
+//
+// property("KafkaStorage append should send data to Kafka") {
+// forAll(Gen.chooseNum[Long](1, 1000), Gen.chooseNum[Long](0, 1000),
+// Gen.alphaStr, Gen.oneOf(true, false)) {
+// (time: Long, offset: Long, topic: String, topicExists: Boolean) =>
+// val producer = mock[KafkaProducer[Array[Byte], Array[Byte]]]
+// val getConsumer = () => mock[KafkaConsumer]
+// val connectZk = () => mock[ZkClient]
+// val storage = new KafkaStorage(topic, topicExists, producer, getConsumer(), connectZk())
+// val offsetBytes = Injection[Long, Array[Byte]](offset)
+// storage.append(time, offsetBytes)
+// verify(producer).send(anyObject[ProducerRecord[Array[Byte], Array[Byte]]]())
+// }
+// }
+//
+// val topicAndPartitionGen = for {
+// topic <- Gen.alphaStr
+// partition <- Gen.choose[Int](0, 100)
+// } yield TopicAndPartition(topic, partition)
+// property("KafkaStorage should load data from Kafka") {
+// val kafkaMsgGen = for {
+// timestamp <- Gen.choose[Long](1L, 1000L)
+// offset <- Gen.choose[Long](0L, 1000L)
+// } yield (timestamp, Injection[Long, Array[Byte]](offset))
+// val msgListGen = Gen.listOf[(Long, Array[Byte])](kafkaMsgGen)
+//
+// val topicExistsGen = Gen.oneOf(true, false)
+//
+// forAll(topicAndPartitionGen, msgListGen) {
+// (topicAndPartition: TopicAndPartition, msgList: List[(Long, Array[Byte])]) =>
+// val producer= mock[KafkaProducer[Array[Byte], Array[Byte]]]
+// val consumer = mock[KafkaConsumer]
+// val getConsumer = () => consumer
+// val connectZk = () => mock[ZkClient]
+// val kafkaStorage = new KafkaStorage(topicAndPartition.topic,
+// topicExists = true, producer, getConsumer(), connectZk())
+// msgList match {
+// case Nil =>
+// when(consumer.hasNext).thenReturn(false)
+// case list =>
+// val hasNexts = List.fill(list.tail.size)(true) :+ false
+// val kafkaMsgList = list.zipWithIndex.map { case ((timestamp, bytes), index) =>
+// KafkaMessage(topicAndPartition, index.toLong,
+// Some(Injection[Long, Array[Byte]](timestamp)), bytes)
+// }
+// when(consumer.hasNext).thenReturn(true, hasNexts: _*)
+// when(consumer.next).thenReturn(kafkaMsgList.head, kafkaMsgList.tail: _*)
+// }
+// kafkaStorage.load(consumer) shouldBe msgList
+// }
+// }
+//
+// property("KafkaStorage should not get consumer when topic doesn't exist") {
+// forAll(Gen.alphaStr) { (topic: String) =>
+// val producer = mock[KafkaProducer[Array[Byte], Array[Byte]]]
+// val getConsumer = mock[() => KafkaConsumer]
+// val connectZk = () => mock[ZkClient]
+// val kafkaStorage = new KafkaStorage(topic,
+// topicExists = false, producer, getConsumer(), connectZk())
+// verify(getConsumer, never()).apply()
+// kafkaStorage.close()
+// }
+// }
+//
+// property("KafkaStorage should fail to load invalid KafkaMessage") {
+// val invalidKafkaMsgGen = for {
+// tp <- topicAndPartitionGen
+// offset <- Gen.choose[Long](1L, 1000L)
+// timestamp <- Gen.oneOf(Some(Injection[ByteBuffer, Array[Byte]](ByteBuffer.allocate(0))),
+// None)
+// msg <- Gen.alphaStr.map(Injection[String, Array[Byte]])
+// } yield KafkaMessage(tp, offset, timestamp, msg)
+// forAll(invalidKafkaMsgGen) { (invalidKafkaMsg: KafkaMessage) =>
+// val consumer = mock[KafkaConsumer]
+// val getConsumer = () => consumer
+// val producer = mock[KafkaProducer[Array[Byte], Array[Byte]]]
+// val connectZk = () => mock[ZkClient]
+// val kafkaStorage = new KafkaStorage(invalidKafkaMsg.topicAndPartition.topic,
+// topicExists = true, producer, getConsumer(), connectZk())
+// when(consumer.hasNext).thenReturn(true, false)
+// when(consumer.next).thenReturn(invalidKafkaMsg, invalidKafkaMsg)
+// Try(kafkaStorage.load(consumer)).isFailure shouldBe true
+// }
+// }
+//
+// property("KafkaStorage close should close kafka producer and delete topic") {
+// val producer = mock[KafkaProducer[Array[Byte], Array[Byte]]]
+// val getConsumer = () => mock[KafkaConsumer]
+// val zkClient = mock[ZkClient]
+// val connectZk = () => zkClient
+// val kafkaStorage = new KafkaStorage("topic", false, producer, getConsumer(), connectZk())
+// kafkaStorage.close()
+// verify(producer).close()
+// verify(zkClient).createPersistent(anyString(), anyString())
+// }
+// }
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/lib/KafkaUtilSpec.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/lib/KafkaUtilSpec.scala b/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/lib/KafkaUtilSpec.scala
new file mode 100644
index 0000000..099be3d
--- /dev/null
+++ b/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/lib/KafkaUtilSpec.scala
@@ -0,0 +1,107 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.kafka.lib
+
+import kafka.common.TopicAndPartition
+import kafka.server.{KafkaConfig => KafkaServerConfig}
+import kafka.utils.{TestUtils, TestZKUtils}
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{BeforeAndAfterEach, Matchers, PropSpec}
+
+import org.apache.gearpump.streaming.kafka.lib.grouper.KafkaGrouper
+import org.apache.gearpump.streaming.kafka.util.KafkaServerHarness
+
+class KafkaUtilSpec
+ extends PropSpec with PropertyChecks with BeforeAndAfterEach
+ with Matchers with KafkaServerHarness {
+
+ val numServers = 1
+ override val configs: List[KafkaServerConfig] =
+ for (props <- TestUtils.createBrokerConfigs(numServers, enableControlledShutdown = false))
+ yield new KafkaServerConfig(props) {
+ override val zkConnect = TestZKUtils.zookeeperConnect
+ override val numPartitions = 4
+ }
+
+ override def beforeEach(): Unit = {
+ super.setUp()
+ }
+
+ override def afterEach(): Unit = {
+ super.tearDown()
+ }
+
+ import org.apache.gearpump.streaming.kafka.lib.KafkaUtil._
+
+ property("KafkaUtil should be able to create topic") {
+ val args = {
+ Table(
+ ("topic", "partitions", "replicas"),
+ (TestUtils.tempTopic, 1, numServers),
+ (TestUtils.tempTopic, 2, numServers + 1),
+ ("", 1, numServers),
+ (TestUtils.tempTopic, 0, numServers),
+ (TestUtils.tempTopic, 1, 0)
+ )
+ }
+ forAll(args) {
+ (topic: String, partitions: Int, replicas: Int) =>
+ if (topic.nonEmpty && partitions > 0 && replicas > 0 && replicas <= numServers) {
+ createTopic(connectZk(), topic, partitions, replicas) shouldBe false
+ createTopic(connectZk(), topic, partitions, replicas) shouldBe true
+ } else {
+ intercept[RuntimeException] {
+ createTopic(connectZk(), topic, partitions, replicas)
+ }
+ }
+ }
+ }
+
+ property("KafkaUtil should be able to get broker info") {
+ val brokerList = getBrokerList
+ val partitions = 2
+ val replicas = numServers
+ val topic = TestUtils.tempTopic()
+ intercept[RuntimeException] {
+ getBroker(connectZk(), topic, partitions)
+ }
+ val partitionsToBrokers = createTopicUntilLeaderIsElected(topic, partitions, replicas)
+ 0.until(partitions).foreach { part =>
+ val hostPorts = brokerList(partitionsToBrokers(part).get).split(":")
+ val broker = getBroker(connectZk(), topic, part)
+
+ broker.host shouldBe hostPorts(0)
+ broker.port.toString shouldBe hostPorts(1)
+ }
+ }
+
+ property("KafkaUtil should be able to get TopicAndPartitions info and group with KafkaGrouper") {
+ val grouper: KafkaGrouper = new KafkaGrouper {
+ override def group(taskNum: Int, taskIndex: Int, topicAndPartitions: Array[TopicAndPartition])
+ : Array[TopicAndPartition] = {
+ topicAndPartitions
+ }
+ }
+ val topicNum = 3
+ val topics = List.fill(topicNum)(TestUtils.tempTopic())
+ topics.foreach(t => createTopicUntilLeaderIsElected(t, partitions = 1, replicas = 1))
+ KafkaUtil.getTopicAndPartitions(connectZk(), topics).toSet shouldBe
+ topics.map(t => TopicAndPartition(t, 0)).toSet
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/lib/consumer/ExponentialBackoffSleeperSpec.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/lib/consumer/ExponentialBackoffSleeperSpec.scala b/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/lib/consumer/ExponentialBackoffSleeperSpec.scala
new file mode 100644
index 0000000..cc83b51
--- /dev/null
+++ b/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/lib/consumer/ExponentialBackoffSleeperSpec.scala
@@ -0,0 +1,68 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.kafka.lib.consumer
+
+import org.scalatest.{Matchers, WordSpec}
+
+class ExponentialBackoffSleeperSpec extends WordSpec with Matchers {
+
+ "ExponentialBackOffSleeper" should {
+ "sleep for increasing duration" in {
+ val sleeper = new ExponentialBackoffSleeper(
+ backOffMultiplier = 2.0,
+ initialDurationMs = 100,
+ maximumDurationMs = 10000
+ )
+ sleeper.getSleepDuration shouldBe 100
+ sleeper.setNextSleepDuration()
+ sleeper.getSleepDuration shouldBe 200
+ sleeper.setNextSleepDuration()
+ sleeper.getSleepDuration shouldBe 400
+ sleeper.setNextSleepDuration()
+ sleeper.getSleepDuration shouldBe 800
+ }
+
+ "sleep for no more than maximum duration" in {
+ val sleeper = new ExponentialBackoffSleeper(
+ backOffMultiplier = 2.0,
+ initialDurationMs = 6400,
+ maximumDurationMs = 10000
+ )
+ sleeper.getSleepDuration shouldBe 6400
+ sleeper.setNextSleepDuration()
+ sleeper.getSleepDuration shouldBe 10000
+ sleeper.setNextSleepDuration()
+ sleeper.getSleepDuration shouldBe 10000
+ }
+
+ "sleep for initial duration after reset" in {
+ val sleeper = new ExponentialBackoffSleeper(
+ backOffMultiplier = 2.0,
+ initialDurationMs = 100,
+ maximumDurationMs = 10000
+ )
+ sleeper.getSleepDuration shouldBe 100
+ sleeper.setNextSleepDuration()
+ sleeper.getSleepDuration shouldBe 200
+ sleeper.reset()
+ sleeper.getSleepDuration shouldBe 100
+ }
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/lib/consumer/FetchThreadSpec.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/lib/consumer/FetchThreadSpec.scala b/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/lib/consumer/FetchThreadSpec.scala
new file mode 100644
index 0000000..b6659a1
--- /dev/null
+++ b/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/lib/consumer/FetchThreadSpec.scala
@@ -0,0 +1,113 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.kafka.lib.consumer
+
+import java.util.concurrent.LinkedBlockingQueue
+
+import kafka.common.TopicAndPartition
+import org.mockito.Mockito._
+import org.scalacheck.Gen
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{Matchers, PropSpec}
+
+class FetchThreadSpec extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
+
+ val nonNegativeGen = Gen.choose[Int](0, 1000)
+ val positiveGen = Gen.choose[Int](1, 1000)
+ val startOffsetGen = Gen.choose[Long](0L, 1000L)
+ property("FetchThread should set startOffset to iterators") {
+ forAll(nonNegativeGen, nonNegativeGen, startOffsetGen) {
+ (fetchThreshold: Int, fetchSleepMS: Int, startOffset: Long) =>
+ val topicAndPartition = mock[TopicAndPartition]
+ val consumer = mock[KafkaConsumer]
+ val createConsumer = (tp: TopicAndPartition) => consumer
+ val incomingQueue = new LinkedBlockingQueue[KafkaMessage]()
+ val fetchThread = new FetchThread(Array(topicAndPartition), createConsumer,
+ incomingQueue, fetchThreshold, fetchSleepMS)
+ fetchThread.setStartOffset(topicAndPartition, startOffset)
+ verify(consumer).setStartOffset(startOffset)
+ }
+ }
+
+ val topicAndPartitionGen = for {
+ topic <- Gen.alphaStr
+ partition <- Gen.choose[Int](0, Int.MaxValue)
+ } yield TopicAndPartition(topic, partition)
+ property("FetchThread should only fetchMessage when the number " +
+ "of messages in queue is below the threshold") {
+ forAll(positiveGen, nonNegativeGen, nonNegativeGen, startOffsetGen, topicAndPartitionGen) {
+ (messageNum: Int, fetchThreshold: Int, fetchSleepMS: Int,
+ startOffset: Long, topicAndPartition: TopicAndPartition) =>
+ val message = mock[KafkaMessage]
+ val consumer = mock[KafkaConsumer]
+ val createConsumer = (tp: TopicAndPartition) => consumer
+ when(consumer.hasNext).thenReturn(true)
+ when(consumer.next).thenReturn(message)
+ val incomingQueue = new LinkedBlockingQueue[KafkaMessage]()
+ val fetchThread = new FetchThread(Array(topicAndPartition), createConsumer,
+ incomingQueue, fetchThreshold, fetchSleepMS)
+
+ 0.until(messageNum) foreach { _ =>
+ fetchThread.fetchMessage
+ }
+
+ incomingQueue.size() shouldBe Math.min(messageNum, fetchThreshold)
+ }
+ }
+
+ property("FetchThread poll should try to retrieve and remove the head of incoming queue") {
+ val topicAndPartition = mock[TopicAndPartition]
+ val consumer = mock[KafkaConsumer]
+ val createConsumer = (tp: TopicAndPartition) => consumer
+ val kafkaMsg = mock[KafkaMessage]
+ val incomingQueue = new LinkedBlockingQueue[KafkaMessage]()
+ incomingQueue.put(kafkaMsg)
+ val fetchThread = new FetchThread(Array(topicAndPartition), createConsumer, incomingQueue, 0, 0)
+ fetchThread.poll shouldBe Some(kafkaMsg)
+ fetchThread.poll shouldBe None
+ }
+
+ val tpAndHasNextGen = for {
+ tp <- topicAndPartitionGen
+ hasNext <- Gen.oneOf(true, false)
+ } yield (tp, hasNext)
+
+ val tpHasNextMapGen = Gen.listOf[(TopicAndPartition, Boolean)](tpAndHasNextGen)
+ .map(_.toMap) suchThat (_.nonEmpty)
+
+ property("FetchThread fetchMessage should return false when there are no more messages " +
+ "from any TopicAndPartition") {
+ forAll(tpHasNextMapGen, nonNegativeGen) {
+ (tpHasNextMap: Map[TopicAndPartition, Boolean], fetchSleepMS: Int) =>
+ val createConsumer = (tp: TopicAndPartition) => {
+ val consumer = mock[KafkaConsumer]
+ val kafkaMsg = mock[KafkaMessage]
+ val hasNext = tpHasNextMap(tp)
+ when(consumer.hasNext).thenReturn(hasNext)
+ when(consumer.next).thenReturn(kafkaMsg)
+ consumer
+ }
+ val incomingQueue = new LinkedBlockingQueue[KafkaMessage]()
+ val fetchThread = new FetchThread(tpHasNextMap.keys.toArray,
+ createConsumer, incomingQueue, tpHasNextMap.size + 1, fetchSleepMS)
+ fetchThread.fetchMessage shouldBe tpHasNextMap.values.reduce(_ || _)
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/lib/consumer/KafkaConsumerSpec.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/lib/consumer/KafkaConsumerSpec.scala b/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/lib/consumer/KafkaConsumerSpec.scala
new file mode 100644
index 0000000..3c6a663
--- /dev/null
+++ b/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/lib/consumer/KafkaConsumerSpec.scala
@@ -0,0 +1,88 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.kafka.lib.consumer
+
+import com.twitter.bijection.Injection
+import kafka.api.OffsetRequest
+import kafka.common.TopicAndPartition
+import kafka.consumer.SimpleConsumer
+import kafka.message.{Message, MessageAndOffset}
+import org.mockito.Mockito._
+import org.scalacheck.Gen
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{Matchers, PropSpec}
+
+class KafkaConsumerSpec extends PropSpec with PropertyChecks with Matchers with MockitoSugar {
+ val messageGen = Gen.alphaStr map (msg => new Message(Injection[String, Array[Byte]](msg)))
+ val messageNumGen = Gen.choose[Int](0, 1000)
+ val topicAndPartitionGen = for {
+ topic <- Gen.alphaStr
+ partition <- Gen.choose[Int](0, Int.MaxValue)
+ } yield (topic, partition)
+
+ property("KafkaConsumer should iterate MessageAndOffset calling hasNext and next") {
+ forAll(messageGen, messageNumGen, topicAndPartitionGen) {
+ (message: Message, num: Int, topicAndPartition: (String, Int)) =>
+ val (topic, partition) = topicAndPartition
+ val consumer = mock[SimpleConsumer]
+ when(consumer.earliestOrLatestOffset(TopicAndPartition(topic, partition),
+ OffsetRequest.EarliestTime, -1)).thenReturn(0)
+ val iterator = 0.until(num).map(index => MessageAndOffset(message, index.toLong)).iterator
+ val getIterator = (offset: Long) => iterator
+ val kafkaConsumer = new KafkaConsumer(consumer, topic, partition, getIterator)
+ 0.until(num).foreach { i =>
+ kafkaConsumer.hasNext shouldBe true
+ val kafkaMessage = kafkaConsumer.next
+ kafkaMessage.offset shouldBe i.toLong
+ kafkaMessage.key shouldBe None
+ }
+ kafkaConsumer.hasNext shouldBe false
+ }
+ }
+
+ val startOffsetGen = Gen.choose[Long](1L, 1000L)
+ property("KafkaConsumer setStartOffset should reset internal iterator") {
+ forAll(topicAndPartitionGen, startOffsetGen) {
+ (topicAndPartition: (String, Int), startOffset: Long) =>
+ val (topic, partition) = topicAndPartition
+ val consumer = mock[SimpleConsumer]
+ val getIterator = mock[Long => Iterator[MessageAndOffset]]
+ when(consumer.earliestOrLatestOffset(TopicAndPartition(topic, partition),
+ OffsetRequest.EarliestTime, -1)).thenReturn(0)
+ val kafkaConsumer = new KafkaConsumer(consumer, topic, partition, getIterator)
+ kafkaConsumer.setStartOffset(startOffset)
+ verify(getIterator).apply(startOffset)
+ }
+ }
+
+ property("KafkaConsumer close should close SimpleConsumer") {
+ forAll(topicAndPartitionGen) {
+ (topicAndPartition: (String, Int)) =>
+ val (topic, partition) = topicAndPartition
+ val consumer = mock[SimpleConsumer]
+ when(consumer.earliestOrLatestOffset(TopicAndPartition(topic, partition),
+ OffsetRequest.EarliestTime, -1)).thenReturn(0)
+ val getIterator = mock[Long => Iterator[MessageAndOffset]]
+ val kafkaConsumer = new KafkaConsumer(consumer, topic, partition, getIterator)
+ kafkaConsumer.close()
+ verify(consumer).close()
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/lib/grouper/KafkaDefaultGrouperSpec.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/lib/grouper/KafkaDefaultGrouperSpec.scala b/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/lib/grouper/KafkaDefaultGrouperSpec.scala
new file mode 100644
index 0000000..32b8685
--- /dev/null
+++ b/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/lib/grouper/KafkaDefaultGrouperSpec.scala
@@ -0,0 +1,42 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.kafka.lib.grouper
+
+import kafka.common.TopicAndPartition
+import org.scalacheck.Gen
+import org.scalatest.prop.PropertyChecks
+import org.scalatest.{Matchers, PropSpec}
+
+class KafkaDefaultGrouperSpec extends PropSpec with PropertyChecks with Matchers {
+ property("KafkaDefaultGrouper should group TopicAndPartitions in a round-robin way") {
+ forAll(Gen.posNum[Int], Gen.posNum[Int], Gen.posNum[Int]) {
+ (topicNum: Int, partitionNum: Int, taskNum: Int) => {
+ val topicAndPartitions = for {
+ t <- 0.until(topicNum)
+ p <- 0.until(partitionNum)
+ } yield TopicAndPartition("topic" + t, p)
+ 0.until(taskNum).foreach { taskIndex =>
+ val grouper = new KafkaDefaultGrouper
+ grouper.group(taskNum, taskIndex, topicAndPartitions.toArray).forall(
+ tp => topicAndPartitions.indexOf(tp) % taskNum == taskIndex)
+ }
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/util/KafkaServerHarness.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/util/KafkaServerHarness.scala b/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/util/KafkaServerHarness.scala
new file mode 100644
index 0000000..99231f5
--- /dev/null
+++ b/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/util/KafkaServerHarness.scala
@@ -0,0 +1,69 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.kafka.util
+
+import java.util.Properties
+
+import kafka.admin.AdminUtils
+import kafka.common.KafkaException
+import kafka.server.{KafkaConfig => KafkaServerConfig, KafkaServer}
+import kafka.utils.{TestUtils, Utils}
+
+trait KafkaServerHarness extends ZookeeperHarness {
+ val configs: List[KafkaServerConfig]
+ private var servers: List[KafkaServer] = null
+ private var brokerList: String = null
+
+ def getServers: List[KafkaServer] = servers
+ def getBrokerList: Array[String] = brokerList.split(",")
+
+ override def setUp() {
+ super.setUp
+ if (configs.size <= 0) {
+ throw new KafkaException("Must supply at least one server config.")
+ }
+ brokerList = TestUtils.getBrokerListStrFromConfigs(configs)
+ servers = configs.map(TestUtils.createServer(_))
+ }
+
+ override def tearDown() {
+ servers.map(server => server.shutdown())
+ servers.map(server => server.config.logDirs.map(Utils.rm(_)))
+ super.tearDown
+ }
+
+ def createTopicUntilLeaderIsElected(
+ topic: String, partitions: Int, replicas: Int, timeout: Long = 10000)
+ : Map[Int, Option[Int]] = {
+ val zkClient = connectZk()
+ try {
+ // Creates topic
+ AdminUtils.createTopic(zkClient, topic, partitions, replicas, new Properties)
+ // Waits until the update metadata request for new topic reaches all servers
+ (0 until partitions).map { case i =>
+ TestUtils.waitUntilMetadataIsPropagated(servers, topic, i, timeout)
+ i -> TestUtils.waitUntilLeaderIsElectedOrChanged(zkClient, topic, i, timeout)
+ }.toMap
+ } catch {
+ case e: Exception => throw e
+ } finally {
+ zkClient.close()
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/util/ZookeeperHarness.scala
----------------------------------------------------------------------
diff --git a/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/util/ZookeeperHarness.scala b/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/util/ZookeeperHarness.scala
new file mode 100644
index 0000000..8fb23c2
--- /dev/null
+++ b/external/kafka/src/test/scala/org/apache/gearpump/streaming/kafka/util/ZookeeperHarness.scala
@@ -0,0 +1,43 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.kafka.util
+
+import kafka.utils.{TestZKUtils, Utils, ZKStringSerializer}
+import kafka.zk.EmbeddedZookeeper
+import org.I0Itec.zkclient.ZkClient
+
+trait ZookeeperHarness {
+ val zkConnect: String = TestZKUtils.zookeeperConnect
+ val zkConnectionTimeout = 60000
+ val zkSessionTimeout = 60000
+ private var zookeeper: EmbeddedZookeeper = null
+
+ def getZookeeper: EmbeddedZookeeper = zookeeper
+ def connectZk: () => ZkClient = () => {
+ new ZkClient(zkConnect, zkSessionTimeout, zkConnectionTimeout, ZKStringSerializer)
+ }
+
+ def setUp() {
+ zookeeper = new EmbeddedZookeeper(zkConnect)
+ }
+
+ def tearDown() {
+ Utils.swallow(zookeeper.shutdown())
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/monoid/src/main/scala/io/gearpump/streaming/monoid/AlgebirdMonoid.scala
----------------------------------------------------------------------
diff --git a/external/monoid/src/main/scala/io/gearpump/streaming/monoid/AlgebirdMonoid.scala b/external/monoid/src/main/scala/io/gearpump/streaming/monoid/AlgebirdMonoid.scala
deleted file mode 100644
index 3199128..0000000
--- a/external/monoid/src/main/scala/io/gearpump/streaming/monoid/AlgebirdMonoid.scala
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.monoid
-
-import com.twitter.algebird.{Group => ABGroup, Monoid => ABMonoid}
-
-import io.gearpump.streaming.state.api.{Group, Monoid}
-
-class AlgebirdMonoid[T](monoid: ABMonoid[T]) extends Monoid[T] {
- override def plus(l: T, r: T): T = monoid.plus(l, r)
-
- override def zero: T = monoid.zero
-}
-
-class AlgebirdGroup[T](group: ABGroup[T]) extends Group[T] {
- override def zero: T = group.zero
-
- override def plus(l: T, r: T): T = group.plus(l, r)
-
- override def minus(l: T, r: T): T = group.minus(l, r)
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/monoid/src/main/scala/org/apache/gearpump/streaming/monoid/AlgebirdMonoid.scala
----------------------------------------------------------------------
diff --git a/external/monoid/src/main/scala/org/apache/gearpump/streaming/monoid/AlgebirdMonoid.scala b/external/monoid/src/main/scala/org/apache/gearpump/streaming/monoid/AlgebirdMonoid.scala
new file mode 100644
index 0000000..2d831e1
--- /dev/null
+++ b/external/monoid/src/main/scala/org/apache/gearpump/streaming/monoid/AlgebirdMonoid.scala
@@ -0,0 +1,36 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.monoid
+
+import com.twitter.algebird.{Group => ABGroup, Monoid => ABMonoid}
+import org.apache.gearpump.streaming.state.api.{Group, Monoid}
+
+class AlgebirdMonoid[T](monoid: ABMonoid[T]) extends Monoid[T] {
+ override def plus(l: T, r: T): T = monoid.plus(l, r)
+
+ override def zero: T = monoid.zero
+}
+
+class AlgebirdGroup[T](group: ABGroup[T]) extends Group[T] {
+ override def zero: T = group.zero
+
+ override def plus(l: T, r: T): T = group.plus(l, r)
+
+ override def minus(l: T, r: T): T = group.minus(l, r)
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/serializer/src/main/scala/io/gearpump/streaming/serializer/ChillSerializer.scala
----------------------------------------------------------------------
diff --git a/external/serializer/src/main/scala/io/gearpump/streaming/serializer/ChillSerializer.scala b/external/serializer/src/main/scala/io/gearpump/streaming/serializer/ChillSerializer.scala
deleted file mode 100644
index 9578e0a..0000000
--- a/external/serializer/src/main/scala/io/gearpump/streaming/serializer/ChillSerializer.scala
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * 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.
- */
-
-package io.gearpump.streaming.serializer
-
-import scala.util.Try
-
-import com.twitter.chill.KryoInjection
-
-import io.gearpump.streaming.state.api.Serializer
-
-class ChillSerializer[T] extends Serializer[T] {
- override def serialize(t: T): Array[Byte] =
- KryoInjection(t)
-
- override def deserialize(bytes: Array[Byte]): Try[T] =
- KryoInjection.invert(bytes).map(_.asInstanceOf[T])
-}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/external/serializer/src/main/scala/org/apache/gearpump/streaming/serializer/ChillSerializer.scala
----------------------------------------------------------------------
diff --git a/external/serializer/src/main/scala/org/apache/gearpump/streaming/serializer/ChillSerializer.scala b/external/serializer/src/main/scala/org/apache/gearpump/streaming/serializer/ChillSerializer.scala
new file mode 100644
index 0000000..29d26c0
--- /dev/null
+++ b/external/serializer/src/main/scala/org/apache/gearpump/streaming/serializer/ChillSerializer.scala
@@ -0,0 +1,32 @@
+/*
+ * 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.
+ */
+
+package org.apache.gearpump.streaming.serializer
+
+import com.twitter.chill.KryoInjection
+import org.apache.gearpump.streaming.state.api.Serializer
+
+import scala.util.Try
+
+class ChillSerializer[T] extends Serializer[T] {
+ override def serialize(t: T): Array[Byte] =
+ KryoInjection(t)
+
+ override def deserialize(bytes: Array[Byte]): Try[T] =
+ KryoInjection.invert(bytes).map(_.asInstanceOf[T])
+}
http://git-wip-us.apache.org/repos/asf/incubator-gearpump/blob/83b36ef7/integrationtest/README.md
----------------------------------------------------------------------
diff --git a/integrationtest/README.md b/integrationtest/README.md
index 53befc0..034632b 100644
--- a/integrationtest/README.md
+++ b/integrationtest/README.md
@@ -34,7 +34,7 @@ The integration test framework use docker to simulate a real cluster. The test s
The test will launch a Gearpump cluster with 1 master and 2 worker nodes as 3 Docker containers. It might take 10-20 minutes to go through all the test cases. It depends on, how powerful your machine is. The Docker container itself does not have a Gearpump distribution. It will link your local build to the Docker container. When tests are finished, you can see the test result on the screen, or you can save them to a file with this command `sbt it:test > test_report.out`. To investigate Gearpump log, please check the directory `output/target/pack/logs`.
-### How To test single integration test suite like `io.gearpump.integrationtest.checklist.CommandlineSpec`?
+### How To test single integration test suite like `org.apache.gearpump.integrationtest.checklist.CommandlineSpec`?
Unfortunately, I searched around, and didn't find a clean way to do this in sbt. Gearpump is using nested suite for
integration test, which I think sbt don't support well with `sbt test-only <className>`. Please also see discussion at:
@@ -42,8 +42,8 @@ integration test, which I think sbt don't support well with `sbt test-only <clas
For a not that clean solution, here is the steps:
-1. Locate class `io.gearpump.integrationtest.suites.StandaloneModeSuite` source file at
- `gearpump/integrationtest/core/src/it/scala/io/gearpump/integrationtest/suites`
+1. Locate class `org.apache.gearpump.integrationtest.suites.StandaloneModeSuite` source file at
+ `gearpump/integrationtest/core/src/it/scala/org.apache.gearpump/integrationtest/suites`
2. Document out suite you don't want to test like this:
```