@@ -68,6 +68,38 @@ const deploy = async ({username, existing, resultStream}) => {
6868 await template . executeTemplate ( templateProps ) ;
6969} ;
7070
71+ const scheduleCleanup = ( { username, project, existing} ) => {
72+ process . nextTick ( async ( ) => {
73+ // wait a bit for it to start
74+ await sleep ( WAIT_TIME ) ;
75+
76+ // get all current containers
77+ const containers = await docker . listContainers ( ) ;
78+ // find containers for current user and project
79+ const running = containers . filter (
80+ c => c . Labels [ 'exoframe.user' ] === username && c . Labels [ 'exoframe.project' ] === project
81+ ) ;
82+
83+ // filter out old container that don't have new containers
84+ // that are already up and running
85+ const toRemove = existing . filter ( container => {
86+ const newInstance = running . find ( runningContainer =>
87+ util . compareNames ( container . Labels [ 'exoframe.name' ] , runningContainer . Labels [ 'exoframe.name' ] )
88+ ) ;
89+ return newInstance && newInstance . State === 'running' && newInstance . Status . toLowerCase ( ) . includes ( 'up' ) ;
90+ } ) ;
91+
92+ // remove old containers
93+ await Promise . all ( toRemove . map ( removeContainer ) ) ;
94+
95+ // if not done - schedule with remaining containers
96+ if ( toRemove . length !== existing . length ) {
97+ const notRemoved = existing . filter ( c => ! toRemove . find ( rc => rc . Id === c . Id ) ) ;
98+ scheduleCleanup ( { username, project, existing : notRemoved } ) ;
99+ }
100+ } ) ;
101+ } ;
102+
71103module . exports = fastify => {
72104 fastify . route ( {
73105 method : 'POST' ,
@@ -138,13 +170,7 @@ module.exports = fastify => {
138170 // deploy new versions
139171 deploy ( { username, payload : request . payload , resultStream} ) ;
140172 // schedule cleanup
141- process . nextTick ( async ( ) => {
142- // wait a bit for it to start
143- await sleep ( WAIT_TIME ) ;
144-
145- // remove old containers
146- await Promise . all ( existing . map ( removeContainer ) ) ;
147- } ) ;
173+ scheduleCleanup ( { username, project, existing} ) ;
148174 // reply with deploy stream
149175 reply . code ( 200 ) . send ( new Readable ( ) . wrap ( resultStream ) ) ;
150176 } ,
0 commit comments