Deep Dive into StreamPark Source Code: Architecture, Flink Cluster Management, and Job Lifecycle
This article provides a comprehensive source code analysis of StreamPark (dev-2.1.5), covering project structure, initialization, Flink cluster lifecycle management (YARN/Kubernetes session modes), job deployment and execution flows, savepoint/checkpoint handling, project building pipelines, and common troubleshooting scenarios.
Reading font
Project Import and Environment Setup
The article begins with environment requirements for StreamPark development: JDK 11, Maven 3.9.0, Scala 2.12.8, Node.js v18.12.0, and pnpm 9.1.4. It details IDEA configuration including JDK, Scala, Maven, and plugin settings, plus packaging profiles (scala-2.12, shaded, webapp, dist). The startup process involves building with Maven, extracting the dist package, setting -Dapp.home VM option to the extracted directory, then launching StreamParkConsoleBootstrap for backend and running pnpm install + npm run dev in streampark-console-webapp for frontend.
Project Structure and Module Analysis
The multi-module Maven project comprises:
streampark-parent : Root POM managing submodules (common, shaded, flink, spark, console) and plugins (shade, checkstyle, spotless, dependency-check, apache-rat).
streampark-common : Shared utilities depending on Hadoop/HBase clients, HikariCP, Jedis, enumeratum.
streampark-shaded : Relocates Jackson and SLF4J/logback to avoid conflicts via Maven Shade plugin.
streampark-console : Console API ( streampark-console-service with Spring Boot, Docker client, MySQL/PostgreSQL/H2) and frontend ( streampark-console-webapp with Vue, Ant Design, Monaco Editor).
streampark-flink : Flink ecosystem parent with submodules: flink-core: Core Flink dependencies (table, RocksDB, connectors). flink-shims: Version-specific shims (base, test, flink-1.12~1.14 for Scala 2.11, flink-1.15~1.19 for Scala 2.12) using shade plugin for isolation. flink-kubernetes: Kubernetes native client for Flink on K8s. flink-udf: UDF functions. flink-connector: Connectors (Kafka, JDBC, Elasticsearch, Doris, ClickHouse, HBase, MongoDB, InfluxDB, HTTP). flink-packer: Maven Shade + Aether for dependency management and Docker image building. flink-sqlclient: SQL CLI execution entry point. flink-client: API and core submission clients. flink-proxy: ClassLoader proxy to invoke version-specific Flink methods.
streampark-spark : Placeholder for Spark modules (Core, CLI, Connector).
Database Schema
An ER diagram illustrates tables for applications, projects, resources, savepoints, checkpoints, alerts, and configurations.
Project Startup and Initialization
Bootstrap and Configuration
StreamParkConsoleBootstrapinitializes Spring via SpringProperties.get(), which loads config.yaml (preferred) or legacy application.yml, merges user and Spring configs, sets data source properties, and pushes all into system properties.
Environment Initialization
EnvInitializer(implements ApplicationRunner) runs on startup (skipping test profile). It validates -Dapp.home, initializes internal config, overrides HADOOP_USER_NAME, and calls storageInitialize(LFS) to create local directories: dist, uploads, workspace, backups, savepoints, jars, client, shims, and local Maven repo. It uploads client JARs and versioned shim JARs (matched by pattern streampark-flink-shims-*.jar) into workspace.
Scheduled Tasks
Job Metrics Watcher (YARN/Standalone)
FlinkAppHttpWatcher#startruns every second via @Scheduled(fixedDelay=1000). It queries Flink REST API ( /jobs/overview, /jobs/{jobId}/checkpoints) first; on failure falls back to YARN REST API. It updates job start/end time, duration, task counts, slot metrics, and processes checkpoints: completed checkpoints may be saved as savepoints or retained checkpoints based on config; failed checkpoints trigger alert or restart per FailoverStrategy (ALERT/RESTART) when failure rate exceeds thresholds ( cpFailureRateInterval, cpMaxFailureInterval). State transitions (STARTING→RUNNING, CANCELED, FAILED, RESTARTING) are handled with caches ( STARTING_CACHE, SAVEPOINT_CACHE, CANCELING_CACHE).
Kubernetes Job Watcher
FlinkK8sWatcherWrapperregisters a FlinkK8sWatcher bean (EventBus pattern). FlinkJobStatusWatcher#doWatch polls Kubernetes for Application and Session mode jobs, posting FlinkJobStatusChangeEvent to EventBus. FlinkK8sChangeEventListener#subscribeJobStatusChange persists metrics and alerts on FAILED/LOST/RESTARTING/FINISHED states.
Packer Resource GC
PackerResourceGCTask#collectGarbageruns every 6 hours (cron 0 0 0/6 * * ?), deleting build directories under workspace older than maxResourceIntervalHours (default 120h) matching pattern *@*.
WebSocket
WebSocketEndpoint(JSR-356) manages sessions in a CopyOnWriteMap, providing pushNotice to send messages to specific users.
Core Source Code Analysis
Starting Flink Clusters (Session Mode)
Flow: FlinkClusterController → FlinkClusterService (validates existing YARN session via app status+type+tag) → builds DeployRequest → FlinkClient selects version-specific ClassLoader (child-first/parent-first) → reflective invoke → FlinkClientHelper.deploy dispatches to YarnSessionClient or KubernetesNativeSessionClient.
YARN Session
YarnSessionClient.deployextracts Flink config, applies deployment config (Kerberos, ship files), gets YarnClusterDescriptor. If clusterId provided and app status UNDEFINED, retrieves existing cluster; else deploys new session cluster via deploySessionCluster, returning web UI URL and cluster ID.
Kubernetes Session
Requires RBAC setup: namespace, ServiceAccount, ClusterRole (pods, services, configmaps, deployments, jobs, roles), ClusterRoleBinding, and kubeconfig with server IP. KubernetesNativeSessionClient.deploy builds FlinkK8sConfig, creates FlinkKubeClient, checks for existing service; if absent, deploys session cluster via KubernetesClusterDescriptor.
Stopping Flink Clusters
Similar flow ending in YarnSessionClient.shutdown (retrieves cluster client, calls shutDownCluster()) or KubernetesNativeSessionClient.shutdown (retrieves client via cluster descriptor, calls shutDownCluster()).
Job Deployment (Online)
Steps: checkVersion (Flink 1.12~1.19), checkEnv (storage type per exec mode, EnvInitializer.checkFlinkEnv creates HDFS/LFS dirs, uploads client/shim JARs), storageInitialize (re-creates dirs, uploads JARs), connection test (REST API for standalone/YARN session), allowToBuildNow (prevents concurrent builds), checkBuildAndUpdate (updates release state, backs up SQL versions), buildApplication (creates pipeline per mode: FlinkYarnApplicationBuildPipeline, FlinkRemoteBuildPipeline, FlinkK8sSessionBuildPipeline, FlinkK8sApplicationBuildPipeline; registers PipeWatcher / DockerProgressWatcher; executes BuildPipeline#launch with steps onStart, onStepStateChange, onFinish).
Build Pipeline Details
Standalone (FlinkRemoteBuildPipeline) : 2 steps — clean workspace, build fat JAR via MavenTool.buildFatJar.
YARN Application (FlinkYarnApplicationBuildPipeline) : SQL-only; 3 steps — clean HDFS provided lib dir, resolve Maven artifacts, upload JARs to HDFS.
K8s Session (FlinkK8sSessionBuildPipeline) : 2 steps — clean workspace (subdir clusterId@namespace), build fat JAR.
K8s Application (FlinkK8sApplicationBuildPipeline) : 8 steps — clean workspace, export pod templates, build fat JAR + handle ext libs, generate Dockerfile ( FlinkDockerfileTemplate or FlinkHadoopDockerfileTemplate), pull base image, build Docker image, push to registry, export ingress template. Uses DockerProgressWatcher for pull/build/push progress.
Pipeline steps defined in PipelineType enum with step descriptions and response types ( ShadedBuildResponse, SimpleBuildResponse, DockerImageBuildResponse).
Job Start
ApplicationController#start→ env check → build submit request per mode → async submit via FlinkClient proxy (version-specific ClassLoader, reflective invoke) → map execution mode to client impl ( RemoteClient, YarnClient, etc.) → future stored in map.
FlinkClientTrait Template
submitbuilds command line and Flink config, sets common options (job name, target, savepoint path, main class, args, checkpoint retention, JVM opts), then calls abstract setConfig and doSubmit.
RemoteClient Example
Overrides doSubmit calling trySubmit which prefers JobGraph submission (constructs PackagedProgram, JobGraph, submits via StandaloneClusterDescriptor), falling back to REST API ( FlinkSessionSubmitHelper.submitViaRestApi).
SQL Client Execution
Entry org.apache.streampark.flink.cli.SqlClient parses args, decrypts/decompresses Base64 SQL, determines runtime mode (STREAMING/BATCH/AUTOMATIC) from SQL SET commands, dynamic params, or flink-conf.yaml. Dispatches to StreamSqlApp or BatchSqlApp (both extend FlinkStreamTable / FlinkTable with template method main→init→ready→handle→context.start→destroy). StreamTableContext.sql() delegates to FlinkSqlExecutor.executeSql which parses SQL statements, executes DDL/DML via TableEnvironment, requires at least one INSERT to trigger job, uses StatementSet for batch execution.
Job Stop
ApplicationController#cancel→ ApplicationService#cancel (updates log, notifies watchers) → build cancel request → FlinkClient#cancel (proxy pattern) → mode-specific client doCancel → cleanup watchers ( FlinkAppHttpWatcher, FlinkK8sWatcher).
Job Mapping
Compensates for lost state by mapping a running Flink job to an application record. ApplicationServiceImpl#mapping updates application_id / jobId in DB, then registers watcher (K8s or HTTP).
Job Snapshots (Savepoint/Checkpoint)
Two mechanisms: manual savepoint via ClusterClient#triggerSavepoint (runtime or on cancel with drain flag: cancelWithSavepoint vs stopWithSavepoint), and automatic checkpoint via Flink config (interval, mode, retention, tolerable failures, state backend). Checkpoint monitoring in FlinkAppHttpWatcher#handleCheckPoints → CheckpointProcessor#process: completed checkpoints saved as savepoint/checkpoint per config; failed checkpoints counted, triggering alert or restart when thresholds exceeded.
Project Building
ProjectController#build→ ProjectService#build → ProjectBuildTask (async, 20-min timeout, logs to /tmp/streampark/logs/build_logs/{id}/build.log). Task: clone source (Git), Maven build, deploy (publish artifacts). Uses GitTool and Command utilities. On success, updates dependent applications' release state to NEED_RELEASE.
Core Annotations
In org.apache.streampark.console.core.annotation: @ApiAccess (allows external cURL), @AppUpdated (triggers flinkAppHttpWatcher.initialize()), @PermissionScope (RBAC checks on user/team/app). Enforced by StreamParkAspect AOP: @Around pointcuts validate API token, re-initialize watcher, verify admin or ownership/team membership.
Runtime Directory Layout
Under app.home/workspace: backups, client (sqlclient JAR), dist (project builds), flink/{version}, jars, logs/build_logs/{appId}, plugins, project (cloned sources), savepoints, shims/flink-{version}, uploads, workspace/{appId}/{clusterId@namespace}. HDFS mirrors for YARN mode. Storage abstraction via FsOperator.of(StorageType) returning LfsOperator or HdfsOperator.
Troubleshooting (Q&A)
Unmet peer dependencies : pnpm strict peer deps; fix via .npmrc with auto-install-peers=true, strict-peer-dependencies=false.
TypeError: presetWind not a function : UnoCSS version mismatch; workaround delete uno.config.ts (ref unocss/unocss#3869).
Could not load @purge-icons/generated : TLS network issue; replace import with @iconify/iconify.
shaded package not found : streampark-shaded not installed locally; mvn clean install shaded module, then disable shaded profile.
System initialization check failed : Missing -Dapp.home VM option; set to extracted dist directory.
Client network socket disconnected (frontend) : External resource blocked; same fix as purge-icons.
InaccessibleObjectException (JDK internal) : Java 9+ module encapsulation; add --add-opens java.base/jdk.internal.loader=ALL-UNNAMED to VM options.
Could not find or load main class (YARN Application Flink 1.19) : HDFS /streampark/flink/flink-1.19.0 stale; delete and re-deploy (avoid double-click).
ClassCastException: File vs Path (YARN PerJob Flink 1.19) : Hadoop client version mismatch; align local Hadoop with cluster (download from Huawei mirror).
Could not get REST endpoint of flink-cluster (K8s Session) : Wrong kubeconfig; replace ~/.kube/config with cluster-bound config.
For questions about attribution, corrections or content rights, please contactand we will review it promptly.