File size: 9,043 Bytes
105b369
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
"""Phidata Kubectl Cli

This is the entrypoint for the `phi k` commands.
"""

from pathlib import Path
from typing import Optional

import typer

from phi.cli.console import (
    print_info,
    log_config_not_available_msg,
    log_active_workspace_not_available,
    print_available_workspaces,
)
from phi.utils.log import logger, set_log_level_to_debug

k_cli = typer.Typer(
    name="k",
    short_help="Manage kubernetes resources",
    help="""\b
Use `phi k [COMMAND]` to save, get, update kubernetes resources.
Run `phi k [COMMAND] --help` for more info.
""",
    no_args_is_help=True,
    add_completion=False,
    invoke_without_command=True,
    options_metavar="",
    subcommand_metavar="[COMMAND] [OPTIONS]",
)


@k_cli.command(short_help="Save your K8s Resources")
def save(
    resource_filter: Optional[str] = typer.Argument(
        None,
        help="Resource filter. Format - ENV:GROUP:NAME:TYPE",
    ),
    env_filter: Optional[str] = typer.Option(None, "-e", "--env", metavar="", help="Filter the environment to deploy."),
    group_filter: Optional[str] = typer.Option(
        None, "-g", "--group", metavar="", help="Filter resources using group name."
    ),
    name_filter: Optional[str] = typer.Option(None, "-n", "--name", metavar="", help="Filter resource using name."),
    type_filter: Optional[str] = typer.Option(
        None,
        "-t",
        "--type",
        metavar="",
        help="Filter resource using type",
    ),
    print_debug_log: bool = typer.Option(
        False,
        "-d",
        "--debug",
        help="Print debug logs.",
    ),
):
    """
    Saves your k8s resources. Used to validate what is being deployed

    \b
    Examples:
    > `phi k save`      -> Save resources for the active workspace
    """
    if print_debug_log:
        set_log_level_to_debug()

    from phi.cli.config import PhiCliConfig
    from phi.workspace.config import WorkspaceConfig
    from phi.k8s.operator import save_resources
    from phi.utils.resource_filter import parse_k8s_resource_filter

    phi_config: Optional[PhiCliConfig] = PhiCliConfig.from_saved_config()
    if not phi_config:
        log_config_not_available_msg()
        return

    active_ws_config: Optional[WorkspaceConfig] = phi_config.get_active_ws_config()
    if active_ws_config is None:
        log_active_workspace_not_available()
        avl_ws = phi_config.available_ws
        if avl_ws:
            print_available_workspaces(avl_ws)
        return

    current_path: Path = Path(".").resolve()
    if active_ws_config.ws_root_path != current_path:
        ws_at_current_path = phi_config.get_ws_config_by_path(current_path)
        if ws_at_current_path is not None:
            active_ws_dir_name = active_ws_config.ws_root_path.stem
            ws_at_current_path_dir_name = ws_at_current_path.ws_root_path.stem

            print_info(
                f"Workspace at the current directory ({ws_at_current_path_dir_name}) "
                + f"is not the Active Workspace ({active_ws_dir_name})"
            )
            update_active_workspace = typer.confirm(
                f"Update active workspace to {ws_at_current_path_dir_name}", default=True
            )
            if update_active_workspace:
                phi_config.set_active_ws_dir(ws_at_current_path.ws_root_path)
                active_ws_config = ws_at_current_path

    target_env: Optional[str] = None
    target_group: Optional[str] = None
    target_name: Optional[str] = None
    target_type: Optional[str] = None

    # derive env:infra:name:type:group from ws_filter
    if resource_filter is not None:
        if not isinstance(resource_filter, str):
            raise TypeError(f"Invalid resource_filter. Expected: str, Received: {type(resource_filter)}")
        (
            target_env,
            target_group,
            target_name,
            target_type,
        ) = parse_k8s_resource_filter(resource_filter)

    # derive env:infra:name:type:group from command options
    if target_env is None and env_filter is not None and isinstance(env_filter, str):
        target_env = env_filter
    if target_group is None and group_filter is not None and isinstance(group_filter, str):
        target_group = group_filter
    if target_name is None and name_filter is not None and isinstance(name_filter, str):
        target_name = name_filter
    if target_type is None and type_filter is not None and isinstance(type_filter, str):
        target_type = type_filter

    logger.debug("Processing workspace")
    logger.debug(f"\ttarget_env   : {target_env}")
    logger.debug(f"\ttarget_group : {target_group}")
    logger.debug(f"\ttarget_name  : {target_name}")
    logger.debug(f"\ttarget_type  : {target_type}")
    save_resources(
        phi_config=phi_config,
        ws_config=active_ws_config,
        target_env=target_env,
        target_group=target_group,
        target_name=target_name,
        target_type=target_type,
    )


# @app.command(short_help="Print your K8s Resources")
# def print(
#     refresh: bool = typer.Option(
#         False,
#         "-r",
#         "--refresh",
#         help="Refresh the workspace config, use this if you've just changed your phi-config.yaml",
#         show_default=True,
#     ),
#     type_filters: List[str] = typer.Option(
#         None, "-k", "--kind", help="Filter the K8s resources by kind"
#     ),
#     name_filters: List[str] = typer.Option(
#         None, "-n", "--name", help="Filter the K8s resources by name"
#     ),
# ):
#     """
#     Print your k8s resources so you know exactly what is being deploying
#
#     \b
#     Examples:
#     * `phi k print`      -> Print resources for the primary workspace
#     * `phi k print data` -> Print resources for the workspace named data
#     """
#
#     from phi import schemas
#     from phiterm.k8s import k8s_operator
#     from phiterm.conf.phi_conf import PhiConf
#
#     config: Optional[PhiConf] = PhiConf.get_saved_conf()
#     if not config:
#         conf_not_available_msg()
#         raise typer.Exit(1)
#
#     primary_ws: Optional[schemas.WorkspaceSchema] = config.primary_ws
#     if primary_ws is None:
#         primary_ws_not_available_msg()
#         raise typer.Exit(1)
#
#     k8s_operator.print_k8s_resources_as_yaml(
#         primary_ws, config, refresh, type_filters, name_filters
#     )
#
#
# @app.command(short_help="Apply your K8s Resources")
# def apply(
#     refresh: bool = typer.Option(
#         False,
#         "-r",
#         "--refresh",
#         help="Refresh the workspace config, use this if you've just changed your phi-config.yaml",
#         show_default=True,
#     ),
#     service_filters: List[str] = typer.Option(
#         None, "-s", "--svc", help="Filter the Services"
#     ),
#     type_filters: List[str] = typer.Option(
#         None, "-k", "--kind", help="Filter the K8s resources by kind"
#     ),
#     name_filters: List[str] = typer.Option(
#         None, "-n", "--name", help="Filter the K8s resources by name"
#     ),
# ):
#     """
#     Apply your k8s resources. You can filter the resources by services, kind or name
#
#     \b
#     Examples:
#     * `phi k apply`      -> Apply resources for the primary workspace
#     """
#
#     from phi import schemas
#     from phiterm.k8s import k8s_operator
#     from phiterm.conf.phi_conf import PhiConf
#
#     config: Optional[PhiConf] = PhiConf.get_saved_conf()
#     if not config:
#         conf_not_available_msg()
#         raise typer.Exit(1)
#
#     primary_ws: Optional[schemas.WorkspaceSchema] = config.primary_ws
#     if primary_ws is None:
#         primary_ws_not_available_msg()
#         raise typer.Exit(1)
#
#     k8s_operator.apply_k8s_resources(
#         primary_ws, config, refresh, service_filters, type_filters, name_filters
#     )
#
#
# @app.command(short_help="Get active K8s Objects")
# def get(
#     service_filters: List[str] = typer.Option(
#         None, "-s", "--svc", help="Filter the Services"
#     ),
#     type_filters: List[str] = typer.Option(
#         None, "-k", "--kind", help="Filter the K8s resources by kind"
#     ),
#     name_filters: List[str] = typer.Option(
#         None, "-n", "--name", help="Filter the K8s resources by name"
#     ),
# ):
#     """
#     Get active k8s resources.
#
#     \b
#     Examples:
#     * `phi k apply`      -> Get active resources for the primary workspace
#     """
#
#     from phi import schemas
#     from phiterm.k8s import k8s_operator
#     from phiterm.conf.phi_conf import PhiConf
#
#     config: Optional[PhiConf] = PhiConf.get_saved_conf()
#     if not config:
#         conf_not_available_msg()
#         raise typer.Exit(1)
#
#     primary_ws: Optional[schemas.WorkspaceSchema] = config.primary_ws
#     if primary_ws is None:
#         primary_ws_not_available_msg()
#         raise typer.Exit(1)
#
#     k8s_operator.print_active_k8s_resources(
#         primary_ws, config, service_filters, type_filters, name_filters
#     )
#
#
# if __name__ == "__main__":
#     app()