View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase.master.handler;
20  
21  import java.io.IOException;
22  import java.util.HashMap;
23  import java.util.HashSet;
24  import java.util.List;
25  import java.util.Map;
26  
27  import org.apache.commons.logging.Log;
28  import org.apache.commons.logging.LogFactory;
29  import org.apache.hadoop.hbase.classification.InterfaceAudience;
30  import org.apache.hadoop.hbase.TableName;
31  import org.apache.hadoop.hbase.HRegionInfo;
32  import org.apache.hadoop.hbase.Server;
33  import org.apache.hadoop.hbase.ServerName;
34  import org.apache.hadoop.hbase.TableNotDisabledException;
35  import org.apache.hadoop.hbase.TableNotFoundException;
36  import org.apache.hadoop.hbase.MetaTableAccessor;
37  import org.apache.hadoop.hbase.client.TableState;
38  import org.apache.hadoop.hbase.executor.EventHandler;
39  import org.apache.hadoop.hbase.executor.EventType;
40  import org.apache.hadoop.hbase.master.AssignmentManager;
41  import org.apache.hadoop.hbase.master.BulkAssigner;
42  import org.apache.hadoop.hbase.master.GeneralBulkAssigner;
43  import org.apache.hadoop.hbase.master.HMaster;
44  import org.apache.hadoop.hbase.master.MasterCoprocessorHost;
45  import org.apache.hadoop.hbase.master.MasterServices;
46  import org.apache.hadoop.hbase.master.RegionStates;
47  import org.apache.hadoop.hbase.master.ServerManager;
48  import org.apache.hadoop.hbase.master.TableLockManager;
49  import org.apache.hadoop.hbase.master.TableLockManager.TableLock;
50  import org.apache.hadoop.hbase.util.Pair;
51  import org.apache.hadoop.hbase.zookeeper.MetaTableLocator;
52  
53  /**
54   * Handler to run enable of a table.
55   */
56  @InterfaceAudience.Private
57  public class EnableTableHandler extends EventHandler {
58    private static final Log LOG = LogFactory.getLog(EnableTableHandler.class);
59    private final TableName tableName;
60    private final AssignmentManager assignmentManager;
61    private final TableLockManager tableLockManager;
62    private boolean skipTableStateCheck = false;
63    private TableLock tableLock;
64    private MasterServices services;
65  
66    public EnableTableHandler(Server server, TableName tableName,
67        AssignmentManager assignmentManager, TableLockManager tableLockManager,
68        boolean skipTableStateCheck) {
69      super(server, EventType.C_M_ENABLE_TABLE);
70      this.tableName = tableName;
71      this.assignmentManager = assignmentManager;
72      this.tableLockManager = tableLockManager;
73      this.skipTableStateCheck = skipTableStateCheck;
74    }
75  
76    public EnableTableHandler(MasterServices services, TableName tableName,
77        AssignmentManager assignmentManager,
78        TableLockManager tableLockManager, boolean skipTableStateCheck) {
79      this((Server)services, tableName, assignmentManager, tableLockManager,
80          skipTableStateCheck);
81      this.services = services;
82    }
83  
84    public EnableTableHandler prepare()
85        throws TableNotFoundException, TableNotDisabledException, IOException {
86      //acquire the table write lock, blocking
87      this.tableLock = this.tableLockManager.writeLock(tableName,
88          EventType.C_M_ENABLE_TABLE.toString());
89      this.tableLock.acquire();
90  
91      boolean success = false;
92      try {
93        // Check if table exists
94        if (!MetaTableAccessor.tableExists(this.server.getShortCircuitConnection(), tableName)) {
95          // retainAssignment is true only during recovery.  In normal case it is false
96          if (!this.skipTableStateCheck) {
97            throw new TableNotFoundException(tableName);
98          }
99          this.assignmentManager.getTableStateManager().setDeletedTable(tableName);
100       }
101 
102       // There could be multiple client requests trying to disable or enable
103       // the table at the same time. Ensure only the first request is honored
104       // After that, no other requests can be accepted until the table reaches
105       // DISABLED or ENABLED.
106       if (!skipTableStateCheck) {
107         if (!this.assignmentManager.getTableStateManager().setTableStateIfInStates(
108             this.tableName, TableState.State.ENABLING,
109             TableState.State.DISABLED)) {
110           LOG.info("Table " + tableName + " isn't disabled; skipping enable");
111           throw new TableNotDisabledException(this.tableName);
112         }
113       }
114       success = true;
115     } finally {
116       if (!success) {
117         releaseTableLock();
118       }
119     }
120     return this;
121   }
122 
123   @Override
124   public String toString() {
125     String name = "UnknownServerName";
126     if(server != null && server.getServerName() != null) {
127       name = server.getServerName().toString();
128     }
129     return getClass().getSimpleName() + "-" + name + "-" + getSeqid() + "-" +
130         tableName;
131   }
132 
133   @Override
134   public void process() {
135     try {
136       LOG.info("Attempting to enable the table " + this.tableName);
137       MasterCoprocessorHost cpHost = ((HMaster) this.server)
138           .getMasterCoprocessorHost();
139       if (cpHost != null) {
140         cpHost.preEnableTableHandler(this.tableName);
141       }
142       handleEnableTable();
143       if (cpHost != null) {
144         cpHost.postEnableTableHandler(this.tableName);
145       }
146     } catch (IOException | InterruptedException e) {
147       LOG.error("Error trying to enable the table " + this.tableName, e);
148     } finally {
149       releaseTableLock();
150     }
151   }
152 
153   private void releaseTableLock() {
154     if (this.tableLock != null) {
155       try {
156         this.tableLock.release();
157       } catch (IOException ex) {
158         LOG.warn("Could not release the table lock", ex);
159       }
160     }
161   }
162 
163   private void handleEnableTable() throws IOException,
164       InterruptedException {
165     // I could check table is disabling and if so, not enable but require
166     // that user first finish disabling but that might be obnoxious.
167 
168     this.assignmentManager.getTableStateManager().setTableState(this.tableName,
169       TableState.State.ENABLING);
170     boolean done = false;
171     ServerManager serverManager = ((HMaster)this.server).getServerManager();
172     // Get the regions of this table. We're done when all listed
173     // tables are onlined.
174     List<Pair<HRegionInfo, ServerName>> tableRegionsAndLocations;
175     if (TableName.META_TABLE_NAME.equals(tableName)) {
176       tableRegionsAndLocations = new MetaTableLocator().getMetaRegionsAndLocations(
177         server.getZooKeeper());
178     } else {
179       tableRegionsAndLocations = MetaTableAccessor.getTableRegionsAndLocations(
180         server.getShortCircuitConnection(), tableName, true);
181     }
182 
183     int countOfRegionsInTable = tableRegionsAndLocations.size();
184     Map<HRegionInfo, ServerName> regionsToAssign =
185         regionsToAssignWithServerName(tableRegionsAndLocations);
186     if (services != null) {
187       // need to potentially create some regions for the replicas
188       List<HRegionInfo> unrecordedReplicas = AssignmentManager.replicaRegionsNotRecordedInMeta(
189           new HashSet<HRegionInfo>(regionsToAssign.keySet()), services);
190       Map<ServerName, List<HRegionInfo>> srvToUnassignedRegs =
191             this.assignmentManager.getBalancer().roundRobinAssignment(unrecordedReplicas,
192                 serverManager.getOnlineServersList());
193       if (srvToUnassignedRegs != null) {
194         for (Map.Entry<ServerName, List<HRegionInfo>> entry : srvToUnassignedRegs.entrySet()) {
195           for (HRegionInfo h : entry.getValue()) {
196             regionsToAssign.put(h, entry.getKey());
197           }
198         }
199       }
200     }
201     int regionsCount = regionsToAssign.size();
202     if (regionsCount == 0) {
203       done = true;
204     }
205     LOG.info("Table '" + this.tableName + "' has " + countOfRegionsInTable
206       + " regions, of which " + regionsCount + " are offline.");
207     List<ServerName> onlineServers = serverManager.createDestinationServersList();
208     Map<ServerName, List<HRegionInfo>> bulkPlan =
209         this.assignmentManager.getBalancer().retainAssignment(regionsToAssign, onlineServers);
210     LOG.info("Bulk assigning " + regionsCount + " region(s) across " + bulkPlan.size()
211       + " server(s), retainAssignment=true");
212 
213     BulkAssigner ba = new GeneralBulkAssigner(this.server, bulkPlan, this.assignmentManager, true);
214     try {
215       if (ba.bulkAssign()) {
216         done = true;
217       }
218     } catch (InterruptedException e) {
219       LOG.warn("Enable operation was interrupted when enabling table '"
220         + this.tableName + "'");
221       // Preserve the interrupt.
222       Thread.currentThread().interrupt();
223     }
224     if (done) {
225       // Flip the table to enabled.
226       this.assignmentManager.getTableStateManager().setTableState(
227         this.tableName, TableState.State.ENABLED);
228       LOG.info("Table '" + this.tableName
229       + "' was successfully enabled. Status: done=" + done);
230     } else {
231       LOG.warn("Table '" + this.tableName
232       + "' wasn't successfully enabled. Status: done=" + done);
233     }
234   }
235 
236   /**
237    * @param regionsInMeta
238    * @return List of regions neither in transition nor assigned.
239    * @throws IOException
240    */
241   private Map<HRegionInfo, ServerName> regionsToAssignWithServerName(
242       final List<Pair<HRegionInfo, ServerName>> regionsInMeta) throws IOException {
243     Map<HRegionInfo, ServerName> regionsToAssign =
244         new HashMap<HRegionInfo, ServerName>(regionsInMeta.size());
245     RegionStates regionStates = this.assignmentManager.getRegionStates();
246     for (Pair<HRegionInfo, ServerName> regionLocation : regionsInMeta) {
247       HRegionInfo hri = regionLocation.getFirst();
248       ServerName sn = regionLocation.getSecond();
249       if (regionStates.isRegionOffline(hri)) {
250         regionsToAssign.put(hri, sn);
251       } else {
252         if (LOG.isDebugEnabled()) {
253           LOG.debug("Skipping assign for the region " + hri + " during enable table "
254               + hri.getTable() + " because its already in tranition or assigned.");
255         }
256       }
257     }
258     return regionsToAssign;
259   }
260 }