cmdr 04 - simple micro-service (daemon)

cmdr 04 - simple micro-service
based on cmdr v0.2.21

My ado is too much.

So this time straight into the subject, declined to Tucao. I do not know cmdrwhy use, may wish to see earlier

So, golang suitable for back-end development, whether or RESTful gRPC are its strengths.

Once we want to develop a micro-services, aside core logic aside, and regardless of whether the terms of DevOps is K8s, or Docker, or bare metal, always face a startup, commissioning, testing everyday problems.

cmdr In addition to providing the ability to interpret the command line arguments, but also provides a daemon additional plug-in, it can help you simplify daily development work, so you do not have to be concerned about the pid file, log, exit signals and so on, and need not be repeated scheduling daemon related the command line instructions.

Here's how to use daemon plugin, how to write the actual business logic. Our demo for example write a simple example micro-services and explains specific practices.

Use Daemon Plug

Daemon Enable plug-ins

Daemon Enable plug-ins just one line of code:

// Entry is app main entry
func Entry() {

	logrus.SetLevel(logrus.DebugLevel)
	logrus.SetFormatter(&logrus.TextFormatter{ForceColors: true})

	daemon.Enable(svr.NewDaemon(), nil, nil, nil)

	if err := cmdr.Exec(rootCmd); err != nil {
		logrus.Errorf("Error: %v", err)
	}

}
复制代码

Implement daemon.DaemonInterface

Daemon is enabled plug-ins, you need to implement daemon.Daemonan interface, and write some wrapper code to connect cmdr, daemonas well as your business logic.

daemon.Daemon interface

daemon.Daemon Interface is this:

// Daemon interface should be implemented when you are using `daemon.Enable()`.
type Daemon interface {
	OnRun(cmd *cmdr.Command, args []string, stopCh, doneCh chan struct{}) (err error)
	OnStop(cmd *cmdr.Command, args []string) (err error)
	OnReload()
	OnStatus(cxt *Context, cmd *cmdr.Command, p *os.Process) (err error)
	OnInstall(cxt *Context, cmd *cmdr.Command, args []string) (err error)
	OnUninstall(cxt *Context, cmd *cmdr.Command, args []string) (err error)
}
复制代码

For a micro-services, you must write that OnRun, OnStopthe two methods. Several other methods, is usually optional, daemon plugin for RESTful http2 completed a default logic to support reload, status. In addition, daemon for systemd plug-in also implements the default install and uninstall logic.

So here we have completed the first part:

OnRun
type daemonImpl struct {}

func (*daemonImpl) OnRun(cmd *cmdr.Command, args []string, stopCh, doneCh chan struct{}) (err error) {
	logrus.Debugf("demo daemon OnRun, pid = %v, ppid = %v", os.Getpid(), os.Getppid())
	go worker(stopCh, doneCh)
	return
}

func worker(stopCh, doneCh chan struct{}) {
LOOP:
	for {
		time.Sleep(time.Second) // this is work to be done by worker.
		select {
		case <-stopCh:
			break LOOP
		default:
		}
	}
	doneCh <- struct{}{}
}
复制代码

daemon provides two channels, stopChshould make your code end an infinite loop, when your code exits the loop should trigger doneChevent. Such a graceful shutdown logic to ensure that the entire micro-services.

As for the core logic, our worker, now it is just an infinite loop, you can complete the replacement based on actual business needs them.

Next time we may provide a sample of a RESTful micro-service.

OnStop And other

func (*daemonImpl) OnStop(cmd *cmdr.Command, args []string) (err error) {
	logrus.Debugf("demo daemon OnStop")
	return
}

func (*daemonImpl) OnReload() {
	logrus.Debugf("demo daemon OnReload")
}

func (*daemonImpl) OnStatus(cxt *daemon.Context, cmd *cmdr.Command, p *os.Process) (err error) {
	fmt.Printf("%v v%v\n", cmd.GetRoot().AppName, cmd.GetRoot().Version)
	fmt.Printf("PID=%v\nLOG=%v\n", cxt.PidFileName, cxt.LogFileName)
	return
}

func (*daemonImpl) OnInstall(cxt *daemon.Context, cmd *cmdr.Command, args []string) (err error) {
	logrus.Debugf("demo daemon OnInstall")
	return
}

func (*daemonImpl) OnUninstall(cxt *daemon.Context, cmd *cmdr.Command, args []string) (err error) {
	logrus.Debugf("demo daemon OnUninstall")
	return
}
复制代码

Other interface methods basically do nothing, because for our worker, it is not necessary to OnStopclean up the database connection, the release of other resources, nor need OnReloadwhen you load the new configuration file.

test demo

Now we can demorun up look. First, there are studies under what command line instructions are available, we used --treeto look at:

It may be noted s, server, serve, svr, daemoncommand is new, it contains a set of sub-command to provide daemon-related operations.

Which server startexplain the sub-command is this:

In other words, starttwo deformation subcommand allows you to run the micro at the front desk, which docker in order to facilitate the integration and commissioning services in the IDE micro Objective:

# 在前台运行微服务,而不是进入 daemon 模式
demo run
demo start --foreground
复制代码

For daemon mode, there is no standard specification defines what elements have to ask certain, but in general there are still things evolved. daemon is often referred to in Chinese 守护进程.

Generally daemon mode contains these elements:

  • After the process starts, fork own copy of the operating system running, and tty associated with such copy would be detach, and in addition also has a separate child process environment and process space, or even identity, will not receive other services, interference of other ttys.
  • Keeping a child process pid file in / var / run, which indicates the child's basic state
  • The child to interact with the front desk, in general, SIGHUP signal causes the child process via syscall signals reload the configuration information to complete the restart, yet not shut down the process and restart the process; SIGTERM et signaled the end of the child process service. and many more.
  • The child process log output to / var / log / log files under
Foreground

So, we run demo in the foreground:

Then press CTRL-C to terminate it, you can see the "micro-service" can properly run, can normally self-destruct.

Daemon running

And if we want to run the demo for the daemon, the first thing you need to compile it into an executable file before you can start as a daemon mode.

By vagrant environment, we can see that the daemon is started, and then we stop instruction properly closed.

systemd services running

In support systemd Linux distributions, we can test the micro-service installation to systemd services.

Among them, sudo /vagrant/demo server installcomplete the installation action, after the success of the demo service is installed and ready, and has been pre-set to start automatically with system startup mode.

Then we start it in accordance with the norms of systemd: sudo systemctl start demo@$USER.service.

It is noteworthy that, we will demo installation for wildcard mode, demo can be activated under different user identities. If you want to start it with a dedicated micro-service account, you can use: sudo systemctl start [email protected].

We then sudo systemctl status [email protected]see the demo has been launched successfully, and which has three errors, but they can be ignored, they are trying to build for the purpose of several related folder, so just precautionary instructions. The demo of the Lord is, is ExecStart line indicates a successful startup, and the state is running Active state.

In this case, log / logrus log output, etc. are also forwarded to the log file in /var/log/demo/demo.log.

Then we can also sudo systemctl stop demo@$USER.serviceserve to stop.

summary

Because systemd are not directly supported in macOS in, so for this part of the test is done on the vagrant.

For Windows, you can only use server runmanner running in the foreground, we have no plans to temporarily support the NT Service. But you can do daily development through debugging running in the foreground.

The actual production environment, you can choose centos, ubuntu and other releases, deployments require only sudo demo server installone instruction.

For environmental container, you should use demo server runthis mode to start running in the foreground.

reference

Reproduced in: https: //juejin.im/post/5cf4b2ab6fb9a07eae2a485e

Guess you like

Origin blog.csdn.net/weixin_34221276/article/details/91439566