Skip to content
This repository was archived by the owner on Sep 12, 2018. It is now read-only.

Commit 31ab559

Browse files
author
Mangled Deutz
committed
Fixes to follow new Config
- replace get(key) and ['key'] calls by dotted notation - removed defaults from the codebase (as they now all live in the config) - tweak existence tests - simplified calls to load() when possible - assume proper typage Docker-DCO-1.1-Signed-off-by: Mangled Deutz <[email protected]> (github: dmp42)
1 parent 713d7bc commit 31ab559

File tree

12 files changed

+71
-115
lines changed

12 files changed

+71
-115
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,7 @@ common:
252252
mirroring:
253253
source: https://registry-1.docker.io
254254
source_index: https://index.docker.io
255-
tags_cache_ttl: 864000 # 10 days
255+
tags_cache_ttl: 172800 # 2 days
256256
```
257257

258258
### Cache options

config/config_mirror.yml

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
# The `common' part is automatically included (and possibly overriden by all
22
# other flavors)
3-
common:
3+
common: &common
44
mirroring:
55
source: https://registry-1.docker.io
66
source_index: https://index.docker.io
7-
tags_cache_ttl: 864000 # seconds
7+
tags_cache_ttl: 172800 # seconds
88

99
dev:
10+
<<: *common
1011
storage: local
1112
storage_path: /tmp/registry
1213
loglevel: debug

config/config_sample.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ common: &common
2121
mirroring:
2222
source: _env:MIRROR_SOURCE # https://registry-1.docker.io
2323
source_index: _env:MIRROR_SOURCE_INDEX # https://index.docker.io
24-
tags_cache_ttl: _env:MIRROR_TAGS_CACHE_TTL # 864000 # seconds
24+
tags_cache_ttl: _env:MIRROR_TAGS_CACHE_TTL:172800 # seconds
2525

2626
cache:
2727
host: _env:CACHE_REDIS_HOST:localhost

docker_registry/app.py

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,8 @@
1818

1919
app = flask.Flask('docker-registry')
2020
cfg = config.load()
21-
loglevel = getattr(logging, cfg.get('loglevel', 'INFO').upper())
2221
logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s',
23-
level=loglevel)
22+
level=getattr(logging, cfg.loglevel.upper()))
2423

2524

2625
@app.route('/_ping')
@@ -48,20 +47,20 @@ def after_request(response):
4847
def init():
4948
# Configure the email exceptions
5049
info = cfg.email_exceptions
51-
if info and 'smtp_host' in info:
52-
mailhost = info['smtp_host']
53-
mailport = info.get('smtp_port')
50+
if info and info.smtp_host:
51+
mailhost = info.smtp_host
52+
mailport = info.smtp_port
5453
if mailport:
5554
mailhost = (mailhost, mailport)
56-
smtp_secure = info.get('smtp_secure', None)
55+
smtp_secure = info.smtp_secure
5756
secure_args = _adapt_smtp_secure(smtp_secure)
5857
mail_handler = logging.handlers.SMTPHandler(
5958
mailhost=mailhost,
60-
fromaddr=info['from_addr'],
61-
toaddrs=[info['to_addr']],
59+
fromaddr=info.from_addr,
60+
toaddrs=[info.to_addr],
6261
subject='Docker registry exception',
63-
credentials=(info['smtp_login'],
64-
info['smtp_password']),
62+
credentials=(info.smtp_login,
63+
info.smtp_password),
6564
secure=secure_args)
6665
mail_handler.setLevel(logging.ERROR)
6766
app.logger.addHandler(mail_handler)
@@ -91,9 +90,9 @@ def _adapt_smtp_secure(value):
9190
if isinstance(value, basestring):
9291
# a string - wrap it in the tuple
9392
return (value,)
94-
if isinstance(value, dict):
93+
if isinstance(value, config.Config):
9594
assert set(value.keys()) <= set(['keyfile', 'certfile'])
96-
return (value['keyfile'], value.get('certfile', None))
95+
return (value.keyfile, value.certfile)
9796
if value:
9897
return ()
9998

docker_registry/lib/cache.py

Lines changed: 27 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -7,67 +7,48 @@
77

88
from . import config
99

10-
11-
# Default options
10+
logger = logging.getLogger(__name__)
1211

1312
redis_conn = None
1413
cache_prefix = None
1514

15+
cfg = config.load()
16+
1617

1718
def init():
18-
cfg = config.load()
19-
enable_redis_cache(cfg)
20-
enable_redis_lru(cfg)
19+
enable_redis_cache(cfg.cache, cfg.storage_path)
20+
enable_redis_lru(cfg.cache_lru, cfg.storage_path)
2121

2222

23-
def enable_redis_cache(cfg):
23+
def enable_redis_cache(cache, path):
2424
global redis_conn, cache_prefix
25-
cache = cfg.cache
26-
if not cache:
25+
if not cache or not cache.host:
26+
logger.warn('Cache storage disabled!')
2727
return
2828

29-
logging.info('Enabling storage cache on Redis')
30-
if not isinstance(cache, dict):
31-
cache = {}
32-
redis_opts = {
33-
'host': 'localhost',
34-
'port': 6379,
35-
'db': 0,
36-
'password': None
37-
}
38-
for k, v in cache.iteritems():
39-
redis_opts[k] = v
40-
logging.info('Redis config: {0}'.format(redis_opts))
41-
redis_conn = redis.StrictRedis(host=redis_opts['host'],
42-
port=int(redis_opts['port']),
43-
db=int(redis_opts['db']),
44-
password=redis_opts['password'])
45-
cache_prefix = 'cache_path:{0}'.format(cfg.get('storage_path', '/'))
29+
logger.info('Enabling storage cache on Redis')
30+
logger.info('Redis config: {0}'.format(cache))
31+
redis_conn = redis.StrictRedis(
32+
host=cache.host,
33+
port=int(cache.port),
34+
db=int(cache.db),
35+
password=cache.password
36+
)
37+
cache_prefix = 'cache_path:{0}'.format(path or '/')
4638

4739

48-
def enable_redis_lru(cfg):
49-
cache = cfg.cache_lru
50-
if not cache:
40+
def enable_redis_lru(cache, path):
41+
if not cache or not cache.host:
42+
logger.warn('LRU cache disabled!')
5143
return
52-
logging.info('Enabling lru cache on Redis')
53-
if not isinstance(cache, dict):
54-
cache = {}
55-
redis_opts = {
56-
'host': 'localhost',
57-
'port': 6379,
58-
'db': 0,
59-
'password': None
60-
}
61-
for k, v in cache.iteritems():
62-
redis_opts[k] = v
63-
64-
logging.info('Redis lru config: {0}'.format(redis_opts))
44+
logger.info('Enabling lru cache on Redis')
45+
logger.info('Redis lru config: {0}'.format(cache))
6546
lru.init(
66-
host=redis_opts['host'],
67-
port=int(redis_opts['port']),
68-
db=int(redis_opts['db']),
69-
password=redis_opts['password'],
70-
path=cfg.get('storage_path', '/')
47+
host=cache.host,
48+
port=cache.port,
49+
db=cache.db,
50+
password=cache.password,
51+
path=path or '/'
7152
)
7253

7354
init()

docker_registry/lib/mirroring.py

Lines changed: 11 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,12 @@
1010
from . import cache
1111
from . import config
1212

13-
14-
DEFAULT_CACHE_TAGS_TTL = 48 * 3600
1513
logger = logging.getLogger(__name__)
14+
cfg = config.load()
1615

1716

1817
def is_mirror():
19-
cfg = config.load()
20-
return bool(cfg.get('mirroring', False))
18+
return bool(cfg.mirroring and cfg.mirroring.source)
2119

2220

2321
def _response_headers(base):
@@ -34,11 +32,9 @@ def _response_headers(base):
3432

3533
def lookup_source(path, stream=False, source=None):
3634
if not source:
37-
cfg = config.load()
38-
mirroring_cfg = cfg.mirroring
39-
if not mirroring_cfg:
35+
if not is_mirror():
4036
return
41-
source = cfg.mirroring['source']
37+
source = cfg.mirroring.source
4238
source_url = '{0}{1}'.format(source, path)
4339
headers = {}
4440
for k, v in flask.request.headers.iteritems():
@@ -67,14 +63,12 @@ def lookup_source(path, stream=False, source=None):
6763
def source_lookup_tag(f):
6864
@functools.wraps(f)
6965
def wrapper(namespace, repository, *args, **kwargs):
70-
cfg = config.load()
7166
mirroring_cfg = cfg.mirroring
7267
resp = f(namespace, repository, *args, **kwargs)
73-
if not mirroring_cfg:
68+
if not is_mirror():
7469
return resp
75-
source = mirroring_cfg['source']
76-
tags_cache_ttl = mirroring_cfg.get('tags_cache_ttl',
77-
DEFAULT_CACHE_TAGS_TTL)
70+
source = mirroring_cfg.source
71+
tags_cache_ttl = mirroring_cfg.tags_cache_ttl
7872

7973
if resp.status_code != 404:
8074
logger.debug('Status code is not 404, no source '
@@ -129,14 +123,13 @@ def source_lookup(cache=False, stream=False, index_route=False):
129123
def decorator(f):
130124
@functools.wraps(f)
131125
def wrapper(*args, **kwargs):
132-
cfg = config.load()
133126
mirroring_cfg = cfg.mirroring
134127
resp = f(*args, **kwargs)
135-
if not mirroring_cfg:
128+
if not is_mirror():
136129
return resp
137-
source = mirroring_cfg['source']
138-
if index_route:
139-
source = mirroring_cfg.get('source_index', source)
130+
source = mirroring_cfg.source
131+
if index_route and mirroring_cfg.source_index:
132+
source = mirroring_cfg.source_index
140133
logger.debug('Source provided, registry acts as mirror')
141134
if resp.status_code != 404:
142135
logger.debug('Status code is not 404, no source '

docker_registry/status.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
from .lib import cache
1919
from .lib import config
2020

21-
_config = config.load()
21+
cfg = config.load()
2222

2323

2424
def redis_status():
@@ -41,7 +41,7 @@ def redis_status():
4141
def storage_status():
4242
message = ''
4343
try:
44-
_storage = storage.load(_config.storage)
44+
_storage = storage.load(cfg.storage)
4545
key = toolkit.gen_random_string()
4646
value = toolkit.gen_random_string()
4747
_storage.put_content(key, value)

docker_registry/storage/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ def load(kind=None):
3434
return _storage[kind]
3535

3636
_storage[kind] = engine.fetch(kind)(
37-
path=cfg.get('storage_path'),
37+
path=cfg.storage_path,
3838
config=cfg)
3939

4040
return _storage[kind]

docker_registry/toolkit.py

Lines changed: 8 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
from . import storage
2020
from .lib import config
2121

22-
22+
cfg = config.load()
2323
logger = logging.getLogger(__name__)
2424
_re_docker_version = re.compile('docker/([^\s]+)')
2525
_re_authorization = re.compile(r'(\w+)[:=][\s"]?([^",]+)"?')
@@ -98,8 +98,7 @@ def response(data=None, code=200, headers=None, raw=False):
9898

9999

100100
def validate_parent_access(parent_id):
101-
cfg = config.load()
102-
if cfg.standalone is True:
101+
if cfg.standalone:
103102
return True
104103
auth = _parse_auth_header()
105104
if not auth:
@@ -108,12 +107,8 @@ def validate_parent_access(parent_id):
108107
if len(full_repos_name) != 2:
109108
logger.debug('validate_parent: Invalid repository field')
110109
return False
111-
index_endpoint = cfg.index_endpoint
112-
if index_endpoint is None:
113-
index_endpoint = 'https://index.docker.io'
114-
index_endpoint = index_endpoint.strip('/')
115110
url = '{0}/v1/repositories/{1}/{2}/layer/{3}/access'.format(
116-
index_endpoint, full_repos_name[0], full_repos_name[1], parent_id
111+
cfg.index_endpoint, full_repos_name[0], full_repos_name[1], parent_id
117112
)
118113
headers = {'Authorization': flask.request.headers.get('authorization')}
119114
resp = requests.get(url, verify=True, headers=headers)
@@ -136,12 +131,7 @@ def validate_token(auth):
136131
if len(full_repos_name) != 2:
137132
logger.debug('validate_token: Invalid repository field')
138133
return False
139-
cfg = config.load()
140-
index_endpoint = cfg.index_endpoint
141-
if index_endpoint is None:
142-
index_endpoint = 'https://index.docker.io'
143-
index_endpoint = index_endpoint.strip('/')
144-
url = '{0}/v1/repositories/{1}/{2}/images'.format(index_endpoint,
134+
url = '{0}/v1/repositories/{1}/{2}/images'.format(cfg.index_endpoint,
145135
full_repos_name[0],
146136
full_repos_name[1])
147137
headers = {'Authorization': flask.request.headers.get('authorization')}
@@ -190,7 +180,6 @@ def _parse_auth_header():
190180

191181
def check_token(args):
192182
logger.debug('args = {0}'.format(args))
193-
cfg = config.load()
194183
if cfg.disable_token_auth is True or cfg.standalone is True:
195184
return True
196185
auth = _parse_auth_header()
@@ -224,8 +213,7 @@ def check_token(args):
224213

225214

226215
def check_signature():
227-
cfg = config.load()
228-
if not cfg.get('privileged_key'):
216+
if not cfg.privileged_key:
229217
return False
230218
headers = flask.request.headers
231219
signature = headers.get('X-Signature')
@@ -242,7 +230,7 @@ def check_signature():
242230
['{}:{}'.format(k, headers[k]) for k in header_keys])
243231
logger.debug('Signed message: {}'.format(message))
244232
try:
245-
return rsa.verify(message, sigdata, cfg.get('privileged_key'))
233+
return rsa.verify(message, sigdata, cfg.privileged_key)
246234
except rsa.VerificationError:
247235
return False
248236

@@ -303,10 +291,8 @@ def get_repository():
303291
return (parts[0], parts[1])
304292

305293

306-
def get_endpoints(cfg=None):
307-
if not cfg:
308-
cfg = config.load()
309-
registry_endpoints = cfg.registry_endpoints
294+
def get_endpoints(overcfg=None):
295+
registry_endpoints = (overcfg or cfg).registry_endpoints
310296
if not registry_endpoints:
311297
#registry_endpoints = socket.gethostname()
312298
registry_endpoints = flask.request.environ['HTTP_HOST']

docker_registry/wsgi.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
if __name__ == '__main__':
1111
# Bind to PORT if defined, otherwise default to 5000.
1212
host = env.source('REGISTRY_HOST')
13-
port = int(env.source('REGISTRY_PORT'))
13+
port = env.source('REGISTRY_PORT')
1414
app.debug = True
1515
app.run(host=host, port=port)
1616
# Or you can run:

0 commit comments

Comments
 (0)