-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.py
161 lines (137 loc) · 6.03 KB
/
api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
#!flask/bin/python
from flask import Flask, request
from flask.views import MethodView
from libterraform import TerraformCommand
from threading import Thread
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = ""
db = SQLAlchemy(app)
dir = '/home/user/lab/terraform'
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String, unique=True, nullable=False)
email = db.Column(db.String, unique=True, nullable=False)
def api_creation(lab_name):
class Lab(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, unique=True, nullable=False)
state = db.Column(db.String)
class LabAPI(MethodView):
def __init__(self):
self.dir = f'{dir}/{lab_name}'
self.cli = TerraformCommand(self.dir)
# func for ferraform apply/destroy
def change_lab(self, action, userid):
self.cli.workspace('select', userid)
option = {'var': f'user-id={userid}', 'auto-approve': ...}
self.cli.run(action, option)
self.cli.workspace('select', 'default')
def create_user(self, username, email):
user = User(username=username, email=email)
db.session.add(user)
db.session.commit()
return user.id
# list users or lab status
def get(self, user_id):
if user_id is None:
stdout = self.cli.workspace('list').value
return stdout.split('\n')
else:
self.cli.workspace('select', str(user_id))
return self.cli.state('list').value
# deploy lab
def post(self):
data = request.get_json()
user_id = str(self.create_user(data['username'], data['email']))
if self.cli.workspace('new', user_id).retcode in (0, 2):
self.thread = Thread(target=self.change_lab,
args=('apply', user_id), daemon=True)
self.thread.start()
return {'status': 202,
'message': f'{lab_name} is creating...'}, 202
else:
return {'status': 409,
'message': f'{lab_name} already exist'}, 409
# destroy lab
def delete(self, user_id):
if self.cli.workspace('select', str(user_id)).retcode in [0, 2]:
self.thread = Thread(
target=self.change_lab,
args=('destroy', str(user_id)), daemon=True)
self.thread.start()
return {'status': 202,
'message': f'{lab_name} is destroying...'}, 202
else:
return {'status': 404,
'message': f'{lab_name} not found'}, 404
lab_view = LabAPI.as_view('lab_api')
app.add_url_rule(f'/api/{lab_name}', defaults={'user_id': None},
view_func=lab_view, methods=['GET', ])
app.add_url_rule(f'/api/{lab_name}', view_func=lab_view,
methods=['POST', ])
app.add_url_rule(f'/api/{lab_name}/<int:user_id>', view_func=lab_view,
methods=['GET', 'DELETE', ])
class UserAPI(MethodView):
def get(self, user_id):
if user_id is None:
users = User.query.all()
return {'status': 200, 'message': {'users':
[{'id': user.id,
'username': user.username,
'email': user.email}
for user in users]}}
else:
if (user := db.session.get(User, user_id)) is None:
return {'status': 404, 'message': 'User not found'}
else:
return {'status': 200, 'message': {'user':
{'id': user.id,
'username': user.username,
'email': user.email}}}
def post(self):
data = request.get_json()
user = User(username=data['username'], email=data['email'])
db.session.add(user)
db.session.commit()
return {'status': 200, 'message':
{'user': {'id': user.id,
'username': user.username,
'email': user.email}}}
def put(self, user_id):
if (user := db.session.get(User, user_id)) is None:
return {'status': 404, 'message': 'User not found'}
else:
data = request.get_json()
if (email := data.get('email')) is not None:
user.email = email
if (username := data.get('username')) is not None:
user.username = username
db.session.add(user)
db.session.commit()
return {'status': 200, 'message': {'user':
{'id': user.id,
'username': user.username,
'email': user.email}}}
def delete(self, user_id):
if (user := db.session.get(User, user_id)) is None:
return {'status': 404, 'message': 'User not found'}
else:
db.session.delete(user)
db.session.commit()
return {'status:': 200, 'message': 'User succesfully deleted'}
user_view = UserAPI.as_view('user_api')
app.add_url_rule('/api/user/', view_func=user_view, methods=['GET', ],
defaults={'user_id': None})
app.add_url_rule('/api/user/', view_func=user_view, methods=['POST', ])
app.add_url_rule('/api/user/<int:user_id>',
view_func=user_view, methods=['DELETE', 'GET', 'PUT'])
# @app.route('/api/lab1/check', methods=['GET'])
# def check_lab():
# pass
with app.app_context():
db.create_all()
if __name__ == '__main__':
api_creation('lab1')
app.run(debug=True)
db.init_app(app)