惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

A
Arctic Wolf
IT之家
IT之家
Blog — PlanetScale
Blog — PlanetScale
GbyAI
GbyAI
博客园 - 【当耐特】
F
Fortinet All Blogs
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
博客园 - 三生石上(FineUI控件)
The Register - Security
The Register - Security
Google DeepMind News
Google DeepMind News
Schneier on Security
Schneier on Security
Application and Cybersecurity Blog
Application and Cybersecurity Blog
罗磊的独立博客
B
Blog RSS Feed
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
H
Heimdal Security Blog
O
OpenAI News
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Vercel News
Vercel News
Help Net Security
Help Net Security
I
InfoQ
P
Privacy International News Feed
W
WeLiveSecurity
T
The Exploit Database - CXSecurity.com
S
Secure Thoughts
G
GRAHAM CLULEY
NISL@THU
NISL@THU
SecWiki News
SecWiki News
S
Schneier on Security
D
Docker
T
Threatpost
Cloudbric
Cloudbric
C
CERT Recently Published Vulnerability Notes
Forbes - Security
Forbes - Security
H
Hacker News: Front Page
T
Tailwind CSS Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Hacker News - Newest:
Hacker News - Newest: "LLM"
Security Latest
Security Latest
Recorded Future
Recorded Future
I
Intezer
MyScale Blog
MyScale Blog
阮一峰的网络日志
阮一峰的网络日志
Google DeepMind News
Google DeepMind News
Jina AI
Jina AI
M
MIT News - Artificial intelligence
N
Netflix TechBlog - Medium
Y
Y Combinator Blog
美团技术团队

祈雨的笔记

安全多方计算MPC spark原理解析 kueue执行源码分析 spark-operator源码解析 系统压测遇到的缓存击穿问题 我的世界PC与安卓联机 蚂蚁金服流量投放平台的AIG改造 G1大对象致Old区占用率高 日志打印导致接口响应率下跌分析 Groovy加载类导致OOM分析 ERROR日志打印导致CPU满载 记OceanBase死锁超时 应用发版期间服务响应超时 Ark Serverless初探 系统优化复盘一二三 The user specified as a definer does not exist Kong网关初探 API网关选型调研 CPU火焰图常用工具 配置中心选型调研 root操作Nginx导致用户组错误 基于Proxifier使用代理 FastJSON字段智能匹配踩坑 Nacos初探 记一次Nginx服务器CPU满荷载故障 基于券系统分库分表的思考 limit不参与SQL成本计算致索引失效 Linux常用性能监控命令 golang低版本http2偶现400 hostname in certificate didn't match 常见对称加密原理以及应用 tcp_tw_recycle引起的TCP握手失败 记一次mysql执行DDL导致锁表 mysql磁盘占用查看 mysql对text字段update致磁盘增长 elasticsearch报错index read-only TIME_WAIT与Http的Keep-Alive 记一次TIME_WAIT导致连接数报警 记一次生产事故OOM问题排查 redis分布式锁RedissonLock的实现细节 webservice复杂加密签名(2)java调用 webservice复杂加密签名(1)SoapUI mysql延时关联 利用中间人拦截实现APP内H5窜改 MySQL表字符集不同导致关联查询索引失效 通过SSH隧道远程办公 数据落盘方案 BeanDefinitionRegistryPostProcessor扩展 mysql空间索引 HTTPS攻击 spring循环依赖过程解析 elasticsearch性能优化 mysql IS NULL 使用索引 mysql字符集utf8mb4失效踩坑 常用加密算法 xml与javaBean转换 初探InnoDB MVCC源码实现 mysql索引原理 redis之list源码分析 redis之key过期源码分析 redis之string源码分析 redis之hash源码分析 线程池之ThreadPoolExecutor mysql数据页结构 Using temporary与Using filesort mysql回表致索引失效 springboot(28)HTTP连接池 定时任务之ScheduledThreadPoolExecutor elasticsearch常用script聚合 elasticsearch实现like查询 elasticsearch实现乐观锁 elasticsearch准实时原理 springboot(27)自定义缓存读写机制CachingConfigurerSupport optimizer tracing arthas常用命令 HTTP和HTTPS详解 redis集群选举机制 kafka消息重试 一点压力测试的经验 kafka架构概念 explain分析sql语句字段的解释 JVM问题分析处理手册 logstash过滤器(2)date logstash过滤器(3)dissect logstash编码器(1)json logstash编码器(2)multiline logstash表达式 logstash输入(1)通用选项 logstash输入(3)file logstash过滤器(1)通用选项 logstash输入(2)stdin logstash安装 记一次前端vConsole导致JSON序列化错误排查 解决多个异步操作嵌套问题 fastjson反序列化失败autoType is not support RTMP串流服务 POI自动调整列宽错误 Nginx+Lua实现动态黑名单 使用curl命令模拟POST和GET请求 ResponseEntity下载文件
spark on k8s执行源码分析
祈雨的笔记 · 2024-07-29 · via 祈雨的笔记

1. submit任务

1.1 spark-submit

image

1
2
3
4
5
6
7
8
$ ./bin/spark-submit \
--master k8s://https://<k8s-apiserver-host>:<k8s-apiserver-port> \
--deploy-mode cluster \
--name spark-pi \
--class org.apache.spark.examples.SparkPi \
--conf spark.executor.instances=5 \
--conf spark.kubernetes.container.image=<spark-image> \
local:///path/to/examples.jar

如上代码,是一个典型使用spark-submit提交任务的命令。查看spark-submit脚本,代码如下,可见实际上执行的是Spark的org.apache.spark.deploy.SparkSubmit类。

1
2
3
4
5
6
7
8
if [ -z "${SPARK_HOME}" ]; then
source "$(dirname "$0")"/find-spark-home
fi


export PYTHONHASHSEED=0

exec "${SPARK_HOME}"/bin/spark-class org.apache.spark.deploy.SparkSubmit "$@"

1.2 SparkSubmit

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
private def runMain(args: SparkSubmitArguments, uninitLog: Boolean): Unit = {


val (childArgs, childClasspath, sparkConf, childMainClass) = prepareSubmitEnvironment(args)

...

val loader = getSubmitClassLoader(sparkConf)
for (jar <- childClasspath) {
addJarToClasspath(jar, loader)
}

var mainClass: Class[_] = null

try {
mainClass = Utils.classForName(childMainClass)
} catch {
...
}

val app: SparkApplication = if (classOf[SparkApplication].isAssignableFrom(mainClass)) {
mainClass.getConstructor().newInstance().asInstanceOf[SparkApplication]
} else {
new JavaMainApplication(mainClass)
}

...

try {

app.start(childArgs.toArray, sparkConf)
} catch {
case t: Throwable =>
throw findCause(t)
} finally {
...
}
}

prepareSubmitEnvironment的核心代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
private[deploy] def prepareSubmitEnvironment(
args: SparkSubmitArguments,
conf: Option[HadoopConfiguration] = None)
: (Seq[String], Seq[String], SparkConf, String) = {

val childArgs = new ArrayBuffer[String]()
val childClasspath = new ArrayBuffer[String]()
val sparkConf = args.toSparkConf()
if (sparkConf.contains("spark.local.connect")) sparkConf.remove("spark.remote")
var childMain Class = ""


val clusterManager: Int = args.maybeMaster match {
case Some(v) =>
assert(args.maybeRemote.isEmpty || sparkConf.contains("spark.local.connect"))
v match {
case "yarn" => YARN
case m if m.startsWith("spark") => STANDALONE
case m if m.startsWith("k8s") => KUBERNETES
case m if m.startsWith("local") => LOCAL
case _ =>
error("Master must either be yarn or start with spark, k8s, or local")
-1
}
case None => LOCAL
}


val deployMode: Int = args.deployMode match {
case "client" | null => CLIENT
case "cluster" => CLUSTER
case _ =>
error("Deploy mode must be either client or cluster")
-1
}

...

val isKubernetesCluster = clusterManager == KUBERNETES && deployMode == CLUSTER

...

if (isKubernetesCluster) {

childMainClass = KUBERNETES_CLUSTER_SUBMIT_CLASS
if (args.primaryResource != SparkLauncher.NO_RESOURCE) {
if (args.isPython) {
childArgs ++= Array("--primary-py-file", args.primaryResource)
childArgs ++= Array("--main-class", "org.apache.spark.deploy.PythonRunner")
} else if (args.isR) {
childArgs ++= Array("--primary-r-file", args.primaryResource)
childArgs ++= Array("--main-class", "org.apache.spark.deploy.RRunner")
}
else {
childArgs ++= Array("--primary-java-resource", args.primaryResource)
childArgs ++= Array("--main-class", args.mainClass)
}
} else {
childArgs ++= Array("--main-class", args.mainClass)
}
if (args.childArgs != null) {
args.childArgs.foreach { arg =>
childArgs += "--arg" += arg
}
}

if (args.proxyUser != null) {
childArgs += "--proxy-user" += args.proxyUser
}
}


for ((k, v) <- args.sparkProperties) {
sparkConf.setIfMissing(k, v)
}


if (deployMode == CLUSTER) {
sparkConf.remove(DRIVER_HOST_ADDRESS)
}

...

(childArgs.toSeq, childClasspath.toSeq, sparkConf, childMainClass)
}

1.3 KubernetesClientApplication

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
private[spark] class KubernetesClientApplication extends SparkApplication {

override def start(args: Array[String], conf: SparkConf): Unit = {
val parsedArguments = ClientArguments.fromCommandLineArgs(args)
run(parsedArguments, conf)
}

private def run(clientArguments: ClientArguments, sparkConf: SparkConf): Unit = {
val kubernetesAppId = KubernetesConf.getKubernetesAppId()
val kubernetesConf = KubernetesConf.createDriverConf(
sparkConf,
kubernetesAppId,
clientArguments.mainAppResource,
clientArguments.mainClass,
clientArguments.driverArgs,
clientArguments.proxyUser)
val master = KubernetesUtils.parseMasterUrl(sparkConf.get("spark.master"))
val watcher = new LoggingPodStatusWatcherImpl(kubernetesConf)

Utils.tryWithResource(SparkKubernetesClientFactory.createKubernetesClient(
master,
Some(kubernetesConf.namespace),
KUBERNETES_AUTH_SUBMISSION_CONF_PREFIX,
SparkKubernetesClientFactory.ClientType.Submission,
sparkConf,
None)) { kubernetesClient =>

val client = new Client(
kubernetesConf,

new KubernetesDriverBuilder(),
kubernetesClient,
watcher)
client.run()
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

class KubernetesDriverBuilder {

def buildFromFeatures(
conf: KubernetesDriverConf,
client: KubernetesClient): KubernetesDriverSpec = {

...

val features = Seq(

new BasicDriverFeatureStep(conf),
new DriverKubernetesCredentialsFeatureStep(conf),

new DriverServiceFeatureStep(conf),
new MountSecretsFeatureStep(conf),
new EnvSecretsFeatureStep(conf),
new MountVolumesFeatureStep(conf),

new DriverCommandFeatureStep(conf),
new HadoopConfDriverFeatureStep(conf),
new KerberosConfDriverFeatureStep(conf),
new PodTemplateConfigMapStep(conf),
new LocalDirsFeatureStep(conf)) ++ userFeatures

val spec = KubernetesDriverSpec(
initialPod,
driverPreKubernetesResources = Seq.empty,
driverKubernetesResources = Seq.empty,
conf.sparkConf.getAll.toMap)

features.foldLeft(spec) { case (spec, feature) =>
val configuredPod = feature.configurePod(spec.pod)
val addedSystemProperties = feature.getAdditionalPodSystemProperties()
val addedPreResources = feature.getAdditionalPreKubernetesResources()
val addedResources = feature.getAdditionalKubernetesResources()
KubernetesDriverSpec(
configuredPod,
spec.driverPreKubernetesResources ++ addedPreResources,
spec.driverKubernetesResources ++ addedResources,
spec.systemProperties ++ addedSystemProperties)
}
}

}

2. Driver执行

2.1 driver启动参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
java \
-Divy.home=/tmp/.ivy \
-Dos.name=Linux \
-XX:-UseCompressedOops \
-Djdk.lang.Process.launchMechanism=vfork \
-cp ':/opt/spark/jars/*:/bin/jars/*' \
-Xmx1g \
-XX:ActiveProcessorCount=4 \
-Dio.netty.availableProcessors=16 \
org.apache.spark.deploy.SparkSubmit \
--conf spark.driver.bindAddress=10.244.0.145 \
--deploy-mode client \
--properties-file /opt/spark/conf/spark.properties \
--class com.demo.JavaSparkInputSql \
local:/opt/spark/examples/jars/spark-demo-3.5.0-jar-with-dependencies.jar \
U0VMRUNUICogRlJPTSBxaXl1MjAyNDA3MjY=

spark.properties配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#Java properties built from Kubernetes config map with name: spark-drv-fa733f9102d7b49f-conf-map
#Tue Jul 30 16:52:56 CST 2024
spark.kubernetes.driverEnv.META_SPACE=1024m
spark.driver.port=7078
spark.executorEnv.SGX_THREAD=2048
spark.kubernetes.resource.type=java
spark.executor.cores=4
spark.kubernetes.executor.podTemplateFile=/opt/spark/pod-template/pod-spec-template.yml
spark.submit.pyFiles=
spark.executor.memory=1g
spark.kubernetes.driverEnv.SGX_KERNEL_HEAP=2GB
spark.kubernetes.authenticate.submission.clientCertFile=/opt/k8s/client.crt
spark.kubernetes.container.image=spark-tee\:0.0.1
spark.kubernetes.file.upload.path=file\:///tmp
spark.master=k8s\://https\://172.25.165.206\:6443
spark.driver.memory=1g
spark.kubernetes.driver.podTemplateFile=/opt/k8s/driver.yaml
spark.executorEnv.SGX_MEM_SIZE=12GB
spark.kubernetes.driver.pod.name=spark-tee-cluster-29c9989102d7b13e-driver
spark.driver.host=spark-tee-cluster-29c9989102d7b13e-driver-svc.default.svc
spark.executorEnv.SGX_KERNEL_HEAP=1GB
spark.executorEnv.SGX_HEAP=1GB
spark.kubernetes.driverEnv.SGX_HEAP=1GB
spark.kubernetes.authenticate.submission.clientKeyFile=/opt/k8s/client.key
spark.submit.deployMode=cluster
spark.executor.extraJavaOptions=-Dio.netty.tryReflectionSetAccessible\=true
spark.kubernetes.authenticate.driver.serviceAccountName=spark
spark.kubernetes.driverEnv.SGX_MEM_SIZE=10GB
spark.kubernetes.submitInDriver=true
spark.app.submitTime=1722329575709
spark.kubernetes.memoryOverheadFactor=0.1
spark.app.name=spark-tee-cluster
spark.kubernetes.container.image.pullPolicy=IfNotPresent
spark.driver.cores=1
spark.kubernetes.sgx.executor.jvm.mem=7G
spark.kubernetes.authenticate.submission.caCertFile=/opt/k8s/ca.crt
spark.driver.blockManager.port=7079
spark.kubernetes.executor.deleteOnTermination=true
spark.app.id=spark-61f9fb98296548a2b29d78d0ff25988f
spark.kubernetes.driverEnv.DRIVER_MEMORY=1g
spark.kubernetes.driverEnv.SGX_THREAD=2048
spark.network.timeout=300
spark.cores.max=8
spark.kubernetes.sgx.driver.jvm.mem=1G
spark.driver.extraJavaOptions=-Dio.netty.tryReflectionSetAccessible\=true
spark.executor.instances=2
spark.jars=local\:/opt/spark/examples/jars/spark-demo-3.5.0-jar-with-dependencies.jar

2.2 SparkContext

在K8S集群中拉起Driver Pod后,Driver中的Spark进程先创建SparkContext,然后开始尝试创建Executor。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
private def createTaskScheduler(
sc: SparkContext,
master: String): (SchedulerBackend, TaskScheduler) = {
...

master match {
...

case masterUrl =>

val cm = getClusterManager(masterUrl) match {
case Some(clusterMgr) => clusterMgr
case None => throw new SparkException("Could not parse Master URL: '" + master + "'")
}
try {
val scheduler = cm.createTaskScheduler(sc, masterUrl)

val backend = cm.createSchedulerBackend(sc, masterUrl, scheduler)
cm.initialize(scheduler, backend)
(backend, scheduler)
} catch {
case se: SparkException => throw se
case NonFatal(e) =>
throw new SparkException("External scheduler cannot be instantiated", e)
}
}

2.3 KubernetesClusterManager

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
  
override def createSchedulerBackend(
sc: SparkContext,
masterURL: String,
scheduler: TaskScheduler): SchedulerBackend = {
...

val kubernetesClient = SparkKubernetesClientFactory.createKubernetesClient(
apiServerUri,
Some(sc.conf.get(KUBERNETES_NAMESPACE)),
authConfPrefix,
SparkKubernetesClientFactory.ClientType.Driver,
sc.conf,
defaultServiceAccountCaCrt)

...


val executorPodsAllocator = makeExecutorPodsAllocator(sc, kubernetesClient, snapshotsStore)

val podsWatchEventSource = new ExecutorPodsWatchSnapshotSource(
snapshotsStore,
kubernetesClient,
sc.conf)

val eventsPollingExecutor = ThreadUtils.newDaemonSingleThreadScheduledExecutor(
"kubernetes-executor-pod-polling-sync")
val podsPollingEventSource = new ExecutorPodsPollingSnapshotSource(
sc.conf, kubernetesClient, snapshotsStore, eventsPollingExecutor)

new KubernetesClusterSchedulerBackend(
scheduler.asInstanceOf[TaskSchedulerImpl],
sc,
kubernetesClient,
schedulerExecutorService,
snapshotsStore,
executorPodsAllocator,
executorPodsLifecycleEventHandler,
podsWatchEventSource,
podsPollingEventSource)
}



private[k8s] def makeExecutorPodsAllocator(sc: SparkContext, kubernetesClient: KubernetesClient,
snapshotsStore: ExecutorPodsSnapshotsStore) = {

...
cstr.newInstance(
sc.conf,
sc.env.securityManager,

new KubernetesExecutorBuilder(),
kubernetesClient,
snapshotsStore,
new SystemClock())
}

2.4 KubernetesExecutorBuilder

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

def buildFromFeatures(
conf: KubernetesExecutorConf,
secMgr: SecurityManager,
client: KubernetesClient,
resourceProfile: ResourceProfile): KubernetesExecutorSpec = {
...

val features = Seq(

new BasicExecutorFeatureStep(conf, secMgr, resourceProfile),
new ExecutorKubernetesCredentialsFeatureStep(conf),
new MountSecretsFeatureStep(conf),
new EnvSecretsFeatureStep(conf),
new MountVolumesFeatureStep(conf),
new HadoopConfExecutorFeatureStep(conf),
new LocalDirsFeatureStep(conf)) ++ userFeatures

val spec = KubernetesExecutorSpec(
initialPod,
executorKubernetesResources = Seq.empty)

features.foldLeft(spec) { case (spec, feature) =>
val configuredPod = feature.configurePod(spec.pod)
val addedResources = feature.getAdditionalKubernetesResources()
KubernetesExecutorSpec(
configuredPod,
spec.executorKubernetesResources ++ addedResources)
}
}

3. Executor执行

3.1 executor启动参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
java \
-Djava.net.preferIPv6Addresses=false \
-XX:+IgnoreUnrecognizedVMOptions \
--add-opens=java.base/java.lang=ALL-UNNAMED \
--add-opens=java.base/java.lang.invoke=ALL-UNNAMED \
--add-opens=java.base/java.lang.reflect=ALL-UNNAMED \
--add-opens=java.base/java.io=ALL-UNNAMED \
--add-opens=java.base/java.net=ALL-UNNAMED \
--add-opens=java.base/java.nio=ALL-UNNAMED \
--add-opens=java.base/java.util=ALL-UNNAMED \
--add-opens=java.base/java.util.concurrent=ALL-UNNAMED \
--add-opens=java.base/java.util.concurrent.atomic=ALL-UNNAMED \
--add-opens=java.base/jdk.internal.ref=ALL-UNNAMED \
--add-opens=java.base/sun.nio.ch=ALL-UNNAMED \
--add-opens=java.base/sun.nio.cs=ALL-UNNAMED \
--add-opens=java.base/sun.security.action=ALL-UNNAMED \
--add-opens=java.base/sun.util.calendar=ALL-UNNAMED \
--add-opens=java.security.jgss/sun.security.krb5=ALL-UNNAMED \
-Djdk.reflect.useDirectMethodHandle=false \
-Dio.netty.tryReflectionSetAccessible=true \
-Dspark.driver.port=7078 \
-Dspark.network.timeout=300 \
-Dspark.driver.blockManager.port=7079 \
-XX:-UseCompressedOops \
-XX:ActiveProcessorCount=4 \
-Divy.home=/tmp/.ivy \
-Xms10m \
-Xmx1024m \
-Dos.name=Linux \
-Dio.netty.availableProcessors=32 \
-Djdk.lang.Process.launchMechanism=vfork \
-cp ':/opt/spark/jars/*:/bin/jars/*' \
org.apache.spark.executor.CoarseGrainedExecutorBackend \
--driver-url spark://CoarseGrainedScheduler@spark-tee-cluster-29c9989102d7b13e-driver-svc.default.svc:7078 \
--executor-id 1 \
--cores 4 \
--app-id spark-61f9fb98296548a2b29d78d0ff25988f \
--hostname 10.244.0.146