|
| 1 | +import json |
| 2 | +import os |
| 3 | + |
| 4 | +from docker import errors |
| 5 | +from docker.context.config import get_meta_dir |
| 6 | +from docker.context.config import METAFILE |
| 7 | +from docker.context.config import get_current_context_name |
| 8 | +from docker.context.config import write_context_name_to_docker_config |
| 9 | +from docker.context import Context |
| 10 | + |
| 11 | + |
| 12 | +class ContextAPI(object): |
| 13 | + """Context API. |
| 14 | + Contains methods for context management: |
| 15 | + create, list, remove, get, inspect. |
| 16 | + """ |
| 17 | + DEFAULT_CONTEXT = Context("default") |
| 18 | + |
| 19 | + @classmethod |
| 20 | + def create_context( |
| 21 | + cls, name, orchestrator="swarm", host=None, tls_cfg=None, |
| 22 | + default_namespace=None, skip_tls_verify=False): |
| 23 | + """Creates a new context. |
| 24 | + Returns: |
| 25 | + (Context): a Context object. |
| 26 | + Raises: |
| 27 | + :py:class:`docker.errors.MissingContextParameter` |
| 28 | + If a context name is not provided. |
| 29 | + :py:class:`docker.errors.ContextAlreadyExists` |
| 30 | + If a context with the name already exists. |
| 31 | + :py:class:`docker.errors.ContextException` |
| 32 | + If name is default. |
| 33 | +
|
| 34 | + Example: |
| 35 | +
|
| 36 | + >>> from docker.context import ContextAPI |
| 37 | + >>> ctx = ContextAPI.create_context(name='test') |
| 38 | + >>> print(ctx.Metadata) |
| 39 | + { |
| 40 | + "Name": "test", |
| 41 | + "Metadata": { |
| 42 | + "StackOrchestrator": "swarm" |
| 43 | + }, |
| 44 | + "Endpoints": { |
| 45 | + "docker": { |
| 46 | + "Host": "unix:///var/run/docker.sock", |
| 47 | + "SkipTLSVerify": false |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + """ |
| 52 | + if not name: |
| 53 | + raise errors.MissingContextParameter("name") |
| 54 | + if name == "default": |
| 55 | + raise errors.ContextException( |
| 56 | + '"default" is a reserved context name') |
| 57 | + ctx = Context.load_context(name) |
| 58 | + if ctx: |
| 59 | + raise errors.ContextAlreadyExists(name) |
| 60 | + endpoint = "docker" if orchestrator == "swarm" else orchestrator |
| 61 | + ctx = Context(name, orchestrator) |
| 62 | + ctx.set_endpoint( |
| 63 | + endpoint, host, tls_cfg, |
| 64 | + skip_tls_verify=skip_tls_verify, |
| 65 | + def_namespace=default_namespace) |
| 66 | + ctx.save() |
| 67 | + return ctx |
| 68 | + |
| 69 | + @classmethod |
| 70 | + def get_context(cls, name=None): |
| 71 | + """Retrieves a context object. |
| 72 | + Args: |
| 73 | + name (str): The name of the context |
| 74 | +
|
| 75 | + Example: |
| 76 | +
|
| 77 | + >>> from docker.context import ContextAPI |
| 78 | + >>> ctx = ContextAPI.get_context(name='test') |
| 79 | + >>> print(ctx.Metadata) |
| 80 | + { |
| 81 | + "Name": "test", |
| 82 | + "Metadata": { |
| 83 | + "StackOrchestrator": "swarm" |
| 84 | + }, |
| 85 | + "Endpoints": { |
| 86 | + "docker": { |
| 87 | + "Host": "unix:///var/run/docker.sock", |
| 88 | + "SkipTLSVerify": false |
| 89 | + } |
| 90 | + } |
| 91 | + } |
| 92 | + """ |
| 93 | + if not name: |
| 94 | + name = get_current_context_name() |
| 95 | + if name == "default": |
| 96 | + return cls.DEFAULT_CONTEXT |
| 97 | + return Context.load_context(name) |
| 98 | + |
| 99 | + @classmethod |
| 100 | + def contexts(cls): |
| 101 | + """Context list. |
| 102 | + Returns: |
| 103 | + (Context): List of context objects. |
| 104 | + Raises: |
| 105 | + :py:class:`docker.errors.APIError` |
| 106 | + If the server returns an error. |
| 107 | + """ |
| 108 | + names = [] |
| 109 | + for dirname, dirnames, fnames in os.walk(get_meta_dir()): |
| 110 | + for filename in fnames + dirnames: |
| 111 | + if filename == METAFILE: |
| 112 | + try: |
| 113 | + data = json.load( |
| 114 | + open(os.path.join(dirname, filename), "r")) |
| 115 | + names.append(data["Name"]) |
| 116 | + except Exception as e: |
| 117 | + raise errors.ContextException( |
| 118 | + "Failed to load metafile {}: {}".format( |
| 119 | + filename, e)) |
| 120 | + |
| 121 | + contexts = [cls.DEFAULT_CONTEXT] |
| 122 | + for name in names: |
| 123 | + contexts.append(Context.load_context(name)) |
| 124 | + return contexts |
| 125 | + |
| 126 | + @classmethod |
| 127 | + def get_current_context(cls): |
| 128 | + """Get current context. |
| 129 | + Returns: |
| 130 | + (Context): current context object. |
| 131 | + """ |
| 132 | + return cls.get_context() |
| 133 | + |
| 134 | + @classmethod |
| 135 | + def set_current_context(cls, name="default"): |
| 136 | + ctx = cls.get_context(name) |
| 137 | + if not ctx: |
| 138 | + raise errors.ContextNotFound(name) |
| 139 | + |
| 140 | + err = write_context_name_to_docker_config(name) |
| 141 | + if err: |
| 142 | + raise errors.ContextException( |
| 143 | + 'Failed to set current context: {}'.format(err)) |
| 144 | + |
| 145 | + @classmethod |
| 146 | + def remove_context(cls, name): |
| 147 | + """Remove a context. Similar to the ``docker context rm`` command. |
| 148 | +
|
| 149 | + Args: |
| 150 | + name (str): The name of the context |
| 151 | +
|
| 152 | + Raises: |
| 153 | + :py:class:`docker.errors.MissingContextParameter` |
| 154 | + If a context name is not provided. |
| 155 | + :py:class:`docker.errors.ContextNotFound` |
| 156 | + If a context with the name does not exist. |
| 157 | + :py:class:`docker.errors.ContextException` |
| 158 | + If name is default. |
| 159 | +
|
| 160 | + Example: |
| 161 | +
|
| 162 | + >>> from docker.context import ContextAPI |
| 163 | + >>> ContextAPI.remove_context(name='test') |
| 164 | + >>> |
| 165 | + """ |
| 166 | + if not name: |
| 167 | + raise errors.MissingContextParameter("name") |
| 168 | + if name == "default": |
| 169 | + raise errors.ContextException( |
| 170 | + 'context "default" cannot be removed') |
| 171 | + ctx = Context.load_context(name) |
| 172 | + if not ctx: |
| 173 | + raise errors.ContextNotFound(name) |
| 174 | + if name == get_current_context_name(): |
| 175 | + write_context_name_to_docker_config(None) |
| 176 | + ctx.remove() |
| 177 | + |
| 178 | + @classmethod |
| 179 | + def inspect_context(cls, name="default"): |
| 180 | + """Remove a context. Similar to the ``docker context inspect`` command. |
| 181 | +
|
| 182 | + Args: |
| 183 | + name (str): The name of the context |
| 184 | +
|
| 185 | + Raises: |
| 186 | + :py:class:`docker.errors.MissingContextParameter` |
| 187 | + If a context name is not provided. |
| 188 | + :py:class:`docker.errors.ContextNotFound` |
| 189 | + If a context with the name does not exist. |
| 190 | +
|
| 191 | + Example: |
| 192 | +
|
| 193 | + >>> from docker.context import ContextAPI |
| 194 | + >>> ContextAPI.remove_context(name='test') |
| 195 | + >>> |
| 196 | + """ |
| 197 | + if not name: |
| 198 | + raise errors.MissingContextParameter("name") |
| 199 | + if name == "default": |
| 200 | + return cls.DEFAULT_CONTEXT() |
| 201 | + ctx = Context.load_context(name) |
| 202 | + if not ctx: |
| 203 | + raise errors.ContextNotFound(name) |
| 204 | + |
| 205 | + return ctx() |
0 commit comments