Click on the above blue words to follow us and learn about microservices
In the previous article, we introduced you to using Service-Center. In this article, we will analyze the startup process of service-Center.
The startup process of service-Center consists of three parts: initialization, startup, and Service startup. The following describes the startup process:
As with all Golang projects, the process starts with the main function. In main.go, a total of three methods are run (two init functions are done by importing anonymous import packages). The server/init/init. Go init () to the execution of the project initialization server bootstrap/bootstrap. Go init () is mainly responsible for directing, server/main go Run () is the specific service startup. Let’s analyze their work in detail.
I. Initialization process
It can be seen from the above flow chart
Server /init/init.go init()
The actual work is done in server/core/core.go
It mainly does the following three things:
1. Monitor the related termination signal of the system to realize the graceful restart of the program
2. Parse the cli parameters to confirm the current running mode
3. Load the configuration file to provide parameters for the subsequent startup process
server/pkg/grace/grace.go
Grace.go init() init()
Here are three things:
1. Read parameters fork and filesorder from the command line
2. Initialize the system listener set (SIGHUP, SIGINT, SIGKILL, SIGTERM) and add it to the hook queue
3. Start the system signal monitoring, and after receiving the qualified signals, preposition, fork, postposition and other processing will be carried out. Fork: SIGHUP signal processing function, and the graceful restart will be actually executed. After receiving the signal, the -fork-filesorder = XXX parameter is added to the original command line to form a new command line and restart the application in the child process.
server/core/core.go
In server/core/core.go, the program explicitly calls the following three methods:
ParseCommandLine(): parses the command line parameters. If -v is true, the version information is printed and the command line exits
Configure() : service startup configuration
•setCPUs(): sets the number of concurrent cpus
•newInfo() : Gets the parameters from the configuration file parsed by BeeGo and saves the startup configuration to the global variable ServerInfo for subsequent processes to read. Go init(), which loads the configuration file from the default file location: “./conf/app.conf “.
•SetPluginDir(): Set the directory for custom plugins (service-Center is designed with plugins in mind and allows users to use custom plugins, which will be discussed in more detail in a later introduction article)
•initLogger() : Initializes the logging tool according to the configuration of ServerInfo
• version.ver ().log () : Prints version information
Go handleSignals(): monitors system signals. After receiving signals, exit the system after 5 seconds and perform log dropping (with the subprocess to restart the application).
Start the boot process
Start the boot process is mainly responsible for the registration and initialization module within the service, all work on server bootstrap/bootstrap. Go and involves the following several aspects:
The API of service-Center is built RESTful. HTTP Service listening needs to be enabled. In this step, HTTP routes are registered. Because of the compatibility of the two versions, v3 and V4 API groups are registered, and the specific implementation is consistent, except for the difference in URL routing. The following is an analysis of v4 code only; the V3 version registry is no different from it.
server/rest/controller/v4/v4.go
As shown in figure 4, multiple RESTful processing objects are registered with ROA separately in V4.go.
pkg/rest/roa.go
Let’s look at the implementation of roa.registerservant () :
• In the first red box above, you can see that the method takes and executes the URLPatterns method of the input object by reflection
• In the second red box, assert the []Route slice of the first parameter returned in the previous step and register it with the HTTP Route if the type matches (serverHandler.addroute ())
server/rest/controller/v4/main_controller.go
Let’s take a look at the implementation of the object registered in v4. Go. Here we select MainService.
The URLPatterns() method returns a slice of a Route that includes HTTP methods, routing, and specific processing methods. The methods defined here are triggered when listening is started and the corresponding method and route are matched.
server/rest/controller/handler.go
In this file, service-Center registers the Service master route, where all requests will have processing logic to enter the Service. In the processing method, incoming requests are sequentially logged with start time, interceptor calls, and route matches.
server/rest/controller/metrics.go
Connect to Prometheus system, register access request counters, success request counters, request timers, and preprocessing timers with Prometheus, and register performance monitoring routes with the service
server/rest/controller/pprof.go
Register golang performance profiling routes
server/rest/controller/reporter.go
Register the REST request logger with the performance monitoring module
server/rest/controller/reporter.go
The service-center performance indicator module connects to Prometheus. In this file, an indicator collector is started, and indicators are periodically collected and recorded
Service-center abstracts the interface of the Service registration engine so that we can connect with different registration systems. Three default registration systems are provided: buildin (empty implementation only defines interfaces without registration), embededetCD (service-center embedded ETCD), and ETCD (other ETcds or their clusters). For convenience, only buildin content is shown below, the principle of other types is the same:
server/plugin/pkg/registry/buildin/buildin.go
In the init() method, a Registery instance named “buildin” is registered with the plug-in registration manager; This example implements the corresponding warehouse interface
In order to facilitate the interconnection of different Service discovery engines (which will be introduced in the heterogeneous scenario), service-Center also abstracted the Discovey interface of Service discovery and made plug-in support. Currently, four types of services are built-in: Aggregate, ETCD, K8S, and servicecenter. Here we only take servicecenter as an example, view its initialization process, we can see the specific implementation of the project source code:
In the init() method, a Discovery instance named “servicecenter” is registered with the plug-in registration manager
Service-center also supports ciphers, quotas, Auth, uUID, tracing, TLS, and the basic implementation of these plug-ins. Users can use a customized plug-in for replacement. Since this part of the code is similar to the registration method of the two plug-ins above, I won’t expand the description here.
Before route matching: Through the interceptor. RegisterInterceptFunc (), will visit check (access), cross-domain support (cors) registered to intercept processing prior to the visit, the specific implementation in server/interceptor/interceptor. Go, As shown in figure:
, in the request into the server/rest/controller/handler. Go, interceptor. InvokeInterceptors (w, r) method, will call before routing matching method in the red box above, Specific please see the “other routing registered – server/rest/controller/handler. Go”
After the routes are matched:
In the maxBody, Metric link tracing, Auth, Context, and request cache module RegisterHandler() methods, Use the chain.registerHandler () method to register itself in the interception processing after access: file location: server/rest/handler.go
The registered Handlers are stored in the variable handlersMap, and the Handlers() method is called and executed in the red box. The Handlers() method is called in server/rest/route.go by tracing:
In the request into the server/rest/controller/handler. Go, roa. GetRouter () ServeHTTP (w, r) will perform in the picture above ServeHTTP () method, Specific please see the “other routing registered – server/rest/controller/handler. Go”
Service startup process
After the initialization and boot process is complete, service-Center starts the Service.
server/service/event/event.go
Service-center uses events to make registration and discovery purely asynchronous. When the Service is started, the Service discovery engine listens for events:
In the figure above, events are monitored for resources such as Domain, Service, Instance, Rule, Tag, Dependency, DependencyRule and SchemaSummary. When watch finds changes in the system from the Service, The corresponding event is emitted within the service for the event listener to process.
server/server/server.go
The initialize ()
• Initialize the cacheService, apiService, notifyService, goroutine
• startServices ()
• Start the notification service, load the plug-in from the configured plug-in directory, register its own service on demand, start the cache service, compress back-end storage data on demand, and start the RESTful API service
• waitForQuit ()
Wait until the service ends, call the stop method to stop the started service, close the coroutine pool and the service registration system, and perform log falling.
At the end of the article summary
The purpose of this article to the reader describes the ServiceCenter startup process, the user to understand the content of ServiceCenter, to the subsequent understanding of other aspects.
In the meantime, we welcome fans to ask questions and contribute code to the community 🙂
The next part introduces the overall architecture of service-Center.
If you have any questions and want to communicate while reading the code, please scan the code and join the wechat group.
Scan the QR code
Add the microservices widget assistant
Look forward to like-minded friends to join
ServiceComb is open for you
Early reading
[Learn Microservices Day 9]
Getting started with service-center
[Learning Microservices – Day 8]
ServiceComb Built-in load balancing component handler-loadBalance
[Learn Microservices Day 7]
ServiceComb+SpringCloud Ribbon source code interpretation
[Learning Microservices – Day 6]
ServiceComb + SpringCloud Ribbon for load balancing
[Learning Microservices – Day 5]
ServiceComb+Zipkin source code interpretation
[Learning Microservices – Day 4]
ServiceComb+Zipkin
[Learn Microservices – Day 3]
ServiceComb Provides high-performance gateway services
Learn microservices every day – source code interpretation
ServiceComb+SpringCloud Zuul
[Daily Learning microservices – Gateways]
ServiceComb+SpringCloud Zuul
—————————————————-
For more information visit:
Official website ↓↓↓
http://servicecomb.apache.org/
Github Code Repository ↓↓↓
https://github.com/apache?q=ServiceComb
Click “Read the original” to read the source code
And give ServiceComb a “Star”