blob: 0e09defdc8c57c2c61eb85d1778530b379d796d7 [file] [log] [blame]
Thomas Vachuska1eff3a62016-05-03 01:07:24 -07001/*
2 * Copyright 2016 Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package org.onlab.warden;
18
19import com.google.common.collect.ImmutableList;
20import com.google.common.collect.ImmutableSet;
21import com.google.common.io.ByteStreams;
22
23import java.io.File;
24import java.io.FileInputStream;
25import java.io.FileOutputStream;
26import java.io.IOException;
27import java.io.InputStream;
28import java.io.PrintWriter;
29import java.text.SimpleDateFormat;
30import java.util.Date;
31import java.util.HashSet;
32import java.util.List;
33import java.util.Random;
34import java.util.Set;
35import java.util.Timer;
36import java.util.TimerTask;
37import java.util.concurrent.TimeUnit;
38import java.util.regex.Matcher;
39import java.util.regex.Pattern;
40
41import static com.google.common.base.Preconditions.*;
42
43/**
44 * Warden for tracking use of shared test cells.
45 */
46class Warden {
47
48 private static final String CELL_NOT_NULL = "Cell name cannot be null";
49 private static final String USER_NOT_NULL = "User name cannot be null";
50 private static final String KEY_NOT_NULL = "User key cannot be null";
51 private static final String UTF_8 = "UTF-8";
Thomas Vachuska1eff3a62016-05-03 01:07:24 -070052
53 private static final String AUTHORIZED_KEYS = "authorized_keys";
54
Thomas Vachuska0d337002016-05-04 10:00:18 -070055 private static final long TIMEOUT = 10; // 10 seconds
Thomas Vachuska1eff3a62016-05-03 01:07:24 -070056 private static final int MAX_MINUTES = 240; // 4 hours max
57 private static final int MINUTE = 60_000; // 1 minute
58
59 private final File log = new File("warden.log");
60
61 private final File cells = new File("cells");
62 private final File supported = new File(cells, "supported");
63 private final File reserved = new File(cells, "reserved");
64
65 private final Random random = new Random();
66
67 private final Timer timer = new Timer("cell-pruner", true);
68
69 /**
70 * Creates a new cell warden.
71 */
72 Warden() {
73 random.setSeed(System.currentTimeMillis());
Thomas Vachuska71ff3322016-05-03 15:33:05 -070074 timer.schedule(new Reposessor(), MINUTE / 4, MINUTE / 2);
Thomas Vachuska1eff3a62016-05-03 01:07:24 -070075 }
76
77 /**
78 * Returns list of names of supported cells.
79 *
80 * @return list of cell names
81 */
82 Set<String> getCells() {
83 String[] list = supported.list();
84 return list != null ? ImmutableSet.copyOf(list) : ImmutableSet.of();
85 }
86
87 /**
88 * Returns list of names of available cells.
89 *
90 * @return list of cell names
91 */
92 Set<String> getAvailableCells() {
93 Set<String> available = new HashSet<>(getCells());
94 available.removeAll(getReservedCells());
95 return ImmutableSet.copyOf(available);
96 }
97
98 /**
99 * Returns list of names of reserved cells.
100 *
101 * @return list of cell names
102 */
103 Set<String> getReservedCells() {
104 String[] list = reserved.list();
105 return list != null ? ImmutableSet.copyOf(list) : ImmutableSet.of();
106 }
107
108
109 /**
110 * Returns reservation for the specified user.
111 *
112 * @param userName user name
113 * @return cell reservation record or null if user does not have one
114 */
115 Reservation currentUserReservation(String userName) {
116 checkNotNull(userName, USER_NOT_NULL);
117 for (String cellName : getReservedCells()) {
118 Reservation reservation = currentCellReservation(cellName);
119 if (reservation != null && userName.equals(reservation.userName)) {
120 return reservation;
121 }
122 }
123 return null;
124 }
125
126 /**
127 * Returns the name of the user who reserved the given cell.
128 *
129 * @param cellName cell name
130 * @return cell reservation record or null if cell is not reserved
131 */
132 Reservation currentCellReservation(String cellName) {
133 checkNotNull(cellName, CELL_NOT_NULL);
134 File cellFile = new File(reserved, cellName);
135 if (!cellFile.exists()) {
136 return null;
137 }
138 try (InputStream stream = new FileInputStream(cellFile)) {
139 return new Reservation(new String(ByteStreams.toByteArray(stream), "UTF-8"));
140 } catch (IOException e) {
141 throw new IllegalStateException("Unable to get current user for cell " + cellName, e);
142 }
143 }
144
145 /**
146 * Reserves a cell for the specified user and their public access key.
147 *
148 * @param userName user name
149 * @param sshKey user ssh public key
150 * @param minutes number of minutes for reservation
151 * @return reserved cell definition
152 */
153 synchronized String borrowCell(String userName, String sshKey, int minutes) {
154 checkNotNull(userName, USER_NOT_NULL);
155 checkNotNull(sshKey, KEY_NOT_NULL);
Thomas Vachuska1eff3a62016-05-03 01:07:24 -0700156 checkArgument(minutes < MAX_MINUTES, "Number of minutes must be less than %d", MAX_MINUTES);
157 long now = System.currentTimeMillis();
158 Reservation reservation = currentUserReservation(userName);
159 if (reservation == null) {
Thomas Vachuskab8261902016-05-04 00:10:42 -0700160 checkArgument(minutes > 0, "Number of minutes must be positive");
Thomas Vachuska1eff3a62016-05-03 01:07:24 -0700161 Set<String> cells = getAvailableCells();
162 checkState(!cells.isEmpty(), "No cells are presently available");
163 String cellName = ImmutableList.copyOf(cells).get(random.nextInt(cells.size()));
Thomas Vachuskab8261902016-05-04 00:10:42 -0700164 reservation = new Reservation(cellName, userName, now, minutes);
Thomas Vachuska0d337002016-05-04 10:00:18 -0700165 } else if (minutes == 0) {
166 // If minutes are 0, simply return the cell definition
167 return getCellDefinition(reservation.cellName);
Thomas Vachuska1eff3a62016-05-03 01:07:24 -0700168 } else {
169 reservation = new Reservation(reservation.cellName, userName, now, minutes);
170 }
171
172 reserveCell(reservation.cellName, reservation);
173 installUserKeys(reservation.cellName, userName, sshKey);
174 log(userName, reservation.cellName, "borrowed for " + minutes + " minutes");
175 return getCellDefinition(reservation.cellName);
176 }
177
178 /**
179 * Reserves the specified cell for the user the source file and writes the
180 * specified content to the target file.
181 *
182 * @param cellName cell name
183 * @param reservation cell reservation record
184 */
185 private void reserveCell(String cellName, Reservation reservation) {
186 try (FileOutputStream stream = new FileOutputStream(new File(reserved, cellName))) {
187 stream.write(reservation.encode().getBytes(UTF_8));
188 } catch (IOException e) {
189 throw new IllegalStateException("Unable to reserve cell " + cellName, e);
190 }
191 }
192
193 /**
194 * Returns the specified cell for the specified user and their public access key.
195 *
196 * @param userName user name
197 */
198 synchronized void returnCell(String userName) {
199 checkNotNull(userName, USER_NOT_NULL);
200 Reservation reservation = currentUserReservation(userName);
201 checkState(reservation != null, "User %s has no cell reservations", userName);
202 checkState(new File(reserved, reservation.cellName).delete(),
203 "Unable to return cell %s", reservation.cellName);
204 uninstallUserKeys(reservation.cellName);
205 log(userName, reservation.cellName, "returned");
206 }
207
208 /**
209 * Reads the definition of the specified cell.
210 *
211 * @param cellName cell name
212 * @return cell definition
213 */
214 String getCellDefinition(String cellName) {
215 File cellFile = new File(supported, cellName);
216 try (InputStream stream = new FileInputStream(cellFile)) {
217 return new String(ByteStreams.toByteArray(stream), UTF_8);
218 } catch (IOException e) {
219 throw new IllegalStateException("Unable to definition for cell " + cellName, e);
220 }
221 }
222
223 // Returns list of cell hosts, i.e. OC#, OCN
224 private List<String> cellHosts(String cellName) {
225 ImmutableList.Builder<String> builder = ImmutableList.builder();
226 Pattern pattern = Pattern.compile("export OC[0-9N]=(.*)");
227 for (String line : getCellDefinition(cellName).split("\n")) {
228 Matcher matcher = pattern.matcher(line);
229 if (matcher.matches()) {
230 builder.add(matcher.group(1).replaceAll("[\"']", ""));
231 }
232 }
233 return builder.build();
234 }
235
236 // Installs the specified user's key on all hosts of the given cell.
237 private void installUserKeys(String cellName, String userName, String sshKey) {
238 File authKeysFile = authKeys(sshKey);
239 for (String host : cellHosts(cellName)) {
240 installAuthorizedKey(host, authKeysFile.getPath());
241 }
242 checkState(authKeysFile.delete(), "Unable to install user keys");
243 }
244
245 // Uninstalls the user keys on the specified cell
246 private void uninstallUserKeys(String cellName) {
247 for (String host : cellHosts(cellName)) {
248 installAuthorizedKey(host, AUTHORIZED_KEYS);
249 }
250 }
251
252 // Installs the authorized keys on the specified host.
253 private void installAuthorizedKey(String host, String authorizedKeysFile) {
254 String cmd = "scp " + authorizedKeysFile + " sdn@" + host + ":.ssh/authorized_keys";
255 try {
256 Process process = Runtime.getRuntime().exec(cmd);
257 process.waitFor(TIMEOUT, TimeUnit.SECONDS);
258 } catch (Exception e) {
259 throw new IllegalStateException("Unable to set authorized keys for host " + host);
260 }
261 }
262
263 // Returns the file containing authorized keys that incudes the specified key.
264 private File authKeys(String sshKey) {
265 File keysFile = new File(AUTHORIZED_KEYS);
266 try {
267 File tmp = File.createTempFile("warden-", ".auth");
268 tmp.deleteOnExit();
269 try (InputStream stream = new FileInputStream(keysFile);
270 PrintWriter output = new PrintWriter(tmp)) {
271 String baseKeys = new String(ByteStreams.toByteArray(stream), UTF_8);
272 output.println(baseKeys);
273 output.println(sshKey);
274 return tmp;
275 } catch (IOException e) {
276 throw new IllegalStateException("Unable to generate authorized keys", e);
277 }
278 } catch (IOException e) {
279 throw new IllegalStateException("Unable to generate authorized keys", e);
280 }
281 }
282
283 // Creates an audit log entry.
284 void log(String userName, String cellName, String action) {
285 try (FileOutputStream fos = new FileOutputStream(log, true);
286 PrintWriter pw = new PrintWriter(fos)) {
287 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
288 pw.println(String.format("%s\t%s\t%s\t%s", format.format(new Date()),
289 userName, cellName, action));
290 pw.flush();
291 } catch (IOException e) {
292 throw new IllegalStateException("Unable to log reservation action", e);
293 }
294 }
295
296 // Task for re-possessing overdue cells
297 private class Reposessor extends TimerTask {
298 @Override
299 public void run() {
300 long now = System.currentTimeMillis();
301 for (String cellName : getReservedCells()) {
302 Reservation reservation = currentCellReservation(cellName);
303 if (reservation != null &&
304 (reservation.time + reservation.duration * MINUTE) < now) {
305 try {
306 returnCell(reservation.userName);
307 } catch (Exception e) {
308 e.printStackTrace();
309 }
310 }
311 }
312 }
313 }
314}