Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Crc setup #17

Merged
merged 4 commits into from
Mar 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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) => {
gbraad marked this conversation as resolved.
Show resolved Hide resolved
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';
gbraad marked this conversation as resolved.
Show resolved Hide resolved

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