View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.procedure;
19  
20  import java.io.IOException;
21  import java.util.Arrays;
22  import java.util.List;
23  
24  import org.apache.commons.logging.Log;
25  import org.apache.commons.logging.LogFactory;
26  import org.apache.hadoop.classification.InterfaceAudience;
27  import org.apache.hadoop.hbase.errorhandling.ForeignException;
28  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
29  import org.apache.hadoop.hbase.util.Bytes;
30  import org.apache.hadoop.hbase.zookeeper.ZKUtil;
31  import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
32  import org.apache.zookeeper.KeeperException;
33  
34  import com.google.protobuf.InvalidProtocolBufferException;
35  
36  /**
37   * ZooKeeper based controller for a procedure member.
38   * <p>
39   * There can only be one {@link ZKProcedureMemberRpcs} per procedure type per member,
40   * since each procedure type is bound to a single set of znodes. You can have multiple
41   * {@link ZKProcedureMemberRpcs} on the same server, each serving a different member
42   * name, but each individual rpcs is still bound to a single member name (and since they are
43   * used to determine global progress, its important to not get this wrong).
44   * <p>
45   * To make this slightly more confusing, you can run multiple, concurrent procedures at the same
46   * time (as long as they have different types), from the same controller, but the same node name
47   * must be used for each procedure (though there is no conflict between the two procedure as long
48   * as they have distinct names).
49   * <p>
50   * There is no real error recovery with this mechanism currently -- if any the coordinator fails,
51   * its re-initialization will delete the znodes and require all in progress subprocedures to start
52   * anew.
53   */
54  @InterfaceAudience.Private
55  public class ZKProcedureMemberRpcs implements ProcedureMemberRpcs {
56    private static final Log LOG = LogFactory.getLog(ZKProcedureMemberRpcs.class);
57  
58    private final ZKProcedureUtil zkController;
59  
60    protected ProcedureMember member;
61    private String memberName;
62  
63    /**
64     * Must call {@link #start(String, ProcedureMember)} before this can be used.
65     * @param watcher {@link ZooKeeperWatcher} to be owned by <tt>this</tt>. Closed via
66     *          {@link #close()}.
67     * @param procType name of the znode describing the procedure type
68     * @throws KeeperException if we can't reach zookeeper
69     */
70    public ZKProcedureMemberRpcs(final ZooKeeperWatcher watcher, final String procType)
71        throws KeeperException {
72      this.zkController = new ZKProcedureUtil(watcher, procType) {
73        @Override
74        public void nodeCreated(String path) {
75          if (!isInProcedurePath(path)) {
76            return;
77          }
78  
79          LOG.info("Received created event:" + path);
80          // if it is a simple start/end/abort then we just rewatch the node
81          if (isAcquiredNode(path)) {
82            waitForNewProcedures();
83            return;
84          } else if (isAbortNode(path)) {
85            watchForAbortedProcedures();
86            return;
87          }
88          String parent = ZKUtil.getParent(path);
89          // if its the end barrier, the procedure can be completed
90          if (isReachedNode(parent)) {
91            receivedReachedGlobalBarrier(path);
92            return;
93          } else if (isAbortNode(parent)) {
94            abort(path);
95            return;
96          } else if (isAcquiredNode(parent)) {
97            startNewSubprocedure(path);
98          } else {
99            LOG.debug("Ignoring created notification for node:" + path);
100         }
101       }
102 
103       @Override
104       public void nodeChildrenChanged(String path) {
105         if (path.equals(this.acquiredZnode)) {
106           LOG.info("Received procedure start children changed event: " + path);
107           waitForNewProcedures();
108         } else if (path.equals(this.abortZnode)) {
109           LOG.info("Received procedure abort children changed event: " + path);
110           watchForAbortedProcedures();
111         }
112       }
113     };
114   }
115 
116   public ZKProcedureUtil getZkController() {
117     return zkController;
118   }
119 
120   @Override
121   public String getMemberName() {
122     return memberName;
123   }
124 
125   /**
126    * Pass along the procedure global barrier notification to any listeners
127    * @param path full znode path that cause the notification
128    */
129   private void receivedReachedGlobalBarrier(String path) {
130     LOG.debug("Recieved reached global barrier:" + path);
131     String procName = ZKUtil.getNodeName(path);
132     this.member.receivedReachedGlobalBarrier(procName);
133   }
134 
135   private void watchForAbortedProcedures() {
136     LOG.debug("Checking for aborted procedures on node: '" + zkController.getAbortZnode() + "'");
137     try {
138       // this is the list of the currently aborted procedues
139       for (String node : ZKUtil.listChildrenAndWatchForNewChildren(zkController.getWatcher(),
140         zkController.getAbortZnode())) {
141         String abortNode = ZKUtil.joinZNode(zkController.getAbortZnode(), node);
142         abort(abortNode);
143       }
144     } catch (KeeperException e) {
145       member.controllerConnectionFailure("Failed to list children for abort node:"
146           + zkController.getAbortZnode(), new IOException(e));
147     }
148   }
149 
150   private void waitForNewProcedures() {
151     // watch for new procedues that we need to start subprocedures for
152     LOG.debug("Looking for new procedures under znode:'" + zkController.getAcquiredBarrier() + "'");
153     List<String> runningProcedures = null;
154     try {
155       runningProcedures = ZKUtil.listChildrenAndWatchForNewChildren(zkController.getWatcher(),
156         zkController.getAcquiredBarrier());
157       if (runningProcedures == null) {
158         LOG.debug("No running procedures.");
159         return;
160       }
161     } catch (KeeperException e) {
162       member.controllerConnectionFailure("General failure when watching for new procedures",
163         new IOException(e));
164     }
165     if (runningProcedures == null) {
166       LOG.debug("No running procedures.");
167       return;
168     }
169     for (String procName : runningProcedures) {
170       // then read in the procedure information
171       String path = ZKUtil.joinZNode(zkController.getAcquiredBarrier(), procName);
172       startNewSubprocedure(path);
173     }
174   }
175 
176   /**
177    * Kick off a new sub-procedure on the listener with the data stored in the passed znode.
178    * <p>
179    * Will attempt to create the same procedure multiple times if an procedure znode with the same
180    * name is created. It is left up the coordinator to ensure this doesn't occur.
181    * @param path full path to the znode for the procedure to start
182    */
183   private synchronized void startNewSubprocedure(String path) {
184     LOG.debug("Found procedure znode: " + path);
185     String opName = ZKUtil.getNodeName(path);
186     // start watching for an abort notification for the procedure
187     String abortZNode = zkController.getAbortZNode(opName);
188     try {
189       if (ZKUtil.watchAndCheckExists(zkController.getWatcher(), abortZNode)) {
190         LOG.debug("Not starting:" + opName + " because we already have an abort notification.");
191         return;
192       }
193     } catch (KeeperException e) {
194       member.controllerConnectionFailure("Failed to get the abort znode (" + abortZNode
195           + ") for procedure :" + opName, new IOException(e));
196       return;
197     }
198 
199     // get the data for the procedure
200     Subprocedure subproc = null;
201     try {
202       byte[] data = ZKUtil.getData(zkController.getWatcher(), path);
203       LOG.debug("start proc data length is " + data.length);
204       if (!ProtobufUtil.isPBMagicPrefix(data)) {
205         String msg = "Data in for starting procuedure " + opName +
206           " is illegally formatted (no pb magic). " +
207           "Killing the procedure: " + Bytes.toString(data);
208         LOG.error(msg);
209         throw new IllegalArgumentException(msg);
210       }
211       data = Arrays.copyOfRange(data, ProtobufUtil.lengthOfPBMagic(), data.length);
212       LOG.debug("Found data for znode:" + path);
213       subproc = member.createSubprocedure(opName, data);
214       member.submitSubprocedure(subproc);
215     } catch (IllegalArgumentException iae ) {
216       LOG.error("Illegal argument exception", iae);
217       sendMemberAborted(subproc, new ForeignException(getMemberName(), iae));
218     } catch (IllegalStateException ise) {
219       LOG.error("Illegal state exception ", ise);
220       sendMemberAborted(subproc, new ForeignException(getMemberName(), ise));
221     } catch (KeeperException e) {
222       member.controllerConnectionFailure("Failed to get data for new procedure:" + opName,
223         new IOException(e));
224     } catch (InterruptedException e) {
225       member.controllerConnectionFailure("Failed to get data for new procedure:" + opName,
226           new IOException(e));
227       Thread.currentThread().interrupt();
228     }
229   }
230 
231   /**
232    * This attempts to create an acquired state znode for the procedure (snapshot name).
233    *
234    * It then looks for the reached znode to trigger in-barrier execution.  If not present we
235    * have a watcher, if present then trigger the in-barrier action.
236    */
237   @Override
238   public void sendMemberAcquired(Subprocedure sub) throws IOException {
239     String procName = sub.getName();
240     try {
241       LOG.debug("Member: '" + memberName + "' joining acquired barrier for procedure (" + procName
242           + ") in zk");
243       String acquiredZNode = ZKUtil.joinZNode(ZKProcedureUtil.getAcquireBarrierNode(
244         zkController, procName), memberName);
245       ZKUtil.createAndFailSilent(zkController.getWatcher(), acquiredZNode);
246 
247       // watch for the complete node for this snapshot
248       String reachedBarrier = zkController.getReachedBarrierNode(procName);
249       LOG.debug("Watch for global barrier reached:" + reachedBarrier);
250       if (ZKUtil.watchAndCheckExists(zkController.getWatcher(), reachedBarrier)) {
251         receivedReachedGlobalBarrier(reachedBarrier);
252       }
253     } catch (KeeperException e) {
254       member.controllerConnectionFailure("Failed to acquire barrier for procedure: "
255           + procName + " and member: " + memberName, new IOException(e));
256     }
257   }
258 
259   /**
260    * This acts as the ack for a completed snapshot
261    */
262   @Override
263   public void sendMemberCompleted(Subprocedure sub) throws IOException {
264     String procName = sub.getName();
265     LOG.debug("Marking procedure  '" + procName + "' completed for member '" + memberName
266         + "' in zk");
267     String joinPath = ZKUtil.joinZNode(zkController.getReachedBarrierNode(procName), memberName);
268     try {
269       ZKUtil.createAndFailSilent(zkController.getWatcher(), joinPath);
270     } catch (KeeperException e) {
271       member.controllerConnectionFailure("Failed to post zk node:" + joinPath
272           + " to join procedure barrier.", new IOException(e));
273     }
274   }
275 
276   /**
277    * This should be called by the member and should write a serialized root cause exception as
278    * to the abort znode.
279    */
280   @Override
281   public void sendMemberAborted(Subprocedure sub, ForeignException ee) {
282     if (sub == null) {
283       LOG.error("Failed due to null subprocedure", ee);
284       return;
285     }
286     String procName = sub.getName();
287     LOG.debug("Aborting procedure (" + procName + ") in zk");
288     String procAbortZNode = zkController.getAbortZNode(procName);
289     try {
290       String source = (ee.getSource() == null) ? memberName: ee.getSource();
291       byte[] errorInfo = ProtobufUtil.prependPBMagic(ForeignException.serialize(source, ee));
292       ZKUtil.createAndFailSilent(zkController.getWatcher(), procAbortZNode, errorInfo);
293       LOG.debug("Finished creating abort znode:" + procAbortZNode);
294     } catch (KeeperException e) {
295       // possible that we get this error for the procedure if we already reset the zk state, but in
296       // that case we should still get an error for that procedure anyways
297       zkController.logZKTree(zkController.getBaseZnode());
298       member.controllerConnectionFailure("Failed to post zk node:" + procAbortZNode
299           + " to abort procedure", new IOException(e));
300     }
301   }
302 
303   /**
304    * Pass along the found abort notification to the listener
305    * @param abortZNode full znode path to the failed procedure information
306    */
307   protected void abort(String abortZNode) {
308     LOG.debug("Aborting procedure member for znode " + abortZNode);
309     String opName = ZKUtil.getNodeName(abortZNode);
310     try {
311       byte[] data = ZKUtil.getData(zkController.getWatcher(), abortZNode);
312 
313       // figure out the data we need to pass
314       ForeignException ee;
315       try {
316         if (!ProtobufUtil.isPBMagicPrefix(data)) {
317           String msg = "Illegally formatted data in abort node for proc " + opName
318               + ".  Killing the procedure.";
319           LOG.error(msg);
320           // we got a remote exception, but we can't describe it so just return exn from here
321           ee = new ForeignException(getMemberName(), new IllegalArgumentException(msg));
322         } else {
323           data = Arrays.copyOfRange(data, ProtobufUtil.lengthOfPBMagic(), data.length);
324           ee = ForeignException.deserialize(data);
325         }
326       } catch (InvalidProtocolBufferException e) {
327         LOG.warn("Got an error notification for op:" + opName
328             + " but we can't read the information. Killing the procedure.");
329         // we got a remote exception, but we can't describe it so just return exn from here
330         ee = new ForeignException(getMemberName(), e);
331       }
332 
333       this.member.receiveAbortProcedure(opName, ee);
334     } catch (KeeperException e) {
335       member.controllerConnectionFailure("Failed to get data for abort znode:" + abortZNode
336           + zkController.getAbortZnode(), new IOException(e));
337     } catch (InterruptedException e) {
338       LOG.warn("abort already in progress", e);
339       Thread.currentThread().interrupt();
340     }
341   }
342 
343   public void start(final String memberName, final ProcedureMember listener) {
344     LOG.debug("Starting procedure member '" + memberName + "'");
345     this.member = listener;
346     this.memberName = memberName;
347     watchForAbortedProcedures();
348     waitForNewProcedures();
349   }
350 
351   @Override
352   public void close() throws IOException {
353     zkController.close();
354   }
355 
356 }