This repository has been archived by the owner on May 22, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 212
/
CopyJob.scala
198 lines (169 loc) · 6.84 KB
/
CopyJob.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
package com.twitter.gizzard.scheduler
import com.twitter.ostrich.Stats
import com.twitter.util.TimeConversions._
import net.lag.logging.Logger
import collection.mutable.ListBuffer
import collection.mutable
import nameserver.{NameServer, NonExistentShard}
import shards._
object CopyJob {
val MIN_COPY = 500
}
/**
* A factory for creating a new copy job (with default count and a starting cursor) from a source
* and destination shard ID.
*/
trait CopyJobFactory[S <: Shard] extends ((ShardId, List[CopyDestination]) => CopyJob[S])
/**
* A parser that creates a copy job out of json. The basic attributes (source shard ID, destination)
* shard ID, and count) are parsed out first, and the remaining attributes are passed to
* 'deserialize' to decode any shard-specific data (like a cursor).
*/
trait CopyJobParser[S <: Shard] extends JsonJobParser {
def deserialize(attributes: Map[String, Any], sourceId: ShardId,
destinations: List[CopyDestination], count: Int): CopyJob[S]
def apply(attributes: Map[String, Any]): JsonJob = {
val sourceId = ShardId(attributes("source_shard_hostname").toString, attributes("source_shard_table_prefix").toString)
deserialize(attributes,
sourceId,
parseDestinations(attributes).toList,
attributes("count").asInstanceOf[{def toInt: Int}].toInt)
}
private def parseDestinations(attributes: Map[String, Any]) = {
val destinations = new ListBuffer[CopyDestination]
var i = 0
while(attributes.contains("destination_" + i + "_hostname")) {
val prefix = "destination_" + i
val baseKey = prefix + "_base_id"
val baseId = if (attributes.contains(baseKey)) {
Some(attributes(baseKey).asInstanceOf[{def toLong: Long}].toLong)
} else {
None
}
val shardId = ShardId(attributes(prefix + "_shard_hostname").toString, attributes(prefix + "_shard_table_prefix").toString)
destinations += CopyDestination(shardId, baseId)
i += 1
}
destinations.toList
}
}
/**
* A json-encodable job that represents the state of a copy from one shard to another.
*
* The 'toMap' implementation encodes the source and destination shard IDs, and the count of items.
* Other shard-specific data (like the cursor) can be encoded in 'serialize'.
*
* 'copyPage' is called to do the actual data copying. It should return a new CopyJob representing
* the next chunk of work to do, or None if the entire copying job is complete.
*/
abstract case class CopyJob[S <: Shard](sourceId: ShardId,
destinations: List[CopyDestination],
var count: Int,
nameServer: NameServer[S],
scheduler: JobScheduler[JsonJob])
extends JsonJob {
private val log = Logger.get(getClass.getName)
override def shouldReplicate = false
def toMap = {
Map("source_shard_hostname" -> sourceId.hostname,
"source_shard_table_prefix" -> sourceId.tablePrefix,
"count" -> count
) ++ serialize ++ destinationsToMap
}
private def destinationsToMap = {
var i = 0
val map = mutable.Map[String, Any]()
destinations.foreach { destination =>
map("destination_" + i + "_hostname") = destination.shardId.hostname
map("destination_" + i + "_table_prefix") = destination.shardId.tablePrefix
destination.baseId.foreach { id =>
map("destination_" + i + "_base_id") = id
}
i += 1
}
map
}
def finish() {
destinations.foreach { dest =>
nameServer.markShardBusy(dest.shardId, shards.Busy.Normal)
}
log.info("Copying finished for (type %s) from %s to %s",
getClass.getName.split("\\.").last, sourceId, destinations)
Stats.clearGauge(gaugeName)
}
def apply() {
try {
log.info("Copying shard block (type %s) from %s to %s: state=%s",
getClass.getName.split("\\.").last, sourceId, destinations, toMap)
val sourceShard = nameServer.findShardById(sourceId)
val destinationShards = destinations.map { dest =>
CopyDestinationShard[S](nameServer.findShardById(dest.shardId), dest.baseId)
}
// do this on each iteration, so it happens in the queue and can be retried if the db is busy:
destinations.foreach { dest =>
nameServer.markShardBusy(dest.shardId, shards.Busy.Busy)
}
val nextJob = copyPage(sourceShard, destinationShards, count)
nextJob match {
case Some(job) =>
incrGauge
scheduler.put(job)
case None =>
finish()
}
} catch {
case e: NonExistentShard =>
log.error("Shard block copy failed because one of the shards doesn't exist. Terminating the copy.")
case e: ShardTimeoutException if (count > CopyJob.MIN_COPY) =>
log.warning("Shard block copy timed out; trying a smaller block size.")
count = (count * 0.9).toInt
scheduler.put(this)
case e: ShardDatabaseTimeoutException =>
log.warning("Shard block copy failed to get a database connection; retrying.")
scheduler.put(this)
case e: Throwable =>
log.warning("Shard block copy stopped due to exception: %s", e)
throw e
}
}
private def incrGauge = {
Stats.setGauge(gaugeName, Stats.getGauge(gaugeName).getOrElse(0.0) + count)
}
private def gaugeName = {
"x-copying-" + sourceId + "-" + destinations
}
def copyPage(sourceShard: S, destinationShards: List[CopyDestinationShard[S]], count: Int): Option[CopyJob[S]]
def serialize: Map[String, Any]
}
class BasicCopyJobFactory[S <: Shard](
ns: NameServer[S],
s: JobScheduler[JsonJob],
copyAdapter: ShardCopyAdapter[S],
defaultCount: Int)
extends CopyJobFactory[S] {
def apply(sourceId: ShardId, destinations: List[CopyDestination]) = {
new BasicCopyJob(sourceId, destinations, None, defaultCount, ns, s, copyAdapter)
}
def parser = new CopyJobParser[S] {
def deserialize(attrs: Map[String, Any], sourceId: ShardId, destinations: List[CopyDestination], count: Int) = {
val cursor = attrs("cursor").asInstanceOf[Map[String,Any]]
new BasicCopyJob(sourceId, destinations, Some(cursor), count, ns, s, copyAdapter)
}
}
}
class BasicCopyJob[S <: Shard](
sourceId: ShardId,
destinations: List[CopyDestination],
cursor: Option[Map[String, Any]],
count: Int,
nameServer: NameServer[S],
scheduler: JobScheduler[JsonJob],
copyAdapter: ShardCopyAdapter[S])
extends CopyJob[S](sourceId, destinations, count, nameServer, scheduler) {
def serialize = Map("cursor" -> cursor)
def copyPage(source: S, dest: List[CopyDestinationShard[S]], count: Int) = {
copyAdapter.copyPage(source, dest, cursor, count).map { nextCursor =>
new BasicCopyJob(sourceId, destinations, Some(nextCursor), count, nameServer, scheduler, copyAdapter)
}
}
}