-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStorageNode.java
More file actions
201 lines (167 loc) · 8.02 KB
/
Copy pathStorageNode.java
File metadata and controls
201 lines (167 loc) · 8.02 KB
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
199
200
201
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.atomic.*;
import org.apache.thrift.*;
import org.apache.thrift.server.*;
import org.apache.thrift.transport.*;
import org.apache.thrift.transport.layered.*;
import org.apache.thrift.protocol.*;
import org.apache.zookeeper.*;
import org.apache.curator.*;
import org.apache.curator.retry.*;
import org.apache.curator.framework.*;
import org.apache.curator.utils.*;
import org.apache.curator.framework.api.*;
import org.apache.log4j.*;
public class StorageNode {
static Logger log;
public static void setupWatcher(CuratorFramework curClient, String parentPath, String myPath, Logger log, KeyValueHandler handler) throws Exception {
curClient.sync();
List<String> children = curClient.getChildren().forPath(parentPath);
Collections.sort(children);
String myNode = ZKPaths.getNodeFromPath(myPath);
int myIndex = children.indexOf(myNode);
if (myIndex == -1) {
Thread.sleep(100);
curClient.sync();
children = curClient.getChildren().forPath(parentPath);
Collections.sort(children);
myIndex = children.indexOf(myNode);
if (myIndex == -1) {
throw new Exception("My node not found in ZooKeeper children list");
}
}
CuratorWatcher childrenWatcher = new CuratorWatcher() {
@Override
public void process(WatchedEvent event) throws Exception {
if (event.getType() == Watcher.Event.EventType.NodeChildrenChanged) {
try {
setupWatcher(curClient, parentPath, myPath, log, handler);
} catch (Exception e) {
//log.error("Error in setupWatcher after children change", e);
}
}
}
};
if (myIndex == 0) {
handler.setPrimary(true);
if (children.size() > 1) {
String backupChild = children.get(1);
String backupPath = parentPath + "/" + backupChild;
byte[] data = curClient.getData().forPath(backupPath);
String strData = new String(data);
String[] parts = strData.split(":");
InetSocketAddress backupAddr = new InetSocketAddress(parts[0], Integer.parseInt(parts[1]));
handler.setBackupAddr(backupAddr);
//log.info("Backup address set to: " + backupAddr);
} else {
handler.setBackupAddr(null);
//log.info("No backup available yet");
}
curClient.getChildren().usingWatcher(childrenWatcher).forPath(parentPath);
return;
}
handler.setPrimary(false);
//log.info("I AM BACKUP");
InetSocketAddress primaryAddr = null;
boolean syncSuccess = false;
for (int i = 0; i < myIndex; i++) {
String candidateChild = children.get(i);
String candidatePath = parentPath + "/" + candidateChild;
try {
byte[] pdata = curClient.getData().forPath(candidatePath);
String pstr = new String(pdata);
String[] pparts = pstr.split(":");
InetSocketAddress candidateAddr = new InetSocketAddress(pparts[0], Integer.parseInt(pparts[1]));
try {
//log.info("Attempting to sync from candidate " + candidateAddr);
handler.initialSyncFromPrimary(candidateAddr);
//log.info("Synced full state from primary " + candidateAddr);
primaryAddr = candidateAddr;
syncSuccess = true;
break;
} catch (Exception e) {
//log.warn("Could not sync from candidate " + candidateAddr + " (might be dead): " + e.getMessage());
}
} catch (Exception e) {
//log.warn("Could not get data for candidate " + candidatePath + ": " + e.getMessage());
continue;
}
}
curClient.getChildren().usingWatcher(childrenWatcher).forPath(parentPath);
if (syncSuccess && primaryAddr != null) {
String predecessorPath = null;
for (int i = 0; i < myIndex; i++) {
String candidateChild = children.get(i);
String candidatePath = parentPath + "/" + candidateChild;
try {
byte[] pdata = curClient.getData().forPath(candidatePath);
String pstr = new String(pdata);
String[] pparts = pstr.split(":");
InetSocketAddress candidateAddr = new InetSocketAddress(pparts[0], Integer.parseInt(pparts[1]));
if (candidateAddr.equals(primaryAddr)) {
predecessorPath = candidatePath;
break;
}
} catch (Exception e) { }
}
if (predecessorPath != null) {
final String finalPredecessorPath = predecessorPath;
//log.info("I AM BACKUP, watching " + finalPredecessorPath);
curClient.getData().usingWatcher((CuratorWatcher) event -> {
if (event.getType() == Watcher.Event.EventType.NodeDeleted) {
//log.info(finalPredecessorPath + " deleted. Rechecking...");
try {
setupWatcher(curClient, parentPath, myPath, log, handler);
} catch (Exception e) {
//log.error("Error in setupWatcher after predecessor delete", e);
}
}
}).forPath(finalPredecessorPath);
}
}
}
public static void main(String [] args) throws Exception {
BasicConfigurator.configure();
log = Logger.getLogger(StorageNode.class.getName());
Logger.getLogger("org.apache.zookeeper").setLevel(Level.WARN);
Logger.getLogger("org.apache.curator").setLevel(Level.WARN);
Logger.getLogger("org.apache.thrift").setLevel(Level.WARN);
if (args.length != 4) {
//System.err.println("Usage: java StorageNode host port zkconnectstring zknode");
System.exit(-1);
}
CuratorFramework curClient =
CuratorFrameworkFactory.builder()
.connectString(args[2])
.retryPolicy(new RetryNTimes(10, 1000))
.connectionTimeoutMs(5000)
.sessionTimeoutMs(1500)
.build();
curClient.start();
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
curClient.close();
}
});
KeyValueHandler handler = new KeyValueHandler(args[0], Integer.parseInt(args[1]), curClient, args[3]);
KeyValueService.Processor<KeyValueService.Iface> processor = new KeyValueService.Processor<>(handler);
TServerSocket socket = new TServerSocket(Integer.parseInt(args[1]));
TThreadPoolServer.Args sargs = new TThreadPoolServer.Args(socket);
sargs.protocolFactory(new TBinaryProtocol.Factory());
int maxFrameSize = 256 * 1024 * 1024;
sargs.transportFactory(new TFramedTransport.Factory(maxFrameSize));
sargs.processorFactory(new TProcessorFactory(processor));
sargs.maxWorkerThreads(64);
TServer server = new TThreadPoolServer(sargs);
new Thread(new Runnable() {
public void run() {
server.serve();
}
}).start();
String myPath = curClient.create().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath(args[3] + "/n_", (args[0] + ":" + args[1]).getBytes());
//log.info("Registered in ZooKeeper: " + myPath);
setupWatcher(curClient, args[3], myPath, log, handler);
}
}