securityManager主要用于权限设置,比如在使用yarn作为资源调度框架时,用于生成secret key进行登录。该类默认只用一个实例,所以的app使用同一个实例,下面是该类的所有源代码:

[java] view plaincopy
  1. private[spark] class SecurityManager(sparkConf: SparkConf)
  2. extends Logging with SecretKeyHolder {
  3. // key used to store the spark secret in the Hadoop UGI
  4. private val sparkSecretLookupKey = "sparkCookie"
  5. private val authOn = sparkConf.getBoolean("spark.authenticate", false)
  6. // keep spark.ui.acls.enable for backwards compatibility with 1.0
  7. private var aclsOn =
  8. sparkConf.getBoolean("spark.acls.enable", sparkConf.getBoolean("spark.ui.acls.enable", false))
  9. // admin acls should be set before view or modify acls
  10. private var adminAcls: Set[String] =
  11. stringToSet(sparkConf.get("spark.admin.acls", ""))
  12. private var viewAcls: Set[String] = _
  13. // list of users who have permission to modify the application. This should
  14. // apply to both UI and CLI for things like killing the application.
  15. private var modifyAcls: Set[String] = _
  16. // always add the current user and SPARK_USER to the viewAcls
  17. private val defaultAclUsers = Set[String](System.getProperty("user.name", ""),
  18. Utils.getCurrentUserName())
  19. setViewAcls(defaultAclUsers, sparkConf.get("spark.ui.view.acls", ""))
  20. setModifyAcls(defaultAclUsers, sparkConf.get("spark.modify.acls", ""))
  21. private val secretKey = generateSecretKey()
  22. logInfo("SecurityManager: authentication " + (if (authOn) "enabled" else "disabled") +
  23. "; ui acls " + (if (aclsOn) "enabled" else "disabled") +
  24. "; users with view permissions: " + viewAcls.toString() +
  25. "; users with modify permissions: " + modifyAcls.toString())
  26. // Set our own authenticator to properly negotiate user/password for HTTP connections.
  27. // This is needed by the HTTP client fetching from the HttpServer. Put here so its
  28. // only set once.
  29. if (authOn) {
  30. Authenticator.setDefault(
  31. new Authenticator() {
  32. override def getPasswordAuthentication(): PasswordAuthentication = {
  33. var passAuth: PasswordAuthentication = null
  34. val userInfo = getRequestingURL().getUserInfo()
  35. if (userInfo != null) {
  36. val  parts = userInfo.split(":", 2)
  37. passAuth = new PasswordAuthentication(parts(0), parts(1).toCharArray())
  38. }
  39. return passAuth
  40. }
  41. }
  42. )
  43. }
  44. // the default SSL configuration - it will be used by all communication layers unless overwritten
  45. private val defaultSSLOptions = SSLOptions.parse(sparkConf, "spark.ssl", defaults = None)
  46. // SSL configuration for different communication layers - they can override the default
  47. // configuration at a specified namespace. The namespace *must* start with spark.ssl.
  48. val fileServerSSLOptions = SSLOptions.parse(sparkConf, "spark.ssl.fs", Some(defaultSSLOptions))
  49. val akkaSSLOptions = SSLOptions.parse(sparkConf, "spark.ssl.akka", Some(defaultSSLOptions))
  50. logDebug(s"SSLConfiguration for file server: $fileServerSSLOptions")
  51. logDebug(s"SSLConfiguration for Akka: $akkaSSLOptions")
  52. val (sslSocketFactory, hostnameVerifier) = if (fileServerSSLOptions.enabled) {
  53. val trustStoreManagers =
  54. for (trustStore <- fileServerSSLOptions.trustStore) yield {
  55. val input = Files.asByteSource(fileServerSSLOptions.trustStore.get).openStream()
  56. try {
  57. val ks = KeyStore.getInstance(KeyStore.getDefaultType)
  58. ks.load(input, fileServerSSLOptions.trustStorePassword.get.toCharArray)
  59. val tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm)
  60. tmf.init(ks)
  61. tmf.getTrustManagers
  62. } finally {
  63. input.close()
  64. }
  65. }
  66. lazy val credulousTrustStoreManagers = Array({
  67. logWarning("Using 'accept-all' trust manager for SSL connections.")
  68. new X509TrustManager {
  69. override def getAcceptedIssuers: Array[X509Certificate] = null
  70. override def checkClientTrusted(x509Certificates: Array[X509Certificate], s: String) {}
  71. override def checkServerTrusted(x509Certificates: Array[X509Certificate], s: String) {}
  72. }: TrustManager
  73. })
  74. val sslContext = SSLContext.getInstance(fileServerSSLOptions.protocol.getOrElse("Default"))
  75. sslContext.init(null, trustStoreManagers.getOrElse(credulousTrustStoreManagers), null)
  76. val hostVerifier = new HostnameVerifier {
  77. override def verify(s: String, sslSession: SSLSession): Boolean = true
  78. }
  79. (Some(sslContext.getSocketFactory), Some(hostVerifier))
  80. } else {
  81. (None, None)
  82. }
  83. /**
  84. * Split a comma separated String, filter out any empty items, and return a Set of strings
  85. */
  86. private def stringToSet(list: String): Set[String] = {
  87. list.split(',').map(_.trim).filter(!_.isEmpty).toSet
  88. }
  89. /**
  90. * Admin acls should be set before the view or modify acls.  If you modify the admin
  91. * acls you should also set the view and modify acls again to pick up the changes.
  92. */
  93. def setViewAcls(defaultUsers: Set[String], allowedUsers: String) {
  94. viewAcls = (adminAcls ++ defaultUsers ++ stringToSet(allowedUsers))
  95. logInfo("Changing view acls to: " + viewAcls.mkString(","))
  96. }
  97. def setViewAcls(defaultUser: String, allowedUsers: String) {
  98. setViewAcls(Set[String](defaultUser), allowedUsers)
  99. }
  100. def getViewAcls: String = viewAcls.mkString(",")
  101. /**
  102. * Admin acls should be set before the view or modify acls.  If you modify the admin
  103. * acls you should also set the view and modify acls again to pick up the changes.
  104. */
  105. def setModifyAcls(defaultUsers: Set[String], allowedUsers: String) {
  106. modifyAcls = (adminAcls ++ defaultUsers ++ stringToSet(allowedUsers))
  107. logInfo("Changing modify acls to: " + modifyAcls.mkString(","))
  108. }
  109. def getModifyAcls: String = modifyAcls.mkString(",")
  110. /**
  111. * Admin acls should be set before the view or modify acls.  If you modify the admin
  112. * acls you should also set the view and modify acls again to pick up the changes.
  113. */
  114. def setAdminAcls(adminUsers: String) {
  115. adminAcls = stringToSet(adminUsers)
  116. logInfo("Changing admin acls to: " + adminAcls.mkString(","))
  117. }
  118. def setAcls(aclSetting: Boolean) {
  119. aclsOn = aclSetting
  120. logInfo("Changing acls enabled to: " + aclsOn)
  121. }
  122. /**
  123. * Generates or looks up the secret key.
  124. *
  125. * The way the key is stored depends on the Spark deployment mode. Yarn
  126. * uses the Hadoop UGI.
  127. *
  128. * For non-Yarn deployments, If the config variable is not set
  129. * we throw an exception.
  130. */
  131. private def generateSecretKey(): String = {
  132. if (!isAuthenticationEnabled) return null
  133. // first check to see if the secret is already set, else generate a new one if on yarn
  134. val sCookie = if (SparkHadoopUtil.get.isYarnMode) {
  135. val secretKey = SparkHadoopUtil.get.getSecretKeyFromUserCredentials(sparkSecretLookupKey)
  136. if (secretKey != null) {
  137. logDebug("in yarn mode, getting secret from credentials")
  138. return new Text(secretKey).toString
  139. } else {
  140. logDebug("getSecretKey: yarn mode, secret key from credentials is null")
  141. }
  142. val cookie = akka.util.Crypt.generateSecureCookie
  143. // if we generated the secret then we must be the first so lets set it so t
  144. // gets used by everyone else
  145. SparkHadoopUtil.get.addSecretKeyToUserCredentials(sparkSecretLookupKey, cookie)
  146. logInfo("adding secret to credentials in yarn mode")
  147. cookie
  148. } else {
  149. // user must have set spark.authenticate.secret config
  150. sparkConf.getOption("spark.authenticate.secret") match {
  151. case Some(value) => value
  152. case None => throw new Exception("Error: a secret key must be specified via the " +
  153. "spark.authenticate.secret config")
  154. }
  155. }
  156. sCookie
  157. }
  158. /**
  159. * Check to see if Acls for the UI are enabled
  160. * @return true if UI authentication is enabled, otherwise false
  161. */
  162. def aclsEnabled(): Boolean = aclsOn
  163. /**
  164. * Checks the given user against the view acl list to see if they have
  165. * authorization to view the UI. If the UI acls are disabled
  166. * via spark.acls.enable, all users have view access. If the user is null
  167. * it is assumed authentication is off and all users have access.
  168. *
  169. * @param user to see if is authorized
  170. * @return true is the user has permission, otherwise false
  171. */
  172. def checkUIViewPermissions(user: String): Boolean = {
  173. logDebug("user=" + user + " aclsEnabled=" + aclsEnabled() + " viewAcls=" +
  174. viewAcls.mkString(","))
  175. !aclsEnabled || user == null || viewAcls.contains(user)
  176. }
  177. /**
  178. * Checks the given user against the modify acl list to see if they have
  179. * authorization to modify the application. If the UI acls are disabled
  180. * via spark.acls.enable, all users have modify access. If the user is null
  181. * it is assumed authentication isn't turned on and all users have access.
  182. *
  183. * @param user to see if is authorized
  184. * @return true is the user has permission, otherwise false
  185. */
  186. def checkModifyPermissions(user: String): Boolean = {
  187. logDebug("user=" + user + " aclsEnabled=" + aclsEnabled() + " modifyAcls=" +
  188. modifyAcls.mkString(","))
  189. !aclsEnabled || user == null || modifyAcls.contains(user)
  190. }
  191. /**
  192. * Check to see if authentication for the Spark communication protocols is enabled
  193. * @return true if authentication is enabled, otherwise false
  194. */
  195. def isAuthenticationEnabled(): Boolean = authOn
  196. /**
  197. * Gets the user used for authenticating HTTP connections.
  198. * For now use a single hardcoded user.
  199. * @return the HTTP user as a String
  200. */
  201. def getHttpUser(): String = "sparkHttpUser"
  202. /**
  203. * Gets the user used for authenticating SASL connections.
  204. * For now use a single hardcoded user.
  205. * @return the SASL user as a String
  206. */
  207. def getSaslUser(): String = "sparkSaslUser"
  208. /**
  209. * Gets the secret key.
  210. * @return the secret key as a String if authentication is enabled, otherwise returns null
  211. */
  212. def getSecretKey(): String = secretKey
  213. // Default SecurityManager only has a single secret key, so ignore appId.
  214. override def getSaslUser(appId: String): String = getSaslUser()
  215. override def getSecretKey(appId: String): String = getSecretKey()
  216. }

深入理解Spark 2.1 Core (十四):securityManager 类源码分析相关推荐

  1. 第十四课 k8s源码学习和二次开发原理篇-调度器原理

    第十四课 k8s源码学习和二次开发原理篇-调度器原理 tags: k8s 源码学习 categories: 源码学习 二次开发 文章目录 第十四课 k8s源码学习和二次开发原理篇-调度器原理 第一节 ...

  2. Alink漫谈(十六) :Word2Vec源码分析 之 建立霍夫曼树

    Alink漫谈(十六) :Word2Vec源码分析 之 建立霍夫曼树 文章目录 Alink漫谈(十六) :Word2Vec源码分析 之 建立霍夫曼树 0x00 摘要 0x01 背景概念 1.1 词向量 ...

  3. Java 集合系列(四)—— ListIterator 源码分析

    以脑图的形式来展示Java集合知识,让零碎知识点形成体系 Iterator 对比   Iterator(迭代器)是一种设计模式,是一个对象,用于遍历集合中的所有元素.   Iterator 包含四个方 ...

  4. Spring Security(四) —— 核心过滤器源码分析

    摘要: 原创出处 https://www.cnkirito.moe/spring-security-4/ 「老徐」欢迎转载,保留摘要,谢谢! 4 过滤器详解 前面的部分,我们关注了Spring Sec ...

  5. 基于比原链开发Dapp(四)-bufferserver源码分析

    ##简介 ​    本章内容主要直接分析bufferserver源码,也就是比原链官方Dapp-demo的后端接口,里面包含了UTXO的托管逻辑.账单逻辑等,还会介绍一些改进的源码内容. [储蓄分红合 ...

  6. Java源码详解四:String源码分析--openjdk java 11源码

    文章目录 注释 类的继承 数据的存储 构造函数 charAt函数 equals函数 hashCode函数 indexOf函数 intern函数 本系列是Java详解,专栏地址:Java源码分析 Str ...

  7. Spark详解(七):SparkContext源码分析以及整体作业提交流程

    1. SparkContext源码分析 在任何Spark程序中,必须要创建一个SparkContext,在SparkContext中,最主要的就是创建了TaskScheduler和DAGSchedul ...

  8. Spark学习笔记(3)--SparkContext部分源码分析

    SparkContext源码分析 在任何Spark程序中,必须要创建一个SparkContext,在SparkContext中,最主要的就是创建了TaskScheduler和DAGScheduler, ...

  9. 【四】Spring源码分析之启动主流程---AbstractApplicationContext的refresh方法

    入口: 在SpringBoot启动的时候,SpringApplication的run方法中 refreshContext(context); 里面最终调用的是AbstractApplicationCo ...

最新文章

  1. 设备物理像素、设备独立像素
  2. sql server标识一个字符在这一列中是第几次出现
  3. Google Gears 体验(2):本机 web 服务器
  4. c# 智能升级程序代码(2)
  5. HTTP代理实现请求报文的拦截与篡改2--功能介绍+源码下载
  6. VC下ctreectrl的使用方法及节点前图标添加方法
  7. Mybatis 二级缓存简单示例
  8. python ftp编程_【编程】Python FTP
  9. IDEA设置代码背景豆沙色
  10. 经验正交函数分析(EOF)或主成分分析(PCA)在matlab上的实现及实例
  11. 打印纸张尺寸换算_「凭证纸尺寸」【用友凭证打印】自定义纸张尺寸对照表 - seo实验室...
  12. MicroDicom viewer(Dicom格式看图软件) v3.4.7官方版
  13. Excel 批量合并相同内容单元格方法
  14. 信用卡分销系统如何获客
  15. 英文电子专业词汇(新手必备)
  16. Squid缓存代理服务器
  17. Rollup项目的SNARK景观
  18. 邮箱android版,网易邮箱Android版手机通讯录将同步
  19. Java约定俗成怎么定义_Java接口定义规范,摘自晓风轻专栏
  20. 2022年湖南省社会工作者考试综合实务(初级)练习题及答案

热门文章

  1. redis key存在则删除_Redis加锁的几种实现
  2. Windows使用msi安装MySQL安装教程
  3. java pdfbox 解析报错_pdfbox 读取文件报错 java.io.IOException: Page tree root must be a dictionary...
  4. 华为交换机的配置及:access、trunk、hybird端口详解
  5. 初识OSPF(三)——路由重分发及虚链路
  6. 网页中弹出模式对话框
  7. mysql文本自动递增_mysql-如何创建自动递增的字符串?
  8. HTML鼠标悬停图片置顶,jquery实现鼠标悬浮停止轮播特效
  9. mysql实际项目中使用多长时间_存储过程在实际项目中用的多吗?
  10. lepus mysql 慢查询_天兔 -Lepus 慢查询分析平台配置