Giter Club home page Giter Club logo

js-libjuju's Introduction

JS Jujulib

This project provides a JavaScript API client library for interacting with the Juju WebSocket API.

Getting Started

To access the Juju API, a connection must be made to either a Juju controller or a Juju model.

import { connect } from "@canonical/jujulib";

import Client from "@canonical/jujulib/dist/api/facades/client";
import ModelManager from "@canonical/jujulib/dist/api/facades/model-manager";

// Nodejs
// import WebSocket from "ws";

const serverURL = "ws://localhost:17070";
const credentials = {
  username: "admin",
  password: "test",
};

// Connect to the controller
const controller = await connect(`${serverURL}/api`, {
  facades: [ModelManager],
  wsclass: WebSocket,
});
let conn = await controller.login(credentials);

// Get the list of models
const modelManager = conn.facades.modelManager;
const response = await modelManager.listModels({
  tag: conn.info.user.identity,
});
const models = response["user-models"];
console.log("models:", models);

// Close the connection to the controller
conn.transport.close();

// Login to each model
for (const modelDetails of models) {
  const model = await connect(
    `${serverURL}/model/${modelDetails.model.uuid}/api`,
    {
      facades: [Client],
      wsclass: WebSocket,
    }
  );
  conn = await model.login(credentials);

  // Get the details of the model
  const client = conn.facades.client;
  console.log("model details:", await client.fullStatus());

  // Close the connection to the model
  conn.transport.close();
}

In the code above, a connection is established to the provided controller API URL where the client declares interest in using the facade ModelManager, and we establish a new connection with each model API to get the full details using the facade Client.

Note: Facades are used to supported different versions of juju, when multiple versions of the same facade are supported by the juju API (like the two client versions in the example), the most recent version supported by the server is made available to the client.

The connect method returns a juju object which is used to log into the controller or model by providing a user/pass credentials or macaroons. See the various examples.

Client API Reference

Visit the full API documentation for detailed information on the Client API.

Examples

We have a number of examples showing how to perform a few common tasks. Those can be found in the examples folder.

Facade API Reference

Detailed Facade documentation is available as part of the full API documentation or you can visit the facade source directly using the following links:

Facade Versions
ActionPruner
Action
Admin
AgentLifeFlag
AgentTools
Agent
AllModelWatcher
AllWatcher
Annotations
ApplicationOffers
ApplicationScaler
Application
Backups
Block
Bundle
CAASAdmission
CAASAgent
CAASApplicationProvisioner
CAASApplication
CAASFirewallerEmbedded
CAASFirewallerSidecar
CAASFirewaller
CAASModelConfigManager
CAASModelOperator
CAASOperatorProvisioner
CAASOperatorUpgrader
CAASOperator
CAASUnitProvisioner
CharmDownloader
CharmHub
CharmRevisionUpdater
Charms
Cleaner
Client
Cloud
Controller
CredentialManager
CredentialValidator
CrossController
CrossModelRelations
CrossModelSecrets
Deployer
DiskManager
EntityWatcher
EnvironUpgrader
ExternalControllerUpdater
FanConfigurer
FilesystemAttachmentsWatcher
FirewallRules
Firewaller
HighAvailability
HostKeyReporter
ImageManager
ImageMetadataManager
ImageMetadata
InstanceMutater
InstancePoller
KeyManager
KeyUpdater
LeadershipService
LifeFlag
LogForwarding
Logger
MachineActions
MachineManager
MachineUndertaker
Machiner
MeterStatus
MetricsAdder
MetricsDebug
MetricsManager
MigrationFlag
MigrationMaster
MigrationMinion
MigrationStatusWatcher
MigrationTarget
ModelConfig
ModelGeneration
ModelManager
ModelSummaryWatcher
ModelUpgrader
NotifyWatcher
OfferStatusWatcher
PayloadsHookContext
Payloads
Pinger
Provisioner
ProxyUpdater
RaftLease
Reboot
RelationStatusWatcher
RelationUnitsWatcher
RemoteRelationWatcher
RemoteRelations
ResourcesHookContext
Resources
Resumer
RetryStrategy
SecretBackendsManager
SecretBackendsRotateWatcher
SecretBackends
SecretsDrain
SecretsManager
SecretsRevisionWatcher
SecretsRotationWatcher
SecretsTriggerWatcher
Secrets
Singular
Spaces
SSHClient
StatusHistory
StorageProvisioner
Storage
StringsWatcher
Subnets
Undertaker
UnitAssigner
Uniter
UpgradeSeries
UpgradeSteps
Upgrader
UserManager
VolumeAttachmentPlansWatcher
VolumeAttachmentsWatcher

Library Maintenance

Updating Library Facades

The Juju facade API files are generated from a supplied Juju schema.

To generate this schema you will need to clone the Juju repository and then run make rebuild-schema or go run github.com/juju/juju/generate/schemagen -admin-facades --facade-group=client,jimm ./apiserver/facades/schema.json to generate a schema file that contains the publicly available facades as well as the set of facades for JAAS. Other --facade-group options are latest and all.

After generating a new schema run yarn store-schema ../path/to/juju which will store the updated schema and necessary meta data in this project.

To update the facades, run yarn generate-facades on this project. This will generate the facades using the locally stored schema, sha, and version the schema was generated from.

Finally, update CLIENT_VERSION in api/client.ts with the highest support version.

Releasing to NPM

  • Update the version number in package.json, respecting semver.
  • Run the tests with npm test.
  • Run the examples with node to ensure that everything works as expected.
  • Upgrade the Juju Dashboard to this version using npm link and ensure that everything works as expected.
  • Tag the version in the git repository with the version number from above.
  • npm publish.
  • Update the release notes in the repository.
  • Create a post on the Juju Discourse with information about the release.

js-libjuju's People

Contributors

barrymcgee avatar dependabot[bot] avatar frankban avatar goulinkh avatar hatched avatar huwshimi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

js-libjuju's Issues

Improve typing in TS

In api/client.ts one of the main functions such as connect, connectAndLogin are missing return types which loads to a lot of missing typing later in juju-dashboard.

Try all servers on redirection errors

When getting a redirection error in the connectAndLogin call, instead of selecting the public server with a dns name, we should try them all in parallel and just use the first one that actually connects.
Right now we are assuming too much.

Project name?

We already have python-libjuju, we should probably try to have a similar naming scheme for new juju libraries going forward. Might I suggest js-libjuju or javascript-libjuju?

API calls all return object with top level results key

It seems like all api calls return an object with a top level results key which means that in order to use them you must access that key.

const credentialList = await this._getCloudCredentialNames(props.userName, clouds).results;
const modelList = await this.props.modelManager.listModelSummaries().results;

It looks like we can modify this:

return result;

      transform = resp => {
        let result;
        {{ method.result.generate_response('result', 'resp')|indent(8) }}
        return result;
      };

To instead be something like:

      transform = resp => {
        let result;
        {{ method.result.generate_response('result', 'resp')|indent(8) }}
        return result.results || result;
      };

Through a quick glance at the codebase it looks like they always have result.results but it could be I just hadn't found the right api call that doesn't. In that case it would fall back to the whole response object.

Remove the docs HTML files from the repo

With the better support of Typescript the amount of API docs files has grown (+2000 files).
A way to avoid this, is by generating the docs during the GH page build action, the command to run in order to generate the docs is:

yarn build-api-docs

Tests are outdated

Tests are failing because of the usage of type:module as well as outdated test cases.

Failed request response is incorrectly handled

An RPC call can fail for two reasons:

  • The request itself fails, typically because you do not have permissions to perform said request.
  • The response has encountered an error while performing the request.

In the latter the error is returned as part of the response type example

interface AddMachinesResult {
  error?: Error;
  machine: string;
}

In the former however the handler function will replace the response value with the error value.

callback(resp.error || resp.response);

This is an issue because calls like the following are only reporting a response value for the successful path and not the potential error response.

const status = await conn.facades.client.fullStatus()

Can't get model from Charm store

As per our discussions on IRC today, it seems impossible to get a bundle staged via the getChanges API in the bundle facade.

Passing in the raw YAML to the same API call does work.

Whatever we pass in the bundleurl the reponse is "at least one application must be specified"

Log out discrepancy in supplied facades

When creating a new instance and passing in facades it's possible that the Juju controller you're connecting to does not support that facade. In this case we should log out that specific versions of the facades supplied are not supported.

Psudo code...

If debug === true {
  if facadeMissmatch {
    console.log('facade Application versions 7,9 supplied, versions 2,3,4,5,6 supported.")
  }
}

How Do I Tag Units With a `-` in the name?

I am getting an error when trying to pass a unit tag to the Juju API:

"unit-lizardfs-gui/0" is not a valid unit tag 

I'm assuming this is because of the dashes in the unit name. Is there a way to escape the dashes in the unit name or something of the sort?

Schema file not checked into source control

The new schema is not stored in source control which means that any changes to anything outside of the generator requires the editor to build the schema from the Juju source again and then build this project. This can be tedious and challenging for someone new to the project. We should probably include the schema file in the source tree for the current version released on npm.

Document `user-admin` Nuance Necessary to Log In as the Admin User

I just found out that if you want to log in as the admin user, you have to pass the username as user-admin instead of admin or else you get this error: "admin" is not a valid tag. That was super confusing. It would be a good thing to have in the docs. I just noticed that it was the default username in the examples and that seemed suspicious enough to try.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.