sonar ce 的启动过程

/** SonarQube* Copyright (C) 2009-2016 SonarSource SA* mailto:contact AT sonarsource DOT com** This program is free software; you can redistribute it and/or* modify it under the terms of the GNU Lesser General Public* License as published by the Free Software Foundation; either* version 3 of the License, or (at your option) any later version.** This program is distributed in the hope that it will be useful,* but WITHOUT ANY WARRANTY; without even the implied warranty of* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU* Lesser General Public License for more details.** You should have received a copy of the GNU Lesser General Public License* along with this program; if not, write to the Free Software Foundation,* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.*/
package org.sonar.ce.app;import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableMap;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.CheckForNull;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.ce.ComputeEngine;
import org.sonar.ce.ComputeEngineImpl;
import org.sonar.ce.container.ComputeEngineContainerImpl;
import org.sonar.process.MinimumViableSystem;
import org.sonar.process.Monitored;
import org.sonar.process.ProcessEntryPoint;
import org.sonar.process.Props;
import org.sonar.ce.log.CeProcessLogging;import static com.google.common.base.Preconditions.checkState;
import static org.sonar.process.ProcessUtils.awaitTermination;/*** The Compute Engine server which starts a daemon thread to run the {@link ComputeEngineImpl} when it's {@link #start()}* method is called.* <p>* This is the class to call to run a standalone {@link ComputeEngineImpl} (see {@link #main(String[])}).* </p>*/
public class CeServer implements Monitored {private static final Logger LOG = Loggers.get(CeServer.class);private static final String CE_MAIN_THREAD_NAME = "ce-main";/*** Thread that currently is inside our await() method.*/private AtomicReference<Thread> awaitThread = new AtomicReference<>();private volatile boolean stopAwait = false;private final StartupBarrier startupBarrier;private final ComputeEngine computeEngine;@CheckForNullprivate CeMainThread ceMainThread = null;@VisibleForTestingprotected CeServer(StartupBarrier startupBarrier, ComputeEngine computeEngine, MinimumViableSystem mvs) {this.startupBarrier = startupBarrier;this.computeEngine = computeEngine;mvs.checkWritableTempDir().checkRequiredJavaOptions(ImmutableMap.of("file.encoding", "UTF-8"));}@Overridepublic void start() {checkState(ceMainThread == null, "start() can not be called twice");// start main threadceMainThread = new CeMainThread();ceMainThread.start();}@Overridepublic boolean isUp() {checkState(ceMainThread != null, "isUp() can not be called before start()");return ceMainThread.isStarted();}@Overridepublic void awaitStop() {checkState(awaitThread.compareAndSet(null, Thread.currentThread()), "There can't be more than one thread waiting for the Compute Engine to stop");checkState(ceMainThread != null, "awaitStop() must not be called before start()");try {while (!stopAwait) {try {// wait for a quite long time but we will be interrupted if flag changes anywayThread.sleep(10_000);} catch (InterruptedException e) {// continue and check the flag}}} finally {awaitThread = null;}}@Overridepublic void stop() {if (ceMainThread != null) {// signal main Thread to stopceMainThread.stopIt();awaitTermination(ceMainThread);}}/*** Can't be started as is. Needs to be bootstrapped by sonar-application*/public static void main(String[] args) {ProcessEntryPoint entryPoint = ProcessEntryPoint.createForArguments(args);Props props = entryPoint.getProps();new CeProcessLogging().configure(props);CeServer server = new CeServer(new StartupBarrierFactory().create(entryPoint),new ComputeEngineImpl(props, new ComputeEngineContainerImpl()),new MinimumViableSystem());entryPoint.launch(server);}private class CeMainThread extends Thread {private static final int CHECK_FOR_STOP_DELAY = 50;private volatile boolean stop = false;private volatile boolean started = false;public CeMainThread() {super(CE_MAIN_THREAD_NAME);}@Overridepublic void run() {boolean webServerOperational = startupBarrier.waitForOperational();if (!webServerOperational) {LOG.debug("Interrupted while waiting for WebServer to be operational. Assuming it will never be. Stopping.");// signal CE is done booting (obviously, since we are about to stop)this.started = true;// release thread (if any) in CeServer#awaitStop()stopAwait();return;}boolean startupSuccessful = attemptStartup();this.started = true;if (startupSuccessful) {// call below is blockingwaitForStopSignal();} else {stopAwait();}}private boolean attemptStartup() {try {startup();return true;} catch (Throwable e) {LOG.error("Compute Engine startup failed", e);return false;}}private void startup() {LOG.info("Compute Engine starting up...");computeEngine.startup();LOG.info("Compute Engine is up");}private void waitForStopSignal() {while (!stop) {try {Thread.sleep(CHECK_FOR_STOP_DELAY);} catch (InterruptedException e) {// ignore the interruption itself, check the flag}}attemptShutdown();}private void attemptShutdown() {try {shutdown();} catch (Throwable e) {LOG.error("Compute Engine shutdown failed", e);} finally {// release thread waiting for CeServerstopAwait();}}private void shutdown() {LOG.info("Compute Engine shutting down...");computeEngine.shutdown();}public boolean isStarted() {return started;}public void stopIt() {// stop looping indefinitelythis.stop = true;// interrupt current thread in case its waiting for WebServerinterrupt();}private void stopAwait() {stopAwait = true;Thread t = awaitThread.get();if (t != null) {t.interrupt();try {t.join(1000);} catch (InterruptedException e) {// Ignored}}}}}

调用的类ComputeEngineImpl->ComputeEngine:

/** SonarQube* Copyright (C) 2009-2016 SonarSource SA* mailto:contact AT sonarsource DOT com** This program is free software; you can redistribute it and/or* modify it under the terms of the GNU Lesser General Public* License as published by the Free Software Foundation; either* version 3 of the License, or (at your option) any later version.** This program is distributed in the hope that it will be useful,* but WITHOUT ANY WARRANTY; without even the implied warranty of* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU* Lesser General Public License for more details.** You should have received a copy of the GNU Lesser General Public License* along with this program; if not, write to the Free Software Foundation,* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.*/
package org.sonar.ce;import org.sonar.ce.container.ComputeEngineContainer;
import org.sonar.process.Props;import static com.google.common.base.Preconditions.checkState;public class ComputeEngineImpl implements ComputeEngine {private final Props props;private final ComputeEngineContainer computeEngineContainer;private Status status = Status.INIT;public ComputeEngineImpl(Props props, ComputeEngineContainer computeEngineContainer) {this.props = props;this.computeEngineContainer = computeEngineContainer;}@Overridepublic void startup() {checkState(this.status == Status.INIT, "startup() can not be called multiple times");try {this.status = Status.STARTING;this.computeEngineContainer.start(props);} finally {this.status = Status.STARTED;}}@Overridepublic void shutdown() {checkStateAsShutdown(this.status);try {this.status = Status.STOPPING;this.computeEngineContainer.stop();} finally {this.status = Status.STOPPED;}}private static void checkStateAsShutdown(Status currentStatus) {checkState(currentStatus.ordinal() >= Status.STARTED.ordinal(), "shutdown() must not be called before startup()");checkState(currentStatus.ordinal() <= Status.STOPPING.ordinal(), "shutdown() can not be called multiple times");}private enum Status {INIT, STARTING, STARTED, STOPPING, STOPPED}
}

调用ComputeEngineContainerImpl->ComputeEngineContainer

public class ComputeEngineContainerImpl implements ComputeEngineContainer {@CheckForNullprivate ComponentContainer level1;@CheckForNullprivate ComponentContainer level4;@Overridepublic ComputeEngineContainer start(Props props) {this.level1 = new ComponentContainer();this.level1.add(props.rawProperties()).add(level1Components()).add(toArray(CorePropertyDefinitions.all())).add(toArray(ClusterProperties.definitions()));configureFromModules(this.level1);this.level1.startComponents();ComponentContainer level2 = this.level1.createChild();level2.add(level2Components());configureFromModules(level2);level2.startComponents();ComponentContainer level3 = level2.createChild();level3.add(level3Components());configureFromModules(level3);level3.startComponents();this.level4 = level3.createChild();this.level4.add(level4Components());configureFromModules(this.level4);ServerExtensionInstaller extensionInstaller = this.level4.getComponentByType(ServerExtensionInstaller.class);extensionInstaller.installExtensions(this.level4);this.level4.startComponents();startupTasks();return this;}private void startupTasks() {ComponentContainer startupLevel = this.level4.createChild();startupLevel.add(startupComponents());startupLevel.startComponents();// done in PlatformLevelStartupServerLifecycleNotifier serverLifecycleNotifier = startupLevel.getComponentByType(ServerLifecycleNotifier.class);if (serverLifecycleNotifier != null) {serverLifecycleNotifier.notifyStart();}startupLevel.stopComponents();}@Overridepublic ComputeEngineContainer stop() {this.level1.stopComponents();return this;}@VisibleForTestingprotected ComponentContainer getComponentContainer() {return level4;}private static Object[] level1Components() {Version apiVersion = ApiVersion.load(System2.INSTANCE);return new Object[] {ThreadLocalSettings.class,new SonarQubeVersion(apiVersion),SonarRuntimeImpl.forSonarQube(ApiVersion.load(System2.INSTANCE), SonarQubeSide.COMPUTE_ENGINE),CeProcessLogging.class,UuidFactoryImpl.INSTANCE,ClusterImpl.class,LogbackHelper.class,DefaultDatabase.class,DatabaseChecker.class,// must instantiate deprecated class in 5.2 and only this one (and not its replacement)// to avoid having two SqlSessionFactory instancesorg.sonar.core.persistence.MyBatis.class,DatabaseServerCompatibility.class,DatabaseVersion.class,PurgeProfiler.class,ServerFileSystemImpl.class,new TempFolderProvider(),System2.INSTANCE,// user sessionCeUserSession.class,// DBDaoModule.class,ReadOnlyPropertiesDao.class,DbClient.class,// ElasticsearchEsSearchModule.class,// rules/qprofilesRuleIndex.class,ActiveRuleIndex.class,// issuesIssueIndex.class,new OkHttpClientProvider()};}private static Object[] level2Components() {return new Object[] {DatabaseSettingLoader.class,DatabaseSettingsEnabler.class,UrlSettings.class,// add ReadOnlyPropertiesDao at level2 again so that it shadows PropertiesDaoReadOnlyPropertiesDao.class,DefaultServerUpgradeStatus.class,// pluginsPluginClassloaderFactory.class,CePluginJarExploder.class,PluginLoader.class,CePluginRepository.class,InstalledPluginReferentialFactory.class,ComputeEngineExtensionInstaller.class,// depends on pluginsDefaultI18n.class, // used by RuleI18nManagerRuleI18nManager.class, // used by DebtRulesXMLImporterDurations.class, // used in Web Services and DebtCalculator};}private static Object[] level3Components() {return new Object[] {new StartupMetadataProvider(),ServerIdManager.class,UriReader.class,ServerImpl.class,DefaultOrganizationProviderImpl.class};}private static Object[] level4Components() {return new Object[] {ResourceTypes.class,DefaultResourceTypes.get(),Periods.class, // used by JRuby and EvaluationResultTextConverterImpl// quality profileActiveRuleIndexer.class,XMLProfileParser.class,XMLProfileSerializer.class,AnnotationProfileParser.class,Rules.QProfiles.class,QProfileLookup.class,QProfileProjectOperations.class,// ruleRuleIndexer.class,AnnotationRuleParser.class,XMLRuleParser.class,DefaultRuleFinder.class,DeprecatedRulesDefinitionLoader.class,CommonRuleDefinitionsImpl.class,RuleDefinitionsLoader.class,RulesDefinitionXmlLoader.class,// languagesLanguages.class, // used by CommonRuleDefinitionsImpl// measureCoreCustomMetrics.class,DefaultMetricFinder.class,// usersDeprecatedUserFinder.class,DefaultUserFinder.class,UserIndexer.class,UserIndex.class,// permissionsPermissionTemplateService.class,PermissionUpdater.class,UserPermissionChanger.class,GroupPermissionChanger.class,// componentsComponentFinder.class, // used in ComponentServiceComponentService.class, // used in ReportSubmitterNewAlerts.class,NewAlerts.newMetadata(),ComponentCleanerService.class,ProjectMeasuresIndexer.class,// viewsViewIndexer.class,ViewIndex.class,// issuesIssueIndexer.class,PermissionIndexer.class,IssueUpdater.class, // used in Web Services and CE's DebtCalculatorFunctionExecutor.class, // used by IssueWorkflowIssueWorkflow.class, // used in Web Services and CE's DebtCalculatorNewIssuesEmailTemplate.class,MyNewIssuesEmailTemplate.class,IssueChangesEmailTemplate.class,AlertsEmailTemplate.class,ChangesOnMyIssueNotificationDispatcher.class,ChangesOnMyIssueNotificationDispatcher.newMetadata(),NewIssuesNotificationDispatcher.class,NewIssuesNotificationDispatcher.newMetadata(),MyNewIssuesNotificationDispatcher.class,MyNewIssuesNotificationDispatcher.newMetadata(),DoNotFixNotificationDispatcher.class,DoNotFixNotificationDispatcher.newMetadata(),NewIssuesNotificationFactory.class, // used by SendIssueNotificationsStepEmailNotificationChannel.class,// technical debtDebtModelPluginRepository.class,DebtRulesXMLImporter.class,// NotificationsEmailSettings.class,NotificationService.class,NotificationCenter.class,DefaultNotificationManager.class,// TestsTestIndexer.class,// SystemServerLogging.class,// privileged pluginsPrivilegedPluginsBootstraper.class,PrivilegedPluginsStopper.class,// Compute engine (must be after Views and Developer Cockpit)CeConfigurationModule.class,CeQueueModule.class,CeHttpModule.class,CeTaskCommonsModule.class,ProjectAnalysisTaskModule.class,CeTaskProcessorModule.class,InternalPropertiesImpl.class,ProjectSettingsFactory.class,};}private static Object[] startupComponents() {return new Object[] {LogServerId.class,ServerLifecycleNotifier.class,PurgeCeActivities.class,};}private static Object[] toArray(List<?> list) {return list.toArray(new Object[list.size()]);}private static void configureFromModules(ComponentContainer container) {List<Module> modules = container.getComponentsByType(Module.class);for (Module module : modules) {module.configure(container);}}
}

start方法调用startTask方法

SonarQube6.2源码解析(四)相关推荐

  1. SonarQube6.2源码解析(一)

    首先看sonar后台的启动进程: [root@uranuspreweb34 logs]# ps -ef | grep java root 3169 3167 0 Apr19 ? 00:06:04 ja ...

  2. loraserver 源码解析 (四) lora-gateway-bridge

    lora-gateway-bridge  负责接收 gateway 通过 udp 发送的 packet-forwarder 数据 然后通过 MQTT broker 将报文转发给 LoRa Server ...

  3. Tomcat源码解析四:Tomcat关闭过程

    我们在Tomcat启动过程(Tomcat源代码阅读系列之三)一文中已经知道Tomcat启动以后,会启动6条线程,他们分别如下: [java] view plaincopy "ajp-bio- ...

  4. SonarQube6.2源码解析(三)

    sonar web 启动过程,sonar-web 下面含有的代码了还是很大的,主main入口是webserver: webserver类代码: /** SonarQube* Copyright (C) ...

  5. SonarQube6.2源码解析(二)

    分别看下 es(elasticSearch),ce,web 进程入口. es: main入口类 SearchServer: /** SonarQube* Copyright (C) 2009-2016 ...

  6. arcengine遍历属性表_Redis源码解析四--跳跃表

    Redis 跳跃表(skiplist) 1. 跳跃表(skiplist)介绍 定义:跳跃表是一个有序链表,其中每个节点包含不定数量的链接,节点中的第i个链接构成的单向链表跳过含有少于i个链接的节点. ...

  7. kafka-go源码解析四(Writer)

    概要 kafka-go区分同步写与异步写.同步写能严格确保写入的顺序,因为在写成功之前它会block住应用程序,同时返回错误信息.有三种控制写入完成的时机,1是消息发送完成即返回,2是leader收到 ...

  8. QT源码解析(一) QT创建窗口程序、消息循环和WinMain函数

    版权声明 请尊重原创作品.转载请保持文章完整性,并以超链接形式注明原始作者"tingsking18"和主站点地址,方便其他朋友提问和指正. QT源码解析(一) QT创建窗口程序.消 ...

  9. 《React源码解析》系列完结!

    前言 距离第一篇<React源码解析(一)>已经过去将近4个月的时间,由于是我第一次进行源码解析相关的写作,思路和文笔还不够成熟.一百多天以来,我基于读者反馈反思这几篇文章中的不足,同时也 ...

最新文章

  1. SQL Server使用侦听器IP访问时遇到The target principal name is incorrect. Cannot generate SSPI context...
  2. layout-maxWidth属性用法
  3. python算法攻略_算法基础及python实现笔记一(堆和DFS)
  4. python3 for循环怎么用_Python3入门系列之-----循环语句(for/while)
  5. spark代码中添加logger_Spark RDD中Runtime流程解析
  6. 至诚学院MATLAB第四次,MATLAB 第二次实验课课堂作业(4学时)
  7. Java并发AtomicIntegerArray类
  8. Intel APIC Configuration
  9. Maxwell个人初学经验及资料分享
  10. Appstore抓包获取APP历史版本
  11. Excel单元格下拉选择,单元格自动计算
  12. xp系统怎么关闭wmi服务器,教你win10系统wmi服务器怎么关闭
  13. 蒲公英超级签名原理(手动做超级签名)
  14. 探究CSS3中的transition和transform属性方法使用
  15. C语言如何正确初始化数据,C语言变量的初始化
  16. linux phy fixed-link
  17. ACL2021_Enhancing Entity Boundary Detection for Better Chinese Named Entity Recognition
  18. 大数据自助分析平台系列文章(深入讲解由零开始设计一个大数据自助分析平台)
  19. 免费简历,ppt模板
  20. 推荐免费的文本编辑工具

热门文章

  1. pyspark的rdd直接写入mysql
  2. ./和bash的区别
  3. 為什麼system32中放的是64位dll,syswow64中放的是32位dll
  4. solidworks图纸模板添加_Solidworks零件和图纸绘制流程分享
  5. redis序列化_scrapy_redis中序列化源码及其在程序设计中的应用
  6. python sftp模块_python下载paramiko模块准备使用SFTP的坑!!!
  7. bzoj 1670 [Usaco2006 Oct]Building the Moat护城河的挖掘——凸包
  8. 在Webstorm中配置Compass Watcher
  9. 【uva 1617】Laptop(算法效率--贪心,2种理解)
  10. Linux中进行用户UID测试导致系统报错