PageRenderTime 47ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/tags/release-0.0.0-rc0/hive/external/ql/src/java/org/apache/hadoop/hive/ql/session/SessionState.java

#
Java | 639 lines | 436 code | 93 blank | 110 comment | 66 complexity | edbcf8a9817ba72114ed3bdcf7b0a73f MD5 | raw file
Possible License(s): Apache-2.0, BSD-3-Clause, JSON, CPL-1.0
  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.hive.ql.session;
  19. import java.io.File;
  20. import java.io.IOException;
  21. import java.io.InputStream;
  22. import java.io.PrintStream;
  23. import java.net.URI;
  24. import java.net.URL;
  25. import java.util.Calendar;
  26. import java.util.GregorianCalendar;
  27. import java.util.HashMap;
  28. import java.util.HashSet;
  29. import java.util.List;
  30. import java.util.Set;
  31. import org.apache.commons.lang.StringUtils;
  32. import org.apache.commons.logging.Log;
  33. import org.apache.commons.logging.LogFactory;
  34. import org.apache.hadoop.conf.Configuration;
  35. import org.apache.hadoop.fs.FileSystem;
  36. import org.apache.hadoop.fs.Path;
  37. import org.apache.hadoop.hive.conf.HiveConf;
  38. import org.apache.hadoop.hive.ql.exec.Utilities;
  39. import org.apache.hadoop.hive.ql.history.HiveHistory;
  40. import org.apache.hadoop.hive.ql.metadata.HiveException;
  41. import org.apache.hadoop.hive.ql.metadata.HiveUtils;
  42. import org.apache.hadoop.hive.ql.plan.HiveOperation;
  43. import org.apache.hadoop.hive.ql.security.HiveAuthenticationProvider;
  44. import org.apache.hadoop.hive.ql.security.authorization.HiveAuthorizationProvider;
  45. import org.apache.hadoop.hive.ql.util.DosToUnix;
  46. import org.apache.log4j.LogManager;
  47. import org.apache.log4j.PropertyConfigurator;
  48. /**
  49. * SessionState encapsulates common data associated with a session.
  50. *
  51. * Also provides support for a thread static session object that can be accessed
  52. * from any point in the code to interact with the user and to retrieve
  53. * configuration information
  54. */
  55. public class SessionState {
  56. /**
  57. * current configuration.
  58. */
  59. protected HiveConf conf;
  60. /**
  61. * silent mode.
  62. */
  63. protected boolean isSilent;
  64. /**
  65. * verbose mode
  66. */
  67. protected boolean isVerbose;
  68. /*
  69. * HiveHistory Object
  70. */
  71. protected HiveHistory hiveHist;
  72. /**
  73. * Streams to read/write from.
  74. */
  75. public InputStream in;
  76. public PrintStream out;
  77. public PrintStream err;
  78. /**
  79. * Standard output from any child process(es).
  80. */
  81. public PrintStream childOut;
  82. /**
  83. * Error output from any child process(es).
  84. */
  85. public PrintStream childErr;
  86. /**
  87. * type of the command.
  88. */
  89. private HiveOperation commandType;
  90. private HiveAuthorizationProvider authorizer;
  91. private HiveAuthenticationProvider authenticator;
  92. private CreateTableAutomaticGrant createTableGrants;
  93. /**
  94. * Lineage state.
  95. */
  96. LineageState ls;
  97. /**
  98. * Get the lineage state stored in this session.
  99. *
  100. * @return LineageState
  101. */
  102. public LineageState getLineageState() {
  103. return ls;
  104. }
  105. public HiveConf getConf() {
  106. return conf;
  107. }
  108. public void setConf(HiveConf conf) {
  109. this.conf = conf;
  110. }
  111. public boolean getIsSilent() {
  112. if(conf != null) {
  113. return conf.getBoolVar(HiveConf.ConfVars.HIVESESSIONSILENT);
  114. } else {
  115. return isSilent;
  116. }
  117. }
  118. public void setIsSilent(boolean isSilent) {
  119. if(conf != null) {
  120. conf.setBoolVar(HiveConf.ConfVars.HIVESESSIONSILENT, isSilent);
  121. }
  122. this.isSilent = isSilent;
  123. }
  124. public boolean getIsVerbose() {
  125. return isVerbose;
  126. }
  127. public void setIsVerbose(boolean isVerbose) {
  128. this.isVerbose = isVerbose;
  129. }
  130. public SessionState() {
  131. this(null);
  132. }
  133. public SessionState(HiveConf conf) {
  134. this.conf = conf;
  135. isSilent = conf.getBoolVar(HiveConf.ConfVars.HIVESESSIONSILENT);
  136. ls = new LineageState();
  137. }
  138. public void setCmd(String cmdString) {
  139. conf.setVar(HiveConf.ConfVars.HIVEQUERYSTRING, cmdString);
  140. }
  141. public String getCmd() {
  142. return (conf.getVar(HiveConf.ConfVars.HIVEQUERYSTRING));
  143. }
  144. public String getQueryId() {
  145. return (conf.getVar(HiveConf.ConfVars.HIVEQUERYID));
  146. }
  147. public String getSessionId() {
  148. return (conf.getVar(HiveConf.ConfVars.HIVESESSIONID));
  149. }
  150. /**
  151. * Singleton Session object per thread.
  152. *
  153. **/
  154. private static ThreadLocal<SessionState> tss = new ThreadLocal<SessionState>();
  155. /**
  156. * start a new session and set it to current session.
  157. * @throws HiveException
  158. */
  159. public static SessionState start(HiveConf conf) throws HiveException {
  160. SessionState ss = new SessionState(conf);
  161. ss.getConf().setVar(HiveConf.ConfVars.HIVESESSIONID, makeSessionId());
  162. ss.hiveHist = new HiveHistory(ss);
  163. ss.authenticator = HiveUtils.getAuthenticator(conf);
  164. ss.authorizer = HiveUtils.getAuthorizeProviderManager(
  165. conf, ss.authenticator);
  166. ss.createTableGrants = CreateTableAutomaticGrant.create(conf);
  167. tss.set(ss);
  168. return (ss);
  169. }
  170. /**
  171. * set current session to existing session object if a thread is running
  172. * multiple sessions - it must call this method with the new session object
  173. * when switching from one session to another.
  174. * @throws HiveException
  175. */
  176. public static SessionState start(SessionState startSs) {
  177. tss.set(startSs);
  178. if (StringUtils.isEmpty(startSs.getConf().getVar(
  179. HiveConf.ConfVars.HIVESESSIONID))) {
  180. startSs.getConf()
  181. .setVar(HiveConf.ConfVars.HIVESESSIONID, makeSessionId());
  182. }
  183. if (startSs.hiveHist == null) {
  184. startSs.hiveHist = new HiveHistory(startSs);
  185. }
  186. try {
  187. startSs.authenticator = HiveUtils.getAuthenticator(startSs
  188. .getConf());
  189. startSs.authorizer = HiveUtils.getAuthorizeProviderManager(startSs
  190. .getConf(), startSs.authenticator);
  191. startSs.createTableGrants = CreateTableAutomaticGrant.create(startSs
  192. .getConf());
  193. } catch (HiveException e) {
  194. throw new RuntimeException(e);
  195. }
  196. return startSs;
  197. }
  198. /**
  199. * get the current session.
  200. */
  201. public static SessionState get() {
  202. return tss.get();
  203. }
  204. /**
  205. * get hiveHitsory object which does structured logging.
  206. *
  207. * @return The hive history object
  208. */
  209. public HiveHistory getHiveHistory() {
  210. return hiveHist;
  211. }
  212. private static String makeSessionId() {
  213. GregorianCalendar gc = new GregorianCalendar();
  214. String userid = System.getProperty("user.name");
  215. return userid
  216. + "_"
  217. + String.format("%1$4d%2$02d%3$02d%4$02d%5$02d", gc.get(Calendar.YEAR),
  218. gc.get(Calendar.MONTH) + 1, gc.get(Calendar.DAY_OF_MONTH), gc
  219. .get(Calendar.HOUR_OF_DAY), gc.get(Calendar.MINUTE));
  220. }
  221. public static final String HIVE_L4J = "hive-log4j.properties";
  222. public static final String HIVE_EXEC_L4J = "hive-exec-log4j.properties";
  223. public static void initHiveLog4j() {
  224. // allow hive log4j to override any normal initialized one
  225. URL hive_l4j = SessionState.class.getClassLoader().getResource(HIVE_L4J);
  226. if (hive_l4j == null) {
  227. System.out.println(HIVE_L4J + " not found");
  228. } else {
  229. LogManager.resetConfiguration();
  230. PropertyConfigurator.configure(hive_l4j);
  231. }
  232. }
  233. /**
  234. * This class provides helper routines to emit informational and error
  235. * messages to the user and log4j files while obeying the current session's
  236. * verbosity levels.
  237. *
  238. * NEVER write directly to the SessionStates standard output other than to
  239. * emit result data DO use printInfo and printError provided by LogHelper to
  240. * emit non result data strings.
  241. *
  242. * It is perfectly acceptable to have global static LogHelper objects (for
  243. * example - once per module) LogHelper always emits info/error to current
  244. * session as required.
  245. */
  246. public static class LogHelper {
  247. protected Log LOG;
  248. protected boolean isSilent;
  249. public LogHelper(Log LOG) {
  250. this(LOG, false);
  251. }
  252. public LogHelper(Log LOG, boolean isSilent) {
  253. this.LOG = LOG;
  254. this.isSilent = isSilent;
  255. }
  256. public PrintStream getOutStream() {
  257. SessionState ss = SessionState.get();
  258. return ((ss != null) && (ss.out != null)) ? ss.out : System.out;
  259. }
  260. public PrintStream getErrStream() {
  261. SessionState ss = SessionState.get();
  262. return ((ss != null) && (ss.err != null)) ? ss.err : System.err;
  263. }
  264. public PrintStream getChildOutStream() {
  265. SessionState ss = SessionState.get();
  266. return ((ss != null) && (ss.childOut != null)) ? ss.childOut : System.out;
  267. }
  268. public PrintStream getChildErrStream() {
  269. SessionState ss = SessionState.get();
  270. return ((ss != null) && (ss.childErr != null)) ? ss.childErr : System.err;
  271. }
  272. public boolean getIsSilent() {
  273. SessionState ss = SessionState.get();
  274. // use the session or the one supplied in constructor
  275. return (ss != null) ? ss.getIsSilent() : isSilent;
  276. }
  277. public void printInfo(String info) {
  278. printInfo(info, null);
  279. }
  280. public void printInfo(String info, String detail) {
  281. if (!getIsSilent()) {
  282. getErrStream().println(info);
  283. }
  284. LOG.info(info + StringUtils.defaultString(detail));
  285. }
  286. public void printError(String error) {
  287. printError(error, null);
  288. }
  289. public void printError(String error, String detail) {
  290. getErrStream().println(error);
  291. LOG.error(error + StringUtils.defaultString(detail));
  292. }
  293. }
  294. private static LogHelper _console;
  295. /**
  296. * initialize or retrieve console object for SessionState.
  297. */
  298. public static LogHelper getConsole() {
  299. if (_console == null) {
  300. Log LOG = LogFactory.getLog("SessionState");
  301. _console = new LogHelper(LOG);
  302. }
  303. return _console;
  304. }
  305. public static String validateFile(Set<String> curFiles, String newFile) {
  306. SessionState ss = SessionState.get();
  307. LogHelper console = getConsole();
  308. Configuration conf = (ss == null) ? new Configuration() : ss.getConf();
  309. try {
  310. if (Utilities.realFile(newFile, conf) != null) {
  311. return newFile;
  312. } else {
  313. console.printError(newFile + " does not exist");
  314. return null;
  315. }
  316. } catch (IOException e) {
  317. console.printError("Unable to validate " + newFile + "\nException: "
  318. + e.getMessage(), "\n"
  319. + org.apache.hadoop.util.StringUtils.stringifyException(e));
  320. return null;
  321. }
  322. }
  323. public static boolean registerJar(String newJar) {
  324. LogHelper console = getConsole();
  325. try {
  326. ClassLoader loader = Thread.currentThread().getContextClassLoader();
  327. Thread.currentThread().setContextClassLoader(
  328. Utilities.addToClassPath(loader, StringUtils.split(newJar, ",")));
  329. console.printInfo("Added " + newJar + " to class path");
  330. return true;
  331. } catch (Exception e) {
  332. console.printError("Unable to register " + newJar + "\nException: "
  333. + e.getMessage(), "\n"
  334. + org.apache.hadoop.util.StringUtils.stringifyException(e));
  335. return false;
  336. }
  337. }
  338. public static boolean unregisterJar(String jarsToUnregister) {
  339. LogHelper console = getConsole();
  340. try {
  341. Utilities.removeFromClassPath(StringUtils.split(jarsToUnregister, ","));
  342. console.printInfo("Deleted " + jarsToUnregister + " from class path");
  343. return true;
  344. } catch (Exception e) {
  345. console.printError("Unable to unregister " + jarsToUnregister
  346. + "\nException: " + e.getMessage(), "\n"
  347. + org.apache.hadoop.util.StringUtils.stringifyException(e));
  348. return false;
  349. }
  350. }
  351. /**
  352. * ResourceHook.
  353. *
  354. */
  355. public static interface ResourceHook {
  356. String preHook(Set<String> cur, String s);
  357. boolean postHook(Set<String> cur, String s);
  358. }
  359. /**
  360. * ResourceType.
  361. *
  362. */
  363. public static enum ResourceType {
  364. FILE(new ResourceHook() {
  365. public String preHook(Set<String> cur, String s) {
  366. return validateFile(cur, s);
  367. }
  368. public boolean postHook(Set<String> cur, String s) {
  369. return true;
  370. }
  371. }),
  372. JAR(new ResourceHook() {
  373. public String preHook(Set<String> cur, String s) {
  374. String newJar = validateFile(cur, s);
  375. if (newJar != null) {
  376. return (registerJar(newJar) ? newJar : null);
  377. } else {
  378. return null;
  379. }
  380. }
  381. public boolean postHook(Set<String> cur, String s) {
  382. return unregisterJar(s);
  383. }
  384. }),
  385. ARCHIVE(new ResourceHook() {
  386. public String preHook(Set<String> cur, String s) {
  387. return validateFile(cur, s);
  388. }
  389. public boolean postHook(Set<String> cur, String s) {
  390. return true;
  391. }
  392. });
  393. public ResourceHook hook;
  394. ResourceType(ResourceHook hook) {
  395. this.hook = hook;
  396. }
  397. };
  398. public static ResourceType find_resource_type(String s) {
  399. s = s.trim().toUpperCase();
  400. try {
  401. return ResourceType.valueOf(s);
  402. } catch (IllegalArgumentException e) {
  403. }
  404. // try singular
  405. if (s.endsWith("S")) {
  406. s = s.substring(0, s.length() - 1);
  407. } else {
  408. return null;
  409. }
  410. try {
  411. return ResourceType.valueOf(s);
  412. } catch (IllegalArgumentException e) {
  413. }
  414. return null;
  415. }
  416. private final HashMap<ResourceType, HashSet<String>> resource_map =
  417. new HashMap<ResourceType, HashSet<String>>();
  418. public void add_resource(ResourceType t, String value) {
  419. // By default don't convert to unix
  420. add_resource(t, value, false);
  421. }
  422. public String add_resource(ResourceType t, String value, boolean convertToUnix) {
  423. try {
  424. value = downloadResource(value, convertToUnix);
  425. } catch (Exception e) {
  426. getConsole().printError(e.getMessage());
  427. return null;
  428. }
  429. if (resource_map.get(t) == null) {
  430. resource_map.put(t, new HashSet<String>());
  431. }
  432. String fnlVal = value;
  433. if (t.hook != null) {
  434. fnlVal = t.hook.preHook(resource_map.get(t), value);
  435. if (fnlVal == null) {
  436. return fnlVal;
  437. }
  438. }
  439. getConsole().printInfo("Added resource: " + fnlVal);
  440. resource_map.get(t).add(fnlVal);
  441. return fnlVal;
  442. }
  443. /**
  444. * Returns the list of filesystem schemas as regex which
  445. * are permissible for download as a resource.
  446. */
  447. public static String getMatchingSchemaAsRegex() {
  448. String[] matchingSchema = {"s3", "s3n", "hdfs"};
  449. return StringUtils.join(matchingSchema, "|");
  450. }
  451. private String downloadResource(String value, boolean convertToUnix) {
  452. if (value.matches("("+ getMatchingSchemaAsRegex() +")://.*")) {
  453. getConsole().printInfo("converting to local " + value);
  454. File resourceDir = new File(getConf().getVar(HiveConf.ConfVars.DOWNLOADED_RESOURCES_DIR));
  455. String destinationName = new Path(value).getName();
  456. File destinationFile = new File(resourceDir, destinationName);
  457. if ( resourceDir.exists() && ! resourceDir.isDirectory() ) {
  458. throw new RuntimeException("The resource directory is not a directory, resourceDir is set to" + resourceDir);
  459. }
  460. if ( ! resourceDir.exists() && ! resourceDir.mkdirs() ) {
  461. throw new RuntimeException("Couldn't create directory " + resourceDir);
  462. }
  463. try {
  464. FileSystem fs = FileSystem.get(new URI(value), conf);
  465. fs.copyToLocalFile(new Path(value), new Path(destinationFile.getCanonicalPath()));
  466. value = destinationFile.getCanonicalPath();
  467. if (convertToUnix && DosToUnix.isWindowsScript(destinationFile)) {
  468. try {
  469. DosToUnix.convertWindowsScriptToUnix(destinationFile);
  470. } catch (Exception e) {
  471. throw new RuntimeException("Caught exception while converting to unix line endings", e);
  472. }
  473. }
  474. } catch (Exception e) {
  475. throw new RuntimeException("Failed to read external resource " + value, e);
  476. }
  477. }
  478. return value;
  479. }
  480. public boolean delete_resource(ResourceType t, String value) {
  481. if (resource_map.get(t) == null) {
  482. return false;
  483. }
  484. if (t.hook != null) {
  485. if (!t.hook.postHook(resource_map.get(t), value)) {
  486. return false;
  487. }
  488. }
  489. return (resource_map.get(t).remove(value));
  490. }
  491. public Set<String> list_resource(ResourceType t, List<String> filter) {
  492. if (resource_map.get(t) == null) {
  493. return null;
  494. }
  495. Set<String> orig = resource_map.get(t);
  496. if (filter == null) {
  497. return orig;
  498. } else {
  499. Set<String> fnl = new HashSet<String>();
  500. for (String one : orig) {
  501. if (filter.contains(one)) {
  502. fnl.add(one);
  503. }
  504. }
  505. return fnl;
  506. }
  507. }
  508. public void delete_resource(ResourceType t) {
  509. if (resource_map.get(t) != null) {
  510. for (String value : resource_map.get(t)) {
  511. delete_resource(t, value);
  512. }
  513. resource_map.remove(t);
  514. }
  515. }
  516. public String getCommandType() {
  517. if (commandType == null) {
  518. return null;
  519. }
  520. return commandType.getOperationName();
  521. }
  522. public HiveOperation getHiveOperation() {
  523. return commandType;
  524. }
  525. public void setCommandType(HiveOperation commandType) {
  526. this.commandType = commandType;
  527. }
  528. public HiveAuthorizationProvider getAuthorizer() {
  529. return authorizer;
  530. }
  531. public void setAuthorizer(HiveAuthorizationProvider authorizer) {
  532. this.authorizer = authorizer;
  533. }
  534. public HiveAuthenticationProvider getAuthenticator() {
  535. return authenticator;
  536. }
  537. public void setAuthenticator(HiveAuthenticationProvider authenticator) {
  538. this.authenticator = authenticator;
  539. }
  540. public CreateTableAutomaticGrant getCreateTableGrants() {
  541. return createTableGrants;
  542. }
  543. public void setCreateTableGrants(CreateTableAutomaticGrant createTableGrants) {
  544. this.createTableGrants = createTableGrants;
  545. }
  546. }