Commit Graph

262 Commits (232aaf5c95bc1c432a407418aa0d05ebc0473fb3)

Author SHA1 Message Date
David Wilson daa9cfd0a8 ansible: MITOGEN_DUMP_THREAD_STACKS for mux process too 6 years ago
David Wilson d9087c510b ansible: move FileService into mitogen.service. 6 years ago
David Wilson 9cb3878f3f nsible: remove unused master import 6 years ago
David Wilson fdbd954113 ansible: preload built-in modules in ModuleDepScanner.
For "ansible -m setup" over a 25ms link, avoids 65 roundtrips and
reduces runtime from 5.7s to 4.1s (-28%).

For "ansible -m setup" over a simulated 250 ms link, reduces runtime
from m27.015s to 0m8.254s (-69%).
6 years ago
David Wilson 8d45e609ee ansible: preload always-requested modules.
Avoid 9 roundtrips during setup. In combination with previous change,
reduces 'ansible -m stat' execution over 25ms link from 3.7s to 3.07s.

1,3d0
< _on_get_module('ansible')
< _on_get_module('ansible.module_utils')
< _on_get_module('ansible.module_utils.basic')
69,74d65
< _on_get_module('ansible.module_utils.json_utils')
< _on_get_module('ansible.release')
< _on_get_module('ansible_mitogen')
< _on_get_module('ansible_mitogen.runner')
< _on_get_module('ansible_mitogen.target')
< _on_get_module('mitogen.fork')
6 years ago
David Wilson a578250bfb ansible: remove indirect master.py imports.
Avoids sending 10 modules:

77d76
< _send_load_module(mitogen.ssh.Stream(u'ssh.localhost'), 'ansible_mitogen.module_finder')
79d77
< _send_load_module(mitogen.ssh.Stream(u'ssh.localhost'), 'ansible_mitogen.services')
81,84d78
< _send_load_module(mitogen.ssh.Stream(u'ssh.localhost'), 'mitogen.compat')
< _send_load_module(mitogen.ssh.Stream(u'ssh.localhost'), 'mitogen.compat.collections')
< _send_load_module(mitogen.ssh.Stream(u'ssh.localhost'), 'mitogen.compat.functools')
< _send_load_module(mitogen.ssh.Stream(u'ssh.localhost'), 'mitogen.compat.tokenize')
86,87d79
< _send_load_module(mitogen.ssh.Stream(u'ssh.localhost'), 'mitogen.master')
< _send_load_module(mitogen.ssh.Stream(u'ssh.localhost'), 'mitogen.minify')
89,90d80
< _send_load_module(mitogen.ssh.Stream(u'ssh.localhost'), 'mitogen.select')
< _send_load_module(mitogen.ssh.Stream(u'ssh.localhost'), 'mitogen.service')
6 years ago
David Wilson 3b0addcfb0 service: v2. Closes #213 6 years ago
David Wilson ddf28987a0 master: split Select() into new module to reduce wire size.
service.py currently imports master.py(+parent.py) just to get Select().
6 years ago
David Wilson 1eb5c20f57 ansible: add dummy init.pys so setup.py find_packages() DTRT. 6 years ago
David Wilson bb61745a1a issue #217: pass through non-custom module utils to regular importer.
This may come back to bite later, but in the meantime it avoids shipping
up to 12KiB of junk metadata for every single task invocation.

For detachment (aka. async), we must ensure the target has two types of
preloads completed (modules and module_utils files) before detaching.
6 years ago
David Wilson 30034877a5 issue #217: ansible: working, if extremely inefficient implementation 6 years ago
David Wilson 81b62d9a1a issue #217: ansible: beginnings of ModuleDepService. 6 years ago
David Wilson 0f8190eff6 issue #217: ansible: working module_finder.py 6 years ago
David Wilson 6a17042020 issue #217: ansible: merge duplicate ReplacerPlanner. 6 years ago
David Wilson bd2cc0830c Enable unidirectional routing in Ansible; closes #132. 6 years ago
David Wilson f96c552f87 issue #217: initial module scanner code.
This is sketch code, it's being done separately from mitogen.master.* to
begin with to avoid breaking what's there.
6 years ago
David Wilson 2ad0d0521d ansible: reload /etc/resolv.conf for each task.
The OpenShift installer modifies /etc/resolv.conf then tests the new
resolver configuration, however, there was no mechanism to reload
resolv.conf in our reuseable interpreter.

https://github.com/openshift/openshift-ansible/blob/release-3.9/roles/openshift_web_console/tasks/install.yml#L137

This inserts an explicit call to res_init() for every new style
invocation, with an approximate cost of ~1usec on Linux since glibc
verifies resolv.conf has changed before reloading it.

There is little to be done for users of the thread-safe resolver APIs,
their state is hidden from us. If bugs like that manifest, whack-a-mole
style 'del sys.modules[thatmod]' patches may suffice.
6 years ago
David Wilson 49eae23f92 issue #218: ansibe: use Secret and Blob types. 6 years ago
David Wilson 69f58875c8 tests: more ansible fixes from recent brakage. 6 years ago
David Wilson ad1f624750 ansible: document and rearrange Runner params.
Move emulate_tty to where it's used.
6 years ago
David Wilson 1186b927f9 ansible: remove seemingly unused raw_params
Traced git log all the way back to beginning of time, and checked
Ansible versions starting Jan 2016. Zero clue where this came from, but
the convention suggests it came from Ansible at some point.
6 years ago
David Wilson f737ff5276 ansible: stop passing through remote_tmp variable
Ansiballz does not use remote_tmp so neither should we, per #239.
6 years ago
David Wilson f9e1905ec6 issue #199: ansible: stop writing temp files for new style modules
While adding support for non-new style module types, NewStyleRunner
began writing modules to a temporary file, and sys.argv was patched to
actually include the script filename. The argv change was never required
to fix any particular bug, and a search of the standard modules reveals
no argv users. Update argv[0] to be '', like an interactive interpreter
would have.

While fixing #210, new style runner began setting __file__ to the
temporary file path in order to allow apt.py to discover the Ansiballz
temporary directory. 5 out of 1,516 standard modules follow this
pattern, but in each case, none actually attempt to access __file__,
they just call dirname on it. Therefore do not write the contents of
file, simply set it to the path as it would exist, within a real
temporary directory.

Finally move temporary directory creation out of runner and into target.
Now a single directory exists for the duration of a run, and is emptied
by runner.py as necessary after each task invocation.

This could be further extended to stop rewriting non-new-style modules
in a with_items loop, but that's another step.

Finally the last bullet point in the documentation almost isn't a lie
again.
6 years ago
David Wilson 1bc08323bf ansible: more compatible module script naming. 6 years ago
David Wilson 8bd34e1e28 ansible: gracefully report connection timeouts as StreamError. 6 years ago
David Wilson 4d1c6d2101 issue #127: ssh: reasonable solution to host key checking.
Ideally it would be possible to specify a callback function, but this is
not possible for proxied connections. So simply provide the 3 most
useful modes, defaulting to the most secure.

Closes #127. Closes #134.
6 years ago
David Wilson 9cc8b21a07 ansible: missing mitogen_su module. 6 years ago
David Wilson 78c401ba4d ansible: support su become method. 6 years ago
David Wilson 3203846708 issue #239: ansible: ignore remote_tmp in new style runner. 6 years ago
David Wilson 94e048a2e5 ansible: ensure FileService uses exact CHUNK_SIZE multiple
9.8% throughput increase with sudo.
6 years ago
David Wilson dafe12b315 ansible: fix AnsibleUnicode crash when processing "~username". 6 years ago
David Wilson e1a3cea2f9 ansible: FileService: don't send empty last chunk 6 years ago
David Wilson 2a56c672ca ansible: FileService docstring updates. 6 years ago
David Wilson f5d22a3ca1 core: support deleting handlers, make Receiver.close() unregister 6 years ago
David Wilson 69e5902e61 issue #212: support explicit acknowledgements in FileService. 6 years ago
David Wilson b0309b539c ansible: disable interpreter recycling for connections.
Must explicitly specify enable_lru=True in ContextService.get() to
trigger recycling.
6 years ago
David Wilson 65e6a44fe7 docs: add links. 6 years ago
David Wilson 90f7b4baea ansible: stub plugin documentation. 6 years ago
David Wilson c85a5b6446 ansible: make call timing more readable 6 years ago
David Wilson bba2a42e44 ansible: add mitogen_sudo method, split out connection subclasses.
Slowly moving towards real implementations in those files.
6 years ago
David Wilson 0a9126c510 ansible: connection plugins missing from previous commit. 6 years ago
David Wilson 7c5bbc5168 setns: support changing user.
To match existing third party plugin.
6 years ago
David Wilson 003f30b5a9 issue #226: test fixes. 6 years ago
David Wilson 6edb3f165d ansible: avoid a race during shutdown. 6 years ago
David Wilson 780b63520f issue #226: don't attempt to fchmod() a pathname 6 years ago
David Wilson 219a202a82 issue #226: ansible: file transfer improvements
* put_data() supports setting mode and times.
* put_file() refuses to copy non-regular files (sockets, FIFOs).
* put_file() saves one RTT for <32KiB files by using put_data() and
  embedding file content in argument list.
* FileService returns dict with size/mode/owner/group/mtime/atime.
* FileService refuses to copy non-regular files.
* transfer_file() preserves file mode.
* transfer_file() preserves atime/mtime.
* transfer_file() optionally preserves ownership.
* transfer_file() optionally calls fsync().
* transfer_file() uses unique temporary file name to avoid conflicting
  with parallel transfers.
* transfer_file() ensures temporary file is deleted on any error.
* write_path() writes to a temporary file and deletes it on failure.
* write_path() uses unique temporary file name to avoid conflicting
  with parallel transfers.
* write_path() supports setting symbolic owner/group.
* write_path() optionally calls fsync().
* write_path() supports setting symbolic mode/mtime/atime.

Closes #226, #227, #229
6 years ago
David Wilson b5be0fd65b ansible: log _get_file() timings. 6 years ago
David Wilson 95039eea11 ansible: make key_from_kwargs() 10x faster
It was half the cost of the service call
6 years ago
David Wilson 098995539d ansible: implement FreeBSD jail support. 6 years ago
David Wilson b1563cd8c1 ansible: hijack lxd connections too. 6 years ago
David Wilson 131bc768c7 ansible: implement LXC support. 6 years ago
David Wilson 6fb3a76e68 master: annotate LogForwarder messages.
mitogen/master.py:
    Annotate forwarded log entries with their original source, logger
    name, and message.

ansible:
    mark stderr in red with -vvv

    Tempting to make this appaer 100% of the time, but some crappy
    bashrcs may cause lots of junk to be printed.
6 years ago
David Wilson 4893889a88 ansible: remove vestiges of old/wrong sudo_exe source. 6 years ago
David Wilson 3fab8a3af5 ansible: connection delegation v1
This implements the first edition of Connection Delegation, where
delegating connection establishment is initially single-threaded.

ansible_mitogen/strategy.py:
ansible_mitogen/plugins/connection/*:

  Begin splitting connection.Connection into subclasses, exposing them
  directly as "mitogen_ssh", "mitogen_local", etc. connection types.

  This is far from removing strategy.py, but it's a tiny start.

ansible_mitogen/connection.py:

  * config_from_play_context() and config_from_host_vars() build up a
    huge dictionary containing either more or less PlayContext contents,
    or our best attempt at reconstructing a host's connection config
    from its hostvars, where that config is not the current
    WorkerProcess target.

    They both produce the same format with the same keys, allowing
    remaining code to have a single input format.

    These dicts contain fields named after how Ansible refers to them,
    e.g. "sudo_exe".

  * _config_from_via() parses a basic connection specification like
    "username@inventory_name" into one of the aforementioned dicts.

  * _stack_from_config() produces a list of dicts describing the order
    in which (Mitogen) connections should be established, such that each
    element is proxied via= the previous element. The dicts produced by
    this function use Mitogen keyword arguments, the former di.

    These dicts contain fields named after how Mitogen refers to them,
    e.g. "sudo_path".

  * Pass the stack to ContextService, which is responsible for actual
    setup of the full chain.

ansible_mitogen/services.py:

  Teach get() to walk the supplied stack, establishing each connection
  in turn, creating refounts for it before continuing.

  TODO: refcounting is broken in a variety of cases.
6 years ago
David Wilson 7c6ce726aa ansible: rename variable to reflect correct time unit 6 years ago
David Wilson 2f1df7f82d ansible: FileService wasn't sleeping properly.
"_schedule_pending" is a function, "_pending_by_stream" is the map we
want to test.
6 years ago
David Wilson 86c9978e09 Ensure mod.__file__ is set; closes #210. 6 years ago
David Wilson b2abe74ab6 issue #210: run DebOps under v2.5.1 too. 6 years ago
David Wilson 89fc842ca8 ansible: typo. 6 years ago
David Wilson 21082cec40 ansible: fix ugly formatting. 6 years ago
David Wilson 376fc85000 ansible: FileService docstrings. 6 years ago
David Wilson cf30e88a3e ansible: implement missing FileService.on_shutdown() 6 years ago
David Wilson 5913be64d7 docs: remove last remaining major risk :D 6 years ago
David Wilson cb73c44084 ansible: implement streaming in Connection.put_file().
This is the function the copy module uses.
6 years ago
David Wilson 29087018c7 ansible: implement streaming in FileService.
This commit only uses it for the target.get_file() helper, which is only
used for transferring modules. The next commit wires it into the
Connection.transfer_file() API, which is the method the copy module
uses.
6 years ago
David Wilson 8c3b1fcf15 ansible: disable script interpreter processing for new-style
Re: #199
6 years ago
David Wilson 2f02b5c0b1 ansible: prevent Unicode strings leaking into sys.argv
The module name comes from YAML via Jinja2.. it's always Unicode. Mixing
it into a temporary directory name produces a Unicode tempdir name,
which ends up in sys.argv via TemporaryArgv.
6 years ago
David Wilson dc4433ace6 issue #202: ansible: forget all dependent contexts on Stream disconnect
This is a partial fix, there are still at least 2 cases needing covered:

- In-progress connections must have CallError or similar sent to any
  waiters
- Once connection delegation exists, it is possible for other worker
  processes to be active (and in any step in the process), trying to
  communicate with a context that we know can no longer be communicated
  with. The solution to that isn't clear yet.

Additionally ensure root has /bin/bash shell in both Docker images.
6 years ago
David Wilson c5fe817db2 ansible: tidy up log repr slightly 6 years ago
David Wilson e7831a801f issue #195: handle non-ASCII scripts in runner.py. 6 years ago
David Wilson 85e1f5f515 ansible: remove JobResultService, more compatible async jobs; closes #191.
And by "compatible" I mean "terrible". This does not implement async job
timeouts, but I'm not going to bother, upstream async implementation is
so buggy and inconsistent it resists even having its behaviour captured
in tests.
6 years ago
David Wilson 296683b130 ansible: always display Mitogen errors and warnings.
They're no longer buried in -vvv output.
6 years ago
David Wilson 810f557514 issue #195: MITOGEN_DUMP_THREAD_STACKS=1 6 years ago
David Wilson f06ae05734 issue #195: add extra logging around FileService and get_file(). 6 years ago
David Wilson f4d791662e ansible: better planner logging, try again 6 years ago
David Wilson a9a2793a49 tests: yep more debug for Travis 6 years ago
David Wilson 1fa377152d ansible: extra planner log messages. 6 years ago
David Wilson 117607d742 ansible: fix new-style module argv[0]
Previously it was the absolute path to the module on the master. This is
wrong, it should be the temporary file name on the target.
6 years ago
David Wilson f360a1b653 ansibe: fix type check for previous commit 6 years ago
David Wilson 9eacf8faa9 ansible: forward exceptions as job results too.
Ref #191.
6 years ago
David Wilson c8ce3059d1 ansible: make FileService register method synchronous
On Travis it seems it is possible for the fetch message to reach
FileService before the register message is fully processed.
6 years ago
David Wilson ed915b6e63 tests: magic mitogen_shutdown_all action
LRU tests break when run as part of the whole suite rather than
individually, because LRU stuff is already happening for earlier tests.
6 years ago
David Wilson c12ae16369 issue #159: tidy up service.py docstrings again. 6 years ago
David Wilson 9f94fb78c8 issue #159: make LRU size configurable. 6 years ago
David Wilson cc980569a3 issue #159: initial context LRU implementation
Now Connection.close() *must* be called in the worker, to ensure the
reference count for a context drops correctly.

Remove 'discriminator' for now, I'm not using it for testing any more
and it complicated this code.

This code is a car crash, it needs rewritten again. Ideally some/most of
this behaviour could live on services.DeduplicatingService somehow, but
I couldn't come up with a sensible design.
6 years ago
David Wilson e119058d9b issue #182: ensure connection is reset during with_items.
Elements of a with_items loop reuse one WorkerProcess to execute every
iteration, requiring us to reset Connection's idea of the connection on
each iteration, otherwise the tasks will erroneously execute in the
wrong context.
6 years ago
David Wilson 20de3489de ansible: tidy up annoying syntax 6 years ago
David Wilson 98ee3e177a ansible: tests for sudo behaviour; closes #143. 6 years ago
David Wilson 4a61527774 ansible: more docstrings and call_async() 6 years ago
David Wilson 6a4ce84c6b ansible: more docstring fixes. 6 years ago
David Wilson 135b3738ba ansible: don't wait on FileService response
Any (unlikely) execption will show up in the debug logs.
6 years ago
David Wilson 70a735f23a ansible: tidy up service.py docstrings. 6 years ago
David Wilson 79b75aabae ansilbe: remove unused class variables 6 years ago
David Wilson 3613162bc0 ansible: enable forking when requested and for async jobs.
Closes #105.
References #155.

mitogen/service.py:
    Refactor services to support individually exposed methods with
    different security policies for each method.

    - @mitogen.service.expose() to expose a method and set its policy
    - @mitogen.service.arg_spec() to validate input.
    - Require basic service message format to be a tuple of
      `(method, kwargs)`, where kwargs is always a dict.
    - Update DeduplicatingService to match the new scheme.

ansible_mitogen/connection.py:
    - Rename 'method' to 'method_name' to disambiguate it from the
      service.call()'s method= argument.

ansible_mitogen/planner.py:
    - Generate an ID for every job, sync or not, and fetch job results
      from JobResultService rather than via the initiating function
      call's return value.
    - Planner subclasses now get to select whether their Runner should
      run in a forked process. The base implementation requests this if
      the 'mitogen_isolation_mode=fork' task variable is present.

ansible_mitogen/runner.py:
    Teach runners to deliver their result via JobResultService executing
    in their indirect parent mux process.

ansible_mitogen/plugins/actions/mitogen_async_status.py:
    Split the implementation up into methods, and more compatibly
    emulate Ansible's existing output.

ansible_mitogen/process.py:
    Mux processes now host JobResultService.

ansible_mitogen/services.py:
    Update existing services to the new mitogen.service scheme, and
    implement JobResultService:

    * listen() method for synchronous jobs. planner.invoke() registers a
      Sender with the service prior to invoking the job, then sleeps
      waiting for the service to write the job result to the
      corresponding Receiver.

    * Non-blocking get() method for implementing mitogen_async_status
      action.

    * Child-accessible push() method for delivering task results.

ansible_mitogen/target.py:
    New helpers for spawning a virginal subprocess on startup, from
    which asynchronous and mitogen_task_isolation=fork jobs are forked.
    Necessary to avoid a task inheriting potentially
    polluted/monkey-patched parent environment, since remaining jobs
    continue to run in the original child process.

docs/ansible.rst:
    Add/merge/remove some behaviours/risks.

tests/ansible/integration:
    New tests for forking/async.
6 years ago
David Wilson 71057c78f9 ansible: rename helpers.py to target.py, to reflect its purpose 6 years ago
David Wilson 7fd88868a6 ansible: raise AnsibleConnectionFailure on connection failure; closes #183
Before:

    $ ANSIBLE_STRATEGY=mitogen ansible -i derp, derp -m setup
    An exception occurred during task execution. To see the full traceback, use -vvv. The error was:     (''.join(bits)[-300:],)
    derp | FAILED! => {
        "msg": "Unexpected failure during module execution.",
        "stdout": ""
    }

After:

    $ ANSIBLE_STRATEGY=mitogen ansible -i derp, derp -m setup
    derp | UNREACHABLE! => {
        "changed": false,
        "msg": "EOF on stream; last 300 bytes received: 'ssh: Could not resolve hostname derp: nodename nor servname provided, or not known\\r\\n'",
        "unreachable": true
    }
6 years ago
David Wilson 4a823c7a27 issue #164: missing cast() for _remote_file_exists(). 6 years ago
David Wilson d503956493 ansible: Remove duplicate casts already done in Connection 6 years ago
David Wilson 6aeb4e9f05 issue #164: precisely emulate Ansible's stdio behaviour.
* Use identical logic to select when stdout/stderr are merged, so
  'stdout', 'stdout_lines', 'stderr', 'stderr_lines' contain the same
  output before/after the extension.

* When stdout/stderr are merged, synthesize carriage returns just like
  the TTY layer.

* Mimic the SSH connection multiplexing message on stderr. Not really
  for user code, but so compare_output_test.sh needs fewer fixups.
6 years ago
David Wilson 26cc0f2724 issue #164: fix remote_tmp handling on <2.5 6 years ago