Skip to content

Commit

Permalink
Merge pull request #17 from evidolob/crc-setup
Browse files Browse the repository at this point in the history
Crc setup
  • Loading branch information
gbraad authored Mar 17, 2023
2 parents ea06737 + 68120e4 commit 3bb3bd5
Show file tree
Hide file tree
Showing 9 changed files with 302 additions and 109 deletions.
29 changes: 1 addition & 28 deletions scripts/run.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -64,30 +64,10 @@ async function checkAndCloneDesktopRepo() {
}
}

function removeCrcExt() {
const crcExtPath = path.join(desktopPath, 'extensions', 'crc');
if(fs.existsSync(crcExtPath)){
console.log('Deleting old crc extension');
fs.rmSync(crcExtPath, {recursive: true});
}
}

async function patchPDBuild() {
console.log('Removing crc build script from package.json...');
const filePath = path.resolve(desktopPath, 'package.json');
const content = fs.readFileSync(filePath);
const packageObj = JSON.parse(content.toString('utf8'));
packageObj.scripts['build:extensions:crc'] = '';
fs.writeFileSync(filePath, JSON.stringify(packageObj, undefined, ' '));
}

async function prepareDev() {
await checkAndCloneDesktopRepo();
removeCrcExt();
await patchPDBuild();

await exec('yarn',undefined, {cwd: desktopPath });
await buildPD();
await exec('yarn',[], {cwd: path.join(__dirname, '..')});
}

Expand All @@ -112,14 +92,7 @@ async function build() {

async function run() {
await buildCrc();

if(os.platform() === 'darwin') {
await exec('open', ['-W', '-a', path.resolve(desktopPath, 'dist', 'mac', 'Podman Desktop.app')]);
} else if(os.platform() === 'win32') {
await exec(path.resolve(desktopPath, 'dist', 'win-unpacked', '"Podman Desktop.exe"'));
} else {
throw new Error('Cannot launch Podman Desktop on ' + os.platform());
}
await exec('yarn', ['watch'], {cwd: desktopPath});
}

const firstArg = process.argv[2];
Expand Down
9 changes: 9 additions & 0 deletions src/crc-cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,3 +168,12 @@ export function daemonStop() {
daemonProcess.kill();
}
}

export async function needSetup(): Promise<boolean> {
try {
await execPromise(getCrcCli(), ['setup', '--check-only']);
return false;
} catch (e) {
return true;
}
}
108 changes: 108 additions & 0 deletions src/crc-setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
/**********************************************************************
* Copyright (C) 2023 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
***********************************************************************/

import * as extensionApi from '@podman-desktop/api';
import { execPromise, getCrcCli } from './crc-cli';
import type { Preset } from './daemon-commander';
import { productName } from './util';

interface PresetQuickPickItem extends extensionApi.QuickPickItem {
data: Preset;
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
export async function setUpCrc(logger: extensionApi.Logger, askForPreset = false): Promise<boolean> {
if (askForPreset) {
const preset = await extensionApi.window.showQuickPick<PresetQuickPickItem>(createPresetItems(), {
canPickMany: false,
title: `Select ${productName} Preset`,
placeHolder: `Select ${productName} Preset`,
});
if (!preset) {
extensionApi.window.showNotification({
title: productName,
body: 'Default preset will be used.',
});
} else {
await execPromise(getCrcCli(), ['config', 'set', 'preset', preset.data]);
}
}

const setupBar = extensionApi.window.createStatusBarItem('RIGHT', 2000);
try {
setupBar.text = `Configuring ${productName}...`;
setupBar.show();
await execPromise(getCrcCli(), ['setup'], {
logger: {
error: (data: string) => {
if (!data.startsWith('level=')) {
const downloadMsg = 'Downloading bundle: ' + data.substring(data.lastIndexOf(']') + 1, data.length).trim();
setupBar.text = downloadMsg;
setupBar.tooltip =
'Downloading bundle: ' +
data.substring(0, data.indexOf('[')).trim() +
' ' +
data.substring(data.lastIndexOf(']') + 1, data.length).trim();
} else {
const msg = data.substring(data.indexOf('msg="') + 5, data.length - 1);
setupBar.text = msg;
}
},
// eslint-disable-next-line @typescript-eslint/no-unused-vars
warn: (data: string) => {
//ignore
},
// eslint-disable-next-line @typescript-eslint/no-unused-vars
log: (data: string) => {
//ignore
},
},
env: undefined,
});

setupBar.text = 'All done.';
} catch (err) {
console.error(err);
extensionApi.window.showErrorMessage(`${productName} configuration failed:\n${err}`);
return false;
} finally {
setupBar.hide();
setupBar.dispose();
}

return true;
}

function createPresetItems(): PresetQuickPickItem[] {
return [
{
data: 'openshift',
label: 'openshift',
description:
'Run a full OpenShift cluster environment as a single node, providing a registry and access to Operator Hub',
detail:
'Run a full OpenShift cluster environment as a single node, providing a registry and access to Operator Hub',
},
{
data: 'microshift',
label: 'microshift',
description: 'MicroShift is an optimized OpenShift Kubernetes for small form factor and edge computing.',
detail: 'MicroShift is an optimized OpenShift Kubernetes for small form factor and edge computing.',
},
];
}
53 changes: 50 additions & 3 deletions src/daemon-commander.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,10 @@
import got from 'got';
import { isWindows } from './util';

export type CrcStatus = 'Running' | 'Starting' | 'Stopping' | 'Stopped' | 'No Cluster' | 'Error' | 'Unknown';

export interface Status {
readonly CrcStatus: string;
readonly CrcStatus: CrcStatus;
readonly Preset?: string;
readonly OpenshiftStatus?: string;
readonly OpenshiftVersion?: string;
Expand All @@ -29,6 +31,21 @@ export interface Status {
readonly DiskSize?: number;
}

export type Preset = 'openshift' | 'microshift' | 'podman';

export interface Configuration {
preset: Preset;
cpus: number;
memory: number;
'disk-size'?: number;
'consent-telemetry'?: string;
'http-proxy'?: string;
'https-proxy'?: string;
'no-proxy'?: string;
'proxy-ca-file'?: string;
[key: string]: string | number;
}

export class DaemonCommander {
private apiPath: string;

Expand Down Expand Up @@ -87,11 +104,24 @@ export class DaemonCommander {
return body;
}

async configGet() {
async configGet(): Promise<Configuration> {
const url = this.apiPath + '/config';

const { body } = await got(url);
return JSON.parse(body);
return JSON.parse(body).Configs;
}

async configSet(values: Configuration): Promise<void> {
const url = this.apiPath + '/config';

const result = await got.post(url, {
json: { properties: values },
throwHttpErrors: false,
// body: values,
});
if (result.statusCode !== 200) {
throw new Error(result.body);
}
}

async consoleUrl() {
Expand All @@ -117,3 +147,20 @@ export class DaemonCommander {
return body;
}
}

export const commander = new DaemonCommander();

export async function isPullSecretMissing(): Promise<boolean> {
let result = true;

await commander
.pullSecretAvailable()
.then(() => {
result = true;
})
.catch(() => {
result = false;
});

return result;
}
Loading

0 comments on commit 3bb3bd5

Please sign in to comment.