Compare commits
8 Commits
Author | SHA1 | Date |
---|---|---|
Administrator | 6eaa839d51 | |
Administrator | 6cad92952a | |
Administrator | 6bc5791980 | |
Administrator | c28e8b45fc | |
Administrator | 9582ce66b7 | |
Administrator | 1ef7224b1a | |
Administrator | c0ccff7e74 | |
Administrator | 4de17915cb |
|
@ -1,39 +1,47 @@
|
|||
pipeline:
|
||||
steps:
|
||||
python-3.8:
|
||||
group: test
|
||||
image: python:3.8
|
||||
commands:
|
||||
- pip install pipenv==2023.10.24
|
||||
- pip install pipenv==2023.12.1 tomli
|
||||
- pipenv install --dev --deploy
|
||||
- pipenv run almake test
|
||||
- pipenv run almake test-typing
|
||||
- pipenv run almake test-pytest
|
||||
- pipenv run almake build-dist
|
||||
- sha256sum dist/*
|
||||
|
||||
python-3.9:
|
||||
group: test
|
||||
image: python:3.9
|
||||
commands:
|
||||
- pip install pipenv==2023.10.24
|
||||
- pip install pipenv==2023.12.1
|
||||
- pipenv install --dev --deploy
|
||||
- pipenv run almake test
|
||||
- pipenv run almake test-typing
|
||||
- pipenv run almake test-pytest
|
||||
- pipenv run almake build-dist
|
||||
- sha256sum dist/*
|
||||
|
||||
python-3.10:
|
||||
group: test
|
||||
image: python:3.10
|
||||
commands:
|
||||
- pip install pipenv==2023.10.24
|
||||
- pip install pipenv==2023.12.1
|
||||
- pipenv install --dev --deploy
|
||||
- pipenv run almake test-typing
|
||||
- pipenv run almake test-pytest
|
||||
- pipenv run almake build-dist
|
||||
- sha256sum dist/*
|
||||
|
||||
python-3.11:
|
||||
image: python:3.11
|
||||
commands:
|
||||
- pip install pipenv==2023.12.1
|
||||
- pipenv install --dev --deploy
|
||||
- pipenv run almake test
|
||||
- pipenv run almake build-dist
|
||||
- sha256sum dist/*
|
||||
|
||||
python-3.11:
|
||||
group: test
|
||||
python-3.12:
|
||||
image: python:3.11
|
||||
commands:
|
||||
- pip install pipenv==2023.10.24
|
||||
- pip install pipenv==2023.12.1
|
||||
- pipenv install --dev --deploy
|
||||
- pipenv run almake test
|
||||
- pipenv run almake build-dist
|
||||
|
|
44
CHANGELOG.md
44
CHANGELOG.md
|
@ -5,16 +5,52 @@ All notable changes to this project will be documented in this file.
|
|||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## Deprecated features that will be removed in the next major version.
|
||||
## Deprecated features that will be removed in the next major version (12.X.X).
|
||||
|
||||
- `burn_rate` from `TokenInfo` is deprecated. Use `burn_rate_cents` or `burn_rate_usd` instead.
|
||||
- `--no-local` will become the default for `sporestack server list`.
|
||||
- If you want the CLI features, you will have to `pip install sporestack[cli]` instead of just `pip install sporestack`.
|
||||
- `--local` will be removed from `sporestack server list`.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
- Nothing yet.
|
||||
|
||||
## [11.1.0 - 2024-03-16]
|
||||
|
||||
## Added
|
||||
|
||||
### Library
|
||||
|
||||
- `ssh_key` to `client.Client()` and to `client.Token()`. This acts as a default SSH key when launching servers this way.
|
||||
|
||||
### CLI
|
||||
|
||||
- Support for automatic per-token SSH keys (can be overridden with `--ssh-key-file` still.) To generate, run: `ssh-keygen -C "" -t ed25519 -f ~/.sporestack/sshkey/{token}/id_ed25519`
|
||||
- This means that you don't have to pass `--ssh-key-file` if you are using a token that has a locally associated SSH key.
|
||||
- When launching a server with `sporestack server launch`, it will suggest adding a readymade configuration to `~/.ssh/config` to utilize whatever key you selected.
|
||||
|
||||
## Summary
|
||||
|
||||
These changes should make it easier to stay private with SporeStack, conveniently, by utilizing a SSH key per token. In general, we recommend using one unique SSH key per token that you have.
|
||||
|
||||
## [11.0.1 - 2024-02-29]
|
||||
|
||||
## Fixed
|
||||
|
||||
- If a server is deleted during the launch wait phase, it will give up rather than trying to wait forever for an IP address that will never come.
|
||||
- `--hostname` matching is smarter in case of duplicate hostnames.
|
||||
|
||||
## [11.0.0 - 2024-02-26]
|
||||
|
||||
## Changed
|
||||
|
||||
- Various command/help cleanups.
|
||||
- If you want the CLI features, you will have to `pip install sporestack[cli]` instead of just `pip install sporestack`.
|
||||
- `--no-local` is now the default for `sporestack server list`.
|
||||
|
||||
## Removed
|
||||
|
||||
- Deprecated fields from responses and requests.
|
||||
- `legacy_polling=True` support for token add/topup.
|
||||
|
||||
## [10.8.0 - 2024-01-03]
|
||||
|
||||
## Added
|
||||
|
|
9
Makefile
9
Makefile
|
@ -1,13 +1,16 @@
|
|||
format:
|
||||
black .
|
||||
ruff --fix .
|
||||
ruff check --fix .
|
||||
|
||||
test:
|
||||
black --check .
|
||||
ruff .
|
||||
mypy
|
||||
ruff check .
|
||||
$(MAKE) test-typing
|
||||
$(MAKE) test-pytest
|
||||
|
||||
test-typing:
|
||||
mypy
|
||||
|
||||
test-pytest:
|
||||
python -m pytest --cov=sporestack --cov-fail-under=39 --cov-report=term --durations=3 --cache-clear
|
||||
|
||||
|
|
10
Pipfile
10
Pipfile
|
@ -7,13 +7,13 @@ name = "pypi"
|
|||
sporestack = {editable = true, path = "."}
|
||||
|
||||
[dev-packages]
|
||||
black = "~=23.1"
|
||||
black = "~=24.0"
|
||||
mypy = "~=1.0"
|
||||
pytest = "~=7.2"
|
||||
pytest = "~=8.0"
|
||||
pytest-cov = "~=4.0"
|
||||
pytest-mock = "~=3.6"
|
||||
pytest-socket = "~=0.6.0"
|
||||
ruff = "~=0.1.9"
|
||||
pytest-socket = "~=0.7.0"
|
||||
ruff = "~=0.3.4"
|
||||
|
||||
respx = "~=0.20.1"
|
||||
|
||||
|
@ -22,7 +22,7 @@ flit = "~=3.8"
|
|||
wheel = "*"
|
||||
build = "~=1.0"
|
||||
# Publishing
|
||||
twine = "~=4.0"
|
||||
twine = "~=5.0"
|
||||
|
||||
# Docs
|
||||
pdoc = "~=14.0"
|
||||
|
|
File diff suppressed because it is too large
Load Diff
33
README.md
33
README.md
|
@ -1,4 +1,4 @@
|
|||
# Python 3 library and CLI for [SporeStack](https://sporestack.com) [.onion](http://spore64i5sofqlfz5gq2ju4msgzojjwifls7rok2cti624zyq3fcelad.onion)
|
||||
# Python 3 library and CLI for [SporeStack](https://sporestack.com) ([SporeStack Tor Hidden Service](http://spore64i5sofqlfz5gq2ju4msgzojjwifls7rok2cti624zyq3fcelad.onion))
|
||||
|
||||
[Changelog](CHANGELOG.md)
|
||||
|
||||
|
@ -6,24 +6,28 @@
|
|||
|
||||
* Python 3.8-3.11 (and likely newer)
|
||||
|
||||
## Installation
|
||||
|
||||
* `pip install sporestack` (Run `pip install 'sporestack[cli]'` if you wish to use the CLI features and not just the Python library.)
|
||||
* Recommended: Create a virtual environment, first, and use it inside there.
|
||||
* Something else to consider: Installing [rich](https://github.com/Textualize/rich) (`pip install rich`) in the same virtual environment will make `--help`-style output prettier.
|
||||
|
||||
## Running without installing
|
||||
|
||||
* Make sure `pipx` is installed.
|
||||
* Make sure [pipx](https://pipx.pypya.io) is installed.
|
||||
* `pipx run 'sporestack[cli]'`
|
||||
* Make sure you're on the latest stable version comparing `sporestack version` with git tags in this repository, or releases on [PyPI](https://pypi.org/project/sporestack/).
|
||||
|
||||
## Usage
|
||||
## Installation with pipx
|
||||
|
||||
* `sporestack token create --dollars 20 --currency xmr # Can use btc as well.`
|
||||
* Make sure [pipx](https://pipx.pypya.io) is installed.
|
||||
* `pipx install 'sporestack[cli]'`
|
||||
|
||||
## Traditional installation
|
||||
|
||||
* Recommended: Create and activate a virtual environment, first.
|
||||
* `pip install sporestack` (Run `pip install 'sporestack[cli]'` if you wish to use the command line `sporestack` functionality and not just the Python library.)
|
||||
|
||||
## Usage Examples
|
||||
|
||||
* Recommended: Make sure you're on the latest stable version comparing `sporestack version` with git tags in this repository, or releases on [PyPI](https://pypi.org/project/sporestack/).
|
||||
* `sporestack token create --dollars 20 --currency xmr`
|
||||
* `sporestack token list`
|
||||
* `sporestack token info`
|
||||
* `sporestack server launch --hostname SomeHostname --operating-system debian-11 --days 1 # Will use ~/.ssh/id_rsa.pub as your SSH key, by default`
|
||||
* `sporestack server launch --hostname SomeHostname --operating-system debian-12 --days 1 # Will use ~/.ssh/id_rsa.pub as your SSH key, by default`
|
||||
(You may also want to consider passing `--region` to have a non-random region. This will use the "primary" token by default, which is the default when you run `sporestack token create`.)
|
||||
* `sporestack server stop --hostname SomeHostname`
|
||||
* `sporestack server stop --machine-id ss_m_... # Or use --machine-id to be more pedantic.`
|
||||
|
@ -32,16 +36,15 @@
|
|||
* `sporestack server autorenew-disable --hostname SomeHostname`
|
||||
* `sporestack server list`
|
||||
* `sporestack server delete --hostname SomeHostname`
|
||||
* `sporestack server remove --hostname SomeHostname # If expired`
|
||||
|
||||
## Notes
|
||||
|
||||
* If you want to communicate with SporeStack APIs using Tor, set this environment variable: `SPORESTACK_USE_TOR_ENDPOINT=1`
|
||||
* If you want to communicate with the SporeStack API using Tor, set this environment variable: `SPORESTACK_USE_TOR_ENDPOINT=1`. Verify which endpoint is in use with `sporestack api-endpoint`.
|
||||
|
||||
## Developing
|
||||
|
||||
* `pipenv install --deploy --dev`
|
||||
* `pipenv run make test` (If you don't have `make`, use `almake`)
|
||||
* `pipenv run make test`
|
||||
* `pipenv run make format` to format files and apply ruff fixes.
|
||||
|
||||
## Licence
|
||||
|
|
|
@ -25,15 +25,14 @@ sporestack token list
|
|||
sporestack token import importediminvalid --key "imaninvalidkey"
|
||||
sporestack token list | grep importediminvalid
|
||||
sporestack token list | grep imaninvalidkey
|
||||
sporestack server launch --no-quote --token neverbeencreated --operating-system debian-11 --days 1 2>&1 | grep 'does not exist'
|
||||
sporestack server launch --no-quote --token neverbeencreated --operating-system debian-12 --days 1 2>&1 | grep 'does not exist'
|
||||
|
||||
# Online tests start here.
|
||||
|
||||
sporestack token create --dollars 50 --currency fakecurrency ihaveafakecurrency 2>&1 | grep 'Input should be'
|
||||
sporestack server launch --no-quote --token importediminvalid --operating-system debian-11 --days 1 2>&1 | grep 'String should have at least'
|
||||
sporestack server launch --no-quote --token importediminvalid --operating-system debian-12 --days 1 2>&1 | grep 'String should have at least'
|
||||
|
||||
sporestack server flavors | grep vcpu
|
||||
sporestack server operating-systems | grep debian-11
|
||||
sporestack server operating-systems | grep debian-12
|
||||
sporestack server regions | grep sfo3
|
||||
sporestack api-changelog
|
||||
|
||||
|
@ -55,7 +54,7 @@ sporestack token invoices realtestingtoken
|
|||
sporestack token topup realtestingtoken --currency xmr --dollars 26 --no-wait
|
||||
|
||||
sporestack server list --token realtestingtoken
|
||||
sporestack server launch --no-quote --token realtestingtoken --operating-system debian-11 --days 1 --hostname sporestackpythonintegrationtestdelme
|
||||
sporestack server launch --no-quote --token realtestingtoken --operating-system debian-12 --days 1 --hostname sporestackpythonintegrationtestdelme
|
||||
sporestack server list --token realtestingtoken | grep sporestackpythonintegrationtestdelme
|
||||
sporestack server topup --token realtestingtoken --hostname sporestackpythonintegrationtestdelme --days 1
|
||||
sporestack server info --token realtestingtoken --hostname sporestackpythonintegrationtestdelme
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
addopts = "--strict-markers --disable-socket"
|
||||
|
||||
[tool.ruff]
|
||||
select = [
|
||||
lint.select = [
|
||||
"F", # pyflakes
|
||||
"E", # pycodestyle errors
|
||||
"W", # pycodestyle warnings
|
||||
|
@ -13,12 +13,12 @@ select = [
|
|||
"UP", # pyupgrade
|
||||
]
|
||||
|
||||
ignore = [
|
||||
lint.ignore = [
|
||||
"ANN101", # Type annotations for self
|
||||
"ANN401", # Allow ANY
|
||||
]
|
||||
|
||||
unfixable = [
|
||||
lint.unfixable = [
|
||||
"F401", # Don't try to automatically remove unused imports
|
||||
"RUF100", # Unused noqa
|
||||
"F841", # Unused variable
|
||||
|
@ -55,16 +55,12 @@ license = {file = "LICENSE.txt"}
|
|||
dependencies = [
|
||||
"pydantic>=1.10,<3",
|
||||
"httpx[socks]",
|
||||
"segno",
|
||||
"typer>=0.9.0",
|
||||
"rich",
|
||||
]
|
||||
|
||||
# You will have to specify sporestack[cli] for v11+.
|
||||
[project.optional-dependencies]
|
||||
cli = [
|
||||
"segno",
|
||||
"typer",
|
||||
"typer>=0.9.0",
|
||||
"rich",
|
||||
]
|
||||
|
||||
|
|
|
@ -2,4 +2,4 @@
|
|||
|
||||
__all__ = ["api", "api_client", "client", "exceptions"]
|
||||
|
||||
__version__ = "10.8.0"
|
||||
__version__ = "11.1.0"
|
||||
|
|
|
@ -0,0 +1,11 @@
|
|||
# This file is split out to improve CLI performance.
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class Currency(str, Enum):
|
||||
xmr = "xmr"
|
||||
"""Monero"""
|
||||
btc = "btc"
|
||||
"""Bitcoin"""
|
||||
bch = "bch"
|
||||
"""Bitcoin Cash"""
|
|
@ -1,6 +1,5 @@
|
|||
"""SporeStack API request/response models"""
|
||||
|
||||
|
||||
import sys
|
||||
from datetime import datetime
|
||||
from enum import Enum
|
||||
|
@ -8,7 +7,7 @@ from typing import Dict, List, Optional, Union
|
|||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from .models import Flavor, Invoice, OperatingSystem, Payment, Region
|
||||
from .models import Currency, Flavor, Invoice, OperatingSystem, Region
|
||||
|
||||
if sys.version_info >= (3, 9): # pragma: nocover
|
||||
from typing import Annotated
|
||||
|
@ -21,15 +20,11 @@ class TokenAdd:
|
|||
method = "POST"
|
||||
|
||||
class Request(BaseModel):
|
||||
currency: str
|
||||
"""BREAKING: This will change to models.Currency in version 11."""
|
||||
currency: Currency
|
||||
dollars: int
|
||||
affiliate_token: Union[str, None] = None
|
||||
legacy_polling: bool = True
|
||||
|
||||
class Response(BaseModel):
|
||||
token: Annotated[str, Field(deprecated=True)]
|
||||
payment: Annotated[Payment, Field(deprecated=True)]
|
||||
invoice: Invoice
|
||||
|
||||
|
||||
|
@ -38,7 +33,6 @@ class TokenBalance:
|
|||
method = "GET"
|
||||
|
||||
class Response(BaseModel):
|
||||
token: Annotated[str, Field(deprecated=True)]
|
||||
cents: int
|
||||
usd: str
|
||||
|
||||
|
@ -118,7 +112,6 @@ class ServerInfo:
|
|||
ipv6: str
|
||||
region: str
|
||||
flavor: Flavor
|
||||
deleted: Annotated[bool, Field(deprecated=True)]
|
||||
deleted_at: int
|
||||
deleted_by: Union[ServerDeletedBy, None]
|
||||
forgotten_at: Union[datetime, None]
|
||||
|
|
|
@ -7,11 +7,12 @@ import httpx
|
|||
from pydantic import parse_obj_as
|
||||
|
||||
from . import __version__, api, exceptions
|
||||
from .models import Invoice, ServerUpdateRequest, TokenInfo
|
||||
from .models import Currency, Invoice, ServerUpdateRequest, TokenInfo
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
LATEST_API_VERSION = 2
|
||||
"""This is probably not used anymore."""
|
||||
|
||||
CLEARNET_ENDPOINT = "https://api.sporestack.com"
|
||||
TOR_ENDPOINT = (
|
||||
|
@ -273,14 +274,11 @@ class APIClient:
|
|||
self,
|
||||
token: str,
|
||||
dollars: int,
|
||||
currency: str,
|
||||
legacy_polling: bool = True,
|
||||
currency: Currency,
|
||||
) -> api.TokenAdd.Response:
|
||||
"""Add balance (money) to a token."""
|
||||
url = self.api_endpoint + api.TokenAdd.url.format(token=token)
|
||||
request = api.TokenAdd.Request(
|
||||
dollars=dollars, currency=currency, legacy_polling=legacy_polling
|
||||
)
|
||||
request = api.TokenAdd.Request(dollars=dollars, currency=currency)
|
||||
response = self._httpx_client.post(url, json=request.dict())
|
||||
_handle_response(response)
|
||||
response_object = api.TokenAdd.Response.parse_obj(response.json())
|
||||
|
|
|
@ -8,10 +8,12 @@ import os
|
|||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, Dict, Optional
|
||||
from typing import TYPE_CHECKING, Any, Dict, Optional, Union
|
||||
|
||||
import typer
|
||||
|
||||
from ._models import Currency
|
||||
|
||||
if sys.version_info >= (3, 9): # pragma: nocover
|
||||
from typing import Annotated
|
||||
else: # pragma: nocover
|
||||
|
@ -47,11 +49,12 @@ cli = typer.Typer(help=HELP)
|
|||
|
||||
HOME = Path(_home)
|
||||
|
||||
token_cli = typer.Typer(help="Commands to interact with SporeStack tokens")
|
||||
token_cli = typer.Typer(help="Commands to interact with SporeStack tokens.")
|
||||
cli.add_typer(token_cli, name="token")
|
||||
server_cli = typer.Typer(help="Commands to interact with SporeStack servers")
|
||||
server_cli = typer.Typer(help="Commands to interact with SporeStack servers.")
|
||||
cli.add_typer(server_cli, name="server")
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
_log_level = os.getenv("LOG_LEVEL", "warning").upper()
|
||||
_numeric_log_level = getattr(logging, _log_level, None)
|
||||
if _numeric_log_level is None:
|
||||
|
@ -63,6 +66,8 @@ DEFAULT_TOKEN = "primary"
|
|||
DEFAULT_FLAVOR = "vps-1vcpu-1gb"
|
||||
# Users may have a different key file, but this is the most common.
|
||||
DEFAULT_SSH_KEY_FILE = HOME / ".ssh" / "id_rsa.pub"
|
||||
DEFAULT_TOKEN_SSH_KEY_PRIVATE = Path("id_ed25519")
|
||||
DEFAULT_TOKEN_SSH_KEY_PUBLIC = DEFAULT_TOKEN_SSH_KEY_PRIVATE.with_suffix(".pub")
|
||||
|
||||
# On disk format
|
||||
TOKEN_VERSION = 1
|
||||
|
@ -92,20 +97,91 @@ def invoice_qr(invoice: "Invoice") -> None:
|
|||
qr.terminal()
|
||||
|
||||
|
||||
def normalize_ssh_key_file(ssh_key_file: Union[Path, None], token: str) -> Path:
|
||||
if ssh_key_file is None:
|
||||
token_specific_path = ssh_key_path(token)
|
||||
token_specific_key = token_specific_path / DEFAULT_TOKEN_SSH_KEY_PUBLIC
|
||||
if token_specific_key.exists():
|
||||
ssh_key_file = token_specific_key
|
||||
elif DEFAULT_SSH_KEY_FILE.exists():
|
||||
ssh_key_file = DEFAULT_SSH_KEY_FILE
|
||||
|
||||
if ssh_key_file is None:
|
||||
typer.echo(
|
||||
"No SSH key specified with --ssh-key-file, nor was "
|
||||
f"{token_specific_key} or {DEFAULT_SSH_KEY_FILE} found.",
|
||||
err=True,
|
||||
)
|
||||
typer.echo("You can generate a SSH key with `ssh-key-gen`", err=True)
|
||||
raise typer.Exit(code=1)
|
||||
|
||||
return ssh_key_file
|
||||
|
||||
|
||||
@server_cli.command()
|
||||
def launch(
|
||||
days: Annotated[
|
||||
int,
|
||||
typer.Option(min=1, max=90, help="Number of days the server should run for."),
|
||||
typer.Option(
|
||||
min=1,
|
||||
max=90,
|
||||
help=(
|
||||
"Initially fund the server to run for this many days. Use "
|
||||
"--autorenew if you don't want it to expire."
|
||||
),
|
||||
show_default=False,
|
||||
),
|
||||
],
|
||||
operating_system: Annotated[str, typer.Option(help="Example: debian-11")],
|
||||
hostname: str = "",
|
||||
ssh_key_file: Path = DEFAULT_SSH_KEY_FILE,
|
||||
flavor: str = DEFAULT_FLAVOR,
|
||||
token: str = DEFAULT_TOKEN,
|
||||
region: Optional[str] = None,
|
||||
operating_system: Annotated[
|
||||
str,
|
||||
typer.Option(
|
||||
help=(
|
||||
"Example: debian-12 (Run `sporestack server operating-systems` for "
|
||||
"more options.)"
|
||||
),
|
||||
show_default=False,
|
||||
),
|
||||
],
|
||||
hostname: Annotated[
|
||||
str,
|
||||
typer.Option(
|
||||
help=(
|
||||
"Give the server a hostname to help remember what it's for. "
|
||||
"(Note: This is visible to us.)"
|
||||
)
|
||||
),
|
||||
] = "",
|
||||
ssh_key_file: Annotated[
|
||||
Union[Path, None],
|
||||
typer.Option(
|
||||
help=(
|
||||
"SSH key that the new server will allow to login as root. Defaults "
|
||||
"to the token-specific SSH key, or ~/.ssh/id_rsa.pub if the former "
|
||||
"was not found."
|
||||
),
|
||||
show_default=False,
|
||||
),
|
||||
] = None,
|
||||
flavor: Annotated[
|
||||
str, typer.Option(help="Run `sporestack server flavors` to see more options.")
|
||||
] = DEFAULT_FLAVOR,
|
||||
token: Annotated[
|
||||
str, typer.Option(help="Which token to launch the server with.")
|
||||
] = DEFAULT_TOKEN,
|
||||
region: Annotated[
|
||||
Optional[str],
|
||||
typer.Option(
|
||||
help=(
|
||||
"Leave unset for random region selection. Or run `sporestack server "
|
||||
"regions` for options."
|
||||
),
|
||||
show_default=False,
|
||||
),
|
||||
] = None,
|
||||
quote: bool = typer.Option(True, help="Require manual price confirmation."),
|
||||
autorenew: bool = typer.Option(False, help="Automatically renew server."),
|
||||
autorenew: bool = typer.Option(
|
||||
False, help="Automatically renew server. (--days 7) recommended if using this."
|
||||
),
|
||||
wait: bool = typer.Option(
|
||||
True, help="Wait for server to be assigned an IP address."
|
||||
),
|
||||
|
@ -114,21 +190,16 @@ def launch(
|
|||
typer.echo(f"Launching server with token {token}...", err=True)
|
||||
_token = load_token(token)
|
||||
|
||||
from . import utils
|
||||
ssh_key_file = normalize_ssh_key_file(ssh_key_file=ssh_key_file, token=token)
|
||||
typer.echo(f"Using SSH key: {ssh_key_file}")
|
||||
|
||||
from .client import Client
|
||||
|
||||
client = Client(api_client=get_api_client(), client_token=_token)
|
||||
|
||||
typer.echo(f"Loading SSH key from {ssh_key_file}...")
|
||||
if not ssh_key_file.exists():
|
||||
msg = f"{ssh_key_file} does not exist. "
|
||||
msg += "You can try generating a key file with `ssh-keygen`"
|
||||
typer.echo(msg, err=True)
|
||||
raise typer.Exit(code=1)
|
||||
|
||||
ssh_key = ssh_key_file.read_text()
|
||||
|
||||
machine_id = utils.random_machine_id()
|
||||
client = Client(
|
||||
api_client=get_api_client(),
|
||||
client_token=_token,
|
||||
ssh_key=ssh_key_file.read_text(),
|
||||
)
|
||||
|
||||
if quote:
|
||||
quote_response = client.server_quote(days=days, flavor=flavor)
|
||||
|
@ -148,20 +219,23 @@ def launch(
|
|||
)
|
||||
|
||||
server = client.token.launch_server(
|
||||
machine_id=machine_id,
|
||||
days=days,
|
||||
flavor=flavor,
|
||||
operating_system=operating_system,
|
||||
ssh_key=ssh_key,
|
||||
region=region,
|
||||
hostname=hostname,
|
||||
autorenew=autorenew,
|
||||
)
|
||||
|
||||
if wait:
|
||||
tries = 360
|
||||
tries = 60
|
||||
while tries > 0:
|
||||
response = server.info()
|
||||
if response.deleted_at > 0:
|
||||
typer.echo(
|
||||
"Server creation failed, was deleted while waiting.", err=True
|
||||
)
|
||||
raise typer.Exit(code=1)
|
||||
if response.ipv4 != "":
|
||||
break
|
||||
typer.echo("Waiting for server to build...", err=True)
|
||||
|
@ -174,9 +248,44 @@ def launch(
|
|||
raise typer.Exit(code=1)
|
||||
else:
|
||||
print_machine_info(response)
|
||||
return
|
||||
|
||||
print_machine_info(server.info())
|
||||
if not wait:
|
||||
print_machine_info(server.info())
|
||||
return
|
||||
|
||||
typer.echo("Consider adding the following to ~/.ssh/config...")
|
||||
|
||||
config = (
|
||||
"\nHost {host}\n"
|
||||
"\tHostname {hostname}\n"
|
||||
f"\tIdentityFile {str(ssh_key_file).strip('.pub')}\n"
|
||||
"\tUser root\n"
|
||||
"\t # Remove this comment if you wish to connect via Tor. "
|
||||
"ProxyCommand nc -x localhost:9050 %h %p\n"
|
||||
)
|
||||
|
||||
typer.echo("If you wish to connect with IPv4:")
|
||||
typer.echo(
|
||||
config.format(
|
||||
host=hostname if hostname != "" else response.ipv4, hostname=response.ipv4
|
||||
)
|
||||
)
|
||||
|
||||
typer.echo("Or if you wish to connect with IPv6:")
|
||||
typer.echo(
|
||||
config.format(
|
||||
host=hostname if hostname != "" else response.ipv6, hostname=response.ipv6
|
||||
)
|
||||
)
|
||||
|
||||
msg = (
|
||||
"If you've done that, you should be able to run `ssh {host}` "
|
||||
"to connect to the server."
|
||||
)
|
||||
if hostname != "":
|
||||
typer.echo(msg.format(host=hostname))
|
||||
else:
|
||||
typer.echo(msg.format(host=f"({response.ipv4} or {response.ipv6})"))
|
||||
|
||||
|
||||
@server_cli.command()
|
||||
|
@ -209,20 +318,6 @@ def server_info_path() -> Path:
|
|||
# Put servers in a subdirectory
|
||||
servers_dir = SPORESTACK_DIR / "servers"
|
||||
|
||||
# Migrate existing server.json files into servers subdirectory
|
||||
if (
|
||||
SPORESTACK_DIR.exists()
|
||||
and not servers_dir.exists()
|
||||
and len(list(SPORESTACK_DIR.glob("*.json"))) > 0
|
||||
):
|
||||
typer.echo(
|
||||
f"Migrating server profiles found in {SPORESTACK_DIR} to {servers_dir}.",
|
||||
err=True,
|
||||
)
|
||||
servers_dir.mkdir()
|
||||
for json_file in SPORESTACK_DIR.glob("*.json"):
|
||||
json_file.rename(servers_dir / json_file.name)
|
||||
|
||||
# Make it, if it doesn't exist already.
|
||||
SPORESTACK_DIR.mkdir(exist_ok=True)
|
||||
servers_dir.mkdir(exist_ok=True)
|
||||
|
@ -239,6 +334,15 @@ def token_path() -> Path:
|
|||
return token_dir
|
||||
|
||||
|
||||
def ssh_key_path(token: str) -> Path:
|
||||
ssh_key_dir = SPORESTACK_DIR / "sshkey" / token
|
||||
|
||||
# Make it, if it doesn't exist already.
|
||||
ssh_key_dir.mkdir(exist_ok=True, parents=True)
|
||||
|
||||
return ssh_key_dir
|
||||
|
||||
|
||||
def get_machine_info(hostname: str) -> Dict[str, Any]:
|
||||
"""
|
||||
Get info from disk.
|
||||
|
@ -348,7 +452,7 @@ def server_list(
|
|||
token: str = DEFAULT_TOKEN,
|
||||
local: Annotated[
|
||||
bool, typer.Option(help="List older servers not associated to token.")
|
||||
] = True,
|
||||
] = False,
|
||||
show_forgotten: Annotated[
|
||||
bool, typer.Option(help="Show deleted and forgotten servers.")
|
||||
] = False,
|
||||
|
@ -486,11 +590,29 @@ def _get_machine_id(machine_id: str, hostname: str, token: str) -> str:
|
|||
|
||||
api_client = APIClient(api_endpoint=get_api_endpoint())
|
||||
|
||||
candidates = []
|
||||
for server in api_client.servers_launched_from_token(token=_token).servers:
|
||||
if server.forgotten_at is not None:
|
||||
continue
|
||||
if server.hostname == hostname:
|
||||
return server.machine_id
|
||||
candidates.append(server)
|
||||
|
||||
if len(candidates) == 1:
|
||||
return candidates[0].machine_id
|
||||
|
||||
remaining_candidates = []
|
||||
for candidate in candidates:
|
||||
if candidate.deleted_at == 0:
|
||||
remaining_candidates.append(candidate)
|
||||
|
||||
if len(remaining_candidates) == 1:
|
||||
return remaining_candidates[0].machine_id
|
||||
elif len(remaining_candidates) > 1:
|
||||
typer.echo(
|
||||
"Too many servers match that hostname. Please use --machine-id, instead.",
|
||||
err=True,
|
||||
)
|
||||
raise typer.Exit(code=1)
|
||||
|
||||
typer.echo(
|
||||
f"Could not find any servers matching the hostname: {hostname}", err=True
|
||||
|
@ -751,17 +873,23 @@ def save_token(token: str, key: str) -> None:
|
|||
|
||||
@token_cli.command(name="create")
|
||||
def token_create(
|
||||
dollars: Annotated[int, typer.Option()],
|
||||
currency: Annotated[str, typer.Option()],
|
||||
dollars: Annotated[
|
||||
int,
|
||||
typer.Option(help="How many dollars to add to the token.", show_default=False),
|
||||
],
|
||||
currency: Annotated[
|
||||
Currency,
|
||||
typer.Option(help="Which cryptocurrency to pay with.", show_default=False),
|
||||
],
|
||||
token: Annotated[str, typer.Argument()] = DEFAULT_TOKEN,
|
||||
wait: bool = typer.Option(True, help="Wait for the payment to be confirmed."),
|
||||
qr: bool = typer.Option(True, help="Show a QR code for the payment URI."),
|
||||
wait: Annotated[
|
||||
bool, typer.Option(help="Wait for the payment to be confirmed.")
|
||||
] = True,
|
||||
qr: Annotated[
|
||||
bool, typer.Option(help="Show a QR code for the payment URI.")
|
||||
] = True,
|
||||
) -> None:
|
||||
"""
|
||||
Enables a new token.
|
||||
|
||||
Dollars is starting balance.
|
||||
"""
|
||||
"""Enables a new token."""
|
||||
from . import utils
|
||||
|
||||
if Path(SPORESTACK_DIR / "tokens" / f"{token}.json").exists():
|
||||
|
@ -782,6 +910,15 @@ def token_create(
|
|||
)
|
||||
typer.echo(f"{token}'s key is {_token}.")
|
||||
typer.echo("Save it, don't share it, and don't lose it!")
|
||||
typer.echo()
|
||||
typer.echo("Optional: Make a SSH key just for this token.")
|
||||
token_ssh_key_path = ssh_key_path(token) / DEFAULT_TOKEN_SSH_KEY_PRIVATE
|
||||
typer.echo(f'Run: ssh-keygen -C "" -t ed25519 -f "{token_ssh_key_path}"')
|
||||
typer.echo(
|
||||
"If you do this, servers launched from that token will default to use "
|
||||
"that key and you won't have to pass --ssh-key-file every time you "
|
||||
"launch a server!"
|
||||
)
|
||||
|
||||
|
||||
@token_cli.command(name="import")
|
||||
|
@ -794,7 +931,7 @@ def token_import(
|
|||
|
||||
|
||||
def token_add(
|
||||
token: str, dollars: int, currency: str, wait: bool, token_name: str, qr: bool
|
||||
token: str, dollars: int, currency: Currency, wait: bool, token_name: str, qr: bool
|
||||
) -> None:
|
||||
from httpx import HTTPError
|
||||
|
||||
|
@ -805,7 +942,7 @@ def token_add(
|
|||
api_client = APIClient(api_endpoint=get_api_endpoint())
|
||||
client = Client(api_client=api_client, client_token=token)
|
||||
|
||||
invoice = client.token.add(dollars, currency=currency, legacy_polling=False)
|
||||
invoice = client.token.add(dollars, currency=currency)
|
||||
|
||||
if qr:
|
||||
invoice_qr(invoice)
|
||||
|
@ -850,11 +987,21 @@ def token_add(
|
|||
|
||||
@token_cli.command(name="topup")
|
||||
def token_topup(
|
||||
token: str = typer.Argument(DEFAULT_TOKEN),
|
||||
dollars: int = typer.Option(...),
|
||||
currency: str = typer.Option(...),
|
||||
wait: bool = typer.Option(True, help="Wait for the payment to be confirmed."),
|
||||
qr: bool = typer.Option(True, help="Show a QR code for the payment URI."),
|
||||
currency: Annotated[
|
||||
Currency,
|
||||
typer.Option(help="Which cryptocurrency to pay with.", show_default=False),
|
||||
],
|
||||
dollars: Annotated[
|
||||
int,
|
||||
typer.Option(help="How many dollars to add to the token.", show_default=False),
|
||||
],
|
||||
token: Annotated[str, typer.Argument()] = DEFAULT_TOKEN,
|
||||
wait: Annotated[
|
||||
bool, typer.Option(help="Wait for the payment to be confirmed.")
|
||||
] = True,
|
||||
qr: Annotated[
|
||||
bool, typer.Option(help="Show a QR code for the payment URI.")
|
||||
] = True,
|
||||
) -> None:
|
||||
"""Adds balance to an existing token."""
|
||||
real_token = load_token(token)
|
||||
|
@ -917,7 +1064,7 @@ def token_info(token: Annotated[str, typer.Argument()] = DEFAULT_TOKEN) -> None:
|
|||
|
||||
@token_cli.command()
|
||||
def servers(token: Annotated[str, typer.Argument()] = DEFAULT_TOKEN) -> None:
|
||||
"""Returns server info for servers launched by a given token."""
|
||||
"""Use sporestack server list --token TOKEN instead!"""
|
||||
_token = load_token(token)
|
||||
|
||||
from .api_client import APIClient
|
||||
|
|
|
@ -3,7 +3,7 @@ from typing import List, Union
|
|||
|
||||
from . import api
|
||||
from .api_client import APIClient
|
||||
from .models import Invoice, TokenInfo
|
||||
from .models import Currency, Invoice, TokenInfo
|
||||
from .utils import random_machine_id, random_token
|
||||
|
||||
|
||||
|
@ -69,14 +69,15 @@ class Server:
|
|||
class Token:
|
||||
token: str = field(default_factory=random_token)
|
||||
api_client: APIClient = field(default_factory=APIClient)
|
||||
ssh_key: Union[str, None] = None
|
||||
"""SSH public key for launching new servers with."""
|
||||
|
||||
def add(self, dollars: int, currency: str, legacy_polling: bool = True) -> Invoice:
|
||||
"""Add to token"""
|
||||
def add(self, dollars: int, currency: Currency) -> Invoice:
|
||||
"""Fund the token."""
|
||||
response = self.api_client.token_add(
|
||||
token=self.token,
|
||||
dollars=dollars,
|
||||
currency=currency,
|
||||
legacy_polling=legacy_polling,
|
||||
)
|
||||
return response.invoice
|
||||
|
||||
|
@ -120,15 +121,20 @@ class Token:
|
|||
|
||||
def launch_server(
|
||||
self,
|
||||
ssh_key: str,
|
||||
flavor: str,
|
||||
days: int,
|
||||
operating_system: str,
|
||||
ssh_key: Union[str, None] = None,
|
||||
region: Union[str, None] = None,
|
||||
hostname: str = "",
|
||||
autorenew: bool = False,
|
||||
machine_id: str = random_machine_id(),
|
||||
) -> Server:
|
||||
if ssh_key is None:
|
||||
if self.ssh_key is not None:
|
||||
ssh_key = self.ssh_key
|
||||
else:
|
||||
raise ValueError("ssh_key must be set in Client() or launch_server().")
|
||||
self.api_client.server_launch(
|
||||
machine_id=machine_id,
|
||||
days=days,
|
||||
|
@ -151,6 +157,8 @@ class Client:
|
|||
"""Token to manage/pay for servers with."""
|
||||
api_client: APIClient = field(default_factory=APIClient)
|
||||
"""Your own API Client, perhaps if you want to connect through Tor."""
|
||||
ssh_key: Union[str, None] = None
|
||||
"""SSH public key for launching new servers with."""
|
||||
|
||||
def flavors(self) -> api.Flavors.Response:
|
||||
"""Returns available flavors (server sizes)."""
|
||||
|
@ -175,4 +183,6 @@ class Client:
|
|||
@property
|
||||
def token(self) -> Token:
|
||||
"""Returns a Token object with the api_client and token specified."""
|
||||
return Token(token=self.client_token, api_client=self.api_client)
|
||||
return Token(
|
||||
token=self.client_token, api_client=self.api_client, ssh_key=self.ssh_key
|
||||
)
|
||||
|
|
|
@ -1,33 +1,17 @@
|
|||
"""SporeStack API supplemental models"""
|
||||
|
||||
import sys
|
||||
from enum import Enum
|
||||
from typing import Optional, Union
|
||||
from typing import Union
|
||||
|
||||
if sys.version_info >= (3, 9): # pragma: nocover
|
||||
from typing import Annotated
|
||||
else: # pragma: nocover
|
||||
from typing_extensions import Annotated
|
||||
|
||||
# Re-export Currency
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class Currency(str, Enum):
|
||||
xmr = "xmr"
|
||||
"""Monero"""
|
||||
btc = "btc"
|
||||
"""Bitcoin"""
|
||||
bch = "bch"
|
||||
"""Bitcoin Cash"""
|
||||
|
||||
|
||||
class Payment(BaseModel):
|
||||
"""This is deprecated in favor of Invoice."""
|
||||
|
||||
txid: Optional[str]
|
||||
uri: Optional[str]
|
||||
usd: str
|
||||
paid: bool
|
||||
from ._models import Currency as Currency
|
||||
|
||||
|
||||
class Flavor(BaseModel):
|
||||
|
@ -62,7 +46,6 @@ class OperatingSystem(BaseModel):
|
|||
class TokenInfo(BaseModel):
|
||||
balance_cents: int
|
||||
balance_usd: str
|
||||
burn_rate: Annotated[int, Field(deprecated=True)]
|
||||
burn_rate_cents: int
|
||||
burn_rate_usd: str
|
||||
days_remaining: int
|
||||
|
|
|
@ -83,7 +83,6 @@ def test_token_info(respx_mock: respx.MockRouter) -> None:
|
|||
"servers": 0,
|
||||
"autorenew_servers": 0,
|
||||
"suspended_servers": 0,
|
||||
"burn_rate": 0,
|
||||
"burn_rate_usd": "$0.00",
|
||||
"burn_rate_cents": 0,
|
||||
"days_remaining": 0,
|
||||
|
@ -97,7 +96,6 @@ def test_token_info(respx_mock: respx.MockRouter) -> None:
|
|||
info_response = client.token_info(dummy_token)
|
||||
assert info_response.balance_cents == 0
|
||||
assert info_response.balance_usd == "$0.00"
|
||||
assert info_response.burn_rate == 0
|
||||
assert info_response.burn_rate_cents == 0
|
||||
assert info_response.burn_rate_usd == "$0.00"
|
||||
assert info_response.servers == 0
|
||||
|
|
7
tox.ini
7
tox.ini
|
@ -6,11 +6,14 @@ env_list =
|
|||
deps =
|
||||
pydantic1: pydantic~=1.10
|
||||
pydantic2: pydantic~=2.0
|
||||
pytest~=7.2
|
||||
pytest-socket~=0.6.0
|
||||
pytest~=8.0
|
||||
pytest-socket~=0.7.0
|
||||
pytest-cov~=4.0
|
||||
pytest-mock~=3.6
|
||||
respx~=0.20.1
|
||||
segno
|
||||
typer~=0.9.0
|
||||
rich
|
||||
commands =
|
||||
pytest --cov=sporestack --cov-fail-under=39 --cov-report=term --durations=3
|
||||
sporestack api-endpoint
|
||||
|
|
Loading…
Reference in New Issue