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