Salt API Learning Record (i)

Source: Internet
Author: User
Tags glob

Now finally began to learn the salt API, some small excitement ah, we execute the command, the background is how to deal with, what happened, I have a strong curiosity about everything ah.


These are the APIs that correspond to the Saltstack command:

Salt--->salt.client.localclient salt-cp--->salt.cli.cp.saltcp salt-key--->salt.key.keyclisalt-call--- >salt.cli.caller.callersalt-run--->salt.runner.runner salt-ssh--->salt.client.ssh.ssh


The first thing to learn is the Salt command corresponding to the api:salt.client.LocalClient.

First, let's explain how salt is handled with a simple command.

Salt ' * ' test.ping

This first invokes the Salt.cli.SaltCMD class instantiation of an object

salt/cli/__init__.py

Class saltcmd (parsers. Saltcmdoptionparser):     def run (self):         ...    #  set the         #  of the log Call salt.client.localclient api        try:             local = salt.client.localclient (self.get_config_file _path ())         except SaltClientError as exc:             self.exit (2,  ' {0}\n '. Format (exc))              return                  # self.options is a collection of command-line arguments          #  parsing command line parameters via Optparse module          # ,salt -b        if self.options.batch:   of batch execution           batch = salt.cli.batch.batch (self.config )             # printing the output  is already taken care of in run ()  itself             for res in batch.run ():                 pass          else:             #   handles parameters that need to be passed, Kwargs is a parameter dictionary, and is passed using **kwargs              ....                           #  asynchronous execution without waiting for results to return              if self.config[' Async ']:                 jid = local.cmd_async (**kwargs)  #  return jid                 print (' Executed  command with job id: {0} '. Format (Jid))                  return             try:                 #  Next is the main logic                  #  Default Call Cmd_cli method returns generator, looping output                  #&nbSP; there's a get_cli_event_returns method in Cmd_cli to call gather_job_info         .        # gather_job_info is going to trigger Saltutil.find_job mission                  #  is to verify that the operation is still executing                  if local:                     if  self.options.subset: #  Select several minion call cmd_cli                         cmd_func  = local.cmd_subset                         kwargs[' Sub '] = self.options.subset                          kwargs[' CLI '] = true                     else:                         cmd_func =  local.cmd_cli                     if self.options.static:                         if  self.options.verbose:                             kwargs[' verbose '] =  true                         full_ret = local.cmd_full_return (**kwargs)                          ret, out  = self._format_ret (Full_ret)                          self._output_ret (Ret, out)                      elif self.config[' fun '] ==  ' Sys.doc ':                         ret  = {}                         out =  '                          for full_ret in  LOCAL.CMD_CLI (**kwargs):                             ret_, out =  self._format_ret (Full_ret)                              ret.update (ret_)                          self._output_ret (ret, out)                      else:                         if  self.options.verbose:                             kwargs[' verbose '] =  True                         for full_ret in cmd_func (**kwargs):                              ret, out = self._format_ret (Full_ret)                               self._output_ret (Ret, out)

From the code snippet above, we know that Saltcmd is primarily parsing command-line arguments, using parameters to determine which method to call Salt.client.LocalClient, by default calling the Cmd_cli method.

So the real processing operation is the Localclient class, localclient mainly contains the method is cmd_*,get_*_returns,gather_job_info,run_job,pub.

First of all, learn how to use it. It's Ipython learning.

: Import salt.client# Initializes the instance, the parameter must be the configuration file path of master: local = salt.client.LocalClient ('/opt/app/salt/etc/master ') # cmd (TGT, Fun,arg,expr_form= ' Glob ',...): Local.cmd (' 192.168.110.132 ', ' test.ping ') #返回的结果: {' 192.168.110.132 ': true}# Local.cmd_async (' 192.168.110.132 ', ' test.ping ') # return result is a Jid: ' 20140813164423244819 '

The CMD code snippet is as follows:

Def cmd (             self,             tgt,     # salt  target  ' 192.168.110.132 '   ' Os:linux '              fun,     #  Execution Module  test.ping             arg= (),  #  module Parameters              timeout=None,             expr_form= ' Glob ', type of  # target,             ret= ',    # returners             kwarg=None,             **kwargs):    &NBSp; arg = condition_kwarg (arg, kwarg)  #  combine parameters into a single list       # run_job return result form:      #{' Jid ':  ' 20131219215650131543 ',  ' Minions ':  [' Jerry ', ' SDFSD ',]}     pub_data = self.run_job (tgt,         fun,        arg,         expr_form,        ret,         timeout,        **kwargs)       if not pub_data:        return pub_ data          #  need to wait timeout time before returning results       return self.get_returns (pub_data[' Jid '],        pub_ data[' Minions '],        self._get_timeout (timeout)) 

Other cmd_* forms are similar, will call the Run_job method, but return the result is not the same, such as Cmd_async is executed asynchronously, do not wait, directly return a jid. CMD_CLI returns a generator and calls the

Gather_job_info method to trigger the Saltutil.find_job task. CMD_CLI is the default processing method .


The Run_job code is as follows:

# run_job return result form: # {' Jid ':  ' 20131219215650131543 ',  ' Minions ':  [' Jerry ', ' SDFSD ',]}def  run_job (            self,             tgt,             fun,            arg= (),             expr_form= ' Glob ',             ret= ',             timeout=None,             Kwarg=none,            **kwargs):      arg = condition_kwarg (Arg, kwarg)      jid =   '  #  This can be customized JID&NBsp;    # subscribe to all events and subscribe as  early as possible     self.event.subscribe (Jid)      #  Subscribe to Event     pub_data = self.pub (             tgt,             fun,            arg,             expr_form,             ret,            jid= Jid,            timeout=self._get_timeout (Timeout) ,             **kwargs)        return self._cHeck_pub_data (Pub_data) 


The pub code snippet is as follows:

#payload_kwargs信息如下: {' cmd ':  ' publish ', ' TGT ':  tgt, ' fun ':  fun, ' arg ':  arg, ' key ':  Self.key, ' tgt_type ':  expr_form, ' ret ':  ret, ' Jid ':  jid, ' user ': ' Root '}master_uri =  ' TCP ://'  + salt.utils.ip_bracket (self.opts[' interface ')  +      ': '  +  str (self.opts[' Ret_port ') sreq = salt.transport.channel.factory (self.opts, crypt= ' Clear ',  master_uri=master_uri) #  uses ZEROMQ communication, using rep/req socket# payload information #{' enc ':  ' clear ', #   ' Load ':  {' Jid ':  ' 20140807004713142582 ',#   ' Minions ':  [' 192.168.79.47 ',  ' 192.168.110.132 ',  ' 192.168.110.133 ']}}try:    payload = sreq.send (payload_ Kwargs) Except saltreqtimeouterror:      log.error (             ' Salt request timed out. if this error  persists,  ' &NBsp;            ' worker_threads may need  to be increased. '        )       return {}


Speaking so much, now summarize the next process.

Salt ' * ' test.ping process, similar to the process of makeup remover, see the final face.

1, Call saltcmd processing command line arguments, determine which method to call Localclient (default is CMD_CLI)

2, call localclient processing

3, the default call Cmd_cli method processing

4. Call the Run_job method to handle

5, call pub method processing

6. Using ZMQ req/req Socket communication

7, call Gather_job_info trigger Saltutil.find_job task

8, a layer of return results


From this process, the final call is the pub method.

Local.cmd_async (' 192.168.110.132 ', ' test.ping ') local.pub (' 192.168.110.132 ', ' test.ping ')


This is where the salt command-line API is explained.

This article is from the "Fly World" blog, please be sure to keep this source http://liuping0906.blog.51cto.com/2516248/1539978

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.