index.rst 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906
  1. .. _proxy-minion:
  2. =================
  3. Salt Proxy Minion
  4. =================
  5. Proxy minions are a developing Salt feature that enables controlling devices
  6. that, for whatever reason, cannot run a standard salt-minion. Examples include
  7. network gear that has an API but runs a proprietary OS, devices with limited
  8. CPU or memory, or devices that could run a minion, but for security reasons,
  9. will not.
  10. There are some :ref:`proxy modules <all-salt.proxy>` available, but if your device
  11. interface is not currently supported you will most likely have to write the interface
  12. yourself, because there are an infinite number of controllable devices. Fortunately, this
  13. is only as difficult as the actual interface to the proxied device. Devices that have an
  14. existing Python module (PyUSB for example) would be relatively simple to interface.
  15. Code to control a device that has an HTML REST-based interface should be easy. Code to
  16. control your typical housecat would be excellent source material for a PhD thesis.
  17. Salt proxy-minions provide the 'plumbing' that allows device enumeration
  18. and discovery, control, status, remote execution, and state management.
  19. See the :ref:`Proxy Minion Walkthrough <proxy-minion-end-to-end-example>` for an end-to-end
  20. demonstration of a working REST-based proxy minion.
  21. See the :ref:`Proxy Minion SSH Walkthrough <proxy-minion-ssh-end-to-end-example>` for an end-to-end
  22. demonstration of a working SSH proxy minion.
  23. See :ref:`Proxyminion States <proxy-minion-states>` to configure and
  24. run ``salt-proxy`` on a remote minion. Specify all your master side
  25. proxy (pillar) configuration and use this state to remotely configure proxies on one
  26. or more minions.
  27. See :ref:`Proxyminion Beacon <proxy-minion-beacon>` to help
  28. with easy configuration and management of ``salt-proxy`` processes.
  29. New in 2017.7.0
  30. ---------------
  31. The :conf_proxy:`proxy_merge_grains_in_module` configuration variable
  32. introduced in 2016.3, has been changed, defaulting to ``True``.
  33. The connection with the remote device is kept alive by default, when the
  34. module implements the ``alive`` function and :conf_proxy:`proxy_keep_alive`
  35. is set to ``True``. The polling interval is set using the
  36. :conf_proxy:`proxy_keep_alive_interval` option which defaults to 1 minute.
  37. The developers are also able to use the :conf_proxy:`proxy_always_alive`,
  38. when designing a proxy module flexible enough to open the
  39. connection with the remote device only when required.
  40. New in 2016.11.0
  41. ----------------
  42. Proxy minions now support configuration files with names ending in '\*.conf'
  43. and placed in /etc/salt/proxy.d.
  44. Proxy minions can now be configured in /etc/salt/proxy or /etc/salt/proxy.d
  45. instead of just pillar. Configuration format is the same as it would be in pillar.
  46. New in 2016.3
  47. -------------
  48. The deprecated config option ``enumerate_proxy_minions`` has been removed.
  49. As mentioned in earlier documentation, the ``add_proxymodule_to_opts``
  50. configuration variable defaults to ``False`` in this release. This means if you
  51. have proxymodules or other code looking in ``__opts__['proxymodule']`` you
  52. will need to set this variable in your ``/etc/salt/proxy`` file, or
  53. modify your code to use the `__proxy__` injected variable.
  54. The ``__proxyenabled__`` directive now only applies to grains and proxy modules
  55. themselves. Standard execution modules and state modules are not prevented
  56. from loading for proxy minions.
  57. Enhancements in grains processing have made the ``__proxyenabled__`` directive
  58. somewhat redundant in dynamic grains code. It is still required, but best
  59. practices for the ``__virtual__`` function in grains files have changed. It
  60. is now recommended that the ``__virtual__`` functions check to make sure
  61. they are being loaded for the correct proxytype, example below:
  62. .. code-block:: python
  63. def __virtual__():
  64. '''
  65. Only work on proxy
  66. '''
  67. try:
  68. if salt.utils.platform.is_proxy() and \
  69. __opts__['proxy']['proxytype'] == 'ssh_sample':
  70. return __virtualname__
  71. except KeyError:
  72. pass
  73. return False
  74. The try/except block above exists because grains are processed very early
  75. in the proxy minion startup process, sometimes earlier than the proxy
  76. key in the ``__opts__`` dictionary is populated.
  77. Grains are loaded so early in startup that no dunder dictionaries are
  78. present, so ``__proxy__``, ``__salt__``, etc. are not available. Custom
  79. grains located in ``/srv/salt/_grains`` and in the salt install grains
  80. directory can now take a single argument, ``proxy``, that is identical
  81. to ``__proxy__``. This enables patterns like
  82. .. code-block:: python
  83. def get_ip(proxy):
  84. '''
  85. Ask the remote device what IP it has
  86. '''
  87. return {'ip':proxy['proxymodulename.get_ip']()}
  88. Then the grain ``ip`` will contain the result of calling the ``get_ip()`` function
  89. in the proxymodule called ``proxymodulename``.
  90. Proxy modules now benefit from including a function called ``initialized()``. This
  91. function should return ``True`` if the proxy's ``init()`` function has been successfully
  92. called. This is needed to make grains processing easier.
  93. Finally, if there is a function called ``grains`` in the proxymodule, it
  94. will be executed on proxy-minion startup and its contents will be merged with
  95. the rest of the proxy's grains. Since older proxy-minions might have used other
  96. methods to call such a function and add its results to grains, this is config-gated
  97. by a new proxy configuration option called ``proxy_merge_grains_in_module``. This
  98. defaults to ``True`` in the **2017.7.0** release.
  99. New in 2015.8.2
  100. ---------------
  101. *BREAKING CHANGE*: Adding the `proxymodule` variable to __opts__ is deprecated.
  102. The `proxymodule` variable has been moved a new globally-injected variable
  103. called `__proxy__`. A related configuration option called
  104. `add_proxymodule_to_opts` has been added and defaults to `True`. In the next
  105. major release, 2016.3.0, this variable will default to False.
  106. In the meantime, proxies that functioned under 2015.8.0 and .1 should continue
  107. to work under 2015.8.2. You should rework your proxy code to use `__proxy__` as
  108. soon as possible.
  109. The `rest_sample` example proxy minion has been updated to use `__proxy__`.
  110. This change was made because proxymodules are a LazyLoader object, but
  111. LazyLoaders cannot be serialized. `__opts__` gets serialized, and so things
  112. like `saltutil.sync_all` and `state.highstate` would throw exceptions.
  113. Support has been added to Salt's loader allowing custom proxymodules
  114. to be placed in ``salt://_proxy``. Proxy minions that need these modules
  115. will need to be restarted to pick up any changes. A corresponding utility function,
  116. ``saltutil.sync_proxymodules``, has been added to sync these modules to minions.
  117. In addition, a salt.utils helper function called `is_proxy()` was added to make
  118. it easier to tell when the running minion is a proxy minion. **NOTE: This
  119. function was renamed to salt.utils.platform.is_proxy() for the 2018.3.0
  120. release**
  121. New in 2015.8
  122. -------------
  123. Starting with the 2015.8 release of Salt, proxy processes are no longer forked
  124. off from a controlling minion. Instead, they have their own script
  125. ``salt-proxy`` which takes mostly the same arguments that the standard Salt
  126. minion does with the addition of ``--proxyid``. This is the id that the
  127. salt-proxy will use to identify itself to the master. Proxy configurations are
  128. still best kept in Pillar and their format has not changed.
  129. This change allows for better process control and logging. Proxy processes can
  130. now be listed with standard process management utilities (``ps`` from the
  131. command line). Also, a full Salt minion is no longer required (though it is
  132. still strongly recommended) on machines hosting proxies.
  133. Getting Started
  134. ---------------
  135. The following diagram may be helpful in understanding the structure of a Salt
  136. installation that includes proxy-minions:
  137. .. image:: /_static/proxy_minions.png
  138. The key thing to remember is the left-most section of the diagram. Salt's
  139. nature is to have a minion connect to a master, then the master may control
  140. the minion. However, for proxy minions, the target device cannot run a minion.
  141. After the proxy minion is started and initiates its connection to the
  142. device, it connects back to the salt-master and for all intents and purposes
  143. looks like just another minion to the Salt master.
  144. To create support for a proxied device one needs to create four things:
  145. 1. The `proxy_connection_module`_ (located in salt/proxy).
  146. 2. The `grains support code`_ (located in salt/grains).
  147. 3. :ref:`Salt modules <all-salt.modules>` specific to the controlled
  148. device.
  149. 4. :ref:`Salt states <all-salt.states>` specific to the controlled device.
  150. Configuration parameters
  151. ########################
  152. Proxy minions require no configuration parameters in /etc/salt/master.
  153. Salt's Pillar system is ideally suited for configuring proxy-minions
  154. (though they can be configured in /etc/salt/proxy as well). Proxies
  155. can either be designated via a pillar file in pillar_roots, or through an
  156. external pillar. External pillars afford the opportunity for interfacing with
  157. a configuration management system, database, or other knowledgeable system that
  158. that may already contain all the details of proxy targets. To use static files
  159. in pillar_roots, pattern your files after the following examples, which are
  160. based on the diagram above:
  161. ``/srv/pillar/top.sls``
  162. .. code-block:: yaml
  163. base:
  164. net-device1:
  165. - net-device1
  166. net-device2:
  167. - net-device2
  168. net-device3:
  169. - net-device3
  170. i2c-device4:
  171. - i2c-device4
  172. i2c-device5:
  173. - i2c-device5
  174. 433wireless-device6:
  175. - 433wireless-device6
  176. smsgate-device7:
  177. - device7
  178. ``/srv/pillar/net-device1.sls``
  179. .. code-block:: yaml
  180. proxy:
  181. proxytype: networkswitch
  182. host: 172.23.23.5
  183. username: root
  184. passwd: letmein
  185. ``/srv/pillar/net-device2.sls``
  186. .. code-block:: yaml
  187. proxy:
  188. proxytype: networkswitch
  189. host: 172.23.23.6
  190. username: root
  191. passwd: letmein
  192. ``/srv/pillar/net-device3.sls``
  193. .. code-block:: yaml
  194. proxy:
  195. proxytype: networkswitch
  196. host: 172.23.23.7
  197. username: root
  198. passwd: letmein
  199. ``/srv/pillar/i2c-device4.sls``
  200. .. code-block:: yaml
  201. proxy:
  202. proxytype: i2c_lightshow
  203. i2c_address: 1
  204. ``/srv/pillar/i2c-device5.sls``
  205. .. code-block:: yaml
  206. proxy:
  207. proxytype: i2c_lightshow
  208. i2c_address: 2
  209. ``/srv/pillar/433wireless-device6.sls``
  210. .. code-block:: yaml
  211. proxy:
  212. proxytype: 433mhz_wireless
  213. ``/srv/pillar/smsgate-device7.sls``
  214. .. code-block:: yaml
  215. proxy:
  216. proxytype: sms_serial
  217. deventry: /dev/tty04
  218. Note the contents of each minioncontroller key may differ widely based on
  219. the type of device that the proxy-minion is managing.
  220. In the above example
  221. - net-devices 1, 2, and 3 are network switches that have a management
  222. interface available at a particular IP address.
  223. - i2c-devices 4 and 5 are very low-level devices controlled over an i2c bus.
  224. In this case the devices are physically connected to machine
  225. 'minioncontroller2', and are addressable on the i2c bus at their respective
  226. i2c addresses.
  227. - 433wireless-device6 is a 433 MHz wireless transmitter, also physically connected to
  228. minioncontroller2
  229. - smsgate-device7 is an SMS gateway connected to machine minioncontroller3 via a
  230. serial port.
  231. Because of the way pillar works, each of the salt-proxy processes that fork off the
  232. proxy minions will only see the keys specific to the proxies it will be
  233. handling.
  234. Proxies can be configured in /etc/salt/proxy or with files in /etc/salt/proxy.d as of
  235. Salt's 2016.11.0 release.
  236. Also, in general, proxy-minions are lightweight, so the machines that run them
  237. could conceivably control a large number of devices. To run more than one proxy from
  238. a single machine, simply start an additional proxy process with ``--proxyid``
  239. set to the id to which you want the proxy to bind.
  240. It is possible for the proxy services to be spread across
  241. many machines if necessary, or intentionally run on machines that need to
  242. control devices because of some physical interface (e.g. i2c and serial above).
  243. Another reason to divide proxy services might be security. In more secure
  244. environments only certain machines may have a network path to certain devices.
  245. .. _proxy_connection_module:
  246. Proxymodules
  247. ############
  248. A proxy module encapsulates all the code necessary to interface with a device.
  249. Proxymodules are located inside the salt.proxy module, or can be placed in
  250. the ``_proxy`` directory in your file_roots (default is ``/srv/salt/_proxy``.
  251. At a minimum a proxymodule object must implement the following functions:
  252. ``__virtual__()``: This function performs the same duty that it does for other
  253. types of Salt modules. Logic goes here to determine if the module can be
  254. loaded, checking for the presence of Python modules on which the proxy depends.
  255. Returning ``False`` will prevent the module from loading.
  256. ``init(opts)``: Perform any initialization that the device needs. This is
  257. a good place to bring up a persistent connection to a device, or authenticate
  258. to create a persistent authorization token.
  259. ``initialized()``: Returns True if ``init()`` was successfully called.
  260. ``shutdown()``: Code to cleanly shut down or close a connection to
  261. a controlled device goes here. This function must exist, but can contain only
  262. the keyword ``pass`` if there is no shutdown logic required.
  263. ``ping()``: While not required, it is highly recommended that this function also
  264. be defined in the proxymodule. The code for ``ping`` should contact the
  265. controlled device and make sure it is really available.
  266. ``alive(opts)``: Another optional function, it is used together with the
  267. ``proxy_keep_alive`` option (default: ``True``). This function should
  268. return a boolean value corresponding to the state of the connection.
  269. If the connection is down, will try to restart (``shutdown``
  270. followed by ``init``). The polling frequency is controlled using
  271. the ``proxy_keep_alive_interval`` option, in minutes.
  272. ``grains()``: Rather than including grains in /srv/salt/_grains or in
  273. the standard install directories for grains, grains can be computed and
  274. returned by this function. This function will be called automatically
  275. if ``proxy_merge_grains_in_module`` is set to ``True`` in /etc/salt/proxy.
  276. This variable defaults to ``True`` in the release code-named *2017.7.0*.
  277. Pre 2015.8 the proxymodule also must have an ``id()`` function. 2015.8 and following don't use
  278. this function because the proxy's id is required on the command line.
  279. Here is an example proxymodule used to interface to a *very* simple REST
  280. server. Code for the server is in the `salt-contrib GitHub repository`_.
  281. .. _`salt-contrib GitHub repository`: https://github.com/saltstack/salt-contrib/tree/master/proxyminion_rest_example
  282. This proxymodule enables "service" enumeration, starting, stopping, restarting,
  283. and status; "package" installation, and a ping.
  284. .. code-block:: python
  285. # -*- coding: utf-8 -*-
  286. '''
  287. This is a simple proxy-minion designed to connect to and communicate with
  288. the bottle-based web service contained in https://github.com/saltstack/salt-contrib/tree/master/proxyminion_rest_example
  289. '''
  290. from __future__ import absolute_import
  291. # Import python libs
  292. import logging
  293. import salt.utils.http
  294. HAS_REST_EXAMPLE = True
  295. # This must be present or the Salt loader won't load this module
  296. __proxyenabled__ = ['rest_sample']
  297. # Variables are scoped to this module so we can have persistent data
  298. # across calls to fns in here.
  299. GRAINS_CACHE = {}
  300. DETAILS = {}
  301. # Want logging!
  302. log = logging.getLogger(__file__)
  303. # This does nothing, it's here just as an example and to provide a log
  304. # entry when the module is loaded.
  305. def __virtual__():
  306. '''
  307. Only return if all the modules are available
  308. '''
  309. log.debug('rest_sample proxy __virtual__() called...')
  310. return True
  311. def _complicated_function_that_determines_if_alive():
  312. return True
  313. # Every proxy module needs an 'init', though you can
  314. # just put DETAILS['initialized'] = True here if nothing
  315. # else needs to be done.
  316. def init(opts):
  317. log.debug('rest_sample proxy init() called...')
  318. DETAILS['initialized'] = True
  319. # Save the REST URL
  320. DETAILS['url'] = opts['proxy']['url']
  321. # Make sure the REST URL ends with a '/'
  322. if not DETAILS['url'].endswith('/'):
  323. DETAILS['url'] += '/'
  324. def alive(opts):
  325. '''
  326. This function returns a flag with the connection state.
  327. It is very useful when the proxy minion establishes the communication
  328. via a channel that requires a more elaborated keep-alive mechanism, e.g.
  329. NETCONF over SSH.
  330. '''
  331. log.debug('rest_sample proxy alive() called...')
  332. return _complicated_function_that_determines_if_alive()
  333. def initialized():
  334. '''
  335. Since grains are loaded in many different places and some of those
  336. places occur before the proxy can be initialized, return whether
  337. our init() function has been called
  338. '''
  339. return DETAILS.get('initialized', False)
  340. def grains():
  341. '''
  342. Get the grains from the proxied device
  343. '''
  344. if not DETAILS.get('grains_cache', {}):
  345. r = salt.utils.http.query(DETAILS['url']+'info', decode_type='json', decode=True)
  346. DETAILS['grains_cache'] = r['dict']
  347. return DETAILS['grains_cache']
  348. def grains_refresh():
  349. '''
  350. Refresh the grains from the proxied device
  351. '''
  352. DETAILS['grains_cache'] = None
  353. return grains()
  354. def fns():
  355. return {'details': 'This key is here because a function in '
  356. 'grains/rest_sample.py called fns() here in the proxymodule.'}
  357. def service_start(name):
  358. '''
  359. Start a "service" on the REST server
  360. '''
  361. r = salt.utils.http.query(DETAILS['url']+'service/start/'+name, decode_type='json', decode=True)
  362. return r['dict']
  363. def service_stop(name):
  364. '''
  365. Stop a "service" on the REST server
  366. '''
  367. r = salt.utils.http.query(DETAILS['url']+'service/stop/'+name, decode_type='json', decode=True)
  368. return r['dict']
  369. def service_restart(name):
  370. '''
  371. Restart a "service" on the REST server
  372. '''
  373. r = salt.utils.http.query(DETAILS['url']+'service/restart/'+name, decode_type='json', decode=True)
  374. return r['dict']
  375. def service_list():
  376. '''
  377. List "services" on the REST server
  378. '''
  379. r = salt.utils.http.query(DETAILS['url']+'service/list', decode_type='json', decode=True)
  380. return r['dict']
  381. def service_status(name):
  382. '''
  383. Check if a service is running on the REST server
  384. '''
  385. r = salt.utils.http.query(DETAILS['url']+'service/status/'+name, decode_type='json', decode=True)
  386. return r['dict']
  387. def package_list():
  388. '''
  389. List "packages" installed on the REST server
  390. '''
  391. r = salt.utils.http.query(DETAILS['url']+'package/list', decode_type='json', decode=True)
  392. return r['dict']
  393. def package_install(name, **kwargs):
  394. '''
  395. Install a "package" on the REST server
  396. '''
  397. cmd = DETAILS['url']+'package/install/'+name
  398. if kwargs.get('version', False):
  399. cmd += '/'+kwargs['version']
  400. else:
  401. cmd += '/1.0'
  402. r = salt.utils.http.query(cmd, decode_type='json', decode=True)
  403. return r['dict']
  404. def fix_outage():
  405. r = salt.utils.http.query(DETAILS['url']+'fix_outage')
  406. return r
  407. def uptodate(name):
  408. '''
  409. Call the REST endpoint to see if the packages on the "server" are up to date.
  410. '''
  411. r = salt.utils.http.query(DETAILS['url']+'package/remove/'+name, decode_type='json', decode=True)
  412. return r['dict']
  413. def package_remove(name):
  414. '''
  415. Remove a "package" on the REST server
  416. '''
  417. r = salt.utils.http.query(DETAILS['url']+'package/remove/'+name, decode_type='json', decode=True)
  418. return r['dict']
  419. def package_status(name):
  420. '''
  421. Check the installation status of a package on the REST server
  422. '''
  423. r = salt.utils.http.query(DETAILS['url']+'package/status/'+name, decode_type='json', decode=True)
  424. return r['dict']
  425. def ping():
  426. '''
  427. Is the REST server up?
  428. '''
  429. r = salt.utils.http.query(DETAILS['url']+'ping', decode_type='json', decode=True)
  430. try:
  431. return r['dict'].get('ret', False)
  432. except Exception:
  433. return False
  434. def shutdown(opts):
  435. '''
  436. For this proxy shutdown is a no-op
  437. '''
  438. log.debug('rest_sample proxy shutdown() called...')
  439. .. _grains support code:
  440. Grains are data about minions. Most proxied devices will have a paltry amount
  441. of data as compared to a typical Linux server. By default, a proxy minion will
  442. have several grains taken from the host. Salt core code requires values for ``kernel``,
  443. ``os``, and ``os_family``--all of these are forced to be ``proxy`` for proxy-minions.
  444. To add others to your proxy minion for
  445. a particular device, create a file in salt/grains named [proxytype].py and place
  446. inside it the different functions that need to be run to collect the data you
  447. are interested in. Here's an example. Note the function below called ``proxy_functions``.
  448. It demonstrates how a grains function can take a single argument, which will be
  449. set to the value of ``__proxy__``. Dunder variables are not yet injected into Salt processes
  450. at the time grains are loaded, so this enables us to get a handle to the proxymodule so we
  451. can cross-call the functions therein used to commmunicate with the controlled device.
  452. Note that as of 2016.3, grains values can also be calculated in a function called ``grains()``
  453. in the proxymodule itself. This might be useful if a proxymodule author wants to keep
  454. all the code for the proxy interface in the same place instead of splitting it between
  455. the proxy and grains directories.
  456. This function will only be called automatically if the configuration variable
  457. ``proxy_merge_grains_in_module`` is set to True in the proxy configuration file
  458. (default ``/etc/salt/proxy``). This variable defaults to ``True`` in the
  459. release code-named *2017.7.0*.
  460. .. code: python::
  461. # -*- coding: utf-8 -*-
  462. '''
  463. Generate baseline proxy minion grains
  464. '''
  465. from __future__ import absolute_import
  466. import salt.utils.platform
  467. __proxyenabled__ = ['rest_sample']
  468. __virtualname__ = 'rest_sample'
  469. def __virtual__():
  470. try:
  471. if salt.utils.platform.is_proxy() and __opts__['proxy']['proxytype'] == 'rest_sample':
  472. return __virtualname__
  473. except KeyError:
  474. pass
  475. return False
  476. def kernel():
  477. return {'kernel': 'proxy'}
  478. def proxy_functions(proxy):
  479. '''
  480. The loader will execute functions with one argument and pass
  481. a reference to the proxymodules LazyLoader object. However,
  482. grains sometimes get called before the LazyLoader object is setup
  483. so `proxy` might be None.
  484. '''
  485. if proxy:
  486. return {'proxy_functions': proxy['rest_sample.fns']()}
  487. def os():
  488. return {'os': 'RestExampleOS'}
  489. def location():
  490. return {'location': 'In this darn virtual machine. Let me out!'}
  491. def os_family():
  492. return {'os_family': 'proxy'}
  493. def os_data():
  494. return {'os_data': 'funkyHttp release 1.0.a.4.g'}
  495. The __proxyenabled__ directive
  496. ------------------------------
  497. In previous versions of Salt the ``__proxyenabled__`` directive controlled
  498. loading of all Salt modules for proxies (e.g. grains, execution modules, state
  499. modules). From 2016.3 on, the only modules that respect ``__proxyenabled__``
  500. are grains and proxy modules. These modules need to be told which proxy they
  501. work with.
  502. ``__proxyenabled__`` is a list, and can contain a single '*' to indicate
  503. a grains module works with all proxies.
  504. Example from ``salt/grains/rest_sample.py``:
  505. .. code-block:: python
  506. # -*- coding: utf-8 -*-
  507. '''
  508. Generate baseline proxy minion grains
  509. '''
  510. from __future__ import absolute_import
  511. import salt.utils.platform
  512. __proxyenabled__ = ['rest_sample']
  513. __virtualname__ = 'rest_sample'
  514. def __virtual__():
  515. try:
  516. if salt.utils.platform.is_proxy() and __opts__['proxy']['proxytype'] == 'rest_sample':
  517. return __virtualname__
  518. except KeyError:
  519. pass
  520. return False
  521. .. toctree::
  522. :maxdepth: 2
  523. :glob:
  524. demo
  525. SSH Proxymodules
  526. ----------------
  527. See above for a general introduction to writing proxy modules.
  528. All of the guidelines that apply to REST are the same for SSH.
  529. This sections specifically talks about the SSH proxy module and
  530. explains the working of the example proxy module ``ssh_sample``.
  531. Here is a simple example proxymodule used to interface to a device over SSH.
  532. Code for the SSH shell is in the `salt-contrib GitHub repository`_.
  533. This proxymodule enables "package" installation.
  534. .. code-block:: python
  535. # -*- coding: utf-8 -*-
  536. '''
  537. This is a simple proxy-minion designed to connect to and communicate with
  538. a server that exposes functionality via SSH.
  539. This can be used as an option when the device does not provide
  540. an api over HTTP and doesn't have the python stack to run a minion.
  541. '''
  542. from __future__ import absolute_import
  543. # Import python libs
  544. import salt.utils.json
  545. import logging
  546. # Import Salt's libs
  547. from salt.utils.vt_helper import SSHConnection
  548. from salt.utils.vt import TerminalException
  549. # This must be present or the Salt loader won't load this module
  550. __proxyenabled__ = ['ssh_sample']
  551. DETAILS = {}
  552. # Want logging!
  553. log = logging.getLogger(__file__)
  554. # This does nothing, it's here just as an example and to provide a log
  555. # entry when the module is loaded.
  556. def __virtual__():
  557. '''
  558. Only return if all the modules are available
  559. '''
  560. log.info('ssh_sample proxy __virtual__() called...')
  561. return True
  562. def init(opts):
  563. '''
  564. Required.
  565. Can be used to initialize the server connection.
  566. '''
  567. try:
  568. DETAILS['server'] = SSHConnection(host=__opts__['proxy']['host'],
  569. username=__opts__['proxy']['username'],
  570. password=__opts__['proxy']['password'])
  571. # connected to the SSH server
  572. out, err = DETAILS['server'].sendline('help')
  573. except TerminalException as e:
  574. log.error(e)
  575. return False
  576. def shutdown(opts):
  577. '''
  578. Disconnect
  579. '''
  580. DETAILS['server'].close_connection()
  581. def parse(out):
  582. '''
  583. Extract json from out.
  584. Parameter
  585. out: Type string. The data returned by the
  586. ssh command.
  587. '''
  588. jsonret = []
  589. in_json = False
  590. for ln_ in out.split('\n'):
  591. if '{' in ln_:
  592. in_json = True
  593. if in_json:
  594. jsonret.append(ln_)
  595. if '}' in ln_:
  596. in_json = False
  597. return salt.utils.json.loads('\n'.join(jsonret))
  598. def package_list():
  599. '''
  600. List "packages" by executing a command via ssh
  601. This function is called in response to the salt command
  602. ..code-block::bash
  603. salt target_minion pkg.list_pkgs
  604. '''
  605. # Send the command to execute
  606. out, err = DETAILS['server'].sendline('pkg_list')
  607. # "scrape" the output and return the right fields as a dict
  608. return parse(out)
  609. def package_install(name, **kwargs):
  610. '''
  611. Install a "package" on the REST server
  612. '''
  613. cmd = 'pkg_install ' + name
  614. if 'version' in kwargs:
  615. cmd += '/'+kwargs['version']
  616. else:
  617. cmd += '/1.0'
  618. # Send the command to execute
  619. out, err = DETAILS['server'].sendline(cmd)
  620. # "scrape" the output and return the right fields as a dict
  621. return parse(out)
  622. def package_remove(name):
  623. '''
  624. Remove a "package" on the REST server
  625. '''
  626. cmd = 'pkg_remove ' + name
  627. # Send the command to execute
  628. out, err = DETAILS['server'].sendline(cmd)
  629. # "scrape" the output and return the right fields as a dict
  630. return parse(out)
  631. Connection Setup
  632. ################
  633. The ``init()`` method is responsible for connection setup. It uses the ``host``, ``username`` and ``password`` config variables defined in the pillar data. The ``prompt`` kwarg can be passed to ``SSHConnection`` if your SSH server's prompt differs from the example's prompt ``(Cmd)``. Instantiating the ``SSHConnection`` class establishes an SSH connection to the ssh server (using Salt VT).
  634. Command execution
  635. #################
  636. The ``package_*`` methods use the SSH connection (established in ``init()``) to send commands out to the SSH server. The ``sendline()`` method of ``SSHConnection`` class can be used to send commands out to the server. In the above example we send commands like ``pkg_list`` or ``pkg_install``. You can send any SSH command via this utility.
  637. Output parsing
  638. ##############
  639. Output returned by ``sendline()`` is a tuple of strings representing the stdout and the stderr respectively. In the toy example shown we simply scrape the output and convert it to a python dictionary, as shown in the ``parse`` method. You can tailor this method to match your parsing logic.
  640. Connection teardown
  641. ###################
  642. The ``shutdown`` method is responsible for calling the ``close_connection()`` method of ``SSHConnection`` class. This ends the SSH connection to the server.
  643. For more information please refer to class `SSHConnection`_.
  644. .. toctree::
  645. :maxdepth: 2
  646. :glob:
  647. ssh
  648. beacon
  649. state
  650. ../tutorials/esxi_proxy_minion
  651. .. _SSHConnection: https://github.com/saltstack/salt/blob/b8271c7512da7e048019ee26422be9e7d6b795ab/salt/utils/vt_helper.py#L28