-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy pathimage_manager.py
203 lines (185 loc) · 6.81 KB
/
image_manager.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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# Copyright 2022 BAAI. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License")
#!/usr/bin/env python3
# -*- coding:UTF-8 -*-
''' Local sudo docker image manger.
usage:
image_management.py -o [operation] -i [repository] -t [tag]
'''
import os
import sys
import argparse
from run_cmd import run_cmd_wait as rcw
from container_manager import ContainerManager
import time
def _parse_args():
''' Check script input parameter. '''
help_message = '''Operations for docker image:
exist Whether the image exists
remove Remove a docker image
build Build a docker image with two options if the image doesn't exist:
-d [directory] Directory contains dockerfile and install script
-f [framework] AI framework '''
parser = argparse.ArgumentParser(
description='Docker managment script',
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('-o',
type=str,
metavar='[operation]',
required=True,
choices=['exist', 'remove', 'build'],
help=help_message)
parser.add_argument('-i',
type=str,
metavar='[repository]',
required=True,
help='image repository')
parser.add_argument('-t',
type=str,
metavar='[tag]',
required=True,
help='image tag')
args, _ = parser.parse_known_args()
if args.o == "build":
parser.add_argument("-d",
type=str,
required=True,
help="dir contains dockerfile for building image.")
parser.add_argument("-f",
type=str,
required=True,
help="testcase framework of the image.")
args = parser.parse_args()
return args
class ImageManager():
'''Local image manager.
Support operations below:
-- remove, rm image from local
-- exists, query if image exist local
-- build_image, build docker image
'''
def __init__(self, repository, tag):
self.repository = repository
self.tag = tag
def exist(self):
'''Check if local image exist or not
Return code:
0 - image already exist
1 - image doesn't exist
'''
cmd = "sudo docker images|grep -w \"" + self.repository + "\"|grep -w \"" + \
self.tag + "\""
print(cmd)
ret, _ = rcw(cmd, 10)
print(ret)
if ret != 0:
return 1
return 0
def remove(self):
'''Remove local image
Return code:
0 - rm image successfully
1 - rm image failed
'''
cmd = "sudo docker rmi " + self.repository + ":" + self.tag
ret, _ = rcw(cmd, 60)
if ret != 0:
return 1
return 0
def _rm_tmp_image(self, tmp_image_name, cont_mgr):
'''remove temp container and temp image.'''
clean_tmp_cmd = "docker rmi -f " + tmp_image_name
cont_mgr.remove()
rcw(clean_tmp_cmd, 30)
def build_image(self, image_dir, framework):
'''Build docker image in vendor's path.
'''
# First, build base docker image.
tmp_image_name = "tmp_" + self.repository + ":" + self.tag
build_cmd = "cd " + image_dir + " && docker build -t " \
+ tmp_image_name + " ./"
ret, _ = rcw(build_cmd, 600)
if ret != 0:
print("docker build failed. " + tmp_image_name)
return 1
# Second, start a container with the base image
tmp_container_name = "tmp_" + self.repository + "-" + self.tag \
+ "-container"
image_dir_in_container = "/workspace/docker_image"
start_args = " --rm --init --detach --net=host --uts=host " \
+ "--ipc=host --security-opt=seccomp=unconfined " \
+ "--privileged=true --ulimit=stack=67108864 " \
+ "--ulimit=memlock=-1 -v " + image_dir + ":" \
+ image_dir_in_container
cont_mgr = ContainerManager(tmp_container_name)
cont_mgr.remove()
ret, outs = cont_mgr.run_new(start_args, tmp_image_name)
if ret != 0:
print("Start new container with base image failed.")
print("Error: " + outs[0])
self._rm_tmp_image(tmp_image_name, cont_mgr)
return ret
# Third, install packages in container.
install_script = framework + "_install.sh"
if not os.path.isfile(os.path.join(image_dir, install_script)):
print("Can't find <framework>_install.sh")
install_cmd = ":"
else:
install_cmd = "bash " + image_dir_in_container + "/" \
+ install_script
ret, outs = cont_mgr.run_cmd_in(install_cmd, 1800, detach=False)
if ret != 0:
print("Run install command in temp container failed.")
print("Error: " + outs[0])
self._rm_tmp_image(tmp_image_name, cont_mgr)
return ret
commit_cmd = "docker commit -a \"baai\" -m \"flagperf training\" " \
+ tmp_container_name + " " + self.repository + ":" \
+ self.tag
time.sleep(5)
ret, outs = rcw(commit_cmd, 300)
if ret != 0:
print("Commit docker image failed.")
print("Error: " + outs[0])
self._rm_tmp_image(tmp_image_name, cont_mgr)
return ret
# At last, remove temp container and temp image.
self._rm_tmp_image(tmp_image_name, cont_mgr)
return 0
def main():
'''Main process to manage image
Return code:
0 - successfull.
1 - failed.
2 - invalid operation. '''
args = _parse_args()
operation = args.o
image = args.i
tag = args.t
image_manager = ImageManager(image, tag)
if operation == "exist":
ret = image_manager.exist()
if ret == 0:
print("Doker image exists.")
else:
print("Doker image doesn't exist.")
elif operation == "remove":
ret = image_manager.remove()
if ret == 0:
print("Remove doker image successfully.")
else:
print("Remove doker image failed.")
elif operation == "build":
if image_manager.exist() == 0:
ret = 0
else:
image_dir = args.d
framework = args.f
ret = image_manager.build_image(image_dir, framework)
else:
print("Invalid operation.")
sys.exit(2)
sys.exit(ret)
if __name__ == "__main__":
main()