Skip to content

Commit c860d7d

Browse files
committed
Massive update
- Switched to using a config class instead of a dict. Much cleaner but this touched almost every file. - Lots of flake8 fixes - Switched a large chunk of old strings to f-strings.
1 parent e4958c6 commit c860d7d

22 files changed

+809
-1560
lines changed

imagegw/docker-compose.yml

Lines changed: 46 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,46 @@
1-
api:
2-
image: imagegwapi
3-
ports:
4-
- 5555:8000
5-
links:
6-
- mongo
7-
volumes:
8-
- imagegw:/images
9-
- munge:/var/run/munge/
10-
- ./test/config:/config
11-
command: api
12-
munge:
13-
image: munge
14-
volumes:
15-
- munge:/var/run/munge/
16-
mongo:
17-
image: mongo:3
18-
volumes:
19-
- /data/db
20-
command: --smallfiles
21-
systema:
22-
container_name: systema
23-
image: shifter-test
24-
extra_hosts:
25-
- "api:172.17.0.1"
26-
- "registry:172.17.0.1"
27-
ports:
28-
- "2222:22"
29-
volumes:
30-
- /images
31-
- ./test/config/:/config
32-
privileged: true
33-
environment:
34-
- ADDUSER=canon
35-
registry:
36-
image: registry
37-
ports:
38-
- "5000:5000"
39-
volumes:
40-
- registry:/var/lib/registry
1+
services:
2+
api:
3+
image: imagegwapi
4+
ports:
5+
- 5555:8000
6+
links:
7+
- mongo
8+
volumes:
9+
- imagegw:/images
10+
- munge:/var/run/munge/
11+
- ./test/config:/config
12+
command: api
13+
munge:
14+
image: munge
15+
volumes:
16+
- munge:/var/run/munge/
17+
- ./test/config:/config
18+
command: munge
19+
mongo:
20+
image: mongo:3
21+
volumes:
22+
- /data/db
23+
command: --smallfiles
24+
systema:
25+
container_name: systema
26+
image: shifter-test
27+
extra_hosts:
28+
- "api:172.17.0.1"
29+
- "registry:172.17.0.1"
30+
ports:
31+
- "2222:22"
32+
volumes:
33+
- /images
34+
- ./test/config/:/config
35+
privileged: true
36+
environment:
37+
- ADDUSER=canon
38+
# registry:
39+
# image: registry
40+
# ports:
41+
# - "5000:5000"
42+
# volumes:
43+
# - registry:/var/lib/registry
44+
volumes:
45+
imagegw:
46+
munge:

imagegw/shifter_imagegw/api.py

Lines changed: 6 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -21,49 +21,25 @@
2121
This module provides the REST API for the image gateway.
2222
"""
2323

24-
import json
25-
import os
2624
import logging
27-
import shifter_imagegw
2825
from shifter_imagegw.errors import AuthenticationError
2926
from shifter_imagegw.imagemngr import ImageMngr
3027
from contextlib import asynccontextmanager
3128
from fastapi import FastAPI, HTTPException, Request, Header, Query
3229
from fastapi.responses import JSONResponse, PlainTextResponse
3330
from pydantic import BaseModel
31+
from shifter_imagegw.config import Config
3432

3533

3634
mgr = None
37-
logger = logging.getLogger("fastapi.root")
35+
logger = logging.getLogger("imagegwapi")
3836

3937

4038
@asynccontextmanager
4139
async def lifespan(app: FastAPI):
4240
global config
43-
if 'GWCONFIG' in os.environ:
44-
CONFIG_FILE = os.environ['GWCONFIG']
45-
else:
46-
CONFIG_FILE = f'{shifter_imagegw.CONFIG_PATH}/imagemanager.json'
47-
# Configure logging
48-
logger.debug('Initializing api image manager')
49-
50-
logger.info(f"initializing with {CONFIG_FILE}")
51-
with open(CONFIG_FILE) as config_file:
52-
config = json.load(config_file)
53-
if 'LogLevel' in config:
54-
LOG_STRING = config['LogLevel'].lower()
55-
if LOG_STRING == 'debug':
56-
logger.setLevel(logging.DEBUG)
57-
elif LOG_STRING == 'info':
58-
logger.setLevel(logging.INFO)
59-
elif LOG_STRING == 'warn':
60-
logger.setLevel(logging.WARN)
61-
elif LOG_STRING == 'error':
62-
logger.setLevel(logging.ERROR)
63-
elif LOG_STRING == 'critical':
64-
logger.setLevel(logging.CRITICAL)
65-
else:
66-
logger.critical('Unrecongnized Log Level specified')
41+
config = Config()
42+
logger.setLevel(config.LogLevel)
6743
global mgr
6844
mgr = ImageMngr(config, logname="fastapi.root")
6945
yield
@@ -264,10 +240,10 @@ async def doimport(system: str, imgtype: str, tag: str, data: ImportImage,
264240
# Convert to integers
265241
i['groupACL'] = list(map(lambda x: int(x),
266242
data.allowed_gids.split(',')))
267-
if 'ImportUsers' not in config:
243+
if not config.ImportUsers:
268244
raise HTTPException(status_code=403, detail="User image import from file disabled.")
269245

270-
iusers = config['ImportUsers']
246+
iusers = config.ImportUsers
271247
# If ImportUsers is None, no one can do this
272248
if iusers.lower() == "none":
273249
raise HTTPException(status_code=403, detail="User image import from file disabled.")

imagegw/shifter_imagegw/auth.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -23,32 +23,31 @@
2323

2424
import json
2525
from shifter_imagegw import munge
26+
from shifter_imagegw.config import Config
2627

2728

2829
class Authentication(object):
2930
"""
3031
Authentication Class to authenticate user requests
3132
"""
3233

33-
def __init__(self, config):
34+
def __init__(self, config: Config):
3435
"""
3536
Initializes authenication handle.
3637
config is a dictionary. It must define 'Authentication' and it must
3738
be a supported type (currently munge).
3839
Different auth mechanisms may require additional key value pairs
3940
"""
40-
if 'Authentication' not in config:
41-
raise KeyError('Authentication not specified')
4241
self.sockets = dict()
43-
if config['Authentication'] == "munge":
44-
for system in config['Platforms']:
42+
if config.Authentication == "munge":
43+
for system in config.Platforms:
4544
self.sockets[system] = \
46-
config['Platforms'][system]['mungeSocketPath']
45+
config.Platforms[system].mungeSocketPath
4746
self.type = 'munge'
48-
elif config['Authentication'] == "mock":
47+
elif config.Authentication == "mock":
4948
self.type = 'mock'
5049
else:
51-
memo = 'Unsupported auth type %s' % (config['Authentication'])
50+
memo = f'Unsupported auth type {config.Authentication}'
5251
raise NotImplementedError(memo)
5352

5453
def _authenticate_munge(self, authstr, system=None):
@@ -75,7 +74,7 @@ def _authenticate_munge(self, authstr, system=None):
7574
message_json = response['MESSAGE']
7675
try:
7776
ret['tokens'] = json.loads(message_json)['authorized_locations']
78-
except:
77+
except Exception:
7978
pass
8079
return ret
8180

imagegw/shifter_imagegw/config.py

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
import logging
2+
import json
3+
import os
4+
from shifter_imagegw import CONFIG_PATH
5+
6+
7+
class Location():
8+
def __init__(self, data: dict):
9+
self.remotetype = data['remotetype']
10+
self.authentication = data['authentication']
11+
self.url = data.get('url')
12+
self.sslcacert = None
13+
14+
15+
class Platform():
16+
def __init__(self, data):
17+
if data.get('accesstype') != 'local':
18+
return None
19+
self.mungeSocketPath = data.get('mungeSocketPath',
20+
"/var/run/munge/munge.socket.2")
21+
self.accesstype = "local"
22+
self.admins = data.get('admins', ['root'])
23+
self.imageDir = data['local'].get('imageDir', "/tmp")
24+
self.policy_file = None
25+
26+
27+
class Config():
28+
WorkerThreads = 2
29+
LogLevel = "info"
30+
DefaultImageLocation = "index.docker.io"
31+
DefaultImageFormat = "squashfs"
32+
PullUpdateTimeout = 300
33+
ImageExpirationTimeout = "90:00:00:00"
34+
CacheDirectory = "/tmp/imagegw/"
35+
ExpandDirectory = "/tmp/imagegw/"
36+
MongoDBURI = None
37+
MongoDB = "Shifter"
38+
Metrics = True
39+
Authentication = "munge"
40+
ImportUsers = None
41+
Locations = {}
42+
Platforms = {}
43+
examiner = None
44+
ConverterOptions = None
45+
46+
def __init__(self, data=None):
47+
if data:
48+
config = data
49+
else:
50+
if 'GWCONFIG' in os.environ:
51+
CONFIG_FILE = os.environ['GWCONFIG']
52+
else:
53+
CONFIG_FILE = f'{CONFIG_PATH}/imagemanager.json'
54+
# Configure logging
55+
logging.info(f"initializing with {CONFIG_FILE}")
56+
with open(CONFIG_FILE) as config_file:
57+
config = json.load(config_file)
58+
for attr in dir(self):
59+
if attr[0] == "_":
60+
continue
61+
if attr in config:
62+
val = config[attr]
63+
if attr in ['WorkerThreads', 'PullUpdateTimeout']:
64+
val = int(config[attr])
65+
setattr(self, attr, val)
66+
67+
for location in config['Locations']:
68+
data = config['Locations'][location]
69+
self.Locations[location] = Location(data)
70+
71+
for platform in config['Platforms']:
72+
data = config['Platforms'][platform]
73+
self.Platforms[platform] = Platform(data)
74+
75+
self.Locations = config['Locations']
76+
self.Platofrms = config['Platforms']
77+
78+
loglevel = config.get('LogLevel', 'info').lower()
79+
loglevel_map = {
80+
'debug': logging.DEBUG,
81+
'info': logging.INFO,
82+
'warn': logging.WARNING,
83+
'error': logging.ERROR,
84+
'critical': logging.CRITICAL
85+
}
86+
self.LogLevel = loglevel_map[loglevel]
87+
self.worker_threads = config.get('WorkerThreads')

imagegw/shifter_imagegw/converters.py

Lines changed: 5 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@
2525

2626
import os
2727
import subprocess
28-
import shutil
2928
import tempfile
3029
from shifter_imagegw.util import program_exists, rmtree
3130

@@ -43,21 +42,8 @@ def generate_cramfs_image(expand_path, image_path, options):
4342
"""
4443
Creates a CramFS based image
4544
"""
46-
program_exists('mkfs.cramfs')
47-
cmd = ["mkfs.cramfs", expand_path, image_path]
48-
if options is not None:
49-
cmd.extend(options)
50-
ret = subprocess.call(cmd)
51-
if ret != 0:
52-
# error handling
53-
pass
54-
try:
55-
rmtree(expand_path)
56-
except:
57-
# error handling
58-
pass
59-
60-
return True
45+
message = 'cramfs support is not supported'
46+
raise NotImplementedError(message)
6147

6248

6349
def generate_squashfs_image(expand_path, image_path, options):
@@ -80,7 +66,7 @@ def generate_squashfs_image(expand_path, image_path, options):
8066
pass
8167
try:
8268
rmtree(expand_path)
83-
except:
69+
except Exception:
8470
pass
8571

8672
return True
@@ -121,7 +107,7 @@ def convert(fmt, expand_path, image_path, options=None):
121107
success = True
122108
else:
123109
raise NotImplementedError("%s not a supported format" % fmt)
124-
except:
110+
except Exception:
125111
if os.path.exists(temp_path):
126112
os.unlink(temp_path)
127113
raise
@@ -130,7 +116,7 @@ def convert(fmt, expand_path, image_path, options=None):
130116
return False
131117
try:
132118
os.rename(temp_path, image_path)
133-
except:
119+
except Exception:
134120
return False
135121

136122
# Some error must have occurred

0 commit comments

Comments
 (0)