Skip to content

Commit

Permalink
Minor fixes
Browse files Browse the repository at this point in the history
Signed-off-by: Alvaro Saurin <alvaro.saurin@gmail.com>
  • Loading branch information
inercia committed May 27, 2020
1 parent b4c6f73 commit e882d91
Show file tree
Hide file tree
Showing 8 changed files with 86 additions and 28 deletions.
4 changes: 4 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
[submodule "shared-modules"]
path = shared-modules
url = https://github.com/flathub/shared-modules.git
[submodule "flathub"]
path = flathub
url = https://github.com/inercia/flathub.git
branch = k3x
15 changes: 11 additions & 4 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,17 @@ release: ## Adds a new TAG and pushes it to the origin for forcing a new releas
@printf "$(CYN)>>> $(GRN)Pushing tags $(TAG$)$(END)\n"
$(Q)git push --tags || { printf "$(CYN)>>> $(RED)Failed to push new tag $(TAG) to origin$(END)\n" ; exit 1 ; }


flathub-pull: ## Pull changes in the flathub
@printf "$(CYN)>>> $(GRN)Pulling changes in 'flathub' submodule$(END)\n"
$(Q)git submodule update --remote --merge -- flathub
@printf "$(CYN)>>> $(GRN)Done$(END)\n"

flathub-commit:
@printf "$(CYN)>>> $(GRN)Committing current state of flathub$(END)\n"
$(Q)git add flathub && git commit -m "Updated flathub"
@printf "$(CYN)>>> $(GRN)Done. You can now 'git push'$(END)\n"

##############################
# CI
##############################
Expand All @@ -227,7 +238,3 @@ ci/setup:
ci/build: build

ci/release: package




7 changes: 4 additions & 3 deletions data/com.github.inercia.k3x.desktop.in.in
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
[Desktop Entry]
Name=k3d
Name=k3x
Comment=k3x is a graphical user interface for k3d, making it trivial to have your own local Kubernetes cluster(s)
Exec=k3x
Exec=@APP_ID@
Terminal=false
Type=Application
Categories=System;
StartupNotify=true
Icon=@ICON@
X-Flatpak=@APP_IP@
X-GNOME-UsesNotifications=true
X-Flatpak=@APP_ID@
X-Flatpak-Tags=stable;
1 change: 1 addition & 0 deletions flathub
Submodule flathub added at d10289
21 changes: 16 additions & 5 deletions src/cluster_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,12 @@ def __init__(self, controller: K3dController,
delete_button.connect("clicked", self.on_delete_clicked)
self.header.pack_end(delete_button)

if self._controller.active != cluster:
if not cluster.running:
switch_button = Gtk.Button(label="Start")
switch_button.get_style_context().add_class(Gtk.STYLE_CLASS_SUGGESTED_ACTION)
switch_button.connect("clicked", self.on_start_clicked)
self.header.pack_end(switch_button)
elif self._controller.active != cluster:
switch_button = Gtk.Button(label="Switch to")
switch_button.get_style_context().add_class(Gtk.STYLE_CLASS_SUGGESTED_ACTION)
switch_button.connect("clicked", self.on_switch_clicked)
Expand Down Expand Up @@ -161,6 +166,11 @@ def on_switch_clicked(self, *args):
self._controller.active = self.cluster
self.close()

def on_start_clicked(self, *args):
logging.info(f"[VIEW] Starting {self.cluster}")
self.cluster.start()
self.close()

def on_cancel_clicked(self, *args):
self._settings.revert()
self.close()
Expand Down Expand Up @@ -365,11 +375,12 @@ def _open_dashboard(*args):
"If you expected the Dashboard to be available, "
"please wait and try again in a while...")

open_button = Gtk.Button(label="Open")
open_button.connect("clicked", _open_dashboard)
box.pack_start(open_button, True, True, 0)
if self.cluster.running:
open_button = Gtk.Button(label="Open")
open_button.connect("clicked", _open_dashboard)
box.pack_start(open_button, True, True, 0)

self.append_labeled_entry("Server IP address", box)
self.append_labeled_entry("Server IP address", box)

# Disable everything if the cluster already exists
if self.cluster is not None:
Expand Down
38 changes: 35 additions & 3 deletions src/k3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,13 +136,14 @@ class K3dCluster(GObject.GObject):

def __init__(self, settings: ApplicationSettings, docker: DockerController, **kwargs):
super().__init__()
self.__dict__.update(kwargs)
self._docker = docker
self._settings = settings
self._kubeconfig = None
self._docker_server_ip = None
self._notification = None
self._destroyed = False
self._status = kwargs.pop("status", "running")
self.__dict__.update(kwargs)

# TODO: check the name is valid
if len(self.name) == 0:
Expand All @@ -166,7 +167,7 @@ def __eq__(self, other) -> bool:

def __ne__(self, other) -> bool:
if other is None:
return False
return True
if isinstance(other, K3dCluster):
return self.name != other.name
if isinstance(other, str):
Expand Down Expand Up @@ -258,6 +259,7 @@ def create(self, wait=True) -> None:
raise

logging.info("[K3D] The cluster has been created")
self._status = "running"

call_in_main_thread(lambda: self.emit("created", self.name))

Expand Down Expand Up @@ -298,7 +300,7 @@ def _cleanup(self) -> None:
@property
def kubeconfig(self) -> Optional[str]:
"""
Get the kuhbeconfig file for this cluster, or None if no
Get the kubeconfig file for this cluster, or None if no
"""
if self._destroyed:
return None
Expand All @@ -320,6 +322,36 @@ def kubeconfig(self) -> Optional[str]:

return self._kubeconfig

@property
def running(self) -> bool:
return self._status == "running"

def start(self) -> None:
if not self.running:
args = []
args += [f"--name={self.name}"]

logging.debug(f"[K3D] Starting {self.name}...")
while True:
try:
line = next(run_k3d_command("start", *args))
logging.debug(f"[K3D] {line}")
except StopIteration:
break

def stop(self) -> None:
if self.running:
args = []
args += [f"--name={self.name}"]

logging.debug(f"[K3D] Stopping {self.name}...")
while True:
try:
line = next(run_k3d_command("stop", *args))
logging.debug(f"[K3D] {line}")
except StopIteration:
break

@property
def docker_server_name(self) -> Optional[str]:
if self._destroyed:
Expand Down
14 changes: 7 additions & 7 deletions src/k3d_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,9 +108,9 @@ def _k3d_list(self) -> Dict[str, K3dCluster]:
try:
logging.debug(f"[K3D] Parsed components: {components}")
name, image, status = components[0:3]
logging.debug(f"[K3D] Parsed cluster info: name={name}, image={image}")
cs[name] = K3dCluster(settings=self._settings, docker=self._docker, name=name, image=image,
status=status)
logging.debug(f"[K3D] Parsed cluster info: name={name}, image={image}, status={status}")
cs[name] = K3dCluster(settings=self._settings, docker=self._docker,
name=name, image=image, status=status)
except Exception as e:
logging.exception(f"[K3D] PARSER ERROR !!!! Could not parse {line}: {e}")
show_notification(f"Could not parse {line}: {e}", header="f{name} INTERNAL ERROR",
Expand Down Expand Up @@ -143,15 +143,15 @@ def active(self, new_cluster: Union[K3dCluster, str]) -> None:
return

if new_cluster_name not in self.clusters:
logging.warning(f"[K3D] Activating an unknown cluster '{new_cluster_name}'")
logging.info(f"[K3D] Active cluster '{new_cluster_name}' is not known: probably not a K3D cluster")
if self._active is not None:
emit_in_main_thread(self, "change-current-cluster", None)
self._active = None
return

logging.info(f"[K3D] Switching to cluster '{new_cluster_name}'")
try:
kubectl_set_current_context(new_cluster_name)
kubectl_set_current_context(new_cluster_name, kubeconfig=self.kubeconfig)
except Exception as e:
logging.exception(f"[K3D] When switching to cluster '{new_cluster_name}': {e}")
else:
Expand Down Expand Up @@ -288,7 +288,7 @@ def do_refresh():
logging.debug(f"[K3D] Will activate cluster forced cluster {active_cluster.name} later on...")
cluster_name_to_activate = active_cluster.name
elif initial:
cluster_name_to_activate = kubectl_get_current_context()
cluster_name_to_activate = kubectl_get_current_context(kubeconfig=self.kubeconfig)
logging.debug(
f"[K3D] First time we refresh KUBECONFIG: will save currently active cluster {cluster_name_to_activate}...")
elif len(self.clusters) > 0 and self.active is not None:
Expand Down Expand Up @@ -327,7 +327,7 @@ def do_refresh():
if cluster_name_to_activate is not None and cluster_name_to_activate in self.clusters:
self.active = cluster_name_to_activate
else:
self.active = kubectl_get_current_context()
self.active = kubectl_get_current_context(kubeconfig=self.kubeconfig)

if changes:
# note: no need of call_in_main_thread for this `emit`, as `inner_refresh` has
Expand Down
14 changes: 8 additions & 6 deletions src/kubectl.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def run_kubectl_command(*args, **kwargs) -> Iterator[str]:
Run a kubectl command
"""
kubeconfig = kwargs.pop("kubeconfig", None)
if kubeconfig:
if kubeconfig is not None:
env = kwargs.pop("env", os.environ.copy())
env["KUBECONFIG"] = kubeconfig
kwargs["env"] = env
Expand Down Expand Up @@ -88,7 +88,7 @@ def merge_kubeconfigs_to(kubeconfigs: List[str], dest: str):
logging.debug("[KUBECTL] No changes in KUBECONFIG: no need to overwrite it.")


def kubectl_apply_manifest(manifest, kubeconfig=None, **kwargs) -> Iterator[str]:
def kubectl_apply_manifest(manifest: str, kubeconfig: Optional[str] = None, **kwargs) -> Iterator[str]:
"""
Apply a manifest with `kubectl apply -f` (using a temporary file)
"""
Expand All @@ -101,25 +101,27 @@ def kubectl_apply_manifest(manifest, kubeconfig=None, **kwargs) -> Iterator[str]
yield from run_kubectl_command(*args, kubeconfig=kubeconfig, **kwargs)


def kubectl_get_current_context() -> Optional[str]:
def kubectl_get_current_context(kubeconfig: Optional[str] = None) -> Optional[str]:
"""
Get the currently active context
"""
args = ["config", "current-context"]
try:
lines = [line for line in run_kubectl_command("config", "current-context")]
lines = [line for line in run_kubectl_command(*args, kubeconfig=kubeconfig)]
except subprocess.CalledProcessError as e:
logging.warning(f"No current context obtained with kubectl (maybe no clusters exist): {e}")
return None

return lines[0]


def kubectl_set_current_context(context) -> None:
def kubectl_set_current_context(context: str, kubeconfig: Optional[str] = None) -> None:
"""
Run `kubectl config use-context my-cluster-name`
"""
args = ["config", "use-context", context]
try:
lines = [line for line in run_kubectl_command("config", "use-context", context)]
lines = [line for line in run_kubectl_command(*args, kubeconfig=kubeconfig)]
except subprocess.CalledProcessError as e:
logging.exception(f"Could not set the current context with kubectl: {e}")
return None

0 comments on commit e882d91

Please sign in to comment.