Commit graph

434 commits

Author SHA1 Message Date
Paul Stack 45e1917a30
Upgrade to Go 1.14.x (#4697) 2020-05-28 12:01:33 +01:00
Justin Van Patten 6b0a845cc1
Support publishing Python policy packs (#4644)
Adds support for publishing Python policy packs to the service, and downloading/using such policy packs when applied to stacks in an organization.
2020-05-22 15:01:15 -07:00
Justin Van Patten af3d4b890d
Allow pulumi.export calls from unit tests (#4670)
The previous attempt to allow this didn't actually allow it, so this is
take two. As part of the previous attempt, I thought after tweaking the
test I had observed the test failing, and then succeeding after making
the product changes, but I must have been mistaken.

It turns out that our existing mocks tests weren't running at all
because of a missing `__init__.py` file. Once the missing `__init__.py`
is added, the tests run, but other tests ("test mode" tests) fail
because the code that creates the mocks and resources will run during
test discovery, and setting the mocks modifies global state.

To address the test issue, I've moved the mocks tests into their own
`test_with_mocks` package that can be run separately from other tests.

And addressed the original issue, by creating a root Stack resource if
one isn't already present when the mocks are set.
2020-05-20 09:54:40 -07:00
Lee Briggs 8c314ec39a
Add brew make targets to sdk makefiles 2020-05-13 20:42:01 -07:00
solidDoWant b7fb3bae22
Fixed ResourceOption deepcopy bug in stack_reference.py (#4553) 2020-05-08 12:01:59 -07:00
Pat Gavlin 9b1b9cca24
Makefile: properly encode dependencies (#4541)
This allows for the use of `make -j`, which speeds up a full build
dramatically at the cost of rather incomprehensible logs.
2020-05-04 14:26:52 -07:00
Justin Van Patten 16926504c1
Allow pulumi.export calls from unit tests (#4518)
This change allows importing modules with calls to `pulumi.export` in unit tests. Previously, you'd have to structure the Python program in a way that avoids the `pulumi.export` from being called from unit tests.
2020-04-29 10:03:20 -07:00
Komal c7866108e1
Merge branch 'master' into komalali/increase-grpc-message-size 2020-04-24 17:54:32 -07:00
Luke Hoban cfa57914a1
[sdk/python] Improve ResourceOptions.merge type (#4484)
* [sdk/python] Improve `ResoruceOptions.merge` type

The implementation correctly handles `None` inputs, so the type should allow these as well.

* Add CHANGELOG
2020-04-24 17:45:11 -07:00
komal 28d69e963e add tests for node and python 2020-04-23 11:16:36 -07:00
Komal Ali 9cf635ad5a pr changes 2020-04-23 11:16:36 -07:00
Komal Ali de41fecfdc fix python server options 2020-04-23 11:16:36 -07:00
Komal Ali 64f3c4a02a update sdks with new max message size 2020-04-23 11:16:36 -07:00
CyrusNajmabadi 66bd3f4aa8
Breaking changes due to Feature 2.0 work
* Make `async:true` the default for `invoke` calls (#3750)

* Switch away from native grpc impl. (#3728)

* Remove usage of the 'deasync' library from @pulumi/pulumi. (#3752)

* Only retry as long as we get unavailable back.  Anything else continues. (#3769)

* Handle all errors for now. (#3781)


* Do not assume --yes was present when using pulumi in non-interactive mode (#3793)

* Upgrade all paths for sdk and pkg to v2

* Backport C# invoke classes and other recent gen changes (#4288)

Adjust C# generation

* Replace IDeployment with a sealed class (#4318)

Replace IDeployment with a sealed class

* .NET: default to args subtype rather than Args.Empty (#4320)

* Adding system namespace for Dotnet code gen

This is required for using Obsolute attributes for deprecations

```
Iam/InstanceProfile.cs(142,10): error CS0246: The type or namespace name 'ObsoleteAttribute' could not be found (are you missing a using directive or an assembly reference?) [/Users/stack72/code/go/src/github.com/pulumi/pulumi-aws/sdk/dotnet/Pulumi.Aws.csproj]
Iam/InstanceProfile.cs(142,10): error CS0246: The type or namespace name 'Obsolete' could not be found (are you missing a using directive or an assembly reference?) [/Users/stack72/code/go/src/github.com/pulumi/pulumi-aws/sdk/dotnet/Pulumi.Aws.csproj]
```

* Fix the nullability of config type properties in C# codegen (#4379)
2020-04-14 09:30:25 +01:00
Mikhail Shilkov 6d32d575e0
Enable features in mock monitor (#4272) 2020-04-03 08:33:40 +02:00
Mikhail Shilkov 0bce094dc1
Fix python mock's call (#4274)
Fix python mock's call
2020-04-03 07:28:52 +02:00
Justin Van Patten dd104a00a7
Propagate secretness correctly in Python apply (#4273)
* Propagate secretness correctly in Python `apply`

* Improve `apply` test coverage

* Update CHANGELOG.md
2020-04-02 13:01:29 -07:00
Justin Van Patten e6be38e285
PaC: Add initial config support for policy packs (#4233)
The initial config represents any config that was specified programmatically to the Policy Pack, for Policy Packs that support programmatic configuration like AWSGuard.
2020-03-30 12:52:05 -07:00
Matthieu Berthomé 7c75d4fe5b
ephemeral kwargs for log methods (#4197)
Co-authored-by: rienafairefr <rienafairefr@gmail.com>
2020-03-26 14:23:43 -07:00
Luke Hoban 215f5af505
Clarify documentation on Output.from_input (#4178) 2020-03-25 15:28:22 -07:00
evanboyle 5e1f597ea9 make distinction between python VERSION and PYPIVERSION for install vs release 2020-03-19 17:02:10 -07:00
evanboyle ec686bbaf6 Merge branch 'master' of https://github.com/pulumi/pulumi into evan/gomod 2020-03-18 17:57:58 -07:00
evanboyle 48250176a1 Revert "move sdk/python/cmd/pulumi-language-python -> pkg/cmd/pulumi-language-python"
This reverts commit e2ee46fb23.
2020-03-18 17:11:56 -07:00
Justin Van Patten 24e804bbe8
Support for running Python policy packs (#4057)
These changes enable running policy packs written in Python.
2020-03-18 16:15:57 -07:00
evanboyle 30df499838 move pkg/version -> sdk/go/common/version 2020-03-18 15:25:25 -07:00
evanboyle 6552df7139 fix python sdk Makefile, use common pkg/version.go 2020-03-18 12:33:18 -07:00
evanboyle e2ee46fb23 move sdk/python/cmd/pulumi-language-python -> pkg/cmd/pulumi-language-python 2020-03-18 10:19:22 -07:00
Luke Hoban fdd9a57ff8
Implement GetSchema in dynamic providers (#4083)
It's not entirely clear why gRPC doesn't already report these cleanly as unimplemented, but for now we'll explicitly implement them to avoid any spurious warnings.

Fixes #4028.
2020-03-15 15:36:08 -07:00
Luke Hoban 9da774e180
Fix Python mocks (#4074)
The original version of this code caused inconsistencies in the event
loop associated with a given thread. These changes elimintate the event
loop shenanigans the mocks were trying to play by updating _sync_await
to create an event loop if none exists in the current thread.

It's possible that this will cause problems if the tests run on a
different thread than the original program, as the tests are likely to
end up waiting on outputs created by the program, which is not supported
in Python.

Also adds test coverage of the mocking/testing support in Python.
2020-03-12 21:09:47 -07:00
Mikhail Shilkov 8f1534c895
Mention mocks in the missing project error (#4041) 2020-03-09 16:23:49 +01:00
Justin Van Patten 80f6c61310
Initial support for configuring policies (#4015) 2020-03-08 14:11:55 -07:00
Charly Román 560f1f130e Python SDK fix type annotations for Output.all and Output.concat 2020-03-03 22:00:37 -06:00
James Nugent 60eeff3265
Merge pull request #3990 from pulumi/jen20/main-dockerfile-for-proto
Update gRPC library used in Go SDKs and regenerate code with latest tools
2020-02-29 12:46:46 +00:00
Pat Gavlin 682dced40b
Mock resource monitor (#3738)
These changes add support for mocking the resource monitor to the NodeJS
and Python SDKs. The proposed mock interface is a simplified version of
the standard resource monitor that allows an end-user to replace the
usual implementations of ReadResource/RegisterResource and Invoke with
their own. This can be used in unit tests to allow for precise control
of resource outputs and invoke results.
2020-02-28 17:22:50 -08:00
James Nugent a1b55192dd Regenerate protocol buffers code 2020-02-28 11:53:47 +00:00
Pat Gavlin ccde31b713
Add support for extracting schemas from providers. (#3984)
These changes add a new method to the resource provider gRPC interface,
`GetSchema`, that allows consumers of these providers to extract
JSON-serialized schema information for the provider's types, resources,
and functions.
2020-02-27 16:10:47 -08:00
Levi Blackstone 0931c0d419
Fix missing module import on Windows platform (#3983)
#3895 added a module import that apparently doesn't
exist on Windows. Check the platform before importing,
and skip this import for Windows.
2020-02-26 16:08:49 -07:00
Lee Zen 33b232adc4
Fix a regression for CustomTimeouts in Python SDK (#3964)
* Fix a regression for CustomTimeouts in Python SDK
* Accept dict as well as CustomTimeouts object
2020-02-22 19:32:06 -08:00
Lee Zen 54d344f7c1
Serialize CustomTimeouts in Python SDK (#3920)
* Translate CustomTimeouts properly for RPC serialization
* Include integration test for custom timeouts
2020-02-13 10:40:56 -08:00
Levi Blackstone 7efb88de3e
Allow oversize protocol buffers (#3895)
Set an option to increase the memory limit on protobuf
parsing so that we can handle larger gRPC payloads.

Co-authored-by: Evan Boyle <EvanBoyle@users.noreply.github.com>
2020-02-10 15:30:42 -07:00
Justin Van Patten 3bf9067bac
Expose options, parent, deps, and provider config to policies (#3862) 2020-02-07 16:11:34 -08:00
Pat Gavlin 4a201a7dfd
Do not busy wait in Python. (#3892)
Instead, keep a stack of outstanding RPCs and await each in turn. This
allows the main loop to block instead of spin.

Fixes #3759.
2020-02-07 12:10:59 -08:00
Luke Hoban 5bf490228a
Use \n for provider protocol even on Windows (#3855)
The provider plugin protocol is to write a port number followed by `\n`.  We must guarantee we do that even on Windows, so must avoid Python `print` statements which implicitly rewrite newlines to platform specific character sequences.

Fixes #3807.
2020-02-06 11:34:05 -08:00
Evan Boyle 106154f1fc
fix python sdk stack ref regression (#3798) 2020-01-24 09:36:47 -08:00
James Forcier bf84a3482b Add py.typed to Python package for PEP 561 compliance (#3704)
PEP 561 specifies that packages which contain either inline type hints
or type stubs should indicate their support for type hints via
including a file named `py.typed` in the root of the package. Since
Pulumi already includes inline type hints, adding `py.typed` to the
Python SDK simply allows these hints to be used by mypy.
2020-01-17 15:01:36 -08:00
Evan Boyle 972fc44dd7
Enable mypy (#3758) 2020-01-17 14:45:08 -08:00
clstokes 0a3191905c Fixed 'transacational' misspelling. 2020-01-13 10:45:07 -08:00
Luke Hoban 95daaa8cec Fix broken test 2019-12-21 06:51:42 -08:00
Luke Hoban 265acaefe5
Fallback to looking for python when launching Python language host (#3692)
Fixes #3398.
2019-12-20 17:09:00 -08:00
CyrusNajmabadi f4fc00ad0e
Output.apply should lift resources from inner Outputs to the top level output. (#3663) 2019-12-17 14:11:45 -08:00
Justin Van Patten 6c84b008d8
Send resource URN and name to analyzer (#3554)
More information we want to make available to policy packs.
2019-11-21 21:01:15 +00:00
Pat Gavlin e978eaaf5a
Fix Python package versions. (#3505)
Earlier changes to the get-version script were not adopted by the Python
SDK Makefile. This caused package publishing to skip uploads due to
missing versions.
2019-11-13 11:34:59 -08:00
Pat Gavlin 137fd54f1c
Propagate inputs to outputs during preview. (#3327)
These changes restore a more-correct version of the behavior that was
disabled with #3014. The original implementation of this behavior was
done in the SDKs, which do not have access to the complete inputs for a
resource (in particular, default values filled in by the provider during
`Check` are not exposed to the SDK). This lack of information meant that
the resolved output values could disagree with the typings present in
a provider SDK. Exacerbating this problem was the fact that unknown
values were dropped entirely, causing `undefined` values to appear in
unexpected places.

By doing this in the engine and allowing unknown values to be
represented in a first-class manner in the SDK, we can attack both of
these issues.

Although this behavior is not _strictly_ consistent with respect to the
resource model--in an update, a resource's output properties will come
from its provider and may differ from its input properties--this
behavior was present in the product for a fairly long time without
significant issues. In the future, we may be able to improve the
accuracy of resource outputs during a preview by allowing the provider
to dry-run CRUD operations and return partially-known values where
possible.

These changes also introduce new APIs in the Node and Python SDKs
that work with unknown values in a first-class fashion:
- A new parameter to the `apply` function that indicates that the
  callback should be run even if the result of the apply contains
  unknown values
- `containsUnknowns` and `isUnknown`, which return true if a value
  either contains nested unknown values or is exactly an unknown value
- The `Unknown` type, which represents unknown values

The primary use case for these APIs is to allow nested, properties with
known values to be accessed via the lifted property accessor even when
the containing property is not fully know. A common example of this
pattern is the `metadata.name` property of a Kubernetes `Namespace`
object: while other properties of the `metadata` bag may be unknown,
`name` is often known. These APIs allow `ns.metadata.name` to return a
known value in this case.

In order to avoid exposing downlevel SDKs to unknown values--a change
which could break user code by exposing it to unexpected values--a
language SDK must indicate whether or not it supports first-class
unknown values as part of each `RegisterResourceRequest`.

These changes also allow us to avoid breaking user code with the new
behavior introduced by the prior commit.

Fixes #3190.
2019-11-11 12:09:34 -08:00
Alex Clemmer 25d27d09f9 Add StreamInvoke to Provider gRPC interface 2019-11-05 10:47:48 -08:00
Pat Gavlin c383810bf8
Omit unknowns in resources in stack outputs during preview. (#3427)
If a stack output includes a `Resource`, we will as of a recent change
always show the output diff, but this diff will potentially include
unknowns, leading to spurious output like:

```
+ namePrefix : output<string>
```

These changes supress these diffs by adding a special key to the POJO
we generate for resources *during preview only* that indicates that the
POJO represents a Pulumi resource, then stripping all adds of unknown
values from diffs for objects marked with that key.

Fixes #3314.
2019-10-30 11:36:03 -07:00
Chris Smith d2805fcb3f
Add support for aggregate resource analysis (#3366)
* Add AnalyzeStack method to Analyze service

* Protobuf generated code

* Hook up AnalyzeStack method

* Address PR feedback

* Address PR feedback
2019-10-25 08:29:02 -07:00
Ryan Campbell 665b4caa89 Update python FileAsset to accept os.PathLike in addition to str. (#3368)
This should fix #2896.
2019-10-18 14:31:59 -07:00
Luke Hoban 893e51d0ce
Add Python resource transformations support (#3319)
Adds Python support for resource transformations aligned with the existing NodeJS support in #3174.

This PR also moves processing of transformations to earlier in the resource construction process (for both NodeJS and Python) to ensure that invariants established in the constructor cannot be violated by transformations. This change can technically be a breaking change, but given that (a) the transformations features was just released in 1.3.0 and (b) the cases where this is a breaking change are uncommon and unlikely to have been reliable anyway - it feels like a change we should make now.

Fixes #3283.
2019-10-14 19:35:00 -05:00
Pat Gavlin 834e583c95
Revert "Propagate inputs to outputs during preview. (#3245)" (#3324)
This reverts commit 80504bf0bc.
2019-10-10 10:33:05 -07:00
Pat Gavlin 80504bf0bc
Propagate inputs to outputs during preview. (#3245)
These changes restore a more-correct version of the behavior that was
disabled with #3014. The original implementation of this behavior was
done in the SDKs, which do not have access to the complete inputs for a
resource (in particular, default values filled in by the provider during
`Check` are not exposed to the SDK). This lack of information meant that
the resolved output values could disagree with the typings present in
a provider SDK. Exacerbating this problem was the fact that unknown
values were dropped entirely, causing `undefined` values to appear in
unexpected places.

By doing this in the engine and allowing unknown values to be
represented in a first-class manner in the SDK, we can attack both of
these issues.

Although this behavior is not _strictly_ consistent with respect to the
resource model--in an update, a resource's output properties will come
from its provider and may differ from its input properties--this
behavior was present in the product for a fairly long time without
significant issues. In the future, we may be able to improve the
accuracy of resource outputs during a preview by allowing the provider
to dry-run CRUD operations and return partially-known values where
possible.

These changes also introduce new APIs in the Node and Python SDKs
that work with unknown values in a first-class fashion:
- A new parameter to the `apply` function that indicates that the
  callback should be run even if the result of the apply contains
  unknown values
- `containsUnknowns` and `isUnknown`, which return true if a value
  either contains nested unknown values or is exactly an unknown value
- The `Unknown` type, which represents unknown values

The primary use case for these APIs is to allow nested, properties with
known values to be accessed via the lifted property accessor even when
the containing property is not fully know. A common example of this
pattern is the `metadata.name` property of a Kubernetes `Namespace`
object: while other properties of the `metadata` bag may be unknown,
`name` is often known. These APIs allow `ns.metadata.name` to return a
known value in this case.

In order to avoid exposing downlevel SDKs to unknown values--a change
which could break user code by exposing it to unexpected values--a
language SDK must indicate whether or not it supports first-class
unknown values as part of each `RegisterResourceRequest`.

These changes also allow us to avoid breaking user code with the new
behavior introduced by the prior commit.

Fixes #3190.
2019-09-30 11:03:58 -07:00
CyrusNajmabadi da0bcdccda
Coerce dictionary values to a list. (#3242) 2019-09-18 15:58:20 -07:00
Pat Gavlin 82204230e1
Improve tracing support. (#3238)
* Fix some tracing issues.

- Add endpoints for `startUpdate` and `postEngineEventsBatch` so that
  spans for these invocations have proper names
- Inject a tracing span when walking a plan so that resource operations
  are properly parented
- When handling gRPC calls, inject a tracing span into the call's
  metadata if no span is already present so that resource monitor and
  engine spans are properly parented
- Do not trace client gRPC invocations of the empty method so that these
  calls (which are used to determine server availability) do not muddy
  the trace. Note that I tried parenting these spans appropriately, but
  doing so broke the trace entirely.

With these changes, the only unparented span in a typical Pulumi
invocation is a single call to `getUser`. This span is unparented
because that call does not have a context available. Plumbing a context
into that particular call is surprisingly tricky, as it is often called
by other context-less functions.

* Make tracing support more flexible.

- Add support for writing trace data to a local file using Appdash
- Add support for viewing Appdash traces via the CLI
2019-09-16 14:16:43 -07:00
Matt Ellis b019bc571e Use Python 3
Use `python3` and `pip3` explicitly, as we now depend on Python 3.
2019-09-13 11:58:23 -07:00
Matt Ellis 32ac67e6bc Remove the need for pandoc during the build
We had been using `pandoc` to convert our README.md into a README.rst
for use with `setup.py` and the python package ecosystem. It turns out
that we can use markdown if we set a content type. So let's do that
and make things a little simpler.

While I was in the area, I made the encoding of UTF-8 explicit when
opening README.md.
2019-09-09 11:15:42 -07:00
Pat Gavlin 48c8ea1e8a
Do not drop unhandled exceptions in Python (#3170)
- Do not use a non-zero-to-zero transition in the number of outstanding
  RPCs to determine the completion of a Python program until after the
  synchronous piece of the program has finished running is complete
- Instead of using a future to indicate that either a) a zero-to-one
  transition in the number of outstanding RPCs has occurred, or b) an
  unhandled exception has occurred, a) observe the transition itself,
  and b) use an optional exception field to track the presence or
  absence of an exception.

Fixes #3162.
2019-09-06 13:53:07 -07:00
Joe Duffy 2b48611d9c
Don't encourage PULUMI_TEST_MODE (#3146)
We intend to replace PULUMI_TEST_MODE with better testing support
that doesn't suffer from all the pitfalls of our current approach.
Unfortunately, we don't yet have complete guidance or validation
that the new approaches will work for all existing end users. So,
until we do, we'll take a lighter touch approach here, and simply
not encourage new usage of PULUMI_TEST_MODE.

Issue #3045 will remain open to track a mroe permanent fix.
2019-08-26 18:49:13 -07:00
CyrusNajmabadi 590114497e
Simplify merge code. (#3122) 2019-08-20 17:09:53 -07:00
Pat Gavlin 8745440c1b
Allow users to explicitly disable delete-before-replace. (#3118)
With these changes, a user may explicitly set `deleteBeforeReplace` to
`false` in order to disable DBR behavior for a particular resource. This
is the SDK + CLI escape hatch for cases where the changes in
https://github.com/pulumi/pulumi-terraform/pull/465 cause undesirable
behavior.
2019-08-20 15:51:02 -07:00
CyrusNajmabadi d0a72fc24d
Allow ResourceOptions.id to be an Input in python (to match JS sdk). (#3116) 2019-08-20 12:18:48 -07:00
CyrusNajmabadi 8290377cbd
Add some simple typechecking (#3109) 2019-08-19 13:19:16 -07:00
Matt Ellis 0bb4e6d70b Respond to PR feedback
Address post commit feedback from Cyrus on
pulumi/pulumi#3071
2019-08-15 12:42:51 -07:00
CyrusNajmabadi 20058f982d
Make 'ResourceOptions.merge' static so downstream clients don't have to manually handle None cases. (#3072) 2019-08-14 15:55:03 -07:00
Matt Ellis 9308246114 Do not taint all stack outputs as secrets if just one is
When using StackReference, if the stack you reference contains any
secret outputs, we have to mark the entire `outputs` member as a
secret output. This is because we only track secretness on a per
`Output<T>` basis.

For `getSecret` and friends, however, we know the name of the output
you are looking up and we can be smarter about if the returned
`Output<T>` should be treated as a secret or not.

This change augments the provider for StackReference such that it also
returns a list of top level stack output names who's values contain
secrets. In the language SDKs, we use this information, when present,
to decide if we should return an `Output<T>` that is marked as a
secret or not. Since the SDK and CLI are independent components, care
is taken to ensure that when the CLI does not return this information,
we behave as we did before (i.e. if any output is a secret, we treat
every output as a secret).

Fixes #2744
2019-08-13 16:11:38 -07:00
CyrusNajmabadi de254aa389
Do not include 'test' package in our python library. (#3067) 2019-08-12 11:32:33 -07:00
Pat Gavlin 7fef102bc3
Check for valid PB types in serialize_property (#3060)
Just what it says on the tin. This allows us to return an incrementally
better error.

Fixes #2939.
2019-08-09 16:48:28 -07:00
Pat Gavlin 91af1a93c4
Fix a reentrancy issue in _sync_await. (#3056)
_sync_await was not reentrant with respect to _run_once: the latter
captures the length of the ready list before it iterates it, and the
former drains the ready list by reentering _run_once. Fix this by
tracking the length of the list before pumping the event loop and then
pushing cancelled handles on to the list as necessary after pumping the
loop.

These changes also fix an issue with `export`ing awaitables.

Fixes #3038.
2019-08-08 19:51:11 -07:00
CyrusNajmabadi a13a04b193
Move resource-options check down to core layer. (#3043) 2019-08-06 17:39:34 -07:00
CyrusNajmabadi 60206e716b
Fix spellin (#3041) 2019-08-06 16:16:33 -07:00
Pat Gavlin 2ab814fd09
Do not resolve missing outputs to inputs in preview. (#3014)
This can cause `apply`s to run on values that may change during an
update, which can lead to unexpected behavior.

Fixes #2433.
2019-08-05 12:44:04 -07:00
Pat Gavlin 06034fab40
Only await input properties once. (#3024)
These changes fix a bug in the Python runtime that would cause any
awaitable input properties passed to a resource that are missing
from the resource's output properties to be awaited twice. The fix is
straightforward: rather than roundtripping an input property through
serialize/deserialize, just deserialized the already-serialized input
property.

Fixes #2940.
2019-08-03 10:29:19 -07:00
Pat Gavlin 00bc1287af
Support synchronous invokes in Python 3.6. (#3025)
Python 3.6 does not expose _{enter,leave}_task. Detect this situation
and implement the equivalent operation as necessary.
2019-08-02 16:52:56 -07:00
Pat Gavlin 63eb7abb59
Make pulumi.runtime.invoke synchronous. (#3019)
These changes make the `pulumi.runtime.invoke` function invokable in a
synchronous manner. Because this function still needs to perform
asynchronous work under the covers--namely awaiting a provider URN and
ID if a provider instance is present in the `InvokeOptions`--this
requires some creativity. This creativity comes in the form of a helper
function, `_sync_await`, that performs a logical yield from the
currently running event, manually runs the event loop until the given
future completes, performs a logical resume back to the
currently executing event, and returns the result of the future.

The code in `_sync_await` is a bit scary, as it relies upon knowledge of
(and functions in) the internals of the `asyncio` package. The necessary
work performed in this function was derived from the implementations of
`task_step` (which pointed out the need to call `_{enter,leave}_task`)
and `BaseEventLoop.run_forever` (which illustrated how the event loop is
pumped). In addition to potential breaking changes to these internals,
the code may not work if a user has provided an alternative implementation
for `EventLoop`. That said, the code is a close enough copy of
`BaseEventLoop.run_forever` that it should be a reasonable solution.
2019-08-02 14:19:56 -07:00
Charlie Hills 654f5e2d35 Fixes python get_secret always returning None (#3022)
get_secret was looking up secrets by the fully resolved key, but should use the simple key.
2019-08-02 09:59:51 -07:00
CyrusNajmabadi d1376db975
Support arbitrary stack export values in python. (#3015) 2019-08-01 20:00:07 -07:00
Luke Hoban aac25eabc4
Add requireOutput to StackReference (#3007)
Provides an additional helper function to read outputs from a stack reference in case it is known that the stack output must be present. This is similar to the design for config.get and config.require.

Fixes #2343.
2019-08-01 11:27:32 -07:00
Luke Hoban 3d4c01abeb
Add Output.concat to Python (#3006)
Fixes #2366
2019-07-31 11:35:05 -07:00
Pat Gavlin 67ec74bdc5
Pass ignoreChanges to providers. (#3005)
These changes add support for passing `ignoreChanges` paths to resource
providers. This is intended to accommodate providers that perform diffs
between resource inputs and resource state (e.g. all Terraform-based
providers, the k8s provider when using API server dry-runs). These paths
are specified using the same syntax as the paths used in detailed diffs.

In addition to passing these paths to providers, the existing support
for `ignoreChanges` in inputs has been extended to accept paths rather
than top-level keys. It is an error to specify a path that is missing
one or more component in the old or new inputs.

Fixes #2936, #2663.
2019-07-31 11:39:07 -05:00
CyrusNajmabadi 93f0bd708d
Add helper function for merging ResourceOptions (#2988) 2019-07-29 12:01:10 -07:00
CyrusNajmabadi 237f8d2222
Add python aliases support. (#2974) 2019-07-25 11:21:06 -07:00
Chris Smith 208dfc29b4
Update references to pulumi.io (#2979)
* Remove pulumi.io reference in tests

* Remove pulumi.io references in Dockerfiles

* Remove pulumi.io references in CONTRIBUTING.md

* Update README.md's

* Use correct logo
2019-07-25 09:58:12 -07:00
Luke Hoban fa4da84669
Add get_object functions to Python SDK (#2959)
Fixes #2320
2019-07-20 07:04:18 -07:00
Pat Gavlin b0fc599e02 Restore the old pickler in a try/finally (#2954)
Just what it says on the tin.
2019-07-19 12:08:15 -07:00
Luke Hoban 3768e5c690
Python Dynamic Providers (#2900)
Dynamic providers in Python.

This PR uses [dill](https://pypi.org/project/dill/) for code serialization, along with a customization to help ensure deterministic serialization results.

One notable limitation - which I believe is a general requirement of Python - is that any serialization of Python functions must serialize byte code, and byte code is not safely versioned across Python versions.  So any resource created with Python `3.x.y` can only be updated by exactly the same version of Python.  This is very constraining, but it's not clear there is any other option within the realm of what "dynamic providers" are as a feature.  It is plausible that we could ensure that updates which only update the serialized provider can avoid calling the dynamic provider operations, so that version updates could still be accomplished.  We can explore this separately.

```py
from pulumi import ComponentResource, export, Input, Output
from pulumi.dynamic import Resource, ResourceProvider, CreateResult, UpdateResult
from typing import Optional
from github import Github, GithubObject

auth = "<auth token>"
g = Github(auth)

class GithubLabelArgs(object):
    owner: Input[str]
    repo: Input[str]
    name: Input[str]
    color: Input[str]
    description: Optional[Input[str]]
    def __init__(self, owner, repo, name, color, description=None):
        self.owner = owner
        self.repo = repo
        self.name = name
        self.color = color
        self.description = description

class GithubLabelProvider(ResourceProvider):
    def create(self, props):
        l = g.get_user(props["owner"]).get_repo(props["repo"]).create_label(
            name=props["name"],
            color=props["color"],
            description=props.get("description", GithubObject.NotSet))
        return CreateResult(l.name, {**props, **l.raw_data}) 
    def update(self, id, _olds, props):
        l = g.get_user(props["owner"]).get_repo(props["repo"]).get_label(id)
        l.edit(name=props["name"],
               color=props["color"],
               description=props.get("description", GithubObject.NotSet))
        return UpdateResult({**props, **l.raw_data})
    def delete(self, id, props):
        l = g.get_user(props["owner"]).get_repo(props["repo"]).get_label(id)
        l.delete()

class GithubLabel(Resource):
    name: Output[str]
    color: Output[str]
    url: Output[str]
    description: Output[str]
    def __init__(self, name, args: GithubLabelArgs, opts = None):
        full_args = {'url':None, 'description':None, 'name':None, 'color':None, **vars(args)}
        super().__init__(GithubLabelProvider(), name, full_args, opts)

label = GithubLabel("foo", GithubLabelArgs("lukehoban", "todo", "mylabel", "d94f0b"))

export("label_color", label.color)
export("label_url", label.url)
```


Fixes https://github.com/pulumi/pulumi/issues/2902.
2019-07-19 10:18:25 -07:00
Alex Clemmer cd86475009 Add GetAnalyzerInfo to Analyzer gRPC definition
`GetAnalyzerInfo` is an RPC command that allows the Pulumi CLI to ask an
`Analyzer` for metadata about the resource policies it defines.

This is useful because the Pulumi service needs to be able to render
metadata about a policy pack after the user runs a `pulumi policy
publish`. Since we don't execute code on the server, the first step of
`policy publish` is to interrogate the policy pack program about what
policies it has, so that this metadata can be sent to the server, along
with a packed version of those policies.
2019-07-16 00:58:33 -07:00
Paul Stack 02ffff8840
Addition of Custom Timeouts (#2885)
* Plumbing the custom timeouts from the engine to the providers

* Plumbing the CustomTimeouts through to the engine and adding test to show this

* Change the provider proto to include individual timeouts

* Plumbing the CustomTimeouts from the engine through to the Provider RPC interface

* Change how the CustomTimeouts are sent across RPC

These errors were spotted in testing. We can now see that the timeout
information is arriving in the RegisterResourceRequest

```
req=&pulumirpc.RegisterResourceRequest{
           Type:                    "aws:s3/bucket:Bucket",
           Name:                    "my-bucket",
           Parent:                  "urn:pulumi:dev::aws-vpc::pulumi:pulumi:Stack::aws-vpc-dev",
           Custom:                  true,
           Object:                  &structpb.Struct{},
           Protect:                 false,
           Dependencies:            nil,
           Provider:                "",
           PropertyDependencies:    {},
           DeleteBeforeReplace:     false,
           Version:                 "",
           IgnoreChanges:           nil,
           AcceptSecrets:           true,
           AdditionalSecretOutputs: nil,
           Aliases:                 nil,
           CustomTimeouts:          &pulumirpc.RegisterResourceRequest_CustomTimeouts{
               Create:               300,
               Update:               400,
               Delete:               500,
               XXX_NoUnkeyedLiteral: struct {}{},
               XXX_unrecognized:     nil,
               XXX_sizecache:        0,
           },
           XXX_NoUnkeyedLiteral: struct {}{},
           XXX_unrecognized:     nil,
           XXX_sizecache:        0,
       }
```

* Changing the design to use strings

* CHANGELOG entry to include the CustomTimeouts work

* Changing custom timeouts to be passed around the engine as converted value

We don't want to pass around strings - the user can provide it but we want
to make the engine aware of the timeout in seconds as a float64
2019-07-16 00:26:28 +03:00
Pat Gavlin e1a52693dc
Add support for importing existing resources. (#2893)
A resource can be imported by setting the `import` property in the
resource options bag when instantiating a resource. In order to
successfully import a resource, its desired configuration (i.e. its
inputs) must not differ from its actual configuration (i.e. its state)
as calculated by the resource's provider.

There are a few interesting state transitions hiding here when importing
a resource:
1. No prior resource exists in the checkpoint file. In this case, the
   resource is simply imported.
2. An external resource exists in the checkpoint file. In this case, the
   resource is imported and the old external state is discarded.
3. A non-external resource exists in the checkpoint file and its ID is
   different from the ID to import. In this case, the new resource is
   imported and the old resource is deleted.
4. A non-external resource exists in the checkpoint file, but the ID is
   the same as the ID to import. In this case, the import ID is ignored
   and the resource is treated as it would be in all cases except for
   changes that would replace the resource. In that case, the step
   generator issues an error that indicates that the import ID should be
   removed: were we to move forward with the replace, the new state of
   the stack would fall under case (3), which is almost certainly not
   what the user intends.

Fixes #1662.
2019-07-12 11:12:01 -07:00
Matt Ellis 858517a7ca Correctly push secretness up during deserialization in runtimes
There current RPC model for Pulumi allows secret values to be deeply
embedded in lists or maps, however at the language level, since we
track secrets via `Output<T>` we need to ensure that during
deserialization, if a list or a map contains a secret, we need to
instead treat it as if the entire list or map was a secret.

We have logic in the language runtimes to do this as part of
serialization. There were a few issues this commit addresses:

- We were not promoting secretness across arrays in either Node or
  Python
- For Python, our promotion logic was buggy and caused it to behave in
  a manner where if any value was secret, the output values of the
  object would be corrupted, because we'd incorrectly treat the
  outputs as a secret who's value was a map, instead of a map of
  values (some of which may be secret).

This caused very confusing behavior, because it would appear that a
resource creation call just did not set various output properties when
one or more of them ended up containing a secret.
2019-07-09 10:40:27 -07:00
Pat Gavlin 6e5c4a38d8
Defer all diffs to resource providers. (#2849)
Thse changes make a subtle but critical adjustment to the process the
Pulumi engine uses to determine whether or not a difference exists
between a resource's actual and desired states, and adjusts the way this
difference is calculated and displayed accordingly.

Today, the Pulumi engine get the first chance to decide whether or not
there is a difference between a resource's actual and desired states. It
does this by comparing the current set of inputs for a resource (i.e.
the inputs from the running Pulumi program) with the last set of inputs
used to update the resource. If there is no difference between the old
and new inputs, the engine decides that no change is necessary without
consulting the resource's provider. Only if there are changes does the
engine consult the resource's provider for more information about the
difference. This can be problematic for a number of reasons:

- Not all providers do input-input comparison; some do input-state
  comparison
- Not all providers are able to update the last deployed set of inputs
  when performing a refresh
- Some providers--either intentionally or due to bugs--may see changes
  in resources whose inputs have not changed

All of these situations are confusing at the very least, and the first
is problematic with respect to correctness. Furthermore, the display
code only renders diffs it observes rather than rendering the diffs
observed by the provider, which can obscure the actual changes detected
at runtime.

These changes address both of these issues:
- Rather than comparing the current inputs against the last inputs
  before calling a resource provider's Diff function, the engine calls
  the Diff function in all cases.
- Providers may now return a list of properties that differ between the
  requested and actual state and the way in which they differ. This
  information will then be used by the CLI to render the diff
  appropriately. A provider may also indicate that a particular diff is
  between old and new inputs rather than old state and new inputs.

Fixes #2453.
2019-07-01 12:34:19 -07:00
James Nugent a2b8b1d1d3 Use literal string "value" in returned dictionary
Currently, if a secret was present, the value of variable "value" is used as the
key for the dictionary object containing the output. This leads to KeyError
exceptions in various places, as reported in #2782. This PR changes that to use
the literal string "value".

Fixes #2782.
2019-06-25 20:42:39 +01:00
david raistrick 224178874e add .venv/ to python .gitignore to ignore when using PIPENV_VENV_IN_PROJECT=1 2019-06-19 12:43:04 -07:00
Matt Ellis 93025e5f36 Use PULUMI_TEST_MODE to control test mode in Python
This mirrors the UX that we have in node where you can set
`PULUMI_TEST_MODE` to control if test mode is enabled from outside
your program.

Fixes #2818
2019-06-18 10:48:29 -07:00
Alex Clemmer 43ef3acb64 Remove policy ID from the analyzer protocol 2019-06-13 17:39:30 -07:00
Alex Clemmer 346861b9d6 Update Analyzer PB for policy 2019-06-13 16:04:13 -07:00
CyrusNajmabadi 54cbda80c1
Store information about a CustomResource's provider in __providers. (#2816) 2019-06-11 16:57:37 -07:00
CyrusNajmabadi 55bb3b2486
Simplify API for passing providers to a ComponentResource. (#2609) 2019-06-06 16:20:12 -07:00
CyrusNajmabadi 71e8bfb61b
Use 'localhost' vs 0.0.0.0 (#2806) 2019-06-06 13:49:04 -07:00
Alex Clemmer df5273e549 Add __pulumiType to CustomResource class
Running `pulumi query` over state resources will require the ability to
filter resources by type.

This commit begins the process of making this possible simply, using the
TypeScript user-defined type guards feature. This commit changes the
`CustomResource` constructor to record the `t` argument in the
`__pulumiType` field, which acts as a "sentinel" value in the resource
base, which deriving classes need only check to ensure they are of that
type. For example:

    aws.s3.Bucket.isInstance(someOb)

would check the `aws.s3.Bucket.__pulumiType` field, and make sure that
the type field lines up.
2019-06-03 14:56:49 -07:00
Matt Ellis 08d34e8b0f Allow GetRequiredPlugins RPC to return a download location 2019-06-03 09:31:18 -07:00
Luke Hoban 15e924b5cf
Support aliases for renaming, re-typing, or re-parenting resources (#2774)
Adds a new resource option `aliases` which can be used to rename a resource.  When making a breaking change to the name or type of a resource or component, the old name can be added to the list of `aliases` for a resource to ensure that existing resources will be migrated to the new name instead of being deleted and replaced with the new named resource.

There are two key places this change is implemented. 

The first is the step generator in the engine.  When computing whether there is an old version of a registered resource, we now take into account the aliases specified on the registered resource.  That is, we first look up the resource by its new URN in the old state, and then by any aliases provided (in order).  This can allow the resource to be matched as a (potential) update to an existing resource with a different URN.

The second is the core `Resource` constructor in the JavaScript (and soon Python) SDKs.  This change ensures that when a parent resource is aliased, that all children implicitly inherit corresponding aliases.  It is similar to how many other resource options are "inherited" implicitly from the parent.

Four specific scenarios are explicitly tested as part of this PR:
1. Renaming a resource
2. Adopting a resource into a component (as the owner of both component and consumption codebases)
3. Renaming a component instance (as the owner of the consumption codebase without changes to the component)
4. Changing the type of a component (as the owner of the component codebase without changes to the consumption codebase)
4. Combining (1) and (3) to make both changes to a resource at the same time
2019-05-31 23:01:01 -07:00
Pat Gavlin 2324eaaa59
Add StackReference to the Python SDK (#2786)
This commit adds StackReference to the Python SDK, which uses
read_resource to read the remote state of a a Pulumi stack.
2019-05-30 14:12:37 -07:00
Sean Gillespie eda5de0f88 Implementation of Read for Python (#2752)
This commit implements read_resource functionality for Python in a
manner identical to the NodeJS implementation. If an "id" option is
passed to a resource via ResourceOptions on construction, that resource
will be read and not created.
2019-05-30 11:04:47 -07:00
Matt Ellis 75744f1d6c Add some convience methods to pulumi.Config for getting secrets 2019-05-10 17:07:52 -07:00
Matt Ellis 2ff54fa150 Push secretness "up" while deserializing objects.
Since we don't support nesting secrets (as they are modeled as
Outputs), as we deserialize, we push the secretness up to top level,
where we will correctly use it to mark the output as secret.

This fixes an issue where if you created a StackReference resource,
with a mix of secret and non secret properties, you would see the
"wire form" of the secrets as values on the `outputs` map of the
StackReference resource.
2019-05-10 17:07:52 -07:00
Matt Ellis f705dde7fb Remove acceptsSecrets from InvokeRequest
In our system, we model secrets as outputs with an additional bit of
metadata that says they are secret. For Read and Register resource
calls, our RPC interface says if the client side of the interface can
handle secrets being returned (i.e. the language SDK knows how to
sniff for the special signiture and resolve the output with the
special bit set).

For Invoke, we have no such model. Instead, we return a `Promise<T>`
where T's shape has just regular property fields.  There's no place
for us to tack the secretness onto, since there are no Outputs.

So, for now, don't even return secret values back across the invoke
channel. We can still take them as arguments (which is good) but we
can't even return secrets as part of invoke calls. This is not ideal,
but given the way we model these sources, there's no way around
this.  Fortunately, the result of these invoke calls are not stored in
the checkpoint and since the type is not Output<T> it will be clear
that the underlying value is just present in plaintext. A user that
wants to pass the result of an invoke into a resource can turn an
existing property into a secret via `pulumi.secret`.
2019-05-10 17:07:52 -07:00
Matt Ellis cb59c21c01 Rename SecretOutputs to AdditionalSecretOutputs
This makes the intention of this field clearer.
2019-05-10 17:07:52 -07:00
Matt Ellis ae4d126d8c Support Secrets in Python SDK
A new static method, `secret` now exists on `pulumi.Output` which can
be used to create secrets.
2019-05-10 17:07:52 -07:00
Matt Ellis 8e84b3c4fd Regnerate generated code 2019-05-10 17:07:52 -07:00
Matt Ellis 2ad9afc572 Regnerate gRPC generated code 2019-05-10 17:07:52 -07:00
Justin Van Patten fedfc9b6b4
pulumi update => pulumi up (#2702)
We changed the `pulumi update` command to be `pulumi up` a while back
(`update` is an alias of `up`). This change just makes it so we refer to
the actual command, `pulumi up`, instead of the older `pulumi update`.
2019-05-06 14:00:18 -07:00
Alex Clemmer f21da64f96 Add query mode to the language protocol
`pulumi query` requires that language plugins know about "query mode" so
that they don't do things like try to register the default stack
resource.

To communicate that a language host should boot into query mode, we
augment the language plugin protocol to include this information.
2019-05-02 18:08:08 -07:00
Sean Gillespie ad32d9d8ac
Plumb provider version through language hosts to engine (#2656)
* NodeJS: allow callers to override provider version

* Python: allow callers to override provider version

* NodeJS: add version for invoke

* Python: add version to invoke

* NodeJS: add tests for ReadResource

* Post-merge cleanup

* update doc comments
2019-04-23 11:02:51 -07:00
Luke Hoban 0550f71a35
Add an ignoreChanges resource option (#2657)
Fixes #2277.

Adds a new ignoreChanges resource option that allows specifying a list of property names whose values will be ignored during updates. The property values will be used for Create, but will be ignored for purposes of updates, and as a result also cannot trigger replacements.

This is a feature of the Pulumi engine, not of the resource providers, so no new logic is needed in providers to support this feature. Instead, the engine simply replaces the values of input properties in the goal state with old inputs for properties marked as ignoreChanges.

Currently, only top level properties may be specified in ignoreChanges. In the future, this could be extended to support paths to nested properties (including into array elements) with a JSONPath/JMESPath syntax.
2019-04-22 13:54:48 -07:00
Joe Duffy 644d5dc916
Enable unit testing for Pulumi programs (#2638)
* Enable unit testing for Pulumi programs

This change enables rudimentary unit testing of your Pulumi programs, by introducing a `PULUMI_TEST_MODE` envvar that, when set, allows programs to run without a CLI. That includes

* Just being able to import your Pulumi modules, and test ordinary functions -- which otherwise would have often accidentally triggered the "Not Running in a CLI" error message
* Being able to verify a subset of resource properties and shapes, with the caveat that outputs are not included, due to the fact that this is a perpetual "dry run" without any engine operations occurring

In principle, this also means you can attach a debugger and step through your code.

* Finish the unit testing features

This change

1) Incorporates CR feedback, namely requiring that test mode be
   explicitly enabled for any of this to work.

2) Implements Python support for the same capabilities.

3) Includes tests for both JavaScript and Python SDKs.

* Add a note on unit testing to the CHANGELOG

* Use Node 8 friendly assert API

* Embellish the CHANGELOG entry a bit
2019-04-16 22:20:01 -07:00
Sean Gillespie 47a2acaa7b
Protobuf changes for provider versioning (#2642)
In pursuit of pulumi/pulumi#2389, this commit adds the necessary changes
to the resource monitor protocol so that language hosts can communicate
exactly what version of a provider should be used when servicing an
Invoke, ReadResource, or RegisterResource. The expectation here is that,
if a language host provides a version, the engine MUST use EXACTLY that
version of a provider plugin in order to service the request.
2019-04-16 10:06:43 -07:00
Joe Duffy cc7a657628
Make the Python SDK's Config.name argument optional (#2624)
This makes the Python SDK's Config constructor name argument
optional, similar to what we do in the Node.js SDK. If not supplied,
the current project name is used as the default.
2019-04-04 16:55:01 -07:00
CyrusNajmabadi 1f51ec00fc
Revert 'Simplify API for passing providers to a ComponentResource (#2602)' (#2606) 2019-03-28 18:31:03 -07:00
CyrusNajmabadi 49a8e73aa7
Ensure that the values in 'dependsOn' are actually Resources. (#2605) 2019-03-28 17:27:51 -07:00
CyrusNajmabadi 7193622183
Simplify API for passing providers to a ComponentResource (#2602) 2019-03-28 15:04:07 -07:00
CyrusNajmabadi 02369f9d8a
Allows the nodejs launcher to recognize that certain types of errors were printed, ensuring we don't cascade less relevant messages. (#2554) 2019-03-20 11:54:32 -07:00
Pat Gavlin 7ebd70a3e6
Refresh inputs (#2531)
These changes take advantage of the newly-added support for returning
inputs from Read to update a resource's inputs as part of a refresh.
As a consequence, the Pulumi engine will now properly detect drift
between the actual state of a resource and the desired state described
by the program and generate appropriate update or replace steps.

As part of these changes, a resource's old inputs are now passed to the
provider when performing a refresh. The provider can take advantage of
this to maintain the accuracy of any additional data or metadata in the
resource's inputs that may need to be updated during the refresh.

This is required for the complete implementation of
https://github.com/pulumi/pulumi-terraform/pull/349. Without access to
the old inputs for a resource, TF-based providers would lose all
information about default population during a refresh.
2019-03-11 13:50:00 -07:00
Pat Gavlin 905e7353e4
Update the provider RPC interface (#2512)
These changes add two new methods to the provider interface and extend
the results of three others.

The new methods are `CheckConfig` and `DiffConfig`, which fill out the
set of methods required for a complete implementation of the
first-class provider design. Though these methods are optional for
backwards compatibility, they should be implemented by all future
providers for the best possible user experience.

The adjusted result types are `DiffResponse`, `ReadResponse`, and
`ErrorResourceInitFailed`. The first has been updated to include a list
of the properties that changed (if any). The latter two now include
an estimated set of inputs for the resource as well as the resource's
state. Together, these three changes enable the engine to determine the
set of inputs that should be specified by a user in order to match those
that describe the resource's current state.

This contributes to #2453, #1662, #1635, and #1718.
2019-03-05 10:49:24 -08:00
Sean Gillespie e0b516d0cc
Fix an issue with empty ID for CustomResource (#2449)
* Fix an issue with empty ID for CustomResource

The Python runtime was checking the ID field it receives from the engine
against None, assuming that the engine would not set the ID field if one
was not present. However, it does set the ID field; it is set to the
empty string when an ID is not known.

This commit fixes an issue that can cause certain IDs to be erroneously
considered to be known during previews, which can cause problems during
the Check phase of resources that directly reference IDs of other
resources.

* Add CHANGELOG
2019-02-15 09:55:19 -08:00
Sean Gillespie 406c8ea16d
Add a test for exporting Futures (#2447)
It should be possible to export Futures as stack outputs - this test
ensures that this is the case.
2019-02-13 14:05:29 -08:00
Matt Ellis 6f386567f6 Don't install the just built package into user's site-packages
We do all our work in a virtualenv and across repositories we now
consume dependencies via pypi (also installed in a virtualenv) so best
case install into the user site packages wastes time and maybe prints
some warnings and worse case it clobbers something they've installed
for real.
2019-02-01 15:49:36 -08:00
Sean Gillespie 355f6fabe1
Typo: ProviderReference -> ProviderResource (#2418) 2019-01-31 16:03:01 -08:00
Pat Gavlin 6e90ab0341
Add support for explicit delete-before-replace (#2415)
These changes add a new flag to the various `ResourceOptions` types that
indicates that a resource should be deleted before it is replaced, even
if the provider does not require this behavior. The usual
delete-before-replace cascade semantics apply.

Fixes #1620.
2019-01-31 14:27:53 -08:00
Sean Gillespie 87b8b4dcda
Clean up documentation for Python SDK (#2398)
* Clean up documentation for Python SDK

The Python SDK currently does a couple of bad things that make it
difficult to generate documentation:

1. It "wildcard-imports" submodules without each module specifying an
__all__ member
2. Documentation strings don't have a consistent format
3. Documentation strings are in Markdown and not reStructuredText

To remedy this, this commit addresses 1 by explicitly specifying which
members are being exported from submodules, so that we can see in one
place exactly what the public surface area of the pulumi package is. For
2 and 3, this commit fixes a large number of documentation strings to
contain metadata tags that Sphinx is capable of reading. This allows us
to generate high-quality documentation directly from the source without
having to manually parse docstrings.

* Please pylint
2019-01-31 10:36:03 -08:00
Pat Gavlin 35c60d61eb
Follow up on #2369 (#2397)
- Add support for per-property dependencies to the Go SDK
- Add tests for first-class secret rejection in the checkpoint and RPC
  layers and language SDKs
2019-01-28 17:38:16 -08:00
Pat Gavlin 1ecdc83a33 Implement more precise delete-before-replace semantics. (#2369)
This implements the new algorithm for deciding which resources must be
deleted due to a delete-before-replace operation.

We need to compute the set of resources that may be replaced by a
change to the resource under consideration. We do this by taking the
complete set of transitive dependents on the resource under
consideration and removing any resources that would not be replaced by
changes to their dependencies. We determine whether or not a resource
may be replaced by substituting unknowns for input properties that may
change due to deletion of the resources their value depends on and
calling the resource provider's Diff method.

This is perhaps clearer when described by example. Consider the
following dependency graph:

  A
__|__
B   C
|  _|_
D  E F

In this graph, all of B, C, D, E, and F transitively depend on A. It may
be the case, however, that changes to the specific properties of any of
those resources R that would occur if a resource on the path to A were
deleted and recreated may not cause R to be replaced. For example, the
edge from B to A may be a simple dependsOn edge such that a change to
B does not actually influence any of B's input properties. In that case,
neither B nor D would need to be deleted before A could be deleted.

In order to make the above algorithm a reality, the resource monitor
interface has been updated to include a map that associates an input
property key with the list of resources that input property depends on.
Older clients of the resource monitor will leave this map empty, in
which case all input properties will be treated as depending on all
dependencies of the resource. This is probably overly conservative, but
it is less conservative than what we currently implement, and is
certainly correct.
2019-01-28 09:46:30 -08:00
Sean Gillespie 2ca7284179
Remove dependency on Six (#2372) 2019-01-18 13:59:37 -08:00
Sean Gillespie 3a50b84733
Explicitly convert dry_run parameter to a bool (#2361)
On startup, when we were populating the Settings object, we failed to
coerce the dry_run parameter from a string to a boolean, which resulted
in is_dry_run always believing that it was a preview. This PR fixes this
oversight by explicitly coercing to a boolean prior to sending the value
to Settings.
2019-01-16 12:06:17 -08:00
Sean Gillespie a30dcec9b1
Abnormally resolve all outputs on failed resources (#2350)
When is resource is waiting for its dependencies to resolve, it first
informs the RPC_MANAGER that it intends to do an RPC - this is to
prevent premature termination of the program while RPCs are still in
flight or queued to execute.

However, this is a problem whenever a resource fails to create for
whatever reason. The most common ways for this to happen are for invokes
to fail, resource creation itself to fail, or throwing in an apply.
Today, this causes a deadlock, since all consumers of the failed
resources block forever while never decrementing the RPC count.

This commit addresses the issue by deliberately (abnormally) resolving
all futures that are created in the process of preparing a resource.
This solves the problem by immediately terminating all resources that
are waiting for the failed resource's outputs to resolve - they resolve
immediately, and exceptionally.

The end result is now that, instead of deadlocking, a doomed program now
terminates as expected with a single exception message.
2019-01-14 11:27:21 -08:00
Sean Gillespie a3c64ed19a
Fix a Python issue when previewing providers (#2342)
When previewing a real first-class provider, it is often the case that
the provider's ID is unknown during a preview. This commit fixes a bug
where we did not translate an unknown ID into the rpc layer's sentinel
UNKNOWN value where we should have, which caused the engine to fail to
resolve the provider reference.
2019-01-10 13:14:59 -08:00
Sean Gillespie a18610c993
Improve error message when pulumi is not installed (#2348)
For some reason, writing to stderr using sys.stderr.write doesn't work,
but printing to stderr using the print function does. I don't know why
this is, but I do know that this makes the printed messages show up as
messages on the Pulumi CLI.
2019-01-10 12:59:13 -08:00
Sean Gillespie 8b52e480ed
Implement first-class providers for invokes (#2339)
Invoke in Node.js allows users to optionally pass a parent or a provider
to the invoke, which dictates either explicitly or implicitly which
provider to use when performing an invoke. If a provider is specified
explicitly, that provider is used to perform the invoke. If a parent is
specified, that parent's provider is used to perform the invoke.
2019-01-07 12:53:08 -08:00
Sean Gillespie a37b3d89e3
Implement first-class providers for Python (#2335)
* Implement first-class providers for Python

First-class providers are an explicit projection of providers themselves
into Pulumi programs. For the most post, providers are just regular
resources, but the addition of providers to the fray (and the ability of
resources to be constructed by providers in the same program) requires
some changes to the Python resource model.

A summary of the changes:

1. Added ProviderResource, a custom resource that is the base class of
all providers.
2. ResourceOptions now has 'provider' and 'providers' fields.
'provider', when passed to a custom resource, allows users to override
the provider that is used to construct a resource to an instance of a
ProviderResource. 'providers', when passed to a component resource,
allows users to override providers used to construct children of the
component resource.
3. 'protect', 'providers', and 'provider' are all now inherited from
a resource's parent if they aren't specified in the child.

This commit adds the requisite code for the above changes and, in
addition, adds a number of new tests that exercise them and related code
paths.

* Rebase against master
2019-01-04 15:44:27 -08:00
Sean Gillespie 81c0de1e4e
Add 'Output.all' combinator for Python (#2293)
* Add 'Output.all' combinator for Python

Output.all is a useful combinator that we already have in Node that
allows the composition of a list of outputs into an output of a list.
This is very useful when authoring components and its lack of presence
in Python was an oversight.

This commit adds 'Output.all' and 'Output.from_input', adding tests and
documentation for each.

* start unwrap

* Add functionality and test for nested inputs
2018-12-18 13:22:04 -08:00
Sean Gillespie 03e70a188b
Flush stdout and stderr on abnormal lang shutdown (#2226)
The langhost shares its standard out and standard error with the
language executor that it is used (python/nodejs), so we must be sure to
flush our stdout and stderr before reporting a Run failure to the
engine.
2018-11-19 17:59:01 -05:00
Sean Gillespie 03dbf2754c
Launch Python programs with 'python3' by default (#2204)
'python' is not usually symlinked to 'python3' on most distros unless
you are already running in a virtual environment. Launching 'python3'
explicitly ensures that we will either launch the program successfully
or immediately fail, instead of launching the program with Python 2 and
failing with syntax errors at runtime.

This commit also emits an error message asking users to install Python
3.6 or later if we failed to find the 'python3' executable.
2018-11-19 17:54:24 -05:00
Sean Gillespie c1582264e1
Fix, formalize and add tests for property rewrites (#2187)
* Fix, formalize and add tests for property rewrites

The Python SDK provides two hooks for resources to override how their
properties are communicated to and from the engine. The code that
performs this transformation is subtle and, before this commit, subtly
incorrect.

This commit adds a test that verifies that the SDK correctly transforms
properties recursively according to the two transformation hooks, while
also fixing a smattering of test issues encountered when adding the new
test.

* CR feedback
2018-11-12 09:26:31 -08:00
Joe Duffy 1e9f5b96f2
Merge pull request #2164 from pulumi/ellismg/update-tools
Update to Go 1.11 and golangci-lint
2018-11-10 17:32:14 -08:00
Sean Gillespie 828d59665e
Implement Invoke for Python 3 (#2175)
* Implement Invoke for Python 3

* CR feedback
2018-11-09 14:27:10 -08:00
Sean Gillespie f625376915
Fix presentation of RunErrors (#2188)
The correct way to retrieve an exception's message in Python is to
stringify it with str.
2018-11-09 12:55:10 -08:00
Pat Gavlin b753341686
Exclude the unscriptable-object rule (#2184)
Python 3.7 gets this rule wrong for `Generic[]`.

https://github.com/PyCQA/pylint/issues/2416 tracks this issue in pylint.
2018-11-08 18:26:13 -08:00
Matt Ellis 992b048dbf Adopt golangci-lint and address issues
We run the same suite of changes that we did on gometalinter. This
ended up catching a few new issues, some of which were addressed and
some of which were baselined.
2018-11-08 14:11:47 -08:00
Matt Ellis adb0d9aee6 Use pipenv from the toolset
- Remove the forked copy of the toolset
- Stop installing `pipenv` in sdk/python/Makefile

After this, we'll require that you already have `pipenv` present
before building.
2018-11-08 12:09:21 -08:00
Sean Gillespie 9c82082a57
Implement RegisterResourceOutputs for Python 3 (#2173)
* Implement RegisterResourceOutputs for Python 3

RegisterResourceOutputs allows Python 3 programs to export stack outputs
and export outputs off of component resources (which, under the hood,
are the same thing).

Adds a new integration test for stack outputs for Python programs, as
well as add a langhost test for register resource outputs.

Fixes pulumi/pulumi#2163

* CR: Rename stack_output -> export

Fix integration tests that hardcoded paths to stack_outputs

* Fix one more reference to stack_outputs
2018-11-08 09:44:34 -08:00
CyrusNajmabadi 08fc305b7f
Prevent resource registration from overwriting unknown properties at random points in the future. (#2176) 2018-11-07 20:24:16 -08:00
Sean Gillespie 0e868f15fc
Add two new Python tests and fix bugs (#2147)
future_input tests that it's possible to use coroutines as inputs to
Pulumi resources. resource_thens tests that it's possible to use outputs
to chain resource inputs and outputs together and that the SDK reports
correct dependencies to the engine.

This PR also fixes two bugs exposed by the new tests: first, coroutines
needed to be scheduled before awaiting (otherwise we'd deadlock) and
Nones in maps needed to be ignored when serializing and deserializing.
2018-11-02 16:50:10 -07:00
Sean Gillespie 8ca2840577
Enable and fix Pylint warnings (#2146)
* Enable pylint warnings

* Fix or ignore pylint warnings
2018-11-01 14:29:06 -07:00
Sean Gillespie 6fa67329de
Several gardening tasks for Python (#2145)
* Several gardening tasks for Python

1. Update pipenv to 2018.7.1, which is the most recent release that
isn't broken on Python 2
2. Update our pylint dependency to 1.9, the most recently released
version
3. Re-enable pylint for the Pulumi package

* Back out of pipenv upgrade

It's apparently broken in our CI. Also upgrade pylint to 2.1, which is
apparently the "actual" most recently release according to PyPI.

* Fix a bad merge
2018-11-01 12:58:45 -07:00
Sean Gillespie 946ca655d3
Provide a Py hook for providers to rename props (#2140)
* Provide a Py hook for providers to rename props

This commit adds input and output hooks that can be overridden by
providers if they would like to change the names of dictionary fields
when projecting resources into Python.

* Add syntax sugar for dict outputs

Properly recurse when rewriting input dictionaries
2018-11-01 10:25:47 -07:00
Sean Gillespie 56be1a6677
Implement RPC for Python 3 (#2111)
* Implement RPC for Python 3

* Try not setting PYTHONPATH

* Remove PYTHONPATH line

* Implement Invoke for Python 3

* Implement register resource

* progress

* Rewrite the whole thing

* Fix a few bugs

* All tests pass

* Fix an abnormal shutdown bug

* CR feedback

* Provide a hook for resources to rename properties

As dictionaries and other classes come from the engine, the
translate_property hook can be used to intercept them and rename
properties if desired.

* Fix variable names and comments

* Disable Python integration tests for now
2018-10-31 13:35:31 -07:00
Sean Gillespie 85623d6c4d
Implement Output for Python (#2107) 2018-10-26 14:52:30 -07:00
Sean Gillespie 53aea7bc12
Begin Python 3 conversion (#2103)
This commit introduces a 'next' package which we can use as a staging
ground for incrementally adopting new Python 3 code. The next package is
initially populated with the non-runtime portions of the Python SDK,
which is enough to pass all tests when running on Python 3. Future
commits will reach further into the runtime.
2018-10-26 11:05:45 -07:00
Sean Gillespie 8c230e9caa
Implement log functions for the Python SDK (#2048)
With this commit, the functions in 'pulumi.log' can be used to send
diagnostic messages to the Pulumi CLI. The Pulumi SDK bootstrap script
now also uses this feature to send diagnostic information on unhandled
exceptions to the Pulumi CLI.
2018-10-12 09:50:26 -07:00
Sean Gillespie 6707accdc8
Get rid of waitForDeath (#2041)
Instead of looping forever, due to some recent improvements in engine
error handling it's sufficient for a language host to exit cleanly with
a zero exit code when the resource monitor is shutting down.
2018-10-10 10:01:57 -07:00
joeduffy 162157c1a7 Add a Dockerfile for the Pulumi CLI
This introduces a Dockerfile for the Pulumi CLI. This makes it
easier to develop and test the engine in a self-contained environment,
in addition to being suitable for running the actual CLI itself.

For instance,

    $ docker run pulumi/pulumi -e "PULUMI_ACCESS_TOKEN=x" up

will run the Pulumi program mounted under the /app volume. This will
be used in some upcoming CI/CD scenarios.

This uses multi-stage builds, and Debian Stretch as the base, for
relatively fast and lean build times and resulting images. We are
intentional about restoring dep packages independent of the actual
source code so that we don't end up needlessly re-depping, which can
consume quite a bit of time. After fixing
https://github.com/pulumi/pulumi/issues/1986, we should explore an
Alpine base image option.

I made the decision to keep this image scoped to just the Go builds.
Therefore, none of the actual SDK packages themselves are built, just
the engine, CLI, and language plugins for Node.js, Python, and Go.
It's possible to create a mega-container that has all of these full
environments so that we can rebuild them too, but for now I figured
it was better to rely on package management for them.

Another alternative would have been to install released binaries,
rather than building them. To keep the useful flow for development,
however, I decided to go the build route for now. If we build at the
same hashes, the resulting binaries "should" be ~identical anyhow.

I've created a pulumi/pulumi Docker Hub repo that we can publish this
into. For now, there is no CI publishing of the image.

This fixes pulumi/pulumi#1991.
2018-09-29 11:48:21 -07:00
Sean Gillespie 2d4a3f7a6a
Move management of root resource state to engine (#1944)
* Protobuf changes

* Move management of root resource state to engine

This commit fixes a persistent side-by-side issue in the NodeJS SDK by
moving the management of root resource state to the engine. Doing so
adds two new endpoints to the Engine gRPC service: 1) GetRootResource
and 2) SetRootResource, which get and set the root resource
respectively.

* Rebase against master, regenerate proto
2018-09-18 11:47:34 -07:00
Sean Gillespie f284112b4e
Use nightly protoc gRPC plugin for node (#1948)
* Use nightly protoc gRPC plugin for Node

Newer versions of the Node gRPC plugin accept the 'minimum_node_version'
flag, which we can use to instruct protoc to not support Node versions
earlier than Node 6. This allows the compiler to use 'Buffer.from'
instead of the deprecated 'Buffer' constructor, which fixes a
deprecation warning on Node 10.

* Protobuf changes
2018-09-17 15:16:31 -07:00
Alex Clemmer 3cc04a6f75 LogRequest.isStatus -> LogRequest.ephemeral 2018-08-31 15:56:53 -07:00
Alex Clemmer 665b219a0e Allow log events to be marked "status" events
This commit will introduce a field, `IsStatus` to `LogRequest`. A
"status" logging event will be displayed in the `Info` column of the
main display, but will not be printed out at the end, when resource
operations complete.

For example, for complex resource initialization, we'd like to display a
series of intermediate results: `[1/4] Service object created`, for
example. We'd like these to appear in the `Info` column, but not at the
end, where they are not helpful to the user.
2018-08-30 17:17:20 -07:00
Thomas Schersach 3224cdfcec Use go env to resolve GOPATH but escape it properly 2018-08-13 10:54:20 -07:00
Thomas Schersach a254c05271 Fix gopath resolution in python makefile dist target 2018-08-13 10:54:20 -07:00
Matt Ellis 84ac039661 Also copy python helper script during make dist
During Code Review, I forgot that for the python language host we need
both the go binary and the -exec script.
2018-08-08 20:51:02 -07:00
Matt Ellis c8b1872332
Merge pull request #1698 from pulumi/ellismg/fix-1581
Allow eliding name in pulumi.Config .ctor
2018-08-08 14:16:20 -07:00
Thomas Schersach 62463ab3bc Added dist target for make, will help with Homebrew (#1731)
* Added dist target for make, will help with Homebrew

* Try to install go dependencies before building

* Make sure dep ensure is called before trying to build SDKs

* Removed dep ensure from dist initial step
2018-08-08 13:00:42 -07:00
Pat Gavlin a222705143
Implement first-class providers. (#1695)
### First-Class Providers
These changes implement support for first-class providers. First-class
providers are provider plugins that are exposed as resources via the
Pulumi programming model so that they may be explicitly and multiply
instantiated. Each instance of a provider resource may be configured
differently, and configuration parameters may be source from the
outputs of other resources.

### Provider Plugin Changes
In order to accommodate the need to verify and diff provider
configuration and configure providers without complete configuration
information, these changes adjust the high-level provider plugin
interface. Two new methods for validating a provider's configuration
and diffing changes to the same have been added (`CheckConfig` and
`DiffConfig`, respectively), and the type of the configuration bag
accepted by `Configure` has been changed to a `PropertyMap`.

These changes have not yet been reflected in the provider plugin gRPC
interface. We will do this in a set of follow-up changes. Until then,
these methods are implemented by adapters:
- `CheckConfig` validates that all configuration parameters are string
  or unknown properties. This is necessary because existing plugins
  only accept string-typed configuration values.
- `DiffConfig` either returns "never replace" if all configuration
  values are known or "must replace" if any configuration value is
  unknown. The justification for this behavior is given
  [here](https://github.com/pulumi/pulumi/pull/1695/files#diff-a6cd5c7f337665f5bb22e92ca5f07537R106)
- `Configure` converts the config bag to a legacy config map and
  configures the provider plugin if all config values are known. If any
  config value is unknown, the underlying plugin is not configured and
  the provider may only perform `Check`, `Read`, and `Invoke`, all of
  which return empty results. We justify this behavior becuase it is
  only possible during a preview and provides the best experience we
  can manage with the existing gRPC interface.

### Resource Model Changes
Providers are now exposed as resources that participate in a stack's
dependency graph. Like other resources, they are explicitly created,
may have multiple instances, and may have dependencies on other
resources. Providers are referred to using provider references, which
are a combination of the provider's URN and its ID. This design
addresses the need during a preview to refer to providers that have not
yet been physically created and therefore have no ID.

All custom resources that are not themselves providers must specify a
single provider via a provider reference. The named provider will be
used to manage that resource's CRUD operations. If a resource's
provider reference changes, the resource must be replaced. Though its
URN is not present in the resource's dependency list, the provider
should be treated as a dependency of the resource when topologically
sorting the dependency graph.

Finally, `Invoke` operations must now specify a provider to use for the
invocation via a provider reference.

### Engine Changes
First-class providers support requires a few changes to the engine:
- The engine must have some way to map from provider references to
  provider plugins. It must be possible to add providers from a stack's
  checkpoint to this map and to register new/updated providers during
  the execution of a plan in response to CRUD operations on provider
  resources.
- In order to support updating existing stacks using existing Pulumi
  programs that may not explicitly instantiate providers, the engine
  must be able to manage the "default" providers for each package
  referenced by a checkpoint or Pulumi program. The configuration for
  a "default" provider is taken from the stack's configuration data.

The former need is addressed by adding a provider registry type that is
responsible for managing all of the plugins required by a plan. In
addition to loading plugins froma checkpoint and providing the ability
to map from a provider reference to a provider plugin, this type serves
as the provider plugin for providers themselves (i.e. it is the
"provider provider").

The latter need is solved via two relatively self-contained changes to
plan setup and the eval source.

During plan setup, the old checkpoint is scanned for custom resources
that do not have a provider reference in order to compute the set of
packages that require a default provider. Once this set has been
computed, the required default provider definitions are conjured and
prepended to the checkpoint's resource list. Each resource that
requires a default provider is then updated to refer to the default
provider for its package.

While an eval source is running, each custom resource registration,
resource read, and invoke that does not name a provider is trapped
before being returned by the source iterator. If no default provider
for the appropriate package has been registered, the eval source
synthesizes an appropriate registration, waits for it to complete, and
records the registered provider's reference. This reference is injected
into the original request, which is then processed as usual. If a
default provider was already registered, the recorded reference is
used and no new registration occurs.

### SDK Changes
These changes only expose first-class providers from the Node.JS SDK.
- A new abstract class, `ProviderResource`, can be subclassed and used
  to instantiate first-class providers.
- A new field in `ResourceOptions`, `provider`, can be used to supply
  a particular provider instance to manage a `CustomResource`'s CRUD
  operations.
- A new type, `InvokeOptions`, can be used to specify options that
  control the behavior of a call to `pulumi.runtime.invoke`. This type
  includes a `provider` field that is analogous to
  `ResourceOptions.provider`.
2018-08-06 17:50:29 -07:00
Matt Ellis 153729683a Allow eliding name in pulumi.Config .ctor
When this argument is not provided, we'll default to the value of
pulumi.getProject(). This is what you want for application level code
anyway and it matches the CLI behavior where if you don't qualify a
key with a package we use the name of the current project.

Fixes #1581
2018-08-06 16:03:54 -07:00
Sean Gillespie 48aa5e73f8
Save resources obtained from ".get" in the snapshot (#1654)
* Protobuf changes to record dependencies for read resources

* Add a number of tests for read resources, especially around replacement

* Place read resources in the snapshot with "external" bit set

Fixes pulumi/pulumi#1521. This commit introduces two new step ops: Read
and ReadReplacement. The engine generates Read and ReadReplacement steps
when servicing ReadResource RPC calls from the language host.

* Fix an omission of OpReadReplace from the step list

* Rebase against master

* Transition to use V2 Resources by default

* Add a semantic "relinquish" operation to the engine

If the engine observes that a resource is read and also that the
resource exists in the snapshot as a non-external resource, it will not
delete the resource if the IDs of the old and new resources match.

* Typo fix

* CR: add missing comments, DeserializeDeployment -> DeserializeDeploymentV2, ID check
2018-08-03 14:06:00 -07:00
Alex Clemmer 0575595668 Add Pipfile.lock to make Python builds reproducible 2018-07-15 11:05:44 -10:00
Alex Clemmer 0e39b3c868 Add Cancel to gRPC resource provider interface 2018-07-15 11:05:44 -10:00
Matt Ellis 1f638410c7 Include README in pypi package
Use `pandoc` to convert our README.md to a README.rst and then include
that as the long_description in our pypi package.
2018-07-13 18:19:42 -07:00
Alex Clemmer db9277f934
Merge pull request #1590 from hausdorff/hausdorff/partial-update
Add partial state update
2018-07-06 16:14:49 -07:00
Joe Duffy e8b5bb6f11
Export asset members from pulumi module (#1591) 2018-07-03 09:25:40 -07:00
Joe Duffy 416d3f5594
Merge pull request #1586 from pulumi/swgillespie/fix-unknown
Fix an issue where Unknown does not coerce to a bool correctly on Python
2018-07-02 14:55:03 -07:00
Joe Duffy 41996091af
Merge pull request #1587 from pulumi/swgillespie/python-assets
Implementation of Assets for Python
2018-07-02 14:52:30 -07:00
joeduffy ae50253db5 Add support for archives 2018-07-02 14:24:45 -07:00
joeduffy d89192a9d0 Fix reference to _custom_resource_type 2018-07-02 13:51:12 -07:00
Sean Gillespie 8b9e24cd85 Allow dynamic-provider to send structured errors
A critical part of the partial update protocol is to return a structured
error when a resource is successfully created, but fails to initialize.
This structured error contains the properties of the
partially-initialized resource, and instructs the engine to halt.

Most languages implement this by attaching "details" to the error, i.e.,
an arbitrary proto message attached to the error. The JavaScript
implementation is not mature enough to include all the facilities
required to use this, so here we must add a `Status` message, which
protobuf requires as part of its structure for returning details.
2018-07-02 13:32:23 -07:00
Alex Clemmer 3bd2e6f235 Represent init errors in resource provider proto 2018-07-02 13:32:23 -07:00
Sean Gillespie 279282f1e1
Implementation of Assets for Python 2018-06-29 17:07:27 -07:00
Sean Gillespie 1db89a1006
Fix an issue where we fail to rethrow exceptions arising from failed resource operations 2018-06-29 16:32:39 -07:00
Sean Gillespie f0d5d0e4fe
Fix an issue where Unknown does not coerce to a bool correctly on Python
2
2018-06-29 15:51:04 -07:00
Sean Gillespie 5d1a3db4aa
Python Language Host Tests (#1577)
* Test the Python language host end-to-end

This commit introduces an end-to-end language host testing framework for
the Python SDK, similar to what already exists for the Node SDK. The
real language host is used to run Pulumi programs written in Python
while mocking out the resource monitor.

* Add new tests

* Print out better diagnostics when the langhost fails to launch

* Use the in-tree executor for testing

* CR: Place tests and code being tested in the same directory for ease of understanding, add a README

* Turns out I misunderstood the semantics of resource registration - fix two tests so that they pass now and fix a few bugs in the test harness
2018-06-29 14:08:58 -07:00
Sean Gillespie c2b2f3b117
Initial Python 3 port of the Python SDK (#1563)
* Machine-assisted Python 3 port

* Hack around protoc python imports

* Regenerate gRPC and protobuf

* CR: Bash code cleanup
2018-06-26 11:14:03 -07:00
Sean Gillespie abb0c2769b
Pin to a specific Pipenv version (#1570) 2018-06-25 14:08:56 -07:00
Sean Gillespie 89b052fc6d
Use Pipenv to manage Python environments (#1553)
* Use Pipenv to manage Python environments

* Rename PIPENV_ARGS to PIPENV_PYTHON_VERSION to avoid confusion. Also remove two unused variables
2018-06-21 18:01:23 -07:00
Matt Ellis 6f80da24d4 Add Apache 2.0 License metadata to Python package 2018-06-15 12:47:51 -07:00
Matt Ellis d0485f11f6 Include Python and Go langhosts in Windows SDK
This change includes the Python and Golang language hosts in the Windows
SDK. As part of this change, I had to adjust how we launched the second
stage of the language host, since we can't depend on the shebang, so now
we invoke `python` passing the executor and then the arguments.

Fixes #1509
2018-06-15 11:12:33 -07:00
Sean Gillespie 8a00cb4d3b
Support better previews in Python by mocking out Unknown values (#1482) 2018-06-11 10:30:27 -07:00
Sean Gillespie b5e4d87687
Improve the error message when data source invocations fail (#1472) 2018-06-07 11:21:38 -07:00
Sean Gillespie 5cbc979e17
Fix a couple of issues when projecting Protobuf and UNKNOWN in Python (#1468)
* Fix a few issues with the Python language host

1. Fix an issue where the UNKNOWN sentinel was leaking into user
programs
2. Fix an issue where Protobuf types were leaking into user programs

In fixing this issues I also added a framework for writing tests against
the Python SDK.

* License headers, and adopt a more idiomatic testing pattern

* Additional idiomatic Python

* That's what I get for trying to be fancy (Travis CI python version is very old and does not respect this form)

* CR feedback: use more comprehensions, typo fix

* Break a circular dependency between resource, runtime.resource, and runtime.rpc

* Don't check in .vscode

* CR: sort inputs, rename global variable, add a test for CustomResource serialization

* Remove accidental code duplication
2018-06-06 16:09:07 -07:00
joeduffy 5967259795 Add license headers 2018-05-22 15:02:47 -07:00
Sean Gillespie 68911900fd
Graceful shutdown (#1320)
* Graceful RPC shutdown: CLI side

* Handle unavailable resource monitor in language hosts

* Fix a comment

* Don't commit package-lock.json

* fix mangled pylint pragma

* Rebase against master and fix Gopkg.lock

* Code review feedback

* Fix a race between closing the callerEventsOpt channel and terminating a goroutine that writes to it

* glog -> logging
2018-05-16 15:37:34 -07:00
CyrusNajmabadi 72e00810c4
Filter the logs we emit to glog so that we don't leak out secrets. (#1371) 2018-05-15 15:28:00 -07:00
Pat Gavlin 97ace29ab1
Begin tracing Pulumi API calls. (#1330)
These changes enable tracing of Pulumi API calls.

The span with which to associate an API call is passed via a
`context.Context` parameter. This required plumbing a
`context.Context` parameter through a rather large number of APIs,
especially in the backend.

In general, all API calls are associated with a new root span that
exists for essentially the entire lifetime of an invocation of the
Pulumi CLI. There were a few places where the plumbing got a bit hairier
than I was willing to address with these changes; I've used
`context.Background()` in these instances. API calls that receive this
context will create new root spans, but will still be traced.
2018-05-07 18:23:03 -07:00
Sean Gillespie 5decc10cbb
Improve the error message if Pulumi runtime SDK isn't installed (#1286)
* Improve the error message when npm/yarn install hasn't been run

* Same thing, but for Python

* Use PULUMI_RUN in batch script

* Use -e, -f doesn't work for symlinked paths (e.g. yarn link)
2018-04-27 16:55:41 -07:00
Joe Duffy 0d79d2106c
Ensure pip 10.0.0 is installed (#1199)
This change installs pip 10.0.0 in all three places it might come up:

1) Machine-wide packages.

2) User-local packages.

3) In the isolated virtualenv.
2018-04-14 16:43:48 -07:00
Joe Duffy 479a2e6ad5
Add an ID property to ReadResponse (#1145)
The RPC provider interface needs a way to convey back to the engine
that a resource being read no longer exists.  To do this, we'll return
the ID property that was read back.  If it is empty, it means the
resource is gone.  If it is non-empty, we expect it to match the input.
2018-04-10 12:58:50 -07:00
joeduffy 5e28a4ab07 Add the ability to read an existing resource
This change wires up the new Read RPC method in such a manner that
Pulumi programs can invoke it.  This is technically not required for
refreshing state programmatically (as in pulumi/pulumi#1081), however
it's a feature we had eons ago and have wanted since (see
pulumi/pulumi#83), and will allow us to write code like

    let vm = aws.ec2.Instance.get("my-vm", "i-07043cd97bd2c9cfc");
    // use any property from here on out ...

The way this works is simply by bridging the Pulumi program via its
existing RPC connection to the engine, much like Invoke and
RegisterResource RPC requests already do, and then invoking the proper
resource provider in order to read the state.  Note that some resources
cannot be uniquely identified by their ID alone, and so an extra
resource state bag may be provided with just those properties required.

This came almost for free (okay, not exactly) and will come in handy as
we start gaining experience with reading live state from resources.
2018-04-05 09:48:09 -07:00
joeduffy 22584e7e37 Make some resource model changes
This commit changes two things about our resource model:

* Stop performing Pulumi Engine-side diffing of resource state.
  Instead, we defer to the resource plugins themselves to determine
  whether a change was made and, if so, the extent of it.  This
  manifests as a simple change to the Diff function; it is done in
  a backwards compatible way so that we continue with legacy diffing
  for existing resource provider plugins.

* Add a Read RPC method for resource providers.  It simply takes a
  resource's ID and URN, plus an optional bag of further qualifying
  state, and it returns the current property state as read back from
  the actual live environment.  Note that the optional bag of state
  must at least include enough additional properties for resources
  wherein the ID is insufficient for the provider to perform a lookup.
  It may, however, include the full bag of prior state, for instance
  in the case of a refresh operation.

This is part of pulumi/pulumi#1108.
2018-04-05 08:14:25 -07:00
Sean Gillespie a3a6101e79
Improve the error message arising from missing required configs for resource providers (#1097)
* Improve the error message arising from missing required configs for
resource providers

If the resource provider that we are speaking to is new enough, it will send
across a list of keys and their descriptions alongside an error
indicating that the provider we are configuring is missing required
config. This commit packages up the list of missing keys into an error
that can be presented nicely to the user.

* Code review feedback: renaming simplification and correcting errors in comments
2018-04-04 10:08:17 -07:00
Joe Duffy 19e6c9c2bc
Fix Python versions (again) (#1106)
This change actually makes our Python version numbers conformant
to PEP440.  Previously we were including the Git commit hash in the
alpha "version number" part, which is incorrect.  This simply led to
warnings upon publication and installation, but that warning very
clearly states that support for invalid versions will stop at some
point.  This change puts any "informative" parts, like the Git hash,
inside of a local version tag, where such things are permitted.

Also move away from the inline sed silliness so that we can more
easily share this logic across all of our repos.
2018-04-02 10:31:05 -07:00
Joe Duffy 0c308efb1d
Install virtualenv to user packages (#1104)
This installs virtualenv to the user packages site, to insulate us from
permission problems in CI, and also invokes that version.
2018-04-01 18:54:57 -07:00
joeduffy e27ad9eb75 Specify virtualenv>=15.2.0
It appears 15.0.2 generates a bad reference to the pip._install module.
I've tested that 15.2.0 does not so, although I don't really understand
why and when this changed (my current guess is the Travis base image
changed), this should fix pulumi/pulumi#1103.
2018-03-31 16:57:37 -07:00
Sean Gillespie 91c550f1e0
Send structured errors across RPC boundaries (#1072)
* Send structured errors across RPC boundaries

This brings us closer to gRPC best practices where we send structured
errors with error codes across RPC endpoints. The new "rpcerrors"
package can wrap errors from RPC endpoints, so RPC servers can attach
some additional context as to why a request failed.

* Code review feedback:

1. Rename rpcerrors -> rpcerror, better package name
2. Rename RPCError -> Error, RPCErrorCause -> ErrorCause, names
suggested by gometalinter to improve their package-qualified names
3. Fix import organization in rpcerror.go
2018-03-28 17:07:35 -07:00
Pat Gavlin a23b10a9bf
Update the copyright end date to 2018. (#1068)
Just what it says on the tin.
2018-03-21 12:43:21 -07:00
joeduffy 7162f6ea52 Publish proper pre-release PyPI packages
The semantic versions we were using for pre-release PyPI packages wasn't
quite right.  We had been using local version identifiers, a la +, rather
than proper pre-release tags, which means that version specifications like
`pulumi==0.11.0` will match `0.11.0+dev.1521506136.g7f043fd.dirty`, in
addition to just `0.11.0`.  This is clearly not what we want.

This change moves us over to proper alpha and release candidate versions,
as specified in https://www.python.org/dev/peps/pep-0440/#pre-releases.
Namely, any `x.y.z-dev-123456789-abcdef` version will get translated into
an alpha `x.y.za12345679-abcdef`, and any `x.y.z-rc1` will get translated
into a proper release candidate `x.y.zrc1` version number.
2018-03-19 18:18:25 -07:00
joeduffy c50899aca3 Add some TODO refs to pulumi/pulumi#1063 2018-03-19 18:17:57 -07:00
Matt Ellis 38ec631753
Merge pull request #1056 from pulumi/change-version-number
Adopt new version strategy
2018-03-19 13:25:12 -07:00
Joe Duffy 1a475aeb38
Implement Python invoke RPC (#1054)
Implement Python invoke RPC

This change implements the invoke function for resource provider
RPCs.  This is required to support a customer scenario.

There are a few other minor updates:

* Rename pulumi.export to pulumi.output.

* Change register_resource to, like invoke, return the resulting
  object/dictionary, instead of the set_outputs function.

* Initialize the monitor/engine RPC connections to None when not
  attached to the engine, thus ensuring good error messages.

* Fix Python project/stack metadata
2018-03-16 08:39:24 -07:00
Matt Ellis 5c4a31f692 Adopt new version strategy
Our previous strategy of just using `git describe --tags --dirty` to
compute a version caused issues. The major one was that since version
sort lexigrapically, git's strategy of having a commit count without
leading zeros lead to cases where 0.11.0-dev-9 was "newer than"
0.11.0-dev-10 which is not what you want at all.

With this change, we compute a version by first seeing if the commit
is tagged, and if so, we use that tag. Otherwise, we take the closest
tag and to it append the unix timestamp of the commit and then append
a git hash.

Because we use the commit timestamp, things will sort correctly again.

Part of pulumi/home#174
2018-03-15 18:06:04 -07:00
Joe Duffy 98aaf12cdf
Reenable Pylint (#1024)
This change uses virtualenv to insulate us from platform differences
in our building of the Python SDK, and to create an isolated Python 2
environment.  This includes meaning we don't need to worry about the
specific location and behavior of Pylint.  I *think* this will work
no matter whether it's Mac, Ubuntu, ArchLinux, Windows, and so on.

We do install to the --user directory in the install target using
`pip install -e`, however, which enables the machine-wide symlinking
that we need to support various workflows.

This fixes pulumi/pulumi#1007.
2018-03-09 15:11:37 -08:00
joeduffy 66f3f84d16 Disable Pylint temporarily
This change temporarily disables Pylint.  Assuming it is on the path,
and furthermore that the one on the path runs under 2.7, simply won't
work.  See pulumi/pulumi#1007 for details; it also tracks reenabling.
2018-03-07 09:06:51 -08:00
joeduffy 440ffb27e5 Prefer Python2 tools; fail-fast when wrong
This change includes a few things:

1) Prefer python2 and pip2 when on the PATH, over the undecorated
   names python and pip.  This is the standard convention for package
   managers like Pip, etc., to support Python2 and Python3 side-by-side.

2) Fail-fast if neither can be found on the PATH.

3) Check the reported version number for python, pip, and pylint, and
   fail-fast if it doesn't report back 2.7, just to safeguard against
   undecorated binaries with unsupported versions.

Also, we had not listed wheel as a dependency in the requirements.txt
file.  This needs to be there to support building bdist_wheels.  Fixed.
2018-03-06 17:50:42 -08:00
Joe Duffy 9412f4ac7a
Publish Pulumi Python SDK package (#988)
We now publish the Pulumi Python SDK package to our private PyPI
server at the same time we also publish the NPM package.  For now,
we use the test Pulumi.com service, and will switch to staging as
soon as it becomes available.
2018-02-28 18:38:08 -08:00
Luke Hoban ff87af1a44
Workaround for issue with python setup.py (#980)
Pass `--prefix=` to avoid hitting: `error: can't combine user with with prefix/exec_prefix/home or install_(plat)base`.
2018-02-24 17:50:54 -08:00
joeduffy a1c4115fa6 Also setup.py with --user
This ensures we can properly install the built package in Travis's
images, which have everything owned by root by default.
2018-02-24 09:52:30 -08:00
joeduffy 4f591bed76 Use a newer pylint
This ensures the new exclusion syntax is accepted, which is required
to ignore the Protobuf-generated files which have numerous lint warnings.
2018-02-24 09:52:30 -08:00
joeduffy 153344354c Pip install to user homedir
This change passes --user to pip install, so that it installs packages
underneath the home directory.  This is required because, except for the
"python" image in Travis, all Python and Pip-related directories are
root-owned.  The --user approach avoids needing to sudo all over the place.
2018-02-24 09:21:16 -08:00
joeduffy a045e2fb1e Implement more of the Python runtime
This change includes a lot more functionality.  Enough to actually
run the webserver-py example through previews, updates, and destroys!

* Actually wire up the gRPC connections to the engine/monitor.

* Move the Node.js and Python generated Protobuf/gRPC files underneath
  the actual SDK directories to simplify this generally.  No more
  copying during `make` and, in fact, this was required to give a smoother
  experience with good packages/modules for the Python's SDK development.

* Build the Python egg during `make build`.

* Add support for program stacks.  Just like with the Node.js runtime,
  we will auto-parent any resources without explicit parents to a single
  top-level resource component.

* Add support for component resource output properties.

* Add get_project() and get_stack() functions for retrieving the current
  project and stack names.

* Properly use UNKNOWN sentinels.

* Add a set_outputs() function on Resource.  This is defined by the
  code-generator and allows custom logic for output property setting.
  This is cleaner than the way we do this in Node.js, and gives us a
  way to ensure that output properties are "real" properties, complete
  with member documentation.  This also gives us a hook to perform
  name demangling, which the code-generator typically controls anyway.

* Add package dependencies to setuptools.py and requirements.txt.
2018-02-24 08:58:34 -08:00
joeduffy 74563afdc8 Get the empty Python program working
This change gets enough of the Python SDK up and running that the
empty Python program will work.  Mostly just scaffolding, but the
basic structure is now in place.  The primary remaining work is to
wire up resource creation to the gRPC interfaces.

In summary:

* The basic structure is as follows:

    - Everything goes into sdk/python/.

    - sdk/python/cmd/pulumi-langhost-python is a Go language host
      that simply knows how to spawn Python processes to run out
      entrypoint in response to requests by the engine.

    - sdk/python/cmd/pulumi-langhost-python-exec is a little Python
      shim that is invoked by the language host to run Python programs,
      and is responsible for setting up the minimal goo before we can
      do so (RPC connections and the like).

    - sdk/python/lib/ contains a Python Pip package suitable for PyPi.

    - In there, we have two packages: the root pulumi package that
      contains all of the basic Pulumi programming model abstractions,
      and pulumi.runtime, which contains the implementation of
      resource registration, RPC interfacing with the engine, and so on.

* Add logic in our test framework to conditionalize on the language
  type and react accordingly.  This will allow us to skip Yarn for
  Python projects and eventually run Pip if there's a requirements.txt.

* Created the basic project structure, including all of the usual
  Make targets for installing into the proper places.

* Building also runs Pylint and we are clean.

There are a few other minor things in here:

* Add an "empty" test for both Node.js and Python.  These pass.

* Fix an existing bug in plugin shutdown logic.  At some point, we
  started waiting for stderr/stdout to flush before shutting down
  the plugin; but if certain failures happen "early" during the
  plugin launch process, these channels will never get initialized
  and so waiting for them deadlocks.

* Recently we seem to have added logic to delete test temp
  directories  if a failure happened during initialization of said
  temp directories.  This is unfortunate, because you often need to
  look at the temp directory to see what failed.  We already clean
  them up elsewhere after the full test completes successfully, so
  I don't think we need to be doing this, and I've removed it.

Still many loose ends (config, resources, etc), but it's a start!
2018-02-23 19:33:02 -08:00
joeduffy d9a143c8a1 Implement the Python langhost RPC server
This change adds a basic Python langhost RPC server.  It's fairly
barebones and merely acts as a jumping off point for the Pulumi engine
to spawn a Python program.  The host is written in Go, in contrast to
implementing the host in Python, and more closely resembles how I
expect the Node.js language host to work once pulumi/pulumi#331 is done.
2018-02-23 19:33:02 -08:00