backupMainService.ts 8.7 KB
Newer Older
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

6
import * as arrays from 'vs/base/common/arrays';
7 8
import * as fs from 'fs';
import * as path from 'path';
9
import * as crypto from 'crypto';
10
import * as platform from 'vs/base/common/platform';
11
import * as extfs from 'vs/base/node/extfs';
D
Daniel Imms 已提交
12
import { IBackupWorkspacesFormat, IBackupMainService } from 'vs/platform/backup/common/backup';
13
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
14 15
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IFilesConfiguration, HotExitConfiguration } from 'vs/platform/files/common/files';
16
import { TPromise } from 'vs/base/common/winjs.base';
17

D
Daniel Imms 已提交
18
export class BackupMainService implements IBackupMainService {
19 20 21 22

	public _serviceBrand: any;

	protected backupHome: string;
D
Daniel Imms 已提交
23
	protected workspacesJsonPath: string;
24

25
	private backups: IBackupWorkspacesFormat;
B
Benjamin Pasero 已提交
26
	private mapWindowToBackupFolder: { [windowId: number]: string; };
27

28
	constructor(
29 30
		@IEnvironmentService environmentService: IEnvironmentService,
		@IConfigurationService private configurationService: IConfigurationService
31 32
	) {
		this.backupHome = environmentService.backupHome;
D
Daniel Imms 已提交
33
		this.workspacesJsonPath = environmentService.backupWorkspacesPath;
34
		this.mapWindowToBackupFolder = Object.create(null);
D
Daniel Imms 已提交
35

36
		this.loadSync();
37 38
	}

39
	public getWorkspaceBackupPaths(): string[] {
40
		const config = this.configurationService.getConfiguration<IFilesConfiguration>();
D
Daniel Imms 已提交
41
		if (config && config.files && config.files.hotExit === HotExitConfiguration.ON_EXIT_AND_WINDOW_CLOSE) {
42
			// Only non-folder windows are restored on main process launch when
D
Daniel Imms 已提交
43
			// hot exit is configured as onExitAndWindowClose.
44 45
			return [];
		}
46
		return this.backups.folderWorkspaces.slice(0); // return a copy
47 48
	}

49 50
	public getEmptyWorkspaceBackupPaths(): string[] {
		return this.backups.emptyWorkspaces.slice(0); // return a copy
51 52
	}

53 54 55 56 57 58 59 60
	public getBackupPath(windowId: number): TPromise<string> {
		if (!this.mapWindowToBackupFolder[windowId]) {
			throw new Error(`Unknown backup workspace for window ${windowId}`);
		}

		return TPromise.as(path.join(this.backupHome, this.mapWindowToBackupFolder[windowId]));
	}

B
Benjamin Pasero 已提交
61
	public registerWindowForBackupsSync(windowId: number, isEmptyWorkspace: boolean, backupFolder?: string, workspacePath?: string): void {
62
		// Generate a new folder if this is a new empty workspace
D
Daniel Imms 已提交
63
		if (isEmptyWorkspace && !backupFolder) {
64
			backupFolder = this.getRandomEmptyWorkspaceId();
65 66
		}

67
		this.mapWindowToBackupFolder[windowId] = isEmptyWorkspace ? backupFolder : this.getWorkspaceHash(workspacePath);
D
Daniel Imms 已提交
68
		this.pushBackupPathsSync(isEmptyWorkspace ? backupFolder : workspacePath, isEmptyWorkspace);
69
	}
70

B
Benjamin Pasero 已提交
71
	private pushBackupPathsSync(workspaceIdentifier: string, isEmptyWorkspace: boolean): string {
72
		const array = isEmptyWorkspace ? this.backups.emptyWorkspaces : this.backups.folderWorkspaces;
73
		if (this.indexOf(workspaceIdentifier, isEmptyWorkspace) === -1) {
74 75
			array.push(workspaceIdentifier);
			this.saveSync();
76
		}
77 78

		return workspaceIdentifier;
79 80
	}

81 82 83
	protected removeBackupPathSync(workspaceIdentifier: string, isEmptyWorkspace: boolean): void {
		const array = isEmptyWorkspace ? this.backups.emptyWorkspaces : this.backups.folderWorkspaces;
		if (!array) {
84 85
			return;
		}
86
		const index = this.indexOf(workspaceIdentifier, isEmptyWorkspace);
87 88 89
		if (index === -1) {
			return;
		}
90
		array.splice(index, 1);
91 92 93
		this.saveSync();
	}

94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
	private indexOf(workspaceIdentifier: string, isEmptyWorkspace: boolean): number {
		const array = isEmptyWorkspace ? this.backups.emptyWorkspaces : this.backups.folderWorkspaces;
		if (!array) {
			return -1;
		}

		if (isEmptyWorkspace) {
			return array.indexOf(workspaceIdentifier);
		}

		// for backup workspaces, sanitize the workspace identifier to accomodate for case insensitive file systems
		const sanitizedWorkspaceIdentifier = this.sanitizePath(workspaceIdentifier);
		return arrays.firstIndex(array, id => this.sanitizePath(id) === sanitizedWorkspaceIdentifier);
	}

109
	protected loadSync(): void {
110
		let backups: IBackupWorkspacesFormat;
D
Daniel Imms 已提交
111
		try {
112
			backups = JSON.parse(fs.readFileSync(this.workspacesJsonPath, 'utf8').toString()); // invalid JSON or permission issue can happen here
D
Daniel Imms 已提交
113
		} catch (error) {
114
			backups = Object.create(null);
D
Daniel Imms 已提交
115 116 117
		}

		// Ensure folderWorkspaces is a string[]
118 119
		if (backups.folderWorkspaces) {
			const fws = backups.folderWorkspaces;
D
Daniel Imms 已提交
120
			if (!Array.isArray(fws) || fws.some(f => typeof f !== 'string')) {
121
				backups.folderWorkspaces = [];
D
Daniel Imms 已提交
122
			}
123 124
		} else {
			backups.folderWorkspaces = [];
125 126
		}

127 128 129 130 131 132 133 134
		// Ensure emptyWorkspaces is a string[]
		if (backups.emptyWorkspaces) {
			const fws = backups.emptyWorkspaces;
			if (!Array.isArray(fws) || fws.some(f => typeof f !== 'string')) {
				backups.emptyWorkspaces = [];
			}
		} else {
			backups.emptyWorkspaces = [];
135 136
		}

137
		this.backups = this.dedupeFolderWorkspaces(backups);
138 139 140 141 142

		// Validate backup workspaces
		this.validateBackupWorkspaces(backups);
	}

143
	protected dedupeFolderWorkspaces(backups: IBackupWorkspacesFormat): IBackupWorkspacesFormat {
144 145 146
		// De-duplicate folder workspaces, don't worry about cleaning them up any duplicates as
		// they will be removed when there are no backups.
		backups.folderWorkspaces = arrays.distinct(backups.folderWorkspaces, ws => this.sanitizePath(ws));
147 148

		return backups;
D
Daniel Imms 已提交
149 150 151 152 153
	}

	private validateBackupWorkspaces(backups: IBackupWorkspacesFormat): void {
		const staleBackupWorkspaces: { workspaceIdentifier: string; backupPath: string; isEmptyWorkspace: boolean }[] = [];

154
		// Validate Folder Workspaces
155
		backups.folderWorkspaces.forEach(workspacePath => {
156
			const backupPath = path.join(this.backupHome, this.getWorkspaceHash(workspacePath));
157 158 159 160 161 162
			const hasBackups = this.hasBackupsSync(backupPath);
			const missingWorkspace = hasBackups && !fs.existsSync(workspacePath);

			// If the folder has no backups, make sure to delete it
			// If the folder has backups, but the target workspace is missing, convert backups to empty ones
			if (!hasBackups || missingWorkspace) {
163
				staleBackupWorkspaces.push({ workspaceIdentifier: workspacePath, backupPath, isEmptyWorkspace: false });
164 165

				if (missingWorkspace) {
166
					const identifier = this.pushBackupPathsSync(this.getRandomEmptyWorkspaceId(), true /* is empty workspace */);
167 168 169 170 171 172 173 174 175
					const newEmptyWorkspaceBackupPath = path.join(path.dirname(backupPath), identifier);
					try {
						fs.renameSync(backupPath, newEmptyWorkspaceBackupPath);
					} catch (ex) {
						console.error(`Backup: Could not rename backup folder for missing workspace: ${ex.toString()}`);

						this.removeBackupPathSync(identifier, true);
					}
				}
176 177
			}
		});
178

179
		// Validate Empty Workspaces
180 181
		backups.emptyWorkspaces.forEach(backupFolder => {
			const backupPath = path.join(this.backupHome, backupFolder);
182
			if (!this.hasBackupsSync(backupPath)) {
D
Daniel Imms 已提交
183 184 185 186
				staleBackupWorkspaces.push({ workspaceIdentifier: backupFolder, backupPath, isEmptyWorkspace: true });
			}
		});

187
		// Clean up stale backups
D
Daniel Imms 已提交
188
		staleBackupWorkspaces.forEach(staleBackupWorkspace => {
A
Alex Dima 已提交
189
			const { backupPath, workspaceIdentifier, isEmptyWorkspace } = staleBackupWorkspace;
190 191 192 193 194 195 196

			try {
				extfs.delSync(backupPath);
			} catch (ex) {
				console.error(`Backup: Could not delete stale backup: ${ex.toString()}`);
			}

197
			this.removeBackupPathSync(workspaceIdentifier, isEmptyWorkspace);
198 199 200
		});
	}

B
Benjamin Pasero 已提交
201
	private hasBackupsSync(backupPath: string): boolean {
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
		try {
			const backupSchemas = extfs.readdirSync(backupPath);
			if (backupSchemas.length === 0) {
				return false; // empty backups
			}

			return backupSchemas.some(backupSchema => {
				try {
					return extfs.readdirSync(path.join(backupPath, backupSchema)).length > 0;
				} catch (error) {
					return false; // invalid folder
				}
			});
		} catch (error) {
			return false; // backup path does not exist
217 218 219 220 221 222 223 224 225
		}
	}

	private saveSync(): void {
		try {
			// The user data directory must exist so only the Backup directory needs to be checked.
			if (!fs.existsSync(this.backupHome)) {
				fs.mkdirSync(this.backupHome);
			}
226
			fs.writeFileSync(this.workspacesJsonPath, JSON.stringify(this.backups));
227
		} catch (ex) {
228
			console.error(`Backup: Could not save workspaces.json: ${ex.toString()}`);
229 230
		}
	}
231

B
Benjamin Pasero 已提交
232 233 234 235
	private getRandomEmptyWorkspaceId(): string {
		return (Date.now() + Math.round(Math.random() * 1000)).toString();
	}

B
Benjamin Pasero 已提交
236
	private sanitizePath(p: string): string {
D
Daniel Imms 已提交
237 238 239
		return platform.isLinux ? p : p.toLowerCase();
	}

D
Daniel Imms 已提交
240
	protected getWorkspaceHash(workspacePath: string): string {
241
		return crypto.createHash('md5').update(this.sanitizePath(workspacePath)).digest('hex');
242
	}
243
}