HewlettPackard/oneview-sdk-ruby

View on GitHub
README.md

Summary

Maintainability
Test Coverage
# HPE OneView SDK for Ruby

## Build Status 

OV Version | 6.20 | 6.10 | 6.00 | 5.60 | 5.50 | 5.40 |
| ------------- |:-------------:| :-------------:| :-------------:| :-------------:| :-------------:| :-------------:|
SDK Version/Tag |  [v6.2.0](https://github.com/HewlettPackard/oneview-sdk-ruby/releases/tag/v6.2.0)  | [v6.1.0](https://github.com/HewlettPackard/oneview-sdk-ruby/releases/tag/v6.1.0) | [v6.0.0](https://github.com/HewlettPackard/oneview-sdk-ruby/releases/tag/v6.0.0) | [v5.18.0](https://github.com/HewlettPackard/oneview-sdk-ruby/releases/tag/v5.18.0) | [v5.17.0](https://github.com/HewlettPackard/oneview-sdk-ruby/releases/tag/v5.17.0) | [v5.16.0](https://github.com/HewlettPackard/oneview-sdk-ruby/releases/tag/v5.16.0) |
Build Status | [![Build status](https://action-badges.now.sh/JasonEtco/action-badges)](https://github.com/HewlettPackard/oneview-sdk-ruby/runs/2949080207) | [![Build status](https://action-badges.now.sh/JasonEtco/action-badges)](https://github.com/HewlettPackard/oneview-sdk-ruby/actions/runs/769868941)| [![Build status](https://action-badges.now.sh/JasonEtco/action-badges)](https://github.com/HewlettPackard/oneview-sdk-ruby/actions/runs/634796649)| [![Build status](https://action-badges.now.sh/JasonEtco/action-badges)](https://github.com/HewlettPackard/oneview-sdk-ruby/actions/runs/519793086)| [![Build status](https://action-badges.now.sh/JasonEtco/action-badges)](https://github.com/HewlettPackard/oneview-sdk-ruby/actions/runs/349360042)|[![Build status](https://action-badges.now.sh/JasonEtco/action-badges)](https://github.com/HewlettPackard/oneview-sdk-ruby/actions/runs/343154951)|


## Introduction

HPE OneView makes it simple to deploy and manage today’s complex hybrid cloud infrastructure. HPE OneView can help you transform your data center to software-defined, and it supports HPE’s broad portfolio of servers, storage, and networking solutions, ensuring the simple and automated management of your hybrid infrastructure. Software-defined intelligence enables a template-driven approach for deploying, provisioning, updating, and integrating compute, storage, and networking infrastructure.

The HPE OneView Ruby SDK provides library to easily interact with HPE OneView and HPE Image Streamer REST APIs. The HPE OneView Ruby SDK enables developers to easily build integrations and scalable solutions with HPE OneView and HPE Image Streamer.

You can find the latest supported HPE OneView Ruby SDK [here](https://github.com/HewlettPackard/oneview-sdk-ruby/releases/latest)

## What's New

HPE OneView Ruby library extends support of the SDK to OneView REST API version 3000 (OneView v6.20)

Please refer to [notes](https://github.com/HewlettPackard/oneview-sdk-ruby/blob/master/CHANGELOG.md) for more information on the changes , features supported and issues fixed in this version

## Getting Started 

## Installation and Configuration

## Installation
HPE OneView SDK for Ruby can be installed from Source and Docker container installation methods.You can either use a docker container which will have the HPE OneView SDK for Ruby installed or perform local installation.

###  Docker Setup
The light weight containerized version of the HPE OneView SDK for Ruby is available in the [Docker Store](https://store.docker.com/community/images/hewlettpackardenterprise/hpe-oneview-sdk-for-ruby). The Docker Store image tag consist of two sections: <sdk_version-OV_version>

```bash
# Download and store a local copy of oneview-sdk-ruby and use it as a Docker Image.
$ docker pull hewlettpackardenterprise/hpe-oneview-sdk-for-ruby:v6.1.0-OV6.1
# Run docker commands below given, which  will in turn create a sh session 
# where you can create files, issue commands and execute the examples.
$ docker run -it hewlettpackardenterprise/hpe-oneview-sdk-for-ruby:v6.1.0-OV6.1 /bin/sh
```

### Local Setup
- Local installation requires the gem in your Gemfile:

  ```ruby
  gem 'oneview-sdk', '~> 6.1.0'
  ```

  Then run `$ bundle install`
- Or run the command:

  ```bash
  $ gem install oneview-sdk
  ```


## Configuration

### OneView Client Configuration
The OneView Client configuration options that can be passed during OneView Client object creation:

```ruby
# Create a OneView client object:
require 'oneview-sdk'
client = OneviewSDK::Client.new(
  url: 'https://oneview.example.com',
  user: 'Administrator',              # This is the default
  password: 'secret123',
  token: 'xxxx...',                   # Set EITHER token or the username & password
  ssl_enabled: true,                  # This is the default and strongly encouraged
  logger: Logger.new(STDOUT),         # This is the default
  log_level: :info,                   # This is the default
  domain: 'LOCAL',                    # This is the default
  api_version: 3000                   # Defaults to appliance's max API version which is API version of OneView 6.20
)
```

:lock: Tip: Check the file permissions because the password is stored in clear-text.

### Image Streamer Client Configuration
The Image Streamer (I3S) client is very much similar to the OneView client, but has one key difference:
it cannot generate it's own token. However, it uses the same token given to or generated by the OneView client,
so if you need to generate a token, create a OneView client using a user & password, then pass the generated token
into the Image Streamer client.

```ruby
# Create an Image Streamer client object:
require 'oneview-sdk'
i3s_client = OneviewSDK::ImageStreamer::Client.new(
  url: 'https://image-streamer.example.com',
  token: 'xxxx...',                   # Required. Note that you cannot pass the user & password options
  ssl_enabled: true,                  # This is the default and strongly encouraged
  logger: Logger.new(STDOUT),         # This is the default
  log_level: :info,                   # This is the default
  api_version: 2020                   # Defaults to appliance's max API version
)
```

You can also create the Image Streamer(I3S) client through the Oneview client instance.

```ruby
# Create an Image Streamer client object through the Oneview client object:
require 'oneview-sdk'
i3s_client = client.new_i3s_client(
  url: 'https://image-streamer.example.com',
  ssl_enabled: true,                  # This is the default and strongly encouraged
  logger: Logger.new(STDOUT),         # This is the default
  log_level: :info,                   # This is the default
  api_version: 2020                   # Defaults to appliance's max API version
)
```

### Environment Variables

Configuration can also be defined through environment variables.To set these variables in bash:

```bash
# OneView client options:
export ONEVIEWSDK_URL='https://oneview.example.com'
export ONEVIEWSDK_DOMAIN='LOCAL'
# You can set the token if you know it, or set the user and password to generate one:
export ONEVIEWSDK_TOKEN='xxxx...'
export ONEVIEWSDK_USER='Administrator'
export ONEVIEWSDK_PASSWORD='secret123'
export ONEVIEWSDK_SSL_ENABLED=false
# NOTE: Disabling SSL is strongly discouraged. Please see the CLI section for import instructions.

# Image Streamer (I3S) client options:
export I3S_URL='https://image-streamer.example.com'
export I3S_SSL_ENABLED=false
# NOTE: Disabling SSL is strongly discouraged. Please see the CLI section for import instructions.
```

:lock: Tip: Be sure nobody has access to your environment variables, as the password or token is stored in clear-text.

Then you can leave out these options from your config, enabling you to just do:

```ruby
require 'oneview-sdk'
client = OneviewSDK::Client.new
```

You can create the i3s client with environment variables in the following ways:
```ruby
require 'oneview-sdk'
# Note: Both options require the I3S_URL environment variable to be set.

# This way uses the ONEVIEWSDK_URL, ONEVIEWSDK_USER and ONEVIEWSDK_PASSWORD environment variables to generate a token:
client = OneviewSDK::Client.new
i3s_client = client.new_i3s_client

# This way uses the ONEVIEWSDK_TOKEN environment variable directly:
i3s_client = OneviewSDK::ImageStreamer::Client.new
```

NOTE: Run `$ oneview-sdk-ruby env` to see a list of available environment variables and their current values.

### Configuration Files

Configuration files can also be used to define client configuration (json or yaml formats). Here's an example json file:

```json
{
  "url": "https://oneview.example.com",
  "user": "Administrator",
  "password": "secret123",
  "api_version": 3000
}
```

and load via:

```ruby
config = OneviewSDK::Config.load("full_file_path.json")
client = OneviewSDK::Client.new(config)
```

:lock: Tip: Check the file permissions if the password or token is stored in clear-text.

### Custom logging
The default logger is a standard logger to STDOUT, but if you want to specify your own, you can.  However, your logger must implement the following methods:

```ruby
debug(String)
info(String)
warn(String)
error(String)
level=(Symbol, etc.) # The parameter here will be the log_level attribute
```

:lock: Tip: When the log_level is set to debug, API request options will be logged (including auth tokens and passwords); be careful to protect secret information.


## API Implementation

A detailed list of the HPE OneView REST interfaces that have been implemented in this SDK can be found in the [endpoints-support.md](https://github.com/HewlettPackard/oneview-sdk-ruby/blob/master/endpoints-support.md) file.

### HPE OneView API Versions and Appliance types
You may notice resource classes being accessed in a few different ways; for example, `OneviewSDK::EthernetNetwork`, `OneviewSDK::API1000::EthernetNetwork`, and `OneviewSDK::API1000::C7000::EthernetNetwork`. However, each of these accessors may actually be referring to the same class. This is because in order to keep backwards compatibility and make examples a little more simple, there are module methods in place to redirect/resolve the shorthand accessors to their full namespace identifier. In order to automatically complete the full namespace identifier, there are some defaults in place. Here's some example code that should help clear things up (return values are commented behind the code):

```ruby
require 'oneview-sdk'

# Show defaults:
OneviewSDK::SUPPORTED_API_VERSIONS      # [1000, 1200, 1600, 1800, 2000, 2200, 2600, 2800, 3000]
OneviewSDK::DEFAULT_API_VERSION         # 3000
OneviewSDK.api_version                  # 3000
OneviewSDK.api_version_updated?         # false

# Notice the automatic redirection/resolution when we use the shorthand accessor:
OneviewSDK::EthernetNetwork             # OneviewSDK::API3000::EthernetNetwork

# Even this comparison is true:
OneviewSDK::EthernetNetwork == OneviewSDK::API3000::EthernetNetwork  # true

# Now let's set a new API version default:
OneviewSDK.api_version = 3000
OneviewSDK.api_version                  # 3000
OneviewSDK.api_version_updated?         # true

# The API300 and above has 2 variants (C7000 & Synergy): For eg

OneviewSDK::API1800::SUPPORTED_VARIANTS  # ['C7000', 'Synergy']
OneviewSDK::API1800::DEFAULT_VARIANT     # 'C7000'
OneviewSDK::API1800.variant              # 'C7000'
OneviewSDK::API1800.variant_updated?     # false

OneviewSDK::API2000::SUPPORTED_VARIANTS  # ['C7000', 'Synergy']
OneviewSDK::API2000::DEFAULT_VARIANT     # 'C7000'
OneviewSDK::API2000.variant              # 'C7000'
OneviewSDK::API2000.variant_updated?     # false

OneviewSDK::API2200::SUPPORTED_VARIANTS  # ['C7000', 'Synergy']
OneviewSDK::API2200::DEFAULT_VARIANT     # 'C7000'
OneviewSDK::API2200.variant              # 'C7000'
OneviewSDK::API2200.variant_updated?     # false

OneviewSDK::API3000::SUPPORTED_VARIANTS  # ['C7000', 'Synergy']
OneviewSDK::API3000::DEFAULT_VARIANT     # 'C7000'
OneviewSDK::API3000.variant              # 'C7000'
OneviewSDK::API3000.variant_updated?     # false

# Likewise, we can set a new default variant for the API3000 module:
OneviewSDK::3000.variant = 'Synergy'
OneviewSDK::API3000.variant              # 'Synergy'
OneviewSDK::API3000.variant_updated?     # true

```

:lock: Tip: We understand that this can be confusing, so to avoid any confusion or unexpected behavior, we recommend specifying the full namespace identifier in your code. At the very least, set defaults explicitly using `OneviewSDK.api_version = <ver>` and `OneviewSDK::API3000.variant = <variant>`, as the defaults may change.

## Resources
Each OneView and Image Streamer resource is exposed via a Ruby class, enabling CRUD-like functionality (with some exceptions).

Once you instantiate a resource object, you can call intuitive methods such as `resource.create`, `resource.update` and `resource.delete`. In addition, resources respond to helpful methods such as `.each`, `.eql?(other_resource)`, `.like(other_resource)`, `.retrieve!`, and many others.

Please see the [rubydoc.info](http://www.rubydoc.info/gems/oneview-sdk) documentation for complete usage details and the [examples](examples/) directory for more examples and test-scripts, but here are a few examples to get you started:

##### Create a resource

```ruby
ethernet = OneviewSDK::EthernetNetwork.new(
  client, { name: 'TestVlan', vlanId:  1001, purpose:  'General', smartLink: false, privateNetwork: false }
)
ethernet.create # Tells OneView to create this resource
```

##### Access resource attributes

```ruby
ethernet['name'] # Returns 'TestVlan'

ethernet.data # Returns hash of all data

ethernet.each do |key, value|
  puts "Attribute #{key} = #{value}"
end
```

The resource's data is stored in its @data attribute.  However, you can access the data directly using a hash-like syntax on the resource object (recommended). `resource['key']` functions a lot like `resource.data['key']`. The difference is that when using the data attribute, you must be cautious to use the correct key type (Hash vs Symbol).
The direct hash accessor on the resource converts first-level keys to strings; so `resource[:key]` and `resource['key']` access the same thing: `resource.data['key']`. We recommend using strings exclusively for keys, as the JSON data returned from OneView requests supports strings but not symbols.

##### Update a resource

Notice that there are a few different ways to do things, so pick your poison!
```ruby
ethernet.set_all(name: 'newName', vlanId:  1002)
ethernet['purpose'] = 'General'
ethernet['ethernetNetworkType'] = 'Tagged'
ethernet.update # Saves current state to OneView

# Alternatively, you could do this in 1 step with:
ethernet.update(name: 'newName', vlanId:  1002, purpose: 'General', ethernetNetworkType: 'Tagged')
```

##### Check resource equality

You can use the `==`  or `.eql?` method to compare resource equality, or `.like` to compare just a subset of attributes.
```ruby
ethernet2 = OneviewSDK::EthernetNetwork.new(client, { purpose:  'General' })
ethernet == ethernet2    # Returns false
ethernet.eql?(ethernet2) # Returns false


# To compare a subset of attributes:
ethernet.like?(ethernet2)  # Returns true
ethernet.like?(name: 'TestVlan', purpose: 'General')  # Returns true
```


##### Find resources

```ruby
ethernet = OneviewSDK::EthernetNetwork.new(client, { name: 'OtherVlan' })
ethernet.retrieve! # Uses the name attribute to search for the resource on the server and update the data in this object.


# Each resource class also has a searching method (NOTE: class method, not instance method)
ethernet = OneviewSDK::EthernetNetwork.find_by(client, { name: 'OtherVlan' }).first

OneviewSDK::EthernetNetwork.find_by(client, { purpose: 'General' }).each do |network|
  puts "  #{network['name']}"
end

# Get all resources:
networks = client.get_all(:EthernetNetwork)
```

##### Delete a resource

```ruby
ethernet = OneviewSDK::EthernetNetwork.find_by(client, { name: 'OtherVlan' }).first
ethernet.delete # Tells OneView to delete this resource
```

### Save/Load resources with files
Resources can be saved to files and loaded again very easily using the built-in `.to_file` & `.from_file` methods.

 - To save a Resource to a file:

   ```ruby
   ethernet.to_file("full_file_path.json")
   ```
 - To load a resource from a file: (note the class method, not instance method)

   ```ruby
   ethernet4 = OneviewSDK::Resource.from_file(client, "full_file_path.json")
   ```


For more examples and test-scripts, see the [examples](examples/) directory and [rubydoc.info](http://www.rubydoc.info/gems/oneview-sdk) documentation.

## Custom requests
In most cases, interacting with Resource objects is enough, but sometimes you need to make your own custom requests to OneView.
This project makes it extremely easy to do with some built-in methods for the Client object. Here are some examples:

```ruby
# Get the appliance startup progress:
response = client.rest_api(:get, '/rest/appliance/progress')
# or even more simple:
response = client.rest_get('/rest/appliance/progress')

# Then we can validate the response and convert the response body into a hash...
data = client.response_handler(response)
```

This example is about as basic as it gets, but you can make any type of OneView request.
If a resource does not do what you need, this will allow you to do it.
Please refer to the documentation and [code](lib/oneview-sdk/rest.rb) for complete list of methods and information about how to use them.

## CLI
This gem also comes with a command-line interface to make interacting with OneView possible without the need to create a Ruby program or script.

Note: In order to use this, you will need to make sure your Ruby `bin` directory is in your path.
Run `$ gem environment` to see where the executable paths are for your Ruby installation.

To get started, run `$ oneview-sdk-ruby --help`.

To communicate with an appliance, you will need to set up a few environment variables so it knows how to communicate. Run `$ oneview-sdk-ruby env` to see the available environment variables.

The CLI does not expose everything in the SDK, but it is great for doing simple tasks such as creating or deleting resources from files, listing resources, and searching. Here are a few examples:

##### List ServerProfiles:

```bash
# Output a list of ServerProfile names:
$ oneview-sdk-ruby list ServerProfiles
# Or to show in yaml format (json is also supported):
$ oneview-sdk-ruby list ServerProfiles -f yaml
# Or to show specific attributes only:
$ oneview-sdk-ruby list ServerProfiles -a uri,state,bios.overriddenSettings
```

##### Show details for a specific resource:

```bash
$ oneview-sdk-ruby show ServerProfile profile-1
# Or to show specific attributes only:
$ oneview-sdk-ruby show ServerProfile profile-1 -a name,uri,enclosureBay
```

##### Search by an attribute:

```bash
$ oneview-sdk-ruby search ServerProfiles --filter state:Normal affinity:Bay
# By default, it will just show a list of names of matching resources,
#   but again, you can show only certain attributes by using the -a option
# You can also chain keys together to search in nested hashes:
$ oneview-sdk-ruby search ServerProfiles --filter state:Normal boot.manageBoot:true
# Or to show specific attributes only:
$ oneview-sdk-ruby search ServerProfile --filter state:Normal -a name,uri,enclosureBay
```

##### Create or delete resource by file:

```bash
# Save resource details to a file (to be used with the create and delete methods below)
$ oneview-sdk-ruby to_file ServerProfile profile-1 /my-server-profile.json

$ oneview-sdk-ruby create_from_file /my-server-profile.json
$ oneview-sdk-ruby delete_from_file /my-server-profile.json
```

##### Update resources by name:

```bash
$ oneview-sdk-ruby update FCNetwork FC1 -h linkStabilityTime:20  # Using hash format
$ oneview-sdk-ruby update Volume VOL_01 -j '{"shareable": true}' # Using json format
```

##### Make REST calls:

```bash
$ oneview-sdk-ruby rest get rest/fc-networks
$ oneview-sdk-ruby rest PUT rest/enclosures/<id>/configuration
```

##### Start an interactive console session with a OneView connection:

```bash
$ oneview-sdk-ruby console
Console Connected to https://oneview.example.com
HINT: The @client object is available to you
>
```

##### Import a self-signed SSL certificate from your OneView or Image Streamer instance:

Although you can disable SSL validation altogether for the client, this is strongly discouraged.
Instead, please import the certificate using the built-in CLI cert command:
```bash
# Check the certificate first:
$ oneview-sdk-ruby cert check https://oneview.example.com
 Checking certificate for 'https://oneview.example.com' ...
 ERROR: Certificate Validation Failed!

# Import the certificate:
$ oneview-sdk-ruby cert import https://oneview.example.com
 Importing certificate for 'https://oneview.example.com' into '/home/users/user1/.oneview-sdk-ruby/trusted_certs.cer'...
 Cert added to '/home/users/user1/.oneview-sdk-ruby/trusted_certs.cer'
```

##### Subscribe to the OneView State Change Message Bus (SCMB):

```bash
$ oneview-sdk-ruby scmb
$ oneview-sdk-ruby scmb -r 'scmb.ethernet-networks.#'
```
### Building the Gem
First run `$ bundle` (requires the bundler gem), then...
 - To build only, run `$ rake build`.
 - To build and install the gem, run `$ rake install`.

### Testing
 - RuboCop: `$ rake rubocop`
 - Unit: `$ rake spec`
 - Optional: Start guard to run unit tests & rubocop automatically on file changes: `$ bundle exec guard`
 - Integration: See the [spec/integration](spec/integration/) README
 - All: Run `$ rake test:all` to run RuboCop, unit, & integration tests.
 - Examples: See the [examples](examples/) README

For the full testing reference please look into [TESTING.md](TESTING.md) file.

## Getting Help 

Are you running into a road block? Have an issue with unexpected behavior? Feel free to open a new issue on the [issue tracker](https://github.com/HewlettPackard/oneview-ansible/issues)

## License
This project is licensed under the Apache 2.0 license. Please see [LICENSE](LICENSE) for more info.

## Contributing and feature requests

We welcome your contributions to the HPE OneView for Ruby SDK library. 

**Contributing:** You know the drill. Fork it, branch it, change it, commit it, and pull-request it.
We are passionate about improving this project, and glad to accept help to make it better.

NOTE: We reserve the right to reject changes that we feel do not fit the scope of this project, so for feature additions, please open an issue to discuss your ideas before doing the work.

**Feature Requests:** If you have a need that is not met by the current implementation, please let us know opening an new enhancement request/issue.
This feedback is important for us to deliver a useful product. 


## Additional Resources 

**HPE OneView Documentation**

[HPE OneView Release Notes](http://hpe.com/info/OneView/docs)

[HPE OneView Support Matrix](http://hpe.com/info/OneView/docs)

[HPE OneView Installation Guide](http://hpe.com/info/OneView/docs)

[HPE OneView User Guide](http://hpe.com/info/OneView/docs)

[HPE OneView Online Help](http://hpe.com/info/OneView/docs)

[HPE OneView REST API Reference](http://hpe.com/info/OneView/docs)

[HPE OneView Firmware Management White Paper](http://hpe.com/info/OneView/docs)

[HPE OneView Deployment and Management White Paper](http://hpe.com/info/OneView/docs)


**HPE OneView Community**

[HPE OneView Community Forums](http://hpe.com/info/oneviewcommunity)

Learn more about HPE OneView at [hpe.com/info/oneview](https://hpe.com/info/oneview)