Skip to content

Commit 509e492

Browse files
committed
finish adapting nfctl to new logging scheme
1 parent b2fc20f commit 509e492

2 files changed

Lines changed: 43 additions & 14 deletions

File tree

netfoundry/ctl.py

Lines changed: 36 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import platform
1212
import re
1313
import signal
14+
import jwt
1415
import tempfile
1516
from builtins import list as blist
1617
from json import dumps as json_dumps
@@ -40,7 +41,7 @@
4041
from .network import Network, Networks
4142
from .network_group import NetworkGroup
4243
from .organization import Organization
43-
from .utility import DC_PROVIDERS, EMBED_NET_RESOURCES, IDENTITY_ID_PROPERTIES, MUTABLE_NET_RESOURCES, MUTABLE_RESOURCE_ABBREV, RESOURCE_ABBREV, RESOURCES, any_in, get_generic_resource_by_type_and_id, plural, propid2type, singular
44+
from .utility import DC_PROVIDERS, EMBED_NET_RESOURCES, IDENTITY_ID_PROPERTIES, MUTABLE_NET_RESOURCES, MUTABLE_RESOURCE_ABBREV, RESOURCE_ABBREV, RESOURCES, any_in, get_generic_resource_by_type_and_id, normalize_caseless, plural, propid2type, singular
4445

4546
set_metadata(version=f"v{netfoundry_version}", author="NetFoundry", name="nfctl") # must precend import milc.cli
4647
from milc import cli, questions # this uses metadata set above
@@ -603,7 +604,6 @@ def get(cli, echo: bool = True, spinner: object = None):
603604
@cli.argument('-m', '--my-roles', arg_only=True, action='store_true', help="filter roles by caller identity")
604605
@cli.argument('-a', '--as', dest='accept', arg_only=True, choices=['create'], help="request the as=create alternative form of the resources")
605606
@cli.argument('-n', '--names', default=False, action='store_boolean', help=argparse.SUPPRESS)
606-
@cli.argument('-n', '--names', default=False, action='store_boolean', help=argparse.SUPPRESS)
607607
@cli.argument('resource_type', arg_only=True, help='type of resource', metavar="RESOURCE_TYPE",
608608
choices=[choice for group in [[type, RESOURCES[type].abbreviation] for type in RESOURCES.keys()] for choice in group])
609609
@cli.subcommand(description='find a collection of resources by type and query')
@@ -688,7 +688,6 @@ def list(cli, echo: bool = True, spinner: object = None):
688688
for match in matches:
689689
valid_keys = valid_keys.union(match.keys())
690690

691-
valid_keys = valid_keys.intersection(cli.args.keys)
692691
# intersection of the set of valid, observed keys in the first match
693692
default_keys = ['name', 'label', 'organizationShortName', 'type', 'description',
694693
'edgeRouterAttributes', 'serviceAttributes', 'endpointAttributes',
@@ -697,12 +696,11 @@ def list(cli, echo: bool = True, spinner: object = None):
697696
'address', 'binding', 'component']
698697
if cli.config.list.names: # include identity IDs if --names
699698
default_keys.extend(IDENTITY_ID_PROPERTIES)
700-
valid_keys = valid_keys.intersection(default_keys)
701-
'active', 'default', 'region', 'size', 'attributes', 'email', 'productVersion',
702-
'address', 'binding', 'component']
699+
if cli.args.keys:
700+
valid_keys = valid_keys.intersection(cli.args.keys)
701+
else:
702+
valid_keys = valid_keys.intersection(default_keys)
703703
cli.log.debug(f"filtering matches for valid keys: {str(valid_keys)}")
704-
default_keys.extend(IDENTITY_ID_PROPERTIES)
705-
valid_keys = valid_keys.intersection(default_keys)
706704

707705
if valid_keys:
708706
cli.log.debug(f"filtering matches for valid keys: {str(valid_keys)}")
@@ -732,7 +730,7 @@ def list(cli, echo: bool = True, spinner: object = None):
732730
cli.log.debug(f"unexpected value for {k} = {v}")
733731
continue
734732
# get the resource with the name we're after
735-
resource, status = get_generic_resource_by_type_and_id(org=organization, resource_type=type_by_prop[k], resource_id=v)
733+
resource, status = get_generic_resource_by_type_and_id(setup=organization, resource_type=type_by_prop[k], resource_id=v)
736734
if resource.get('name'): # if the name property isn't empty
737735
match[k] = f"{resource['name']}" # wedge the name into the ID column
738736

@@ -759,7 +757,7 @@ def list(cli, echo: bool = True, spinner: object = None):
759757
cli.log.debug(f"unexpected value for {k} = {v}")
760758
continue
761759
# get the resource with the name we're after
762-
resource, status = get_generic_resource_by_type_and_id(org=organization, resource_type=type_by_prop[k], resource_id=v)
760+
resource, status = get_generic_resource_by_type_and_id(setup=organization, resource_type=type_by_prop[k], resource_id=v)
763761
if resource.get('name'): # if the name property isn't empty
764762
match[k] = f"{resource['name']}" # wedge the name into the ID column
765763

@@ -1215,7 +1213,7 @@ def use_organization(cli, spinner: object = None, prompt: bool = True):
12151213
raise NFAPINoCredentials()
12161214
spinner.succeed(f"Logged in profile '{cli.config.general.profile}'")
12171215
cli.log.debug(f"logged-in organization label is {organization.label}.")
1218-
networks = Networks(Organization=organization)
1216+
networks = Networks(setup=organization)
12191217
return organization, networks
12201218

12211219

@@ -1396,6 +1394,33 @@ def get_spinner(cli, text):
13961394
return inner_spinner
13971395

13981396

1397+
def jwt_decode(token):
1398+
# TODO: figure out how to stop doing this because the token is for the
1399+
# API, not this app, and so may change algorithm unexpectedly or stop
1400+
# being a JWT altogether, currently needed to build the URL for HTTP
1401+
# requests, might need to start using env config
1402+
"""Parse the token and return claimset."""
1403+
try:
1404+
claim = jwt.decode(jwt=token, algorithms=["RS256"], options={"verify_signature": False})
1405+
except jwt.exceptions.PyJWTError as e:
1406+
raise jwt.exceptions.PyJWTError(f"failed to parse bearer token as JWT, caught {e}")
1407+
except Exception as e:
1408+
raise RuntimeError(f"unexpected error parsing JWT, caught {e}")
1409+
return claim
1410+
1411+
1412+
def is_jwt(token):
1413+
"""If is a JWT then True."""
1414+
try:
1415+
jwt_decode(token)
1416+
except jwt.exceptions.PyJWTError:
1417+
return False
1418+
except Exception as e:
1419+
raise RuntimeError(f"unexpected error parsing JWT, caught {e}")
1420+
else:
1421+
return True
1422+
1423+
13991424
yaml_lexer = get_lexer_by_name("yaml", stripall=True)
14001425
json_lexer = get_lexer_by_name("json", stripall=True)
14011426
bash_lexer = get_lexer_by_name("bash", stripall=True)

netfoundry/utility.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""Shared helper functions, constants, and classes."""
22

33
import json
4+
import logging
45
import os
56
import re # regex
67
import time # enforce a timeout; sleep
@@ -20,14 +21,17 @@
2021
from requests.adapters import HTTPAdapter
2122
from requests.exceptions import HTTPError
2223
from requests_cache import CachedSession
24+
# FIXME: disable warning for debug proxy
25+
from urllib3 import disable_warnings
26+
from urllib3.exceptions import InsecureRequestWarning
2327
from urllib3.util.retry import Retry
2428

2529
from .exceptions import UnknownResourceType
2630

27-
# FIXME: disable warning for debug proxy
28-
from urllib3 import disable_warnings
29-
from urllib3.exceptions import InsecureRequestWarning
3031
disable_warnings(InsecureRequestWarning)
32+
for name, logger in logging.root.manager.loggerDict.items():
33+
if name.startswith('requests_cache'):
34+
logger.disabled = True
3135

3236

3337
def any_in(a, b):

0 commit comments

Comments
 (0)