Skip to content

Commit

Permalink
Merge pull request #84 from andrewwhitehead/fix-demo-startup
Browse files Browse the repository at this point in the history
Allow demo scripts to run outside of Docker; add command line parsing
  • Loading branch information
swcurran authored Jul 18, 2019
2 parents b043d48 + 9c5835f commit 4f18e14
Show file tree
Hide file tree
Showing 12 changed files with 195 additions and 94 deletions.
6 changes: 4 additions & 2 deletions conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,11 @@ def pytest_sessionstart(session):

INDY_FOUND = True
except ImportError:
"skipping Indy-specific tests: python module not installed",
print("Skipping Indy-specific tests: python3-indy module not installed.")
except OSError:
"skipping Indy-specific tests: shared library not loaded",
print(
"Skipping Indy-specific tests: libindy shared library could not be loaded."
)

if not INDY_FOUND:
modules = {}
Expand Down
1 change: 0 additions & 1 deletion demo/__init__.py

This file was deleted.

36 changes: 18 additions & 18 deletions demo/run_demo
Original file line number Diff line number Diff line change
Expand Up @@ -4,43 +4,42 @@ shopt -s nocasematch

cd $(dirname $0)

AGENT=$1
if [[ $AGENT == "faber" ]] || [[ $AGENT == "alice" ]] || [[ $AGENT == "acme" ]] || [[ $AGENT == "performance" ]]; then
echo "Preparing agent image..."
docker build -q -t faber-alice-demo -f ../docker/Dockerfile.demo .. || exit 1
else
echo "Please specify which agent you want to run. Choose from 'faber', 'alice', 'acme', or 'performance'.";
exit 1;
fi
AGENT="$1"
shift

echo "Starting $AGENT..."
if [[ $AGENT == "faber" ]]; then
if [ "$AGENT" = "faber" ]; then
AGENT_MODULE="faber"
AGENT_PORT=8020
AGENT_PORT_RANGE=8020-8027
elif [[ $AGENT == "alice" ]]; then
elif [ "$AGENT" = "alice" ]; then
AGENT_MODULE="alice"
AGENT_PORT=8030
AGENT_PORT_RANGE=8030-8037
elif [[ $AGENT == "acme" ]]; then
elif [ "$AGENT" = "acme" ]; then
AGENT_MODULE="acme"
AGENT_PORT=8040
AGENT_PORT_RANGE=8040-8047
else
elif [ "$AGENT" = "performance" ]; then
AGENT_MODULE="performance"
AGENT_PORT=8030
AGENT_PORT_RANGE=8030-8038
else
echo "Please specify which agent you want to run. Choose from 'faber', 'alice', 'acme', or 'performance'."
exit 1
fi

if [[ -z "${PWD_HOST_FQDN}" ]]; then
echo "Preparing agent image..."
docker build -q -t faber-alice-demo -f ../docker/Dockerfile.demo .. || exit 1

if [ -z "${PWD_HOST_FQDN}" ]; then
DOCKERHOST=`docker run --rm --net=host codenvy/che-ip`
export RUNMODE="docker"
else
PWD_HOST="${PWD_HOST_FQDN}"
if [ $PWD_HOST_FQDN == "labs.play-with-docker.com" ]
if [ "$PWD_HOST_FQDN" = "labs.play-with-docker.com" ]
then
export ETH_CONFIG="eth1"
elif [ $PWD_HOST_FQDN == "play-with-docker.vonx.io" ]
elif [ "$PWD_HOST_FQDN" = "play-with-docker.vonx.io" ]
then
export ETH_CONFIG="eth0"
else
Expand All @@ -63,12 +62,13 @@ if ! [ -z "$LEDGER_URL" ]; then
fi

# on Windows, docker run needs to be prefixed by winpty
if [[ "$OSTYPE" == "msys" ]]; then
if [ "$OSTYPE" = "msys" ]; then
DOCKER="winpty docker"
fi
DOCKER=${DOCKER:-docker}

echo "Starting $AGENT..."
$DOCKER run --name $AGENT --rm -it \
-p 0.0.0.0:$AGENT_PORT_RANGE:$AGENT_PORT_RANGE \
$DOCKER_ENV \
faber-alice-demo $AGENT_MODULE $AGENT_PORT
faber-alice-demo $AGENT_MODULE --port $AGENT_PORT $@
Empty file added demo/runners/__init__.py
Empty file.
79 changes: 53 additions & 26 deletions demo/acme.py → demo/runners/acme.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,30 @@
import json
import logging
import os
import random
import sys

from .agent import DemoAgent, default_genesis_txns
from .utils import log_json, log_msg, log_status, log_timer, prompt, prompt_loop
from .support.agent import DemoAgent, default_genesis_txns
from .support.utils import (
log_json,
log_msg,
log_status,
log_timer,
prompt,
prompt_loop,
require_indy,
)

LOGGER = logging.getLogger(__name__)

AGENT_PORT = int(sys.argv[1])

TIMING = False


class AcmeAgent(DemoAgent):
def __init__(self, http_port: int, admin_port: int, **kwargs):
super().__init__("Acme Agent", http_port, admin_port, prefix="Acme", **kwargs)
self.connection_id = None
self._connection_ready = asyncio.Future()
self.cred_state = {}
# TODO define a dict to hold credential attributes based on credential_definition_id
# TODO define a dict to hold credential attributes based on
# the credential_definition_id
self.cred_attrs = {}

async def detect_connection(self):
Expand Down Expand Up @@ -75,19 +79,20 @@ async def handle_basicmessages(self, message):
self.log("Received message:", message["content"])


async def main():
async def main(start_port: int, show_timing: bool = False):

genesis = await default_genesis_txns()
if not genesis:
print("Error retrieving ledger genesis transactions")
sys.exit(1)

agent = None
start_port = AGENT_PORT

try:
log_status("#1 Provision an agent and wallet, get back configuration details")
agent = AcmeAgent(start_port, start_port + 1, genesis_data=genesis)
agent = AcmeAgent(
start_port, start_port + 1, genesis_data=genesis, timing=show_timing
)
await agent.listen_webhooks(start_port + 2)
await agent.register_did()

Expand All @@ -99,18 +104,24 @@ async def main():
# Create a schema
log_status("#3 Create a new schema on the ledger")
with log_timer("Publish schema duration:"):
version = format(
"%d.%d.%d"
% (
random.randint(1, 101),
random.randint(1, 101),
random.randint(1, 101),
)
)
pass
# TODO define schema
#(schema_id, credential_definition_id) = await agent.register_schema_and_creddef(
# "employee id schema", version, ["employee_id", "name", "date", "position"]
# )
# version = format(
# "%d.%d.%d"
# % (
# random.randint(1, 101),
# random.randint(1, 101),
# random.randint(1, 101),
# )
# )
# (
# schema_id,
# credential_definition_id,
# ) = await agent.register_schema_and_creddef(
# "employee id schema",
# version,
# ["employee_id", "name", "date", "position"],
# )

with log_timer("Generate invitation duration:"):
# Generate an invitation
Expand Down Expand Up @@ -138,20 +149,18 @@ async def main():
elif option == "1":
log_status("#13 Issue credential offer to X")
# TODO credential offers


elif option == "2":
log_status("#20 Request proof of degree from alice")
# TODO presentation requests


elif option == "3":
msg = await prompt("Enter message: ")
await agent.admin_POST(
f"/connections/{agent.connection_id}/send-message", {"content": msg}
)

if TIMING:
if show_timing:
timing = await agent.fetch_timing()
if timing:
for line in agent.format_timing(timing):
Expand All @@ -173,7 +182,25 @@ async def main():


if __name__ == "__main__":
import argparse

parser = argparse.ArgumentParser(description="Runs an Acme demo agent.")
parser.add_argument(
"-p",
"--port",
type=int,
default=8040,
metavar=("<port>"),
help="Choose the starting port number to listen on",
)
parser.add_argument(
"--timing", action="store_true", help="Enable timing information"
)
args = parser.parse_args()

require_indy()

try:
asyncio.get_event_loop().run_until_complete(main())
asyncio.get_event_loop().run_until_complete(main(args.port, args.timing))
except KeyboardInterrupt:
os._exit(1)
45 changes: 34 additions & 11 deletions demo/alice.py → demo/runners/alice.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,19 @@
import os
import sys

from .agent import DemoAgent, default_genesis_txns
from .utils import log_json, log_msg, log_status, log_timer, prompt, prompt_loop
from .support.agent import DemoAgent, default_genesis_txns
from .support.utils import (
log_json,
log_msg,
log_status,
log_timer,
prompt,
prompt_loop,
require_indy,
)

LOGGER = logging.getLogger(__name__)

AGENT_PORT = int(sys.argv[1])

TIMING = False


class AliceAgent(DemoAgent):
def __init__(self, http_port: int, admin_port: int, **kwargs):
Expand Down Expand Up @@ -163,19 +167,20 @@ async def input_invitation(agent):
await agent.detect_connection()


async def main():
async def main(start_port: int, show_timing: bool = False):

genesis = await default_genesis_txns()
if not genesis:
print("Error retrieving ledger genesis transactions")
sys.exit(1)

agent = None
start_port = AGENT_PORT

try:
log_status("#7 Provision an agent and wallet, get back configuration details")
agent = AliceAgent(start_port, start_port + 1, genesis_data=genesis)
agent = AliceAgent(
start_port, start_port + 1, genesis_data=genesis, timing=show_timing
)
await agent.listen_webhooks(start_port + 2)

with log_timer("Startup duration:"):
Expand Down Expand Up @@ -203,7 +208,7 @@ async def main():
log_status("Input new invitation details")
await input_invitation(agent)

if TIMING:
if show_timing:
timing = await agent.fetch_timing()
if timing:
for line in agent.format_timing(timing):
Expand All @@ -225,7 +230,25 @@ async def main():


if __name__ == "__main__":
import argparse

parser = argparse.ArgumentParser(description="Runs an Alice demo agent.")
parser.add_argument(
"-p",
"--port",
type=int,
default=8030,
metavar=("<port>"),
help="Choose the starting port number to listen on",
)
parser.add_argument(
"--timing", action="store_true", help="Enable timing information"
)
args = parser.parse_args()

require_indy()

try:
asyncio.get_event_loop().run_until_complete(main())
asyncio.get_event_loop().run_until_complete(main(args.port, args.timing))
except KeyboardInterrupt:
os._exit(1)
Loading

0 comments on commit 4f18e14

Please sign in to comment.