首页 文章 精选 留言 我的

精选列表

搜索[源码],共10000篇文章
优秀的个人博客,低调大师

Tensorflow源码解析6 -- TensorFlow本地运行时

1 概述 TensorFlow后端分为四层,运行时层、计算层、通信层、设备层。运行时作为第一层,实现了session管理、graph管理等很多重要的逻辑,是十分关键的一层。根据任务分布的不同,运行时又分为本地运行时和分布式运行时。本地运行时,所有任务运行于本地同一进程内。而分布式运行时,则允许任务运行在不同机器上。 Tensorflow的运行,通过session搭建了前后端沟通的桥梁,前端几乎所有操作都是通过session进行。session的生命周期由创建、运行、关闭、销毁组成,前文已经详细讲述过。可以将session看做TensorFlow运行的载体。而TensorFlow运行的核心对象,则是计算图Graph。它由计算算子和计算数据两部分构成,可以完整描述整个计算内容。Graph的生命周期包括构建和传递、剪枝、分裂、执行等步骤,本

优秀的个人博客,低调大师

【Elasticsearch 5.6.12 源码】——【3】启动过程分析(下)

版权声明:本文为博主原创,转载请注明出处! 简介 本文主要解决以下问题: 1、ES启动过程中的Node对象都初始化了那些服务? 构造流程 Step 1、创建一个List暂存初始化失败时需要释放的资源,并使用临时的Logger对象输出开始初始化的日志。 这里首先创建了一个List<Closeable>然后输出日志initializing ...。代码比较简单: final List<Closeable> resourcesToClose = new ArrayList<>(); // register everything we need to release in the case of an error boolean success = false; { // use temp logger just to say we are starting. we can't use it later on because the node name might not be set Logger logger = Loggers.getLogger(Node.class, NODE_NAME_SETTING.get(environment.settings())); logger.info("initializing ..."); } Step 2、强制设置settings中client.type的配置为node,设置node.name并检查索引data目录的设置。 这部分首先设置client.type为node,接下来调用TribeService的processSettings方法来处理了“部落”的配置,然后创建NodeEnvironment,检查并设置node.name属性,最后按需检查索引数据的Path的配置并打印一些JVM的信息。代码如下: Settings tmpSettings = Settings.builder().put(environment.settings()) .put(Client.CLIENT_TYPE_SETTING_S.getKey(), CLIENT_TYPE).build(); tmpSettings = TribeService.processSettings(tmpSettings); // create the node environment as soon as possible, to recover the node id and enable logging try { nodeEnvironment = new NodeEnvironment(tmpSettings, environment); resourcesToClose.add(nodeEnvironment); } catch (IOException ex) { throw new IllegalStateException("Failed to create node environment", ex); } final boolean hadPredefinedNodeName = NODE_NAME_SETTING.exists(tmpSettings); Logger logger = Loggers.getLogger(Node.class, tmpSettings); final String nodeId = nodeEnvironment.nodeId(); tmpSettings = addNodeNameIfNeeded(tmpSettings, nodeId); if (DiscoveryNode.nodeRequiresLocalStorage(tmpSettings)) { checkForIndexDataInDefaultPathData(tmpSettings, nodeEnvironment, logger); } // this must be captured after the node name is possibly added to the settings final String nodeName = NODE_NAME_SETTING.get(tmpSettings); if (hadPredefinedNodeName == false) { logger.info("node name [{}] derived from node ID [{}]; set [{}] to override", nodeName, nodeId, NODE_NAME_SETTING.getKey()); } else { logger.info("node name [{}], node ID [{}]", nodeName, nodeId); } Step 3、创建PluginsService及Environment实例。 在PluginsService的构造方法中会加载plugins和modules目录下的jar包,并创建相应的plugin和module实例。创建完以后,Node的构造方法中会调用pluginsService的updatedSettings方法来获取plugin和module中定义的配置项。接下来Node或使用新的settings和nodeId来创建LocalNodeFactory,并使用最新的settings重新创建Environment对象。代码如下: this.pluginsService = new PluginsService(tmpSettings, environment.modulesFile(), environment.pluginsFile(), classpathPlugins); this.settings = pluginsService.updatedSettings(); localNodeFactory = new LocalNodeFactory(settings, nodeEnvironment.nodeId()); // create the environment based on the finalized (processed) view of the settings // this is just to makes sure that people get the same settings, no matter where they ask them from this.environment = new Environment(this.settings); Environment.assertEquivalent(environment, this.environment); Step 4、创建ThreadPool及ThreadContext实例。 首先,通过pluginsService获取plugin及module中提供的ExecutorBuilder对象列表。接下来基于settings及获取的ExecutorBuilder对象列表创建ThreadPool及ThreadContext实例。代码如下: final ThreadPool threadPool = new ThreadPool(settings, executorBuilders.toArray(new ExecutorBuilder[0])); resourcesToClose.add(() -> ThreadPool.terminate(threadPool, 10, TimeUnit.SECONDS)); // adds the context to the DeprecationLogger so that it does not need to be injected everywhere DeprecationLogger.setThreadContext(threadPool.getThreadContext()); resourcesToClose.add(() -> DeprecationLogger.removeThreadContext(threadPool.getThreadContext())); Step 5、依次创建NodeClient、ResourceWatcherService、ScriptModule、AnalysisModule、SettingsModule、NetworkService、ClusterService、IngestService及ClusterInfoService等主要模块。 ScriptModule中持有ScriptService通过该服务可以获取到ES中配置的各类脚本引擎的实例。AnalysisModule中持有AnalysisRegistry对象,通过该对象可以获取到ES中配置的各类查询分析器的实例。SettingModule中按类型保存了ES中可以解析的配置对象。NetworkService主要用来解析网络地址,ClusterService用例维护集群的信息。代码如下: final List<Setting<?>> additionalSettings = new ArrayList<>(pluginsService.getPluginSettings()); final List<String> additionalSettingsFilter = new ArrayList<>(pluginsService.getPluginSettingsFilter()); for (final ExecutorBuilder<?> builder : threadPool.builders()) { additionalSettings.addAll(builder.getRegisteredSettings()); } client = new NodeClient(settings, threadPool); final ResourceWatcherService resourceWatcherService = new ResourceWatcherService(settings, threadPool); final ScriptModule scriptModule = ScriptModule.create(settings, this.environment, resourceWatcherService, pluginsService.filterPlugins(ScriptPlugin.class)); AnalysisModule analysisModule = new AnalysisModule(this.environment, pluginsService.filterPlugins(AnalysisPlugin.class)); additionalSettings.addAll(scriptModule.getSettings()); // this is as early as we can validate settings at this point. we already pass them to ScriptModule as well as ThreadPool // so we might be late here already final SettingsModule settingsModule = new SettingsModule(this.settings, additionalSettings, additionalSettingsFilter); scriptModule.registerClusterSettingsListeners(settingsModule.getClusterSettings()); resourcesToClose.add(resourceWatcherService); final NetworkService networkService = new NetworkService(settings, getCustomNameResolvers(pluginsService.filterPlugins(DiscoveryPlugin.class))); final ClusterService clusterService = new ClusterService(settings, settingsModule.getClusterSettings(), threadPool, localNodeFactory::getNode); clusterService.addStateApplier(scriptModule.getScriptService()); resourcesToClose.add(clusterService); final IngestService ingestService = new IngestService(clusterService.getClusterSettings(), settings, threadPool, this.environment, scriptModule.getScriptService(), analysisModule.getAnalysisRegistry(), pluginsService.filterPlugins(IngestPlugin.class)); final ClusterInfoService clusterInfoService = newClusterInfoService(settings, clusterService, threadPool, client); Step 6、创建ModulesBuilder并加入各种Module。 ES使用google开源的Guice管理程序中的依赖。加入ModulesBuilder中的Module有:通过PluginsService获取的插件提供的Module;NodeModule内部持有MonitorService;ClusterModule内部持有ClusterService及相关的ClusterPlugin;IndicesModule内部持有MapperPlugin;SearchModule内部持有相关的SearchPlugin;ActionModule内部持有ThreadPool、ActionPlugin、NodeClient及CircuitBreakerService;GatewayModule;RepositoriesModule内部持有RepositoryPlugin;SttingsModule内部ES可用的各类配置对象等;最好调用modules的createInjector方法创建应用的“依赖注入器”。 Step 7、收集各plugin的LifecycleComponent对象,并出初始化NodeClient。 代码如下: List<LifecycleComponent> pluginLifecycleComponents = pluginComponents.stream() .filter(p -> p instanceof LifecycleComponent) .map(p -> (LifecycleComponent) p).collect(Collectors.toList()); pluginLifecycleComponents.addAll(pluginsService.getGuiceServiceClasses().stream() .map(injector::getInstance).collect(Collectors.toList())); resourcesToClose.addAll(pluginLifecycleComponents); this.pluginLifecycleComponents = Collections.unmodifiableList(pluginLifecycleComponents); client.initialize(injector.getInstance(new Key<Map<GenericAction, TransportAction>>() {}), () -> clusterService.localNode().getId()); if (NetworkModule.HTTP_ENABLED.get(settings)) { logger.debug("initializing HTTP handlers ..."); actionModule.initRestHandlers(() -> clusterService.state().nodes()); } logger.info("initialized"); Step 8、调用Node的Start方法,在该方法内依次调用各重要模块的start方法。 依次启动各个关键服务。代码如下: // hack around dependency injection problem (for now...) injector.getInstance(Discovery.class).setAllocationService(injector.getInstance(AllocationService.class)); pluginLifecycleComponents.forEach(LifecycleComponent::start); injector.getInstance(MappingUpdatedAction.class).setClient(client); injector.getInstance(IndicesService.class).start(); injector.getInstance(IndicesClusterStateService.class).start(); injector.getInstance(IndicesTTLService.class).start(); injector.getInstance(SnapshotsService.class).start(); injector.getInstance(SnapshotShardsService.class).start(); injector.getInstance(RoutingService.class).start(); injector.getInstance(SearchService.class).start(); injector.getInstance(MonitorService.class).start(); final ClusterService clusterService = injector.getInstance(ClusterService.class); final NodeConnectionsService nodeConnectionsService = injector.getInstance(NodeConnectionsService.class); nodeConnectionsService.start(); clusterService.setNodeConnectionsService(nodeConnectionsService); // TODO hack around circular dependencies problems injector.getInstance(GatewayAllocator.class).setReallocation(clusterService, injector.getInstance(RoutingService.class)); injector.getInstance(ResourceWatcherService.class).start(); injector.getInstance(GatewayService.class).start(); Discovery discovery = injector.getInstance(Discovery.class); clusterService.setDiscoverySettings(discovery.getDiscoverySettings()); clusterService.addInitialStateBlock(discovery.getDiscoverySettings().getNoMasterBlock()); clusterService.setClusterStatePublisher(discovery::publish); // start before the cluster service since it adds/removes initial Cluster state blocks final TribeService tribeService = injector.getInstance(TribeService.class); tribeService.start(); // Start the transport service now so the publish address will be added to the local disco node in ClusterService TransportService transportService = injector.getInstance(TransportService.class); transportService.getTaskManager().setTaskResultsService(injector.getInstance(TaskResultsService.class)); transportService.start(); validateNodeBeforeAcceptingRequests(settings, transportService.boundAddress(), pluginsService.filterPlugins(Plugin.class).stream() .flatMap(p -> p.getBootstrapChecks().stream()).collect(Collectors.toList())); clusterService.addStateApplier(transportService.getTaskManager()); clusterService.start(); assert localNodeFactory.getNode() != null; assert transportService.getLocalNode().equals(localNodeFactory.getNode()) : "transportService has a different local node than the factory provided"; assert clusterService.localNode().equals(localNodeFactory.getNode()) : "clusterService has a different local node than the factory provided"; // start after cluster service so the local disco is known discovery.start(); transportService.acceptIncomingRequests(); discovery.startInitialJoin(); // tribe nodes don't have a master so we shouldn't register an observer s final TimeValue initialStateTimeout = DiscoverySettings.INITIAL_STATE_TIMEOUT_SETTING.get(settings); if (initialStateTimeout.millis() > 0) { final ThreadPool thread = injector.getInstance(ThreadPool.class); ClusterState clusterState = clusterService.state(); ClusterStateObserver observer = new ClusterStateObserver(clusterState, clusterService, null, logger, thread.getThreadContext()); if (clusterState.nodes().getMasterNodeId() == null) { logger.debug("waiting to join the cluster. timeout [{}]", initialStateTimeout); final CountDownLatch latch = new CountDownLatch(1); observer.waitForNextChange(new ClusterStateObserver.Listener() { @Override public void onNewClusterState(ClusterState state) { latch.countDown(); } @Override public void onClusterServiceClose() { latch.countDown(); } @Override public void onTimeout(TimeValue timeout) { logger.warn("timed out while waiting for initial discovery state - timeout: {}", initialStateTimeout); latch.countDown(); } }, state -> state.nodes().getMasterNodeId() != null, initialStateTimeout); try { latch.await(); } catch (InterruptedException e) { throw new ElasticsearchTimeoutException("Interrupted while waiting for initial discovery state"); } } } if (NetworkModule.HTTP_ENABLED.get(settings)) { injector.getInstance(HttpServerTransport.class).start(); } if (WRITE_PORTS_FILE_SETTING.get(settings)) { if (NetworkModule.HTTP_ENABLED.get(settings)) { HttpServerTransport http = injector.getInstance(HttpServerTransport.class); writePortsFile("http", http.boundAddress()); } TransportService transport = injector.getInstance(TransportService.class); writePortsFile("transport", transport.boundAddress()); } // start nodes now, after the http server, because it may take some time tribeService.startNodes(); logger.info("started");

优秀的个人博客,低调大师

【Elasticsearch 5.6.12 源码】——【2】启动过程分析(上)

版权声明:本文为博主原创,转载请注明出处! 简介 本文主要解决以下问题: 1、启动ES的入口类及入口方法是哪个?2、分析梳理ES服务启动的主要流程? 入口类 ES的入口类为org.elasticsearch.bootstrap.Elasticsearch,启动方法为: public static void main(final String[] args) throws Exception 该类通过继承EnvironmentAwareCommand类增加了CLI的支持,类图: 启动流程 Step 1、给JVM安装(临时的)安全管理器,并注册错误日志监听器。 ES在程序启动的第一步先给JVM安装了一个安全管理器,并授予了程序所有的权限(临时的,后续会更换新的安全管理器),以方便以后的操作。接下来会注册一个错误日志的监听器,来监听是否有错误发生,随后使用配置文件配置日志组件是会检查监听器是否检测到错误,如果有将通过抛异常的方式中止ES的启动过程。执行该动作的方法: // org.elasticsearch.bootstrap.Elasticsearch public static void main(final String[] args) throws Exception Step 2、创建一个Elasticsearch类的实例(一个CLI的Command实例),并执行实例的main方法。 Elasticsearch类直接继承了EnvironmentAwareCommand,可以认为这一步创建了一个CLI的command对象。在该类的构造方法以及父类中定义了该command对象可以接受的cli的参数。执行该动作的方法: // org.elasticsearch.bootstrap.Elasticsearch public static void main(final String[] args) throws Exception 在bin目录下运行Elasticsearch -h命令,可以查看该实例支持的所有命令行参数: Step 3、添加JVM关闭的构造,使用默认配置配置日志组件。 为JVM添加了一个shutdown的钩子函数,在钩子函数中调用了close()方法。使用系统属性es.logger.level的值来配置日志组件,如果没有该配置则使用默认的INFO级别来配置logger.level。执行该动作的方法: // org.elasticsearch.cli.Command public final int main(String[] args, Terminal terminal) throws Exception Step 4、解析help、silent、verbose或normal的参数配置,并输出或设置到Terminal上。 首先检查控制台是否传入了-h或--help参数,如果有的话打印帮助信息,并结束ES的启动过程。否则,依次检查-s、-v等参数,并根据相应的参数配置terminal的信息输出方式。执行该动作的方法: // org.elasticsearch.cli.Command void mainWithoutErrorHandling(String[] args, Terminal terminal) throws Exception Step 5、解析通过控制台传入的ES的配置参数,并根据配置参数创建Environment对象。 首先,解析通过控制台-E参数传入的ES配置。其次,通过System Property补齐某些确实的配置。这两个过程都会对配置的key进行查重。解析配置的代码: // org.elasticsearch.cli.EnvironmentAwareCommand protected void execute(Terminal terminal, OptionSet options) throws Exception { final Map<String, String> settings = new HashMap<>(); for (final KeyValuePair kvp : settingOption.values(options)) { if (kvp.value.isEmpty()) { throw new UserException(ExitCodes.USAGE, "setting [" + kvp.key + "] must not be empty"); } if (settings.containsKey(kvp.key)) { final String message = String.format( Locale.ROOT, "setting [%s] already set, saw [%s] and [%s]", kvp.key, settings.get(kvp.key), kvp.value); throw new UserException(ExitCodes.USAGE, message); } settings.put(kvp.key, kvp.value); } putSystemPropertyIfSettingIsMissing(settings, "default.path.conf", "es.default.path.conf"); putSystemPropertyIfSettingIsMissing(settings, "default.path.data", "es.default.path.data"); putSystemPropertyIfSettingIsMissing(settings, "default.path.logs", "es.default.path.logs"); putSystemPropertyIfSettingIsMissing(settings, "path.conf", "es.path.conf"); putSystemPropertyIfSettingIsMissing(settings, "path.data", "es.path.data"); putSystemPropertyIfSettingIsMissing(settings, "path.home", "es.path.home"); putSystemPropertyIfSettingIsMissing(settings, "path.logs", "es.path.logs"); execute(terminal, options, createEnv(terminal, settings)); } 接下来,根据解析到的配置项来创建Environment对象。 // org.elasticsearch.cli.EnvironmentAwareCommand protected Environment createEnv(Terminal terminal, Map<String, String> settings) { return InternalSettingsPreparer.prepareEnvironment(Settings.EMPTY, terminal, settings); } 最终,通过InternalSettingsPreparer对象的prepareEnironment方法来创建Enironment对象。 // org.elasticsearch.node.InternalSettingsPreparer public static Environment prepareEnvironment(Settings input, Terminal terminal, Map<String, String> properties) 该方法会合并控制台传入的配置项、部分通过系统环境变量设置的配置项及elasticsearch.yml设置的配置项。最终创建一个Environment对象,该对象中保存了ES程序的配置目录、数据目录、插件目录及日志目录的地址。 Step 6、解析控制台传入的-v、-d、-p及-q等参数,并依据相应的参数初始化Bootstrap。 首先,检查是否传入了-v参数,如果有该参数则打印ES的版本信息并退出。接下来解析-d、-p及-q参数,并依据这些参数调用Bootstrap.init。执行该动作的方法: // org.elasticsearch.bootstrap.Elasticsearch protected void execute(Terminal terminal, OptionSet options, Environment env) throws UserException void init(final boolean daemonize, final Path pidFile, final boolean quiet, Environment initialEnv) Step 7、通过调用BootstrapInfo.init()方法的方式来初始化BootstrapInfo对象。 通过这个对象可以获取JNA是否可用、系统Memory Lock是否可用等一些系统信息。执行该动作的方法: // org.elasticsearch.bootstrap.Bootstrap static void init(final boolean foreground, final Path pidFile, final boolean quiet, final Environment initialEnv) throws BootstrapException, NodeValidationException, UserException Step 8、创建一个Bootstrap实例,加载Secure Settings,并结合原有的配置重新创建Environment对象。 在Bootstrap实例中首先启动了一个keep alive线程。结合SecureSettings重新创建Environment对象。依据env中的配置文件配置日志组件,这时会检查是否有错误日志产生。接下来输出一些配置相关的日志,并按需创建pidFile。执行该动作的方法: // org.elasticsearch.bootstrap.Bootstrap static void init(final boolean foreground, final Path pidFile, final boolean quiet, final Environment initialEnv) throws BootstrapException, NodeValidationException, UserException Step 9、检查Lucene的版本,设置 默认的未捕获异常的处理器 ,并开始配置新建的Bootstrap实例。 首先,根据是否守护经常运行的方式按需关闭SysOut。接下来检查Lucene库的版本是否匹配。最后,设置 DefaultUncaughtExceptionHandler。执行该动作的方法: // org.elasticsearch.bootstrap.Bootstrap static void init(final boolean foreground, final Path pidFile, final boolean quiet, final Environment initialEnv) throws BootstrapException, NodeValidationException, UserException Step 10、设置NativePluginControllers,初始化native资源,初始化资源“探针”,checkJarHell,再次设置系统安全管理器并新建Node对象。 在这些过程中间还会检查老配置项bootstrap.seccomp和新配置项bootstrap.system_call_filter都配置了的情况下是否产生了冲突。执行该动作的方法: // org.elasticsearch.bootstrap.Bootstrap private void setup(boolean addShutdownHook, Environment environment) throws BootstrapException Step 11、关闭SecureSettings的存储文件,并调用Bootstrap对象的start方法,按需closeSysError。 这是启动流程的最后一步。

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

用户登录
用户注册
修改密码
忘记密码