from .. import errors
from .resource import Collection, Model


class Plugin(Model):
    """
    A plugin on the server.
    """
    def __repr__(self):
        return "<%s: '%s'>" % (self.__class__.__name__, self.name)

    @property
    def name(self):
        """
        The plugin's name.
        """
        return self.attrs.get('Name')

    @property
    def enabled(self):
        """
        Whether the plugin is enabled.
        """
        return self.attrs.get('Enabled')

    @property
    def settings(self):
        """
        A dictionary representing the plugin's configuration.
        """
        return self.attrs.get('Settings')

    def configure(self, options):
        """
            Update the plugin's settings.

            Args:
                options (dict): A key-value mapping of options.

            Raises:
                :py:class:`docker.errors.APIError`
                    If the server returns an error.
        """
        self.client.api.configure_plugin(self.name, options)
        self.reload()

    def disable(self):
        """
            Disable the plugin.

            Raises:
                :py:class:`docker.errors.APIError`
                    If the server returns an error.
        """

        self.client.api.disable_plugin(self.name)
        self.reload()

    def enable(self, timeout=0):
        """
            Enable the plugin.

            Args:
                timeout (int): Timeout in seconds. Default: 0

            Raises:
                :py:class:`docker.errors.APIError`
                    If the server returns an error.
        """
        self.client.api.enable_plugin(self.name, timeout)
        self.reload()

    def push(self):
        """
            Push the plugin to a remote registry.

            Returns:
                A dict iterator streaming the status of the upload.

            Raises:
                :py:class:`docker.errors.APIError`
                    If the server returns an error.
        """
        return self.client.api.push_plugin(self.name)

    def remove(self, force=False):
        """
            Remove the plugin from the server.

            Args:
                force (bool): Remove even if the plugin is enabled.
                    Default: False

            Raises:
                :py:class:`docker.errors.APIError`
                    If the server returns an error.
        """
        return self.client.api.remove_plugin(self.name, force=force)

    def upgrade(self, remote=None):
        """
            Upgrade the plugin.

            Args:
                remote (string): Remote reference to upgrade to. The
                    ``:latest`` tag is optional and is the default if omitted.
                    Default: this plugin's name.

            Returns:
                A generator streaming the decoded API logs
        """
        if self.enabled:
            raise errors.DockerError(
                'Plugin must be disabled before upgrading.'
            )

        if remote is None:
            remote = self.name
        privileges = self.client.api.plugin_privileges(remote)
        for d in self.client.api.upgrade_plugin(self.name, remote, privileges):
            yield d
        self._reload()


class PluginCollection(Collection):
    model = Plugin

    def create(self, name, plugin_data_dir, gzip=False):
        """
            Create a new plugin.

            Args:
                name (string): The name of the plugin. The ``:latest`` tag is
                    optional, and is the default if omitted.
                plugin_data_dir (string): Path to the plugin data directory.
                    Plugin data directory must contain the ``config.json``
                    manifest file and the ``rootfs`` directory.
                gzip (bool): Compress the context using gzip. Default: False

            Returns:
                (:py:class:`Plugin`): The newly created plugin.
        """
        self.client.api.create_plugin(name, plugin_data_dir, gzip)
        return self.get(name)

    def get(self, name):
        """
        Gets a plugin.

        Args:
            name (str): The name of the plugin.

        Returns:
            (:py:class:`Plugin`): The plugin.

        Raises:
            :py:class:`docker.errors.NotFound` If the plugin does not
            exist.
            :py:class:`docker.errors.APIError`
                If the server returns an error.
        """
        return self.prepare_model(self.client.api.inspect_plugin(name))

    def install(self, remote_name, local_name=None):
        """
            Pull and install a plugin.

            Args:
                remote_name (string): Remote reference for the plugin to
                    install. The ``:latest`` tag is optional, and is the
                    default if omitted.
                local_name (string): Local name for the pulled plugin.
                    The ``:latest`` tag is optional, and is the default if
                    omitted. Optional.

            Returns:
                (:py:class:`Plugin`): The installed plugin
            Raises:
                :py:class:`docker.errors.APIError`
                    If the server returns an error.
        """
        privileges = self.client.api.plugin_privileges(remote_name)
        it = self.client.api.pull_plugin(remote_name, privileges, local_name)
        for data in it:
            pass
        return self.get(local_name or remote_name)

    def list(self):
        """
        List plugins installed on the server.

        Returns:
            (list of :py:class:`Plugin`): The plugins.

        Raises:
            :py:class:`docker.errors.APIError`
                If the server returns an error.
        """
        resp = self.client.api.plugins()
        return [self.prepare_model(r) for r in resp]

docker/models/plugins.py
from .. import errors
from .resource import Collection, Model


class Plugin(Model):
    """
    A plugin on the server.
    """
    def __repr__(self):
        return "<%s: '%s'>" % (self.__class__.__name__, self.name)

    @property
    def name(self):
        """
        The plugin's name.
        """
        return self.attrs.get('Name')

    @property
    def enabled(self):
        """
        Whether the plugin is enabled.
        """
        return self.attrs.get('Enabled')

    @property
    def settings(self):
        """
        A dictionary representing the plugin's configuration.
        """
        return self.attrs.get('Settings')

    def configure(self, options):
        """
            Update the plugin's settings.

            Args:
                options (dict): A key-value mapping of options.

            Raises:
                :py:class:`docker.errors.APIError`
                    If the server returns an error.
        """
        self.client.api.configure_plugin(self.name, options)
        self.reload()

    def disable(self):
        """
            Disable the plugin.

            Raises:
                :py:class:`docker.errors.APIError`
                    If the server returns an error.
        """

        self.client.api.disable_plugin(self.name)
        self.reload()

    def enable(self, timeout=0):
        """
            Enable the plugin.

            Args:
                timeout (int): Timeout in seconds. Default: 0

            Raises:
                :py:class:`docker.errors.APIError`
                    If the server returns an error.
        """
        self.client.api.enable_plugin(self.name, timeout)
        self.reload()

    def push(self):
        """
            Push the plugin to a remote registry.

            Returns:
                A dict iterator streaming the status of the upload.

            Raises:
                :py:class:`docker.errors.APIError`
                    If the server returns an error.
        """
        return self.client.api.push_plugin(self.name)

    def remove(self, force=False):
        """
            Remove the plugin from the server.

            Args:
                force (bool): Remove even if the plugin is enabled.
                    Default: False

            Raises:
                :py:class:`docker.errors.APIError`
                    If the server returns an error.
        """
        return self.client.api.remove_plugin(self.name, force=force)

    def upgrade(self, remote=None):
        """
            Upgrade the plugin.

            Args:
                remote (string): Remote reference to upgrade to. The
                    ``:latest`` tag is optional and is the default if omitted.
                    Default: this plugin's name.

            Returns:
                A generator streaming the decoded API logs
        """
        if self.enabled:
            raise errors.DockerError(
                'Plugin must be disabled before upgrading.'
            )

        if remote is None:
            remote = self.name
        privileges = self.client.api.plugin_privileges(remote)
        for d in self.client.api.upgrade_plugin(self.name, remote, privileges):
            yield d
        self.reload()


class PluginCollection(Collection):
    model = Plugin

    def create(self, name, plugin_data_dir, gzip=False):
        """
            Create a new plugin.

            Args:
                name (string): The name of the plugin. The ``:latest`` tag is
                    optional, and is the default if omitted.
                plugin_data_dir (string): Path to the plugin data directory.
                    Plugin data directory must contain the ``config.json``
                    manifest file and the ``rootfs`` directory.
                gzip (bool): Compress the context using gzip. Default: False

            Returns:
                (:py:class:`Plugin`): The newly created plugin.
        """
        self.client.api.create_plugin(name, plugin_data_dir, gzip)
        return self.get(name)

    def get(self, name):
        """
        Gets a plugin.

        Args:
            name (str): The name of the plugin.

        Returns:
            (:py:class:`Plugin`): The plugin.

        Raises:
            :py:class:`docker.errors.NotFound` If the plugin does not
            exist.
            :py:class:`docker.errors.APIError`
                If the server returns an error.
        """
        return self.prepare_model(self.client.api.inspect_plugin(name))

    def install(self, remote_name, local_name=None):
        """
            Pull and install a plugin.

            Args:
                remote_name (string): Remote reference for the plugin to
                    install. The ``:latest`` tag is optional, and is the
                    default if omitted.
                local_name (string): Local name for the pulled plugin.
                    The ``:latest`` tag is optional, and is the default if
                    omitted. Optional.

            Returns:
                (:py:class:`Plugin`): The installed plugin
            Raises:
                :py:class:`docker.errors.APIError`
                    If the server returns an error.
        """
        privileges = self.client.api.plugin_privileges(remote_name)
        it = self.client.api.pull_plugin(remote_name, privileges, local_name)
        for data in it:
            pass
        return self.get(local_name or remote_name)

    def list(self):
        """
        List plugins installed on the server.

        Returns:
            (list of :py:class:`Plugin`): The plugins.

        Raises:
            :py:class:`docker.errors.APIError`
                If the server returns an error.
        """
        resp = self.client.api.plugins()
        return [self.prepare_model(r) for r in resp]

docker/models/plugins.py
diff --git a/docker/models/plugins.py b/docker/models/plugins.py
index 06880181f..ae5851c91 100644
--- a/docker/models/plugins.py
+++ b/docker/models/plugins.py
@@ -119,7 +119,7 @@ def upgrade(self, remote=None):
         privileges = self.client.api.plugin_privileges(remote)
         for d in self.client.api.upgrade_plugin(self.name, remote, privileges):
             yield d
-        self._reload()
+        self.reload()
 
 
 class PluginCollection(Collection):

Plugin model upgrade: object has no attribute '_reload'
I've already got a fix for this that I'm about to submit. For reference, here are the steps to reproduce in ipython:
```
~$ ipython                                                                     [venv]
Python 3.7.6 (default, Dec 22 2019, 01:09:06)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.18.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]: import docker

In [2]: c = docker.DockerClient(base_url='unix://var/run/docker.sock')

In [3]: p = c.plugins.get('loki')

In [4]: list(p.upgrade("grafana/loki-docker-driver:latest"))
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-4-e5fc26fa0514> in <module>
----> 1 list(p.upgrade("grafana/loki-docker-driver:latest"))

~/venv/lib/python3.7/site-packages/docker/models/plugins.py in upgrade(self, remote)
    120         for d in self.client.api.upgrade_plugin(self.name, remote, privileges):
    121             yield d
--> 122         self._reload()
    123
    124

AttributeError: 'Plugin' object has no attribute '_reload'
```

```
docker==4.3.1
Python 3.7.6
Client: Docker Engine - Community
 Cloud integration  0.1.18
 Version:           19.03.13
 API version:       1.40
 Go version:        go1.13.15
 Git commit:        4484c46d9d
 Built:             Wed Sep 16 16:58:31 2020
 OS/Arch:           darwin/amd64
 Experimental:      true

Server: Docker Engine - Community
 Engine:
  Version:          19.03.13
  API version:      1.40 (minimum version 1.12)
  Go version:       go1.13.15
  Git commit:       4484c46d9d
  Built:            Wed Sep 16 17:07:04 2020
  OS/Arch:          linux/amd64
  Experimental:     true
 containerd:
  Version:          v1.3.7
  GitCommit:        8fba4e9a7d01810a393d5d25a3621dc101981175
 runc:
  Version:          1.0.0-rc10
  GitCommit:        dc9208a3303feef5b3839f4323d9beb36df0a9dd
 docker-init:
  Version:          0.18.0
  GitCommit:        fec3683
```
