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.HRegionInfo;
30  import org.apache.hadoop.hbase.MetaTableAccessor;
31  import org.apache.hadoop.hbase.Server;
32  import org.apache.hadoop.hbase.ServerName;
33  import org.apache.hadoop.hbase.TableName;
34  import org.apache.hadoop.hbase.TableNotDisabledException;
35  import org.apache.hadoop.hbase.TableNotFoundException;
36  import org.apache.hadoop.hbase.classification.InterfaceAudience;
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.getConnection(), tableName)) {
95          throw new TableNotFoundException(tableName);
96        }
97  
98        // There could be multiple client requests trying to disable or enable
99        // the table at the same time. Ensure only the first request is honored
100       // After that, no other requests can be accepted until the table reaches
101       // DISABLED or ENABLED.
102       if (!skipTableStateCheck) {
103         if (!this.assignmentManager.getTableStateManager().setTableStateIfInStates(
104             this.tableName, TableState.State.ENABLING,
105             TableState.State.DISABLED)) {
106           LOG.info("Table " + tableName + " isn't disabled; skipping enable");
107           throw new TableNotDisabledException(this.tableName);
108         }
109       }
110       success = true;
111     } finally {
112       if (!success) {
113         releaseTableLock();
114       }
115     }
116     return this;
117   }
118 
119   @Override
120   public String toString() {
121     String name = "UnknownServerName";
122     if(server != null && server.getServerName() != null) {
123       name = server.getServerName().toString();
124     }
125     return getClass().getSimpleName() + "-" + name + "-" + getSeqid() + "-" +
126         tableName;
127   }
128 
129   @Override
130   public void process() {
131     try {
132       LOG.info("Attempting to enable the table " + this.tableName);
133       MasterCoprocessorHost cpHost = ((HMaster) this.server)
134           .getMasterCoprocessorHost();
135       if (cpHost != null) {
136         cpHost.preEnableTableHandler(this.tableName);
137       }
138       handleEnableTable();
139       if (cpHost != null) {
140         cpHost.postEnableTableHandler(this.tableName);
141       }
142     } catch (IOException | InterruptedException e) {
143       LOG.error("Error trying to enable the table " + this.tableName, e);
144     } finally {
145       releaseTableLock();
146     }
147   }
148 
149   private void releaseTableLock() {
150     if (this.tableLock != null) {
151       try {
152         this.tableLock.release();
153       } catch (IOException ex) {
154         LOG.warn("Could not release the table lock", ex);
155       }
156     }
157   }
158 
159   private void handleEnableTable() throws IOException,
160       InterruptedException {
161     // I could check table is disabling and if so, not enable but require
162     // that user first finish disabling but that might be obnoxious.
163 
164     this.assignmentManager.getTableStateManager().setTableState(this.tableName,
165       TableState.State.ENABLING);
166     boolean done = false;
167     ServerManager serverManager = ((HMaster)this.server).getServerManager();
168     // Get the regions of this table. We're done when all listed
169     // tables are onlined.
170     List<Pair<HRegionInfo, ServerName>> tableRegionsAndLocations;
171     if (TableName.META_TABLE_NAME.equals(tableName)) {
172       tableRegionsAndLocations = new MetaTableLocator().getMetaRegionsAndLocations(
173         server.getZooKeeper());
174     } else {
175       tableRegionsAndLocations = MetaTableAccessor.getTableRegionsAndLocations(
176         server.getConnection(), tableName, true);
177     }
178 
179     int countOfRegionsInTable = tableRegionsAndLocations.size();
180     Map<HRegionInfo, ServerName> regionsToAssign =
181         regionsToAssignWithServerName(tableRegionsAndLocations);
182     if (services != null) {
183       // need to potentially create some regions for the replicas
184       List<HRegionInfo> unrecordedReplicas = AssignmentManager.replicaRegionsNotRecordedInMeta(
185           new HashSet<HRegionInfo>(regionsToAssign.keySet()), services);
186       Map<ServerName, List<HRegionInfo>> srvToUnassignedRegs =
187             this.assignmentManager.getBalancer().roundRobinAssignment(unrecordedReplicas,
188                 serverManager.getOnlineServersList());
189       if (srvToUnassignedRegs != null) {
190         for (Map.Entry<ServerName, List<HRegionInfo>> entry : srvToUnassignedRegs.entrySet()) {
191           for (HRegionInfo h : entry.getValue()) {
192             regionsToAssign.put(h, entry.getKey());
193           }
194         }
195       }
196     }
197     int regionsCount = regionsToAssign.size();
198     if (regionsCount == 0) {
199       done = true;
200     }
201     LOG.info("Table '" + this.tableName + "' has " + countOfRegionsInTable
202       + " regions, of which " + regionsCount + " are offline.");
203     List<ServerName> onlineServers = serverManager.createDestinationServersList();
204     Map<ServerName, List<HRegionInfo>> bulkPlan =
205         this.assignmentManager.getBalancer().retainAssignment(regionsToAssign, onlineServers);
206     if (bulkPlan != null) {
207       LOG.info("Bulk assigning " + regionsCount + " region(s) across " + bulkPlan.size()
208           + " server(s), retainAssignment=true");
209 
210       BulkAssigner ba =
211           new GeneralBulkAssigner(this.server, bulkPlan, this.assignmentManager, true);
212       try {
213         if (ba.bulkAssign()) {
214           done = true;
215         }
216       } catch (InterruptedException e) {
217         LOG.warn("Enable operation was interrupted when enabling table '"
218             + this.tableName + "'");
219         // Preserve the interrupt.
220         Thread.currentThread().interrupt();
221       }
222     } else {
223       LOG.info("Balancer was unable to find suitable servers for table " + tableName
224           + ", leaving unassigned");
225       done = true;
226     }
227     if (done) {
228       // Flip the table to enabled.
229       this.assignmentManager.getTableStateManager().setTableState(
230         this.tableName, TableState.State.ENABLED);
231       LOG.info("Table '" + this.tableName
232       + "' was successfully enabled. Status: done=" + done);
233     } else {
234       LOG.warn("Table '" + this.tableName
235       + "' wasn't successfully enabled. Status: done=" + done);
236     }
237   }
238 
239   /**
240    * @param regionsInMeta
241    * @return List of regions neither in transition nor assigned.
242    * @throws IOException
243    */
244   private Map<HRegionInfo, ServerName> regionsToAssignWithServerName(
245       final List<Pair<HRegionInfo, ServerName>> regionsInMeta) throws IOException {
246     Map<HRegionInfo, ServerName> regionsToAssign =
247         new HashMap<HRegionInfo, ServerName>(regionsInMeta.size());
248     RegionStates regionStates = this.assignmentManager.getRegionStates();
249     for (Pair<HRegionInfo, ServerName> regionLocation : regionsInMeta) {
250       HRegionInfo hri = regionLocation.getFirst();
251       ServerName sn = regionLocation.getSecond();
252       if (regionStates.isRegionOffline(hri)) {
253         regionsToAssign.put(hri, sn);
254       } else {
255         if (LOG.isDebugEnabled()) {
256           LOG.debug("Skipping assign for the region " + hri + " during enable table "
257               + hri.getTable() + " because its already in tranition or assigned.");
258         }
259       }
260     }
261     return regionsToAssign;
262   }
263 }