backupMainService.ts 7.5 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';
12
import Uri from 'vs/base/common/uri';
D
Daniel Imms 已提交
13
import { IBackupWorkspacesFormat, IBackupMainService } from 'vs/platform/backup/common/backup';
14
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
15
import { TPromise } from 'vs/base/common/winjs.base';
16

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

	public _serviceBrand: any;

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

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

27
	constructor(
B
Benjamin Pasero 已提交
28
		@IEnvironmentService environmentService: IEnvironmentService
29 30
	) {
		this.backupHome = environmentService.backupHome;
D
Daniel Imms 已提交
31
		this.workspacesJsonPath = environmentService.backupWorkspacesPath;
32
		this.mapWindowToBackupFolder = Object.create(null);
D
Daniel Imms 已提交
33

34
		this.loadSync();
35 36
	}

37 38
	public getWorkspaceBackupPaths(): string[] {
		return this.backups.folderWorkspaces.slice(0); // return a copy
39 40
	}

41 42
	public getEmptyWorkspaceBackupPaths(): string[] {
		return this.backups.emptyWorkspaces.slice(0); // return a copy
43 44
	}

45 46 47 48 49 50 51 52
	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 已提交
53
	public registerWindowForBackupsSync(windowId: number, isEmptyWorkspace: boolean, backupFolder?: string, workspacePath?: string): void {
54
		// Generate a new folder if this is a new empty workspace
D
Daniel Imms 已提交
55
		if (isEmptyWorkspace && !backupFolder) {
56
			backupFolder = this.getRandomEmptyWorkspaceId();
57 58
		}

59
		this.mapWindowToBackupFolder[windowId] = isEmptyWorkspace ? backupFolder : this.getWorkspaceHash(workspacePath);
D
Daniel Imms 已提交
60
		this.pushBackupPathsSync(isEmptyWorkspace ? backupFolder : workspacePath, isEmptyWorkspace);
61
	}
62

B
Benjamin Pasero 已提交
63
	private pushBackupPathsSync(workspaceIdentifier: string, isEmptyWorkspace: boolean): string {
64 65 66 67
		const array = isEmptyWorkspace ? this.backups.emptyWorkspaces : this.backups.folderWorkspaces;
		if (array.indexOf(workspaceIdentifier) === -1) {
			array.push(workspaceIdentifier);
			this.saveSync();
68
		}
69 70

		return workspaceIdentifier;
71 72
	}

73 74 75
	protected removeBackupPathSync(workspaceIdentifier: string, isEmptyWorkspace: boolean): void {
		const array = isEmptyWorkspace ? this.backups.emptyWorkspaces : this.backups.folderWorkspaces;
		if (!array) {
76 77
			return;
		}
78
		const index = array.indexOf(workspaceIdentifier);
79 80 81
		if (index === -1) {
			return;
		}
82
		array.splice(index, 1);
83 84 85
		this.saveSync();
	}

86
	protected loadSync(): void {
87
		let backups: IBackupWorkspacesFormat;
D
Daniel Imms 已提交
88
		try {
89
			backups = JSON.parse(fs.readFileSync(this.workspacesJsonPath, 'utf8').toString()); // invalid JSON or permission issue can happen here
D
Daniel Imms 已提交
90
		} catch (error) {
91
			backups = Object.create(null);
D
Daniel Imms 已提交
92 93 94
		}

		// Ensure folderWorkspaces is a string[]
95 96
		if (backups.folderWorkspaces) {
			const fws = backups.folderWorkspaces;
D
Daniel Imms 已提交
97
			if (!Array.isArray(fws) || fws.some(f => typeof f !== 'string')) {
98
				backups.folderWorkspaces = [];
D
Daniel Imms 已提交
99
			}
100 101
		} else {
			backups.folderWorkspaces = [];
102 103
		}

104 105 106 107 108 109 110 111
		// 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 = [];
112 113 114 115 116 117 118 119
		}

		this.backups = backups;

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

120 121 122 123
	protected dedupeFolderWorkspaces(backups: IBackupWorkspacesFormat): void {
		// 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));
D
Daniel Imms 已提交
124 125 126 127 128
	}

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

129
		this.dedupeFolderWorkspaces(backups);
130

131
		backups.folderWorkspaces.forEach(workspacePath => {
132
			const backupPath = path.join(this.backupHome, this.getWorkspaceHash(workspacePath));
133 134 135 136 137 138
			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) {
D
Daniel Imms 已提交
139
				const backupWorkspace = this.sanitizePath(workspacePath);
140
				staleBackupWorkspaces.push({ workspaceIdentifier: Uri.file(backupWorkspace).fsPath, backupPath, isEmptyWorkspace: false });
141 142

				if (missingWorkspace) {
143
					const identifier = this.pushBackupPathsSync(this.getRandomEmptyWorkspaceId(), true /* is empty workspace */);
144 145 146 147 148 149 150 151 152
					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);
					}
				}
153 154
			}
		});
155 156 157

		backups.emptyWorkspaces.forEach(backupFolder => {
			const backupPath = path.join(this.backupHome, backupFolder);
158
			if (!this.hasBackupsSync(backupPath)) {
D
Daniel Imms 已提交
159 160 161 162 163 164
				staleBackupWorkspaces.push({ workspaceIdentifier: backupFolder, backupPath, isEmptyWorkspace: true });
			}
		});

		staleBackupWorkspaces.forEach(staleBackupWorkspace => {
			const {backupPath, workspaceIdentifier, isEmptyWorkspace} = staleBackupWorkspace;
165 166 167 168 169 170 171

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

172
			this.removeBackupPathSync(workspaceIdentifier, isEmptyWorkspace);
173 174 175
		});
	}

B
Benjamin Pasero 已提交
176
	private hasBackupsSync(backupPath: string): boolean {
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
		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
192 193 194 195 196 197 198 199 200
		}
	}

	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);
			}
201
			fs.writeFileSync(this.workspacesJsonPath, JSON.stringify(this.backups));
202
		} catch (ex) {
203
			console.error(`Backup: Could not save workspaces.json: ${ex.toString()}`);
204 205
		}
	}
206

B
Benjamin Pasero 已提交
207 208 209 210
	private getRandomEmptyWorkspaceId(): string {
		return (Date.now() + Math.round(Math.random() * 1000)).toString();
	}

B
Benjamin Pasero 已提交
211
	private sanitizePath(p: string): string {
D
Daniel Imms 已提交
212 213 214
		return platform.isLinux ? p : p.toLowerCase();
	}

D
Daniel Imms 已提交
215
	protected getWorkspaceHash(workspacePath: string): string {
216
		return crypto.createHash('md5').update(this.sanitizePath(workspacePath)).digest('hex');
217
	}
218
}