text,length,is_long_context,metric_val,label_metric ":toc: macro toc::[] :idprefix: :idseparator: - ifdef::env-github[] :tip-caption: :bulb: :note-caption: :information_source: :important-caption: :heavy_exclamation_mark: :caution-caption: :fire: :warning-caption: :warning: endif::[] = devon4j adding Custom Functionality Now we have a fully functional blank project. All we have to do now is to create the components and services which will compose our application. First, we are going to develop the views of the app through its components, then we will create the services with the logic, security and back-end connection. [NOTE] ==== This tutorial is only going to develop a mobile view. The app is not going to be responsive or well suited for desktop use. The new https://github.com/devonfw-forge/jump-the-queue-v2[JumpTheQueue V2] implements these features, but currently no tutorial walkthrough exists for it. ==== == Creating Components [NOTE] ==== You have already learned about creating Components in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-components#create-a-new-component[here]. + You can go back and read that section again to refresh your memory. ==== Our app is going to consist of 3 main views: * Login * Register * ViewQueue To navigate between these views/components, we are going to implement routes using the Angular Router. To see our progress, move to the root folder of the `angular` project and run `ng serve -o` again. This will recompile and publish our client app to http://localhost:4200. Angular will keep watching for changes, so whenever we modify the code, the app will automatically reload. === Root Component `app.component.ts` inside `angular/src/app` will be our root component, so we don't have to create a new file yet. We are going to add elements to the root component that will be common no matter what view will be displayed. [NOTE] ==== You have already learned about the Root Component in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-components#root-component[here]. + You can go back and read that section again to refresh your memory. ==== This applies to the header element which will be on top of the window and on top of all other components. If you want, you can read more about https://teradata.github.io/covalent/#/layouts[Covalent layouts], which we are going to use a lot from now on, for every view component. [NOTE] ==== You have already learned about Covalent Layouts in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-components#teradata-covalent-layouts[here]. + You can go back and read that section again to refresh your memory. ==== We don't really need anything more than a header, so we are going to use the simplest layout for this purpose; the *nav view*. In order to be able to use Covalent and Angular Material we are going to create a core module, which we will import into every other module where we want to use Covalent and Angular Material. First, we create a folder called `shared` in the `angular/src/app` directory. Inside there we are going to create a file called `core.module.ts` and will fill it with the following content: [source, typescript] ---- import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { CommonModule } from '@angular/common'; import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { MatAutocompleteModule, MatButtonModule, MatButtonToggleModule, MatCardModule, MatCheckboxModule, MatChipsModule, MatDatepickerModule, MatDialogModule, MatExpansionModule, MatGridListModule, MatIconModule, MatInputModule, MatListModule, MatMenuModule, MatNativeDateModule, MatPaginatorModule, MatProgressBarModule, MatProgressSpinnerModule, MatRadioModule, MatRippleModule, MatSelectModule, MatSidenavModule, MatSliderModule, MatSlideToggleModule, MatSnackBarModule, MatSortModule, MatTableModule, MatTabsModule, MatToolbarModule, MatTooltipModule, } from '@angular/material'; import { CdkTableModule } from '@angular/cdk/table'; import { CovalentChipsModule, CovalentLayoutModule, CovalentExpansionPanelModule, CovalentDataTableModule, CovalentPagingModule, CovalentDialogsModule, CovalentLoadingModule, CovalentMediaModule, CovalentNotificationsModule, CovalentCommonModule, } from '@covalent/core'; @NgModule({ imports: [ RouterModule, BrowserAnimationsModule, MatCardModule, MatButtonModule, MatIconModule, CovalentMediaModule, CovalentLayoutModule, CdkTableModule, ], exports: [ CommonModule, CovalentChipsModule, CovalentLayoutModule, CovalentExpansionPanelModule, CovalentDataTableModule, CovalentPagingModule, CovalentDialogsModule, CovalentLoadingModule, CovalentMediaModule, CovalentNotificationsModule, CovalentCommonModule, CdkTableModule, MatAutocompleteModule, MatButtonModule, MatButtonToggleModule, MatCardModule, MatCheckboxModule, MatChipsModule, MatDatepickerModule, MatDialogModule, MatExpansionModule, MatGridListModule, MatIconModule, MatInputModule, MatListModule, MatMenuModule, MatNativeDateModule, MatPaginatorModule, MatProgressBarModule, MatProgressSpinnerModule, MatRadioModule, MatRippleModule, MatSelectModule, MatSidenavModule, MatSliderModule, MatSlideToggleModule, MatSnackBarModule, MatSortModule, MatTableModule, MatTabsModule, MatToolbarModule, MatTooltipModule, HttpClientModule, ], declarations: [], providers: [ HttpClientModule ], }) export class CoreModule {} ---- [NOTE] ==== This `CoreModule` has almost every module of the different components for *Angular Material* and *Covalent Teradata*. If you decide to use a component that is not included yet, you need to add the corresponding module here. ==== Remember that we need to import this `CoreModule` module into the `AppModule` and inside every module of the different components that use *Angular Material* and *Covalent Teradata*. If a component does not have a module, it will be imported in the `AppModule` and hence automatically have the `CoreModule`. Our `app.module.ts` should have the following content: [source, typescript] ---- import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; // Application components and services import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { CoreModule } from './shared/core.module'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, CoreModule, ], providers: [ ], bootstrap: [AppComponent] }) export class AppModule { } ---- [NOTE] ==== Remember this step because you will have to repeat it for every other component from Teradata you use in your app. ==== Now we can use this layout, so let's implement it in `app.component.html`. Use the following code: [source, html] ----
Jump The Queue

app works!

---- [NOTE] ==== You have already learned about Toolbars in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-components#toolbars[here]. + You can go back and read that section again to refresh your memory. ==== Once this is done, our app should have a header and ""app works!"" should appear in the body of the page: image::images/devon4ng/3.BuildYourOwn/root_header.jpg[Root Header, 250] To go a step further, we have to modify the body of the root component because it should be the *output of the router*. Now it's time to prepare the routing system. First, we need to create a component to show as default which will be our access view. We will modify it later. Stop `ng serve` and run: ---- ng generate component form-login ---- It will add a folder to our project with all the files needed for a component. Now we can move on to the router task again. Run `ng serve` again to continue the development. Let's create a module that navigates between components when the Router checks for routes. The file `app-routing.module.ts` was created automatically when we chose to include Angular Routing during project creation and we only need to modify it now: [source, typescript] ---- import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { FormLoginComponent } from './form-login/form-login.component'; const appRoutes: Routes = [ { path: 'FormLogin', component: FormLoginComponent}, // Redirect if url path is /FormLogin. { path: '**', redirectTo: '/FormLogin', pathMatch: 'full' } // Redirect if url path do not match any other route. ]; @NgModule({ imports: [ RouterModule.forRoot( appRoutes, { enableTracing: true }, // <-- debugging purposes only ), ], exports: [RouterModule], }) export class AppRoutingModule {} ---- [NOTE] ==== You have already learned about Routing in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-components#routing[here]. + You can go back and read that section again to refresh your memory. ==== Finally, we remove the `

app works!

` from `app.component.html` and replace it with a `` tag. The final result of our root component will look like this: image::images/devon4ng/3.BuildYourOwn/root_router.jpg[Root Router, 250] As you can see, now the body content is the HTML of `FormLoginComponent`. This is because we told the Router to redirect to formlogin when the path is `/FormLogin`, but also, redirect to it by default if any of the other routes match the given path. For now we are going to leave the header like this. In the future we will separate it into another component inside a layout folder. === LoginForm Component As we have already created this component from the section before, let's move on to building the template of the login view. First, we need to add the Covalent Layout and the card to the file `form-login.component.html`: [source, html] ---- Login ---- This will add a grey background to the view and a card on top of it with the title ""Login"" now that we have the basic structure of the view. Now we are going to add this image: image::images/devon4ng/3.BuildYourOwn/jumptheq.png[JumpTheQueue Logo Image, 250] In order to have it available, save it in the following path of the project: `angular/src/assets/images/` and name it `jumptheq.png`. The final code with the form added will look like this: [source, html] ---- ---- This code will give us as a result similar to this: image::images/devon4ng/3.BuildYourOwn/formlogin.png[Form Login, 250] This is going to be the container for the login. + Now we will continue with the second component: Login. === Login Component Our first step will be to create the component in the exact same way we created the `FormLogin` component but this time we are going to generate it in a new folder called components inside formlogin. Putting every child component inside that folder will allow us to keep a good and clear structure. In order to do this, we use the command: ---- ng generate component form-login/components/login ---- After _Angular/CLI_ has finished generating the component, we have to create two modules, one for the form-login and one for the login: 1.- We create a new file called `login-module.ts` in the login root: [source, typescript] ---- import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { CoreModule } from 'src/app/shared/core.module'; import { LoginComponent } from './login.component'; @NgModule({ imports: [CommonModule, CoreModule], providers: [], declarations: [LoginComponent], exports: [LoginComponent], }) export class LoginModule {} ---- 2.- We create a new file called `form-login-module.ts` in the form-login root: [source, typescript] ---- import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormLoginComponent } from './form-login.component'; import { CoreModule } from '../shared/core.module'; import { LoginModule } from './components/login/login-module'; @NgModule({ imports: [CommonModule, CoreModule, LoginModule], providers: [], declarations: [FormLoginComponent], exports: [FormLoginComponent], }) export class FormLoginModule {} ---- As you can see, the `LoginModule` is already added to the `FormLoginModule`. Once this is done, we need to remove the `FormLoginComponent` and the `LoginComponent` from the `declarations` since they are already declared in their own modules. Then add the `FormLoginModule`. This will be done inside `AppModule`: [source, typescript] ---- ... import { FormLoginModule } from './form-login/form-login-module'; ... declarations: [ AppComponent, ] imports: [ BrowserModule, FormLoginModule, CoreModule, AppRoutingModule ] ... ---- [NOTE] ==== This is done so the `form-login` (container/wrapper) and the `login` stay separated allowing us to reuse the login without having the card around in other views. ==== After this, we modify the `login.component.html` and add the form: [source, typescript] ----
---- [NOTE] ==== You have already learned about Forms in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-components#forms[here]. + You can go back and read that section again to refresh your memory. ==== This form contains two input containers from Material. The containers enclose the input with the properties listed above. We also need to add a button to send the information and redirect to the `QueueViewer` or show an error if something went wrong in the process. But for the moment, as we neither have another component nor the auth service yet, we will implement the button visually, as well as the validator to disable it if the form is not correct. We will tackle the on-click-event later. As a last step we will add this component to the `form-login-component.html`: [source, html] ---- ---- Now you should see something like this: image::images/devon4ng/3.BuildYourOwn/login.png[JumpTheQueue Login Screen, 250] With two components already created, we need to use the router to navigate between them. Following the application flow of events, we are going to add a _navigate_ function to the register button. When we press it, we will be redirected to our future register component. === Register Component First, we are going to generate the register component via: ---- ng generate component register` ---- This will create our component so we can start working on it. Turning back to `login.component.html` we have to modify these lines of code: [source, html] ----
... ... ---- Two events were added. First, when we submit the form, the method `submitLogin()` is going to be called. Second, when the user clicks the button `(click)` will send an event to the function `onRegisterClick()`. This function should be inside `login.component.ts` which is going to be created now: [source, typescript] ---- ... import { Router } from '@angular/router'; ... constructor(private router: Router) { } ... onRegisterClick(): void { this.router.navigate(['Register']); } submitLogin(): void { } ---- We need to inject an instance of the Router object and declare it with the name _router_ in order to use it in the code, as we did with `onRegisterClick()`. Doing this will use the navigate function and redirect to the next view. In our case, it will redirect using the route we are going to define in `app.routing.module.ts`: [source, typescript] ---- ... import { RegisterComponent } from './register/register.component'; ... const appRoutes: Routes = [ { path: 'FormLogin', component: FormLoginComponent}, // Redirect if url path is /FormLogin. { path: 'Register', component: RegisterComponent}, // Redirect if url path is /Register. { path: '**', redirectTo: '/FormLogin', pathMatch: 'full' } // Redirect if url path do not match any other route. ]; ... ---- [NOTE] ==== You have already learned about Dependency Injection in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-services#dependency-injection[here]. + You can go back and read that section again to refresh your memory. ==== Now we are going to imitate the `login` to shape our `register.component.html`: [source, html] ----
Accept Terms And conditions
I want to receive notifications
---- Now that we have a minimum of navigation flow inside our application, we are going to generate our first service using the command: ---- ng generate service register/services/register ---- This will create a folder ""services"" inside ""register"" and create the service itself. Services are where we keep the logic that connects to our database and fetches data which is going to be used by our `component.ts`. In order to use the service, we are going to create some interface models. Let's create a folder called `backendModels` inside ""shared"" and inside this folder a file called `interfaces.ts` in which we are going to add the model interfaces that will match our backend: [source, typescript] ---- export class Visitor { id?: number; username: string; name: string; password: string; phoneNumber: string; acceptedCommercial: boolean; acceptedTerms: boolean; userType: boolean; } ---- [NOTE] ==== You have already learned about creating new services in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-services#create-a-new-service[here]. + You can go back and read that section again to refresh your memory. ==== If we take a closer look, we can see that id has a `?` behind it. This indicates that the id is optional. [NOTE] ==== At this point we are going to assume that you have finished the https://github.com/devonfw/jump-the-queue/wiki/build-devon4j-application[devon4j] part of this tutorial, or have at least downloaded the project and have the back end running locally on http://localhost:8081. ==== After doing this, we are going to add an environment variable with our base-URL for the REST services. This way we won't have to change every URL when we switch to production. Inside `environments/environment.ts` we add: [source, typescript] ---- export const environment: {production: boolean, baseUrlRestServices: string} = { production: false, baseUrlRestServices: 'http://localhost:8081/jumpthequeue/services/rest' }; ---- Now in the service, we are going to add a `registerVisitor` method. To call the server in this method we are going to inject the Angular `HttpClient` class from `@angular/common/http`. This class is the standard used by Angular to perform HTTP calls. The register call demands a `Visitor` model which we created in the `interfaces` file. We are going to build a POST call and send the information to the proper URL of the server service. The call will return an observable: [source, typescript] ---- import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Visitor} from 'src/app/shared/backendModels/interfaces'; import { Observable } from 'rxjs'; import { environment } from 'src/environments/environment'; @Injectable({ providedIn: 'root' }) export class RegisterService { private baseUrl = environment.baseUrlRestServices; constructor(private http: HttpClient) { } registerVisitor(visitor: Visitor): Observable { return this.http.post(`${this.baseUrl}` + '/visitormanagement/v1/visitor', visitor); } } ---- This method will send our model to the backend and return an Observable that we will use on the `component.ts`. [NOTE] ==== You have already learned about Observables and RxJs in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-services#server-communication[here]. + You can go back and read that section again to refresh your memory. ==== Now we are going to modify `register.component.ts` to call this service: [source, typescript] ---- import { Component, OnInit } from '@angular/core'; import { RegisterService } from './services/register.service'; import { Visitor } from '../shared/backendModels/interfaces'; import { Router } from '@angular/router'; import { MatSnackBar } from '@angular/material/snack-bar'; @Component({ selector: 'app-register', templateUrl: './register.component.html', styleUrls: ['./register.component.scss'] }) export class RegisterComponent implements OnInit { constructor(private registerService: RegisterService, private router: Router, public snackBar: MatSnackBar) { } submitRegister(formValue): void { const visitor: Visitor = new Visitor(); visitor.username = formValue.username; visitor.name = formValue.name; visitor.phoneNumber = formValue.phoneNumber; visitor.password = formValue.password; visitor.acceptedCommercial = formValue.acceptedCommercial; visitor.acceptedTerms = formValue.acceptedTerms; visitor.userType = false; this.registerService.registerVisitor(visitor).subscribe( (visitorResult: Visitor) => console.log(JSON.stringify(visitorResult)), // When call is received (err) => this.snackBar.open(err.error.message, 'OK', { duration: 5000, }), // When theres an error ); } ngOnInit() { } } ---- In this file we injected `RegisterService` and `Router` to use them. Then, inside the method `submitRegister`, we created a visitor that we are going to pass to the service. We called the service method `registerVisitor`, we passed the visitor and we subscribed to the `Observable`, which we returned from the service. This subscription allows us to control three things: . What to do when the data is received. . What to do when there's an error. . What to do when the call is complete. Finally, we modify the `register.component.html` to send the form values to the method: [source, html] ---- ...
... ---- image::images/devon4ng/3.BuildYourOwn/register.png[Register Page, 250] Using the method and taking a look at the browser console, we should see the visitor model being returned. == Creating Services Now that we registered a `Visitor`, it's time to create 3 important services: - AuthService - AuthGuardService - LoginService The `AuthService` will be the one that contains the login info, the `AuthGuardService` will check if a user is authorized to use a component (via the `canActivate` method), and the `LoginService` will be used to fill the `AuthService`. [NOTE] ==== To keep this tutorial simple, we are going to perform the password check client side. *THIS IS NOT CORRECT!* Usually, you would send the username and password to the backend, check that the values are correct, and create a corresponding token which you would pass in the header and use it inside the `AuthService` -- checking with some interceptors that the token is both in the `AuthService` and in the request. ==== === Login, Auth and AuthGuard Services We are going to create the 3 services via `ng generate service `: . `LoginService` via: + `ng generate service form-login/components/login/services/login` . `Auth` service via: + `ng generate service core/authentication/auth` . `AuthGuard` service via: + `ng generate service core/authentication/auth-guard` After generating the services, we are going to start modyfing the interfaces. Inside `angular/src/app/shared/backendModels/interfaces` we are going to add `Role`, `FilterVisitor`, `Pageable` and a `Sort` interface: [source, typescript] ---- ... export class FilterVisitor { pageable: Pageable; username?: string; password?: string; } export class Pageable { pageSize: number; pageNumber: number; sort?: Sort[]; } export class Sort { property: string; direction: string; } export class Role { name: string; permission: number; } ---- [NOTE] ==== As you can see, we added a `Pageable`, since a lot of the search methods in the backend are using `SearchCriterias`. These need pageables which specify a `paseSize` and `pageNumber`. Also, we can see that in this case `FilterVisitor` uses a pageable and adds parameters as a filter (`username` and `password`), which are optional. ==== Then we are going to create a `config.ts` file inside the root (`angular/app`). We are going to use that file to set up default config variables, for example: role names with their permission number, default pagination settings etc. For now we are just adding the roles: [source, typescript] ---- export const config: any = { roles: [ { name: 'VISITOR', permission: 0 }, { name: 'BOSS', permission: 1 }, ], }; ---- After that, we are going to modify the `auth.service.ts`: [source, typescript] ---- import { Injectable } from '@angular/core'; import { find } from 'lodash'; import { Role } from 'src/app/shared/backendModels/interfaces'; import { config } from 'src/app/config'; @Injectable({ providedIn: 'root' }) export class AuthService { private logged = false; private user = ''; private userId = 0; private currentRole = 'NONE'; private token: string; public isLogged(): boolean { return this.logged; } public setLogged(login: boolean): void { this.logged = login; } public getUser(): string { return this.user; } public setUser(username: string): void { this.user = username; } public getUserId(): number { return this.userId; } public setUserId(userId: number): void { this.userId = userId; } public getToken(): string { return this.token; } public setToken(token: string): void { this.token = token; } public setRole(role: string): void { this.currentRole = role; } public getPermission(roleName: string): number { const role: Role = find(config.roles, { name: roleName }); return role.permission; } public isPermited(userRole: string): boolean { return ( this.getPermission(this.currentRole) === this.getPermission(userRole) ); } } ---- We will use this service to fill it with information from the logged-in user once the user logs in. This will allow us to check the information of the logged-in user in any way necessary. [NOTE] ==== You have already learned about Authentication in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-services#authentication[here]. + You can go back and read that section again to refresh your memory. ==== Now we are going to use this class to fill the `auth-guard.service.ts`: [source, typescript] ---- import { Injectable } from '@angular/core'; import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot, } from '@angular/router'; import { AuthService } from './auth.service'; @Injectable({ providedIn: 'root' }) export class AuthGuardService implements CanActivate { constructor( private authService: AuthService, private router: Router, ) {} canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot, ): boolean { if (this.authService.isLogged() && this.authService.isPermited('VISITOR')) { // If its logged in and its role is visitor return true; } if (!this.authService.isLogged()) { // if its not logged in console.log('Error login'); } if (this.router.url === '/') { // if the router is the app route this.router.navigate(['/login']); } return false; } } ---- This service will be slightly different because we have to implement an interface called `CanActivate`. It has a method called `canActivate()` returning a boolean. This method will be called when navigating to a specified route, and -- depending on the return value of this implemented method -- the navigation will proceed or be rejected. [NOTE] ==== You have already learned about Guards in devon4ng https://github.com/devonfw/jump-the-queue/wiki/devon4ng-services#guards[here]. + You can go back and read that section again to refresh your memory. ==== Once this is done, the last step is to fill the `login.service.ts`. In this case, there's going to be three methods: . `getVisitorByUsername(username: string)`: + A method that recovers a single user corresponding to the email. . `login(username: string, password: string)`: + A method, which is going to use the previous method, to check that the username and password match the form input and then fill the `AuthService`. . `logout()`: + This is going to be used to reset the `AuthService` and log out the user. Also, we see the first use of `pipe` and `map`: + `pipe` allows us to execute a chain of functions, then `map` allows us to return the single visitor instead of all the parameters that the server will send us. [source, typescript] ---- import { map, tap } from 'rxjs/operators'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { Visitor, FilterVisitor, Pageable } from 'src/app/shared/backendModels/interfaces'; import { HttpClient } from '@angular/common/http'; import { environment } from 'src/environments/environment'; import { AuthService } from 'src/app/core/authentication/auth.service'; import { Router } from '@angular/router'; import { MatSnackBar } from '@angular/material/snack-bar'; @Injectable({ providedIn: 'root' }) export class LoginService { private baseUrl = environment.baseUrlRestServices; constructor(private router: Router, private http: HttpClient, private authService: AuthService, public snackBar: MatSnackBar) { } getVisitorByUsername(username: string): Observable { const filters: FilterVisitor = new FilterVisitor(); const pageable: Pageable = new Pageable(); pageable.pageNumber = 0; pageable.pageSize = 1; filters.username = username; filters.pageable = pageable; return this.http.post(`${this.baseUrl}` + '/visitormanagement/v1/visitor/search', filters) .pipe( map(visitors => visitors['content'][0]), ); } login(username: string, password: string): void { // Checks if given username and password are the ones aved in the database this.getVisitorByUsername(username).subscribe( (visitorFound) => { if (visitorFound.username === username && visitorFound.password === password) { this.authService.setUserId(visitorFound.id); this.authService.setLogged(true); this.authService.setUser(visitorFound.username); if (visitorFound.userType === false) { this.authService.setRole('VISITOR'); this.router.navigate(['ViewQueue']); } else { this.authService.setLogged(false); this.snackBar.open('access error', 'OK', { duration: 2000, }); } } else { this.snackBar.open('access error', 'OK', { duration: 2000, }); } }, (err: any) => { this.snackBar.open('access error', 'OK', { duration: 2000, }); }, ); } logout(): void { this.authService.setLogged(false); this.authService.setUser(''); this.authService.setUserId(0); this.router.navigate(['FormLogin']); } } ---- If you remember the devon4j tutorial, we used `Criteria` in order to filter and to search the DB. The `Criteria` require a pageable and you can add extra parameters to get specific results. In `getVisitorByUsername()` you can see the creation of a `FilterVisitor` corresponding to the `Criteria` in the backend. This `FilterVisitor` gets a `Pageable` and a `username` and will return a single result as soon as the POST call is performed. That's why we return the first page and only a single result. [NOTE] ==== For the tutorial we are only considering the visitor side of the application. That's why we `setLogged(false)` if it's `userType === true` (BOSS side). ==== Then we add to the `login-module.ts` and `LoginService`: [source, typescript] ---- ... import { LoginService } from './services/login.service'; @NgModule({ ... providers: [LoginService], ... }) ... ---- After that, we are going to add the `AuthGuard` and the `Auth` into the `shared/core-module.ts`. This will allow us to employ these two services when importing the core module avoiding having to provide these services in every component: [source, typescript] ---- ... providers: [ HttpClientModule, AuthService, AuthGuardService, ], ... ---- You need to import these modules as well, as shown earlier. Finally, we modify the `login.component.html` to send the form values to the `login.component.ts` like we did with the register form. Afterwards, we are going to modify the `register.components.ts`: When the visitor registers, we can log him in automatically to avoid any nuisances. Let's start with the `login.component.html`: [source, html] ---- ... ... ---- As you can see, in the form we just added, the values to the `ngSubmit` allow us to call the method `submitLogin()` within the logic, sending the `loginForm.form.values` which are the form's input values. In the next step we are going to modify the `login.components.ts`, adding the `submitLogin()` method. This method calls the `LoginService`, providing the service with the necessary values received from the form (i.e. the `loginFormValues`). [source, typescript] ---- ... import { LoginService } from './services/login.service'; ... export class LoginComponent implements OnInit { ... constructor(private router: Router, private loginService: LoginService) { } ... submitLogin(loginFormValues): void { this.loginService.login(loginFormValues.username, loginFormValues.password); } } ---- Finally, in the `register.components.ts` we are going to inject the `LoginService` and use it to login the visitor after registering him. This will also send the user to the `ViewQueue`, which we will create and secure later in the tutorial. [source, typescript] ---- import { LoginService } from '../form-login/components/login/services/login.service'; ... constructor(private registerService: RegisterService, private router: Router, public snackBar: MatSnackBar, private loginService: LoginService) { } ... submitRegister(formValue): void { ... this.registerService.registerVisitor(visitor).subscribe( (visitorResult: Visitor) => { this.loginService.login(visitorResult.username, visitorResult.password); }, ... ); } ... ---- == Finishing Touches Now we only need to generate two more components (`header` and `view-queue`) and services (`AccessCodeService` and `QueueService`) in order to finish the implementation of our _JumpTheQueue_ app. === Separating Header from Layout By separating the header on top of the page from the layout, we enable the reuse of this component and reach a better separation of concerns across our application. To do this, we are going to generate a new component inside `angular/src/app/layout/header` via: ---- ng generate component layout/header ---- Now we are going to add it to the main view `app.component.html`: [source, html] ---- ...
... ---- After adding the component to the header view (`app-header`), we are going to modify the HTML of the component (`header.component.html`) and the logic of the component (`header.component.ts`). As a first step, we are going to modify the HTML, adding an icon as a button, which checks whether or not the user is logged in via `*ngIf` by calling the auth service's `isLogged()` method. This will make the icon appear only if the user is logged in: [source, html] ---- Jump The Queue ---- In the header logic (`header.component.ts`) we are simply going to inject the `AuthService` and `LoginService`, then we are going call `logout()` from `LoginService` in the `OnClickLogout()`. Finally, the `AuthService` is needed because it's being used by the HTML template to control if the user is logged in with `isLogged()`: [source, typescript] ---- ... constructor(private authService: AuthService, private loginService: LoginService) { } ... onClickLogout(): void { this.loginService.logout(); } ... ---- Separating components will allow us to keep the code clean and easy to work with. === ViewQueue Component For the last view, we are going to learn how to use our Observables on the HTML template directly without having to `subscribe()` to them. First, we are going to generate the component via: ---- ng generate component view-queue ---- After that, we are going to include the component in the `app-routing.module.ts`, also adding the guard, to only allow users that are `VISITOR` to see the component. It is important to insert the following code before `{ path: '**', redirectTo: '/FormLogin', pathMatch: 'full' }`: [source, typescript] ---- ... const appRoutes: Routes = [ ... { path: 'ViewQueue', component: ViewQueueComponent, canActivate: [AuthGuardService]}, // Redirect if url path is /ViewQueue, check if canActivate() with the AuthGuardService. ... ]; ... ---- Now in order to make this view work, we are going to do these things: . Add the `Queue` and `AccessCode` interface in our `angular/src/app/shared/backendModels/interfaces` and their corresponding filters. . Generate the `QueueService` and `AccessCodeService` and add the necessary methods. . Modify the `view-queue.component.html`. . Modify the logic of the component `view-queue.component.ts`. First, we are going to add the necessary interfaces. We modify `angular/src/app/shared/backendModels/interfaces.ts` and add the `FilterQueue`, `Queue`, `FilterAccessCode` and `AccessCode`. These are going to be necessary in order to communicate with the backend. [source, typescript] ---- ... export class FilterAccessCode { pageable: Pageable; visitorId?: Number; endTime?: string; } export class FilterQueue { pageable: Pageable; active: boolean; } export class AccessCode { id?: number; ticketNumber: string; creationTime: string; startTime?: string; endTime?: string; visitorId: number; queueId: number; } export class Queue { id?: number; name: string; logo: string; currentNumber: string; attentionTime: string; minAttentionTime: string; active: boolean; customers: number; } ... ---- === AccessCode and Queue Services After this is done, we are going to generate the `AccessCodeService` and the `QueueService`: ---- ng generate service view-queue/services/Queue ng generate service view-queue/services/AccessCode ---- Once this is done, we are going to modify them and add the necessary methods: - For the `AccessCodeService` we are going to need a full CRUD: [source, typescript] ---- import { Injectable } from '@angular/core'; import { AuthService } from 'src/app/core/authentication/auth.service'; import { Router } from '@angular/router'; import { HttpClient } from '@angular/common/http'; import { AccessCode, Pageable, FilterAccessCode } from 'src/app/shared/backendModels/interfaces'; import { Observable } from 'rxjs'; import { environment } from 'src/environments/environment'; import { map } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class AccessCodeService { private baseUrl = environment.baseUrlRestServices; constructor(private router: Router, private http: HttpClient, private authService: AuthService) { } getCurrentlyAttendedAccessCode(): Observable { const filters: FilterAccessCode = new FilterAccessCode(); const pageable: Pageable = new Pageable(); filters.endTime = null; pageable.pageNumber = 0; pageable.pageSize = 1; filters.pageable = pageable; return this.http.post(`${this.baseUrl}` + '/accesscodemanagement/v1/accesscode/cto/search', filters) .pipe( map(accesscodes => { if (!accesscodes['content'][0]) { // if theres no response it means theres noone in the queue return null; } else { if (accesscodes['content'][0]['accessCode'].startTime != null) { // if start time is not null it means that hes being attended return accesscodes['content'][0]['accessCode']; } else { // noone being attended return null; } } }), ); } getVisitorAccessCode(visitorId: number): Observable { const filters: FilterAccessCode = new FilterAccessCode(); const pageable: Pageable = new Pageable(); pageable.pageNumber = 0; pageable.pageSize = 1; filters.visitorId = visitorId; filters.pageable = pageable; return this.http.post(`${this.baseUrl}` + '/accesscodemanagement/v1/accesscode/cto/search', filters) .pipe( map(accesscodes => { if (accesscodes['content'][0]) { return accesscodes['content'][0]['accessCode']; } else { return null; } }), ); } deleteAccessCode(codeAccessId: number) { this.http.delete(`${this.baseUrl}` + '/accesscodemanagement/v1/accesscode/' + codeAccessId + '/').subscribe(); } saveAccessCode(visitorId: number, queueId: number) { const accessCode: AccessCode = new AccessCode(); accessCode.visitorId = visitorId; accessCode.queueId = queueId; return this.http.post(`${this.baseUrl}` + '/accesscodemanagement/v1/accesscode/', accessCode); } } ---- In the methods `getCurrentlyAttendedAccessCode` and `getVisitorAccessCode` we can see the use of `Pageable` and `FilterAccessCode` to match the `Criteria` in the backend like we explained in previous steps. In this case, the `getVisitorAccessCode` method will be used to see if the visitor has an `AccessCode` and the `getCurrentlyAttendedAccessCode` is going to recover the first `AccessCode` of the queue. - For the `QueueService` we are only going to need to find the active queue: [source, typescript] ---- import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Router } from '@angular/router'; import { Observable } from 'rxjs'; import { Queue, FilterQueue, Pageable } from 'src/app/shared/backendModels/interfaces'; import { environment } from 'src/environments/environment'; import { map } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class QueueService { private baseUrl = environment.baseUrlRestServices; constructor(private router: Router, private http: HttpClient) { } getActiveQueue(): Observable { const filters: FilterQueue = new FilterQueue(); filters.active = true; const pageable: Pageable = new Pageable(); pageable.pageNumber = 0; pageable.pageSize = 1; filters.pageable = pageable; return this.http.post(`${this.baseUrl}` + '/queuemanagement/v1/queue/search', filters) .pipe( map(queues => queues['content'][0]), ); } } ---- Now we are going to create the template `view-queue.component.html` (which will use this data) and we will also introduce a new concept: ""_async pipes in templates_"". [source, html] ----

Your Number:

{{data.accessCodeVisitor.ticketNumber}}

Currently estimate time: 10:00:00

Currently Being Attended:

{{data.accessCodeAttended?.ticketNumber}}

The queue is not active try again later

---- If you watch closely, the starting `td-layout` has an `*ngIf` inside it. This `*ngIf` allows us to asynchronously pipe the observables that we will asign in the next steps. This solution avoids having to use `subscribe()` (as it subscribes automatically) and -- as a result -- we dont have to worry about where to `unsubscribe()` from the observables. In this HTML, we give `*ngif` another use: We use it to hide certain panels. Using `accessCodeVisitor`, we hide the ticket number panel and the ""leave the queue""-button and show the button to join the queue. On the contrary we can hide the ticket number and the ""leave the queue""-button and only show the ""join the queue""-button. [NOTE] ==== In this case, since we are using HTTP and the calls are finite, there wouldn't be any problems if you dont `unsubscribe()` from their corresponding observables. However, if -- for example -- we use an observable to keep track of an input and `subscribe()` to it but not controlling the `unsubcribe()` method, the app could end up containing a memory leak. This is because -- everytime we visit the component with the input -- it is going to create another subscription without unsubscribing from the last one. ==== Finally, to adapt the async pipe, the `ngOnInit()` method inside `view-queue.component.ts` now does not subscribe to the observable. In its place, we equal the queuers variable directly to the observable, so we can load it using `*ngIf`. [source, typescript] ---- import { Component, OnInit } from '@angular/core'; import { AccessCode, Queue } from '../shared/backendModels/interfaces'; import { Observable, timer } from 'rxjs'; import { AccessCodeService } from './services/access-code.service'; import { switchMap } from 'rxjs/operators'; import { AuthService } from '../core/authentication/auth.service'; import { QueueService } from './services/queue.service'; @Component({ selector: 'app-view-queue', templateUrl: './view-queue.component.html', styleUrls: ['./view-queue.component.scss'] }) export class ViewQueueComponent implements OnInit { accessCodeAttended$: Observable; accessCodeVisitor$: Observable; queue$: Observable; constructor(private accessCodeService: AccessCodeService, private queueService: QueueService, private authService: AuthService) { } ngOnInit() { // Every minute we are going to update accessCodeAttended$ starting instantly this.accessCodeAttended$ = timer(0, 60000).pipe( // we switchMap and give it the value necesary from the accessCodeService switchMap(() => { return this.accessCodeService.getCurrentlyAttendedAccessCode(); }) ); this.accessCodeVisitor$ = this.accessCodeService.getVisitorAccessCode(this.authService.getUserId()); this.queue$ = this.queueService.getActiveQueue(); } onJoinQueue(queueId: number): void { this.accessCodeVisitor$ = this.accessCodeService.saveAccessCode(this.authService.getUserId(), queueId); } onLeaveQueue(accessCodeId: number): void { this.accessCodeService.deleteAccessCode(accessCodeId); this.accessCodeVisitor$ = null; } } ---- In this last component we assign the `Observables` when the component is initiated. After that, when clicking the ""join the queue""-button, we assign a new `Observable` called `AccessCode` to the `accessCodeVisitor$`. Finally, when we leave the queue, we delete the `AccessCode` and set the `accessCodeVisitor` to null. Since we are using an async pipe, everytime we modify the status of the `Observables`, they are going to update the template. image::images/devon4ng/3.BuildYourOwn/withCodeAccess.png[Queue Page with Access Code, 250] image::images/devon4ng/3.BuildYourOwn/withoutCodeAccess.png[Queue Page without Access Code, 250] This is all on how to build your own devon4ng application. Now it's up to you to add features, change styles and do everything you can imagine doing with this app. As a final step to complete the tutorial, however, we are going to run the app outside of our local machine by deploying it. ''' *Next Chapter*: link:devon4ng-deployment.asciidoc[Deploy your devon4ng App]",12138,False,2102.7660396701344,median "// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include ""ui/accessibility/ax_node.h"" #include #include #include ""base/debug/crash_logging.h"" #include ""base/debug/dump_without_crashing.h"" #include ""base/no_destructor.h"" #include ""base/strings/string_util.h"" #include ""base/strings/stringprintf.h"" #include ""base/strings/utf_string_conversions.h"" #include ""build/build_config.h"" #include ""ui/accessibility/ax_computed_node_data.h"" #include ""ui/accessibility/ax_enums.mojom.h"" #include ""ui/accessibility/ax_hypertext.h"" #include ""ui/accessibility/ax_language_detection.h"" #include ""ui/accessibility/ax_role_properties.h"" #include ""ui/accessibility/ax_table_info.h"" #include ""ui/accessibility/ax_tree.h"" #include ""ui/accessibility/ax_tree_manager.h"" #include ""ui/accessibility/ax_tree_manager_map.h"" #include ""ui/gfx/color_utils.h"" #include ""ui/gfx/geometry/transform.h"" namespace ui { // Definition of static class members. constexpr char16_t AXNode::kEmbeddedCharacter[]; constexpr int AXNode::kEmbeddedCharacterLength; AXNode::AXNode(AXNode::OwnerTree* tree, AXNode* parent, AXNodeID id, size_t index_in_parent, size_t unignored_index_in_parent) : tree_(tree), index_in_parent_(index_in_parent), unignored_index_in_parent_(unignored_index_in_parent), parent_(parent) { data_.id = id; } AXNode::~AXNode() = default; AXNodeData&& AXNode::TakeData() { has_data_been_taken_ = true; return std::move(data_); } const std::vector& AXNode::GetAllChildren() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); return children_; } size_t AXNode::GetChildCount() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); return children_.size(); } size_t AXNode::GetChildCountCrossingTreeBoundary() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); const AXTreeManager* child_tree_manager = AXTreeManagerMap::GetInstance().GetManagerForChildTree(*this); if (child_tree_manager) return 1u; return GetChildCount(); } size_t AXNode::GetUnignoredChildCount() const { // TODO(nektar): Should DCHECK that this node is not ignored. DCHECK(!tree_->GetTreeUpdateInProgressState()); return unignored_child_count_; } size_t AXNode::GetUnignoredChildCountCrossingTreeBoundary() const { // TODO(nektar): Should DCHECK that this node is not ignored. DCHECK(!tree_->GetTreeUpdateInProgressState()); const AXTreeManager* child_tree_manager = AXTreeManagerMap::GetInstance().GetManagerForChildTree(*this); if (child_tree_manager) { DCHECK_EQ(unignored_child_count_, 0u) << ""A node cannot be hosting both a child tree and other nodes as "" ""children.""; return 1u; // A child tree is never ignored. } return unignored_child_count_; } AXNode* AXNode::GetChildAtIndex(size_t index) const { DCHECK(!tree_->GetTreeUpdateInProgressState()); if (index >= GetChildCount()) return nullptr; return children_[index]; } AXNode* AXNode::GetChildAtIndexCrossingTreeBoundary(size_t index) const { DCHECK(!tree_->GetTreeUpdateInProgressState()); const AXTreeManager* child_tree_manager = AXTreeManagerMap::GetInstance().GetManagerForChildTree(*this); if (child_tree_manager) { DCHECK_EQ(index, 0u) << ""A node cannot be hosting both a child tree and other nodes as "" ""children.""; return child_tree_manager->GetRootAsAXNode(); } return GetChildAtIndex(index); } AXNode* AXNode::GetUnignoredChildAtIndex(size_t index) const { // TODO(nektar): Should DCHECK that this node is not ignored. DCHECK(!tree_->GetTreeUpdateInProgressState()); for (auto it = UnignoredChildrenBegin(); it != UnignoredChildrenEnd(); ++it) { if (index == 0) return it.get(); --index; } return nullptr; } AXNode* AXNode::GetUnignoredChildAtIndexCrossingTreeBoundary( size_t index) const { // TODO(nektar): Should DCHECK that this node is not ignored. DCHECK(!tree_->GetTreeUpdateInProgressState()); const AXTreeManager* child_tree_manager = AXTreeManagerMap::GetInstance().GetManagerForChildTree(*this); if (child_tree_manager) { DCHECK_EQ(index, 0u) << ""A node cannot be hosting both a child tree and other nodes as "" ""children.""; // A child tree is never ignored. return child_tree_manager->GetRootAsAXNode(); } return GetUnignoredChildAtIndex(index); } AXNode* AXNode::GetParent() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); return parent_; } AXNode* AXNode::GetParentCrossingTreeBoundary() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); if (parent_) return parent_; const AXTreeManager* manager = AXTreeManagerMap::GetInstance().GetManager(tree_->GetAXTreeID()); if (manager) return manager->GetParentNodeFromParentTreeAsAXNode(); return nullptr; } AXNode* AXNode::GetUnignoredParent() const { // TODO(crbug.com/1237353): The following bailout is to test a hypothesis that // this function is sometimes called while a tree update is in progress or // when data_ isn't valid, which may be the cause of the crash detailed in // crbug.com/1237353. Once this hypothesis has been verified, replace the // bailout with a fix, which ideally should not call this function under // the circumstances hypothesized. Also, add back in the following line: // DCHECK(!tree_->GetTreeUpdateInProgressState()); if (tree_->GetTreeUpdateInProgressState() || is_data_still_uninitialized_ || has_data_been_taken_) { static auto* const crash_key = base::debug::AllocateCrashKeyString( ""ax_node_err"", base::debug::CrashKeySize::Size64); std::ostringstream error; error << ""dataUninitialized="" << is_data_still_uninitialized_ << "" dataTaken="" << has_data_been_taken_ << "" treeUpdating="" << tree_->GetTreeUpdateInProgressState(); base::debug::SetCrashKeyString(crash_key, error.str()); base::debug::DumpWithoutCrashing(); return nullptr; } AXNode* unignored_parent = GetParent(); while (unignored_parent && unignored_parent->IsIgnored()) unignored_parent = unignored_parent->GetParent(); return unignored_parent; } AXNode* AXNode::GetUnignoredParentCrossingTreeBoundary() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); AXNode* unignored_parent = GetUnignoredParent(); if (!unignored_parent) { const AXTreeManager* manager = AXTreeManagerMap::GetInstance().GetManager(tree_->GetAXTreeID()); if (manager) unignored_parent = manager->GetParentNodeFromParentTreeAsAXNode(); } return unignored_parent; } base::stack AXNode::GetAncestorsCrossingTreeBoundary() const { base::stack ancestors; AXNode* ancestor = const_cast(this); while (ancestor) { ancestors.push(ancestor); ancestor = ancestor->GetParentCrossingTreeBoundary(); } return ancestors; } size_t AXNode::GetIndexInParent() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); return index_in_parent_; } size_t AXNode::GetUnignoredIndexInParent() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); return unignored_index_in_parent_; } AXNode* AXNode::GetFirstChild() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); return GetChildAtIndex(0); } AXNode* AXNode::GetFirstChildCrossingTreeBoundary() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); return GetChildAtIndexCrossingTreeBoundary(0); } AXNode* AXNode::GetFirstUnignoredChild() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); return ComputeFirstUnignoredChildRecursive(); } AXNode* AXNode::GetFirstUnignoredChildCrossingTreeBoundary() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); const AXTreeManager* child_tree_manager = AXTreeManagerMap::GetInstance().GetManagerForChildTree(*this); if (child_tree_manager) return child_tree_manager->GetRootAsAXNode(); return ComputeFirstUnignoredChildRecursive(); } AXNode* AXNode::GetLastChild() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); size_t n = GetChildCount(); if (n == 0) return nullptr; return GetChildAtIndex(n - 1); } AXNode* AXNode::GetLastChildCrossingTreeBoundary() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); size_t n = GetChildCountCrossingTreeBoundary(); if (n == 0) return nullptr; return GetChildAtIndexCrossingTreeBoundary(n - 1); } AXNode* AXNode::GetLastUnignoredChild() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); return ComputeLastUnignoredChildRecursive(); } AXNode* AXNode::GetLastUnignoredChildCrossingTreeBoundary() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); const AXTreeManager* child_tree_manager = AXTreeManagerMap::GetInstance().GetManagerForChildTree(*this); if (child_tree_manager) return child_tree_manager->GetRootAsAXNode(); return ComputeLastUnignoredChildRecursive(); } AXNode* AXNode::GetDeepestFirstChild() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); if (!GetChildCount()) return nullptr; AXNode* deepest_child = GetFirstChild(); while (deepest_child->GetChildCount()) deepest_child = deepest_child->GetFirstChild(); return deepest_child; } AXNode* AXNode::GetDeepestFirstUnignoredChild() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); if (!GetUnignoredChildCount()) return nullptr; AXNode* deepest_child = GetFirstUnignoredChild(); while (deepest_child->GetUnignoredChildCount()) deepest_child = deepest_child->GetFirstUnignoredChild(); return deepest_child; } AXNode* AXNode::GetDeepestLastChild() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); if (!GetChildCount()) return nullptr; AXNode* deepest_child = GetLastChild(); while (deepest_child->GetChildCount()) deepest_child = deepest_child->GetLastChild(); return deepest_child; } AXNode* AXNode::GetDeepestLastUnignoredChild() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); if (!GetUnignoredChildCount()) return nullptr; AXNode* deepest_child = GetLastUnignoredChild(); while (deepest_child->GetUnignoredChildCount()) deepest_child = deepest_child->GetLastUnignoredChild(); return deepest_child; } AXNode* AXNode::GetNextSibling() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); AXNode* parent = GetParent(); if (!parent) return nullptr; DCHECK(parent || !GetIndexInParent()) << ""Root nodes lack a parent. Their index_in_parent should be 0.""; size_t nextIndex = GetIndexInParent() + 1; if (nextIndex >= parent->GetChildCount()) return nullptr; return parent->GetChildAtIndex(nextIndex); } // Search for the next sibling of this node, skipping over any ignored nodes // encountered. // // In our search: // If we find an ignored sibling, we consider its children as our siblings. // If we run out of siblings, we consider an ignored parent's siblings as our // own siblings. // // Note: this behaviour of 'skipping over' an ignored node makes this subtly // different to finding the next (direct) sibling which is unignored. // // Consider a tree, where (i) marks a node as ignored: // // 1 // ├── 2 // ├── 3(i) // │ └── 5 // └── 4 // // The next sibling of node 2 is node 3, which is ignored. // The next unignored sibling of node 2 could be either: // 1) node 4 - next unignored sibling in the literal tree, or // 2) node 5 - next unignored sibling in the logical document. // // There is no next sibling of node 5. // The next unignored sibling of node 5 could be either: // 1) null - no next sibling in the literal tree, or // 2) node 4 - next unignored sibling in the logical document. // // In both cases, this method implements approach (2). // // TODO(chrishall): Can we remove this non-reflexive case by forbidding // GetNextUnignoredSibling calls on an ignored started node? // Note: this means that Next/Previous-UnignoredSibling are not reflexive if // either of the nodes in question are ignored. From above we get an example: // NextUnignoredSibling(3) is 4, but // PreviousUnignoredSibling(4) is 5. // // The view of unignored siblings for node 3 includes both node 2 and node 4: // 2 <-- [3(i)] --> 4 // // Whereas nodes 2, 5, and 4 do not consider node 3 to be an unignored sibling: // null <-- [2] --> 5 // 2 <-- [5] --> 4 // 5 <-- [4] --> null AXNode* AXNode::GetNextUnignoredSibling() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); const AXNode* current = this; // If there are children of the |current| node still to consider. bool considerChildren = false; while (current) { // A |candidate| sibling to consider. // If it is unignored then we have found our result. // Otherwise promote it to |current| and consider its children. AXNode* candidate; if (considerChildren && (candidate = current->GetFirstChild())) { if (!candidate->IsIgnored()) return candidate; current = candidate; } else if ((candidate = current->GetNextSibling())) { if (!candidate->IsIgnored()) return candidate; current = candidate; // Look through the ignored candidate node to consider their children as // though they were siblings. considerChildren = true; } else { // Continue our search through a parent iff they are ignored. // // If |current| has an ignored parent, then we consider the parent's // siblings as though they were siblings of |current|. // // Given a tree: // 1 // ├── 2(?) // │ └── [4] // └── 3 // // Node 4's view of siblings: // literal tree: null <-- [4] --> null // // If node 2 is not ignored, then node 4's view doesn't change, and we // have no more nodes to consider: // unignored tree: null <-- [4] --> null // // If instead node 2 is ignored, then node 4's view of siblings grows to // include node 3, and we have more nodes to consider: // unignored tree: null <-- [4] --> 3 current = current->GetParent(); if (!current || !current->IsIgnored()) return nullptr; // We have already considered all relevant descendants of |current|. considerChildren = false; } } return nullptr; } AXNode* AXNode::GetPreviousSibling() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); DCHECK(GetParent() || !GetIndexInParent()) << ""Root nodes lack a parent. Their index_in_parent should be 0.""; size_t index = GetIndexInParent(); if (index == 0) return nullptr; return GetParent()->GetChildAtIndex(index - 1); } // Search for the previous sibling of this node, skipping over any ignored nodes // encountered. // // In our search for a sibling: // If we find an ignored sibling, we may consider its children as siblings. // If we run out of siblings, we may consider an ignored parent's siblings as // our own. // // See the documentation for |GetNextUnignoredSibling| for more details. AXNode* AXNode::GetPreviousUnignoredSibling() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); const AXNode* current = this; // If there are children of the |current| node still to consider. bool considerChildren = false; while (current) { // A |candidate| sibling to consider. // If it is unignored then we have found our result. // Otherwise promote it to |current| and consider its children. AXNode* candidate; if (considerChildren && (candidate = current->GetLastChild())) { if (!candidate->IsIgnored()) return candidate; current = candidate; } else if ((candidate = current->GetPreviousSibling())) { if (!candidate->IsIgnored()) return candidate; current = candidate; // Look through the ignored candidate node to consider their children as // though they were siblings. considerChildren = true; } else { // Continue our search through a parent iff they are ignored. // // If |current| has an ignored parent, then we consider the parent's // siblings as though they were siblings of |current|. // // Given a tree: // 1 // ├── 2 // └── 3(?) // └── [4] // // Node 4's view of siblings: // literal tree: null <-- [4] --> null // // If node 3 is not ignored, then node 4's view doesn't change, and we // have no more nodes to consider: // unignored tree: null <-- [4] --> null // // If instead node 3 is ignored, then node 4's view of siblings grows to // include node 2, and we have more nodes to consider: // unignored tree: 2 <-- [4] --> null current = current->GetParent(); if (!current || !current->IsIgnored()) return nullptr; // We have already considered all relevant descendants of |current|. considerChildren = false; } } return nullptr; } AXNode* AXNode::GetNextUnignoredInTreeOrder() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); if (GetUnignoredChildCount()) return GetFirstUnignoredChild(); const AXNode* node = this; while (node) { AXNode* sibling = node->GetNextUnignoredSibling(); if (sibling) return sibling; node = node->GetUnignoredParent(); } return nullptr; } AXNode* AXNode::GetPreviousUnignoredInTreeOrder() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); AXNode* sibling = GetPreviousUnignoredSibling(); if (!sibling) return GetUnignoredParent(); if (sibling->GetUnignoredChildCount()) return sibling->GetDeepestLastUnignoredChild(); return sibling; } AXNode::AllChildIterator AXNode::AllChildrenBegin() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); return AllChildIterator(this, GetFirstChild()); } AXNode::AllChildIterator AXNode::AllChildrenEnd() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); return AllChildIterator(this, nullptr); } AXNode::AllChildCrossingTreeBoundaryIterator AXNode::AllChildrenCrossingTreeBoundaryBegin() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); return AllChildCrossingTreeBoundaryIterator( this, GetFirstChildCrossingTreeBoundary()); } AXNode::AllChildCrossingTreeBoundaryIterator AXNode::AllChildrenCrossingTreeBoundaryEnd() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); return AllChildCrossingTreeBoundaryIterator(this, nullptr); } AXNode::UnignoredChildIterator AXNode::UnignoredChildrenBegin() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); return UnignoredChildIterator(this, GetFirstUnignoredChild()); } AXNode::UnignoredChildIterator AXNode::UnignoredChildrenEnd() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); return UnignoredChildIterator(this, nullptr); } AXNode::UnignoredChildCrossingTreeBoundaryIterator AXNode::UnignoredChildrenCrossingTreeBoundaryBegin() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); return UnignoredChildCrossingTreeBoundaryIterator( this, GetFirstUnignoredChildCrossingTreeBoundary()); } AXNode::UnignoredChildCrossingTreeBoundaryIterator AXNode::UnignoredChildrenCrossingTreeBoundaryEnd() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); return UnignoredChildCrossingTreeBoundaryIterator(this, nullptr); } absl::optional AXNode::CompareTo(const AXNode& other) const { if (this == &other) return 0; AXNode* common_ancestor = nullptr; base::stack our_ancestors = GetAncestorsCrossingTreeBoundary(); base::stack other_ancestors = other.GetAncestorsCrossingTreeBoundary(); while (!our_ancestors.empty() && !other_ancestors.empty() && our_ancestors.top() == other_ancestors.top()) { common_ancestor = our_ancestors.top(); our_ancestors.pop(); other_ancestors.pop(); } if (!common_ancestor) return absl::nullopt; if (common_ancestor == this) return -1; if (common_ancestor == &other) return 1; if (our_ancestors.empty() || other_ancestors.empty()) { NOTREACHED() << ""The common ancestor should be followed by two uncommon "" ""children in the two corresponding lists of ancestors.""; return absl::nullopt; } size_t this_uncommon_ancestor_index = our_ancestors.top()->GetIndexInParent(); size_t other_uncommon_ancestor_index = other_ancestors.top()->GetIndexInParent(); DCHECK_NE(this_uncommon_ancestor_index, other_uncommon_ancestor_index) << ""Deepest uncommon ancestors should truly be uncommon, i.e. not be the "" ""same node.""; return this_uncommon_ancestor_index - other_uncommon_ancestor_index; } bool AXNode::IsText() const { // Regular list markers only expose their alternative text, but do not expose // their descendants; and the descendants should be ignored. This is because // the alternative text depends on the counter style and can be different from // the actual (visual) marker text, and hence, inconsistent with the // descendants. We treat a list marker as non-text only if it still has // non-ignored descendants, which happens only when: // - The list marker itself is ignored but the descendants are not // - Or the list marker contains images if (GetRole() == ax::mojom::Role::kListMarker) return !GetUnignoredChildCount(); return ui::IsText(GetRole()); } bool AXNode::IsLineBreak() const { // The last condition captures inline text nodes whose only content is an '\\n' // character. return GetRole() == ax::mojom::Role::kLineBreak || (GetRole() == ax::mojom::Role::kInlineTextBox && GetBoolAttribute(ax::mojom::BoolAttribute::kIsLineBreakingObject)); } void AXNode::SetData(const AXNodeData& src) { data_ = src; is_data_still_uninitialized_ = false; has_data_been_taken_ = false; } void AXNode::SetLocation(AXNodeID offset_container_id, const gfx::RectF& location, gfx::Transform* transform) { data_.relative_bounds.offset_container_id = offset_container_id; data_.relative_bounds.bounds = location; if (transform) { data_.relative_bounds.transform = std::make_unique(*transform); } else { data_.relative_bounds.transform.reset(); } } void AXNode::SetIndexInParent(size_t index_in_parent) { index_in_parent_ = index_in_parent; } void AXNode::UpdateUnignoredCachedValues() { computed_node_data_.reset(); if (!IsIgnored()) UpdateUnignoredCachedValuesRecursive(0); } void AXNode::SwapChildren(std::vector* children) { children->swap(children_); } void AXNode::Destroy() { delete this; } bool AXNode::IsDescendantOf(const AXNode* ancestor) const { if (!ancestor) return false; if (this == ancestor) return true; if (const AXNode* parent = GetParent()) return parent->IsDescendantOf(ancestor); return false; } bool AXNode::IsDescendantOfCrossingTreeBoundary(const AXNode* ancestor) const { if (!ancestor) return false; if (this == ancestor) return true; if (const AXNode* parent = GetParentCrossingTreeBoundary()) return parent->IsDescendantOfCrossingTreeBoundary(ancestor); return false; } std::vector AXNode::GetOrComputeLineStartOffsets() { DCHECK(!tree_->GetTreeUpdateInProgressState()); std::vector line_offsets; if (GetIntListAttribute(ax::mojom::IntListAttribute::kLineStarts, &line_offsets)) { return line_offsets; } int start_offset = 0; ComputeLineStartOffsets(&line_offsets, &start_offset); data_.AddIntListAttribute(ax::mojom::IntListAttribute::kLineStarts, line_offsets); return line_offsets; } void AXNode::ComputeLineStartOffsets(std::vector* line_offsets, int* start_offset) const { DCHECK(!tree_->GetTreeUpdateInProgressState()); DCHECK(line_offsets); DCHECK(start_offset); for (auto iter = AllChildrenCrossingTreeBoundaryBegin(); iter != AllChildrenCrossingTreeBoundaryEnd(); ++iter) { if (iter->GetChildCountCrossingTreeBoundary()) { iter->ComputeLineStartOffsets(line_offsets, start_offset); continue; } // Don't report if the first piece of text starts a new line or not. if (*start_offset && !iter->HasIntAttribute(ax::mojom::IntAttribute::kPreviousOnLineId)) { // If there are multiple objects with an empty accessible label at the // start of a line, only include a single line start offset. if (line_offsets->empty() || line_offsets->back() != *start_offset) line_offsets->push_back(*start_offset); } std::u16string text = iter->GetString16Attribute(ax::mojom::StringAttribute::kName); *start_offset += static_cast(text.length()); } } SkColor AXNode::ComputeColor() const { return ComputeColorAttribute(ax::mojom::IntAttribute::kColor); } SkColor AXNode::ComputeBackgroundColor() const { return ComputeColorAttribute(ax::mojom::IntAttribute::kBackgroundColor); } SkColor AXNode::ComputeColorAttribute(ax::mojom::IntAttribute attr) const { SkColor color = GetIntAttribute(attr); AXNode* ancestor = GetParent(); // If the color has some transparency, keep blending with background // colors until we get an opaque color or reach the root. while (ancestor && SkColorGetA(color) != SK_AlphaOPAQUE) { SkColor background_color = ancestor->GetIntAttribute(attr); color = color_utils::GetResultingPaintColor(color, background_color); ancestor = ancestor->GetParent(); } return color; } bool AXNode::HasStringAttribute(ax::mojom::StringAttribute attribute) const { return GetComputedNodeData().HasOrCanComputeAttribute(attribute); } const std::string& AXNode::GetStringAttribute( ax::mojom::StringAttribute attribute) const { return GetComputedNodeData().GetOrComputeAttributeUTF8(attribute); } bool AXNode::GetStringAttribute(ax::mojom::StringAttribute attribute, std::string* value) const { if (GetComputedNodeData().HasOrCanComputeAttribute(attribute)) { *value = GetComputedNodeData().GetOrComputeAttributeUTF8(attribute); return true; } return false; } std::u16string AXNode::GetString16Attribute( ax::mojom::StringAttribute attribute) const { return GetComputedNodeData().GetOrComputeAttributeUTF16(attribute); } bool AXNode::GetString16Attribute(ax::mojom::StringAttribute attribute, std::u16string* value) const { if (GetComputedNodeData().HasOrCanComputeAttribute(attribute)) { *value = GetComputedNodeData().GetOrComputeAttributeUTF16(attribute); return true; } return false; } bool AXNode::HasInheritedStringAttribute( ax::mojom::StringAttribute attribute) const { for (const AXNode* current_node = this; current_node; current_node = current_node->GetParent()) { if (current_node->HasStringAttribute(attribute)) return true; } return false; } const std::string& AXNode::GetInheritedStringAttribute( ax::mojom::StringAttribute attribute) const { for (const AXNode* current_node = this; current_node; current_node = current_node->GetParent()) { if (current_node->HasStringAttribute(attribute)) return current_node->GetStringAttribute(attribute); } return base::EmptyString(); } std::u16string AXNode::GetInheritedString16Attribute( ax::mojom::StringAttribute attribute) const { return base::UTF8ToUTF16(GetInheritedStringAttribute(attribute)); } AXLanguageInfo* AXNode::GetLanguageInfo() const { return language_info_.get(); } void AXNode::SetLanguageInfo(std::unique_ptr lang_info) { language_info_ = std::move(lang_info); } void AXNode::ClearLanguageInfo() { language_info_.reset(); } const AXComputedNodeData& AXNode::GetComputedNodeData() const { if (!computed_node_data_) computed_node_data_ = std::make_unique(*this); return *computed_node_data_; } void AXNode::ClearComputedNodeData() { computed_node_data_.reset(); } const std::string& AXNode::GetNameUTF8() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); const AXNode* node = this; if (GetRole() == ax::mojom::Role::kPortal && GetNameFrom() == ax::mojom::NameFrom::kNone) { const AXTreeManager* child_tree_manager = AXTreeManagerMap::GetInstance().GetManagerForChildTree(*this); if (child_tree_manager) node = child_tree_manager->GetRootAsAXNode(); } return node->GetStringAttribute(ax::mojom::StringAttribute::kName); } std::u16string AXNode::GetNameUTF16() const { // Storing a copy of the name in UTF16 would probably not be helpful because // it could potentially double the memory usage of AXTree. return base::UTF8ToUTF16(GetNameUTF8()); } const std::u16string& AXNode::GetHypertext() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); // TODO(nektar): Introduce proper caching of hypertext via // `AXHypertext::needs_update`. hypertext_ = AXHypertext(); // Hypertext is not exposed for descendants of leaf nodes. For such nodes, // their inner text is equivalent to their hypertext. Otherwise, we would // never be able to compute equivalent ancestor positions in atomic text // fields given an AXPosition on an inline text box descendant, because there // is often an ignored generic container between the text descendants and the // text field node. // // For example, look at the following accessibility tree and the text // positions indicated using ""<>"" symbols in the inner text of every node, and // then imagine what would happen if the generic container was represented by // an ""embedded object replacement character"" in the text of its text field // parent. // ++kTextField ""Hell"" IsLeaf=true // ++++kGenericContainer ""Hell"" ignored IsChildOfLeaf=true // ++++++kStaticText ""Hell"" IsChildOfLeaf=true // ++++++++kInlineTextBox ""Hell"" IsChildOfLeaf=true if (IsLeaf() || IsChildOfLeaf()) { hypertext_.hypertext = base::UTF8ToUTF16(GetInnerText()); } else { // Construct the hypertext for this node, which contains the concatenation // of the inner text of this node's textual children, and an ""object // replacement character"" for all the other children. // // Note that the word ""hypertext"" comes from the IAccessible2 Standard and // has nothing to do with HTML. static const base::NoDestructor embedded_character_str( AXNode::kEmbeddedCharacter); auto first = UnignoredChildrenCrossingTreeBoundaryBegin(); for (auto iter = first; iter != UnignoredChildrenCrossingTreeBoundaryEnd(); ++iter) { // Similar to Firefox, we don't expose text nodes in IAccessible2 and ATK // hypertext with the embedded object character. We copy all of their text // instead. if (iter->IsText()) { hypertext_.hypertext += iter->GetInnerTextUTF16(); } else { int character_offset = static_cast(hypertext_.hypertext.size()); auto inserted = hypertext_.hypertext_offset_to_hyperlink_child_index.emplace( character_offset, static_cast(std::distance(first, iter))); DCHECK(inserted.second) << ""An embedded object at "" << character_offset << "" has already been encountered.""; hypertext_.hypertext += *embedded_character_str; } } } hypertext_.needs_update = false; return hypertext_.hypertext; } void AXNode::SetNeedsToUpdateHypertext() { old_hypertext_ = hypertext_; hypertext_.needs_update = true; // TODO(nektar): Introduce proper caching of hypertext via // `AXHypertext::needs_update`. GetHypertext(); // Forces `hypertext_` to immediately update. } const std::map& AXNode::GetHypertextOffsetToHyperlinkChildIndex() const { // TODO(nektar): Introduce proper caching of hypertext via // `AXHypertext::needs_update`. GetHypertext(); // Update `hypertext_` if not up-to-date. return hypertext_.hypertext_offset_to_hyperlink_child_index; } const AXHypertext& AXNode::GetOldHypertext() const { // TODO(nektar): Introduce proper caching of hypertext via // `AXHypertext::needs_update`. GetHypertext(); // Update `hypertext_` if not up-to-date. return old_hypertext_; } const std::string& AXNode::GetInnerText() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); return GetComputedNodeData().GetOrComputeTextContentUTF8(); } const std::u16string& AXNode::GetInnerTextUTF16() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); return GetComputedNodeData().GetOrComputeTextContentUTF16(); } int AXNode::GetInnerTextLength() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); return GetComputedNodeData().GetOrComputeTextContentLengthUTF8(); } int AXNode::GetInnerTextLengthUTF16() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); return GetComputedNodeData().GetOrComputeTextContentLengthUTF16(); } std::string AXNode::GetLanguage() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); // Walk up tree considering both detected and author declared languages. for (const AXNode* cur = this; cur; cur = cur->GetParent()) { // If language detection has assigned a language then we prefer that. const AXLanguageInfo* lang_info = cur->GetLanguageInfo(); if (lang_info && !lang_info->language.empty()) return lang_info->language; // If the page author has declared a language attribute we fallback to that. if (cur->HasStringAttribute(ax::mojom::StringAttribute::kLanguage)) return cur->GetStringAttribute(ax::mojom::StringAttribute::kLanguage); } return std::string(); } std::string AXNode::GetValueForControl() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); if (data().IsTextField()) return GetValueForTextField(); if (data().IsRangeValueSupported()) return GetTextForRangeValue(); if (GetRole() == ax::mojom::Role::kColorWell) return GetValueForColorWell(); if (!IsControl(GetRole())) return std::string(); return GetStringAttribute(ax::mojom::StringAttribute::kValue); } std::ostream& operator<<(std::ostream& stream, const AXNode& node) { return stream << node.data().ToString(); } bool AXNode::IsTable() const { return IsTableLike(GetRole()); } absl::optional AXNode::GetTableColCount() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); const AXTableInfo* table_info = GetAncestorTableInfo(); if (!table_info) return absl::nullopt; return static_cast(table_info->col_count); } absl::optional AXNode::GetTableRowCount() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); const AXTableInfo* table_info = GetAncestorTableInfo(); if (!table_info) return absl::nullopt; return static_cast(table_info->row_count); } absl::optional AXNode::GetTableAriaColCount() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); const AXTableInfo* table_info = GetAncestorTableInfo(); if (!table_info) return absl::nullopt; return absl::make_optional(table_info->aria_col_count); } absl::optional AXNode::GetTableAriaRowCount() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); const AXTableInfo* table_info = GetAncestorTableInfo(); if (!table_info) return absl::nullopt; return absl::make_optional(table_info->aria_row_count); } absl::optional AXNode::GetTableCellCount() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); const AXTableInfo* table_info = GetAncestorTableInfo(); if (!table_info) return absl::nullopt; return static_cast(table_info->unique_cell_ids.size()); } absl::optional AXNode::GetTableHasColumnOrRowHeaderNode() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); const AXTableInfo* table_info = GetAncestorTableInfo(); if (!table_info) return absl::nullopt; return !table_info->all_headers.empty(); } AXNode* AXNode::GetTableCellFromIndex(int index) const { DCHECK(!tree_->GetTreeUpdateInProgressState()); const AXTableInfo* table_info = GetAncestorTableInfo(); if (!table_info) return nullptr; // There is a table but there is no cell with the given index. if (index < 0 || static_cast(index) >= table_info->unique_cell_ids.size()) { return nullptr; } return tree_->GetFromId( table_info->unique_cell_ids[static_cast(index)]); } AXNode* AXNode::GetTableCaption() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); const AXTableInfo* table_info = GetAncestorTableInfo(); if (!table_info) return nullptr; return tree_->GetFromId(table_info->caption_id); } AXNode* AXNode::GetTableCellFromCoords(int row_index, int col_index) const { DCHECK(!tree_->GetTreeUpdateInProgressState()); const AXTableInfo* table_info = GetAncestorTableInfo(); if (!table_info) return nullptr; // There is a table but the given coordinates are outside the table. if (row_index < 0 || static_cast(row_index) >= table_info->row_count || col_index < 0 || static_cast(col_index) >= table_info->col_count) { return nullptr; } return tree_->GetFromId(table_info->cell_ids[static_cast(row_index)] [static_cast(col_index)]); } std::vector AXNode::GetTableColHeaderNodeIds() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); const AXTableInfo* table_info = GetAncestorTableInfo(); if (!table_info) return std::vector(); std::vector col_header_ids; // Flatten and add column header ids of each column to |col_header_ids|. for (std::vector col_headers_at_index : table_info->col_headers) { col_header_ids.insert(col_header_ids.end(), col_headers_at_index.begin(), col_headers_at_index.end()); } return col_header_ids; } std::vector AXNode::GetTableColHeaderNodeIds(int col_index) const { DCHECK(!tree_->GetTreeUpdateInProgressState()); const AXTableInfo* table_info = GetAncestorTableInfo(); if (!table_info) return std::vector(); if (col_index < 0 || static_cast(col_index) >= table_info->col_count) return std::vector(); return std::vector( table_info->col_headers[static_cast(col_index)]); } std::vector AXNode::GetTableRowHeaderNodeIds(int row_index) const { DCHECK(!tree_->GetTreeUpdateInProgressState()); const AXTableInfo* table_info = GetAncestorTableInfo(); if (!table_info) return std::vector(); if (row_index < 0 || static_cast(row_index) >= table_info->row_count) return std::vector(); return std::vector( table_info->row_headers[static_cast(row_index)]); } std::vector AXNode::GetTableUniqueCellIds() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); const AXTableInfo* table_info = GetAncestorTableInfo(); if (!table_info) return std::vector(); return std::vector(table_info->unique_cell_ids); } const std::vector* AXNode::GetExtraMacNodes() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); // Should only be available on the table node itself, not any of its children. const AXTableInfo* table_info = tree_->GetTableInfo(this); if (!table_info) return nullptr; return &table_info->extra_mac_nodes; } // // Table row-like nodes. // bool AXNode::IsTableRow() const { return ui::IsTableRow(GetRole()); } absl::optional AXNode::GetTableRowRowIndex() const { if (!IsTableRow()) return absl::nullopt; const AXTableInfo* table_info = GetAncestorTableInfo(); if (!table_info) return absl::nullopt; const auto& iter = table_info->row_id_to_index.find(id()); if (iter == table_info->row_id_to_index.end()) return absl::nullopt; return static_cast(iter->second); } std::vector AXNode::GetTableRowNodeIds() const { std::vector row_node_ids; const AXTableInfo* table_info = GetAncestorTableInfo(); if (!table_info) return row_node_ids; for (AXNode* node : table_info->row_nodes) row_node_ids.push_back(node->id()); return row_node_ids; } #if defined(OS_APPLE) // // Table column-like nodes. These nodes are only present on macOS. // bool AXNode::IsTableColumn() const { return ui::IsTableColumn(GetRole()); } absl::optional AXNode::GetTableColColIndex() const { if (!IsTableColumn()) return absl::nullopt; const AXTableInfo* table_info = GetAncestorTableInfo(); if (!table_info) return absl::nullopt; int index = 0; for (const AXNode* node : table_info->extra_mac_nodes) { if (node == this) break; index++; } return index; } #endif // defined(OS_APPLE) // // Table cell-like nodes. // bool AXNode::IsTableCellOrHeader() const { return IsCellOrTableHeader(GetRole()); } absl::optional AXNode::GetTableCellIndex() const { if (!IsTableCellOrHeader()) return absl::nullopt; const AXTableInfo* table_info = GetAncestorTableInfo(); if (!table_info) return absl::nullopt; const auto& iter = table_info->cell_id_to_index.find(id()); if (iter != table_info->cell_id_to_index.end()) return static_cast(iter->second); return absl::nullopt; } absl::optional AXNode::GetTableCellColIndex() const { const AXTableInfo* table_info = GetAncestorTableInfo(); if (!table_info) return absl::nullopt; absl::optional index = GetTableCellIndex(); if (!index) return absl::nullopt; return static_cast(table_info->cell_data_vector[*index].col_index); } absl::optional AXNode::GetTableCellRowIndex() const { const AXTableInfo* table_info = GetAncestorTableInfo(); if (!table_info) return absl::nullopt; absl::optional index = GetTableCellIndex(); if (!index) return absl::nullopt; return static_cast(table_info->cell_data_vector[*index].row_index); } absl::optional AXNode::GetTableCellColSpan() const { // If it's not a table cell, don't return a col span. if (!IsTableCellOrHeader()) return absl::nullopt; // Otherwise, try to return a colspan, with 1 as the default if it's not // specified. int col_span; if (GetIntAttribute(ax::mojom::IntAttribute::kTableCellColumnSpan, &col_span)) return col_span; return 1; } absl::optional AXNode::GetTableCellRowSpan() const { // If it's not a table cell, don't return a row span. if (!IsTableCellOrHeader()) return absl::nullopt; // Otherwise, try to return a row span, with 1 as the default if it's not // specified. int row_span; if (GetIntAttribute(ax::mojom::IntAttribute::kTableCellRowSpan, &row_span)) return row_span; return 1; } absl::optional AXNode::GetTableCellAriaColIndex() const { const AXTableInfo* table_info = GetAncestorTableInfo(); if (!table_info) return absl::nullopt; absl::optional index = GetTableCellIndex(); if (!index) return absl::nullopt; int aria_col_index = static_cast(table_info->cell_data_vector[*index].aria_col_index); // |aria-colindex| attribute is one-based, value less than 1 is invalid. // https://www.w3.org/TR/wai-aria-1.2/#aria-colindex return (aria_col_index > 0) ? absl::optional(aria_col_index) : absl::nullopt; } absl::optional AXNode::GetTableCellAriaRowIndex() const { const AXTableInfo* table_info = GetAncestorTableInfo(); if (!table_info) return absl::nullopt; absl::optional index = GetTableCellIndex(); if (!index) return absl::nullopt; int aria_row_index = static_cast(table_info->cell_data_vector[*index].aria_row_index); // |aria-rowindex| attribute is one-based, value less than 1 is invalid. // https://www.w3.org/TR/wai-aria-1.2/#aria-rowindex return (aria_row_index > 0) ? absl::optional(aria_row_index) : absl::nullopt; } std::vector AXNode::GetTableCellColHeaderNodeIds() const { const AXTableInfo* table_info = GetAncestorTableInfo(); if (!table_info || table_info->col_count <= 0) return std::vector(); // If this node is not a cell, then return the headers for the first column. int col_index = GetTableCellColIndex().value_or(0); return std::vector(table_info->col_headers[col_index]); } void AXNode::GetTableCellColHeaders(std::vector* col_headers) const { DCHECK(col_headers); std::vector col_header_ids = GetTableCellColHeaderNodeIds(); IdVectorToNodeVector(col_header_ids, col_headers); } std::vector AXNode::GetTableCellRowHeaderNodeIds() const { const AXTableInfo* table_info = GetAncestorTableInfo(); if (!table_info || table_info->row_count <= 0) return std::vector(); // If this node is not a cell, then return the headers for the first row. int row_index = GetTableCellRowIndex().value_or(0); return std::vector(table_info->row_headers[row_index]); } void AXNode::GetTableCellRowHeaders(std::vector* row_headers) const { DCHECK(row_headers); std::vector row_header_ids = GetTableCellRowHeaderNodeIds(); IdVectorToNodeVector(row_header_ids, row_headers); } bool AXNode::IsCellOrHeaderOfAriaGrid() const { if (!IsTableCellOrHeader()) return false; const AXNode* node = this; while (node && !node->IsTable()) node = node->GetParent(); if (!node) return false; return node->GetRole() == ax::mojom::Role::kGrid || node->GetRole() == ax::mojom::Role::kTreeGrid; } AXTableInfo* AXNode::GetAncestorTableInfo() const { const AXNode* node = this; while (node && !node->IsTable()) node = node->GetParent(); if (node) return tree_->GetTableInfo(node); return nullptr; } void AXNode::IdVectorToNodeVector(const std::vector& ids, std::vector* nodes) const { for (AXNodeID id : ids) { AXNode* node = tree_->GetFromId(id); if (node) nodes->push_back(node); } } absl::optional AXNode::GetHierarchicalLevel() const { int hierarchical_level = GetIntAttribute(ax::mojom::IntAttribute::kHierarchicalLevel); // According to the WAI_ARIA spec, a defined hierarchical level value is // greater than 0. // https://www.w3.org/TR/wai-aria-1.1/#aria-level if (hierarchical_level > 0) return hierarchical_level; return absl::nullopt; } bool AXNode::IsOrderedSetItem() const { return ui::IsItemLike(GetRole()); } bool AXNode::IsOrderedSet() const { return ui::IsSetLike(GetRole()); } // Uses AXTree's cache to calculate node's PosInSet. absl::optional AXNode::GetPosInSet() { return tree_->GetPosInSet(*this); } // Uses AXTree's cache to calculate node's SetSize. absl::optional AXNode::GetSetSize() { return tree_->GetSetSize(*this); } // Returns true if the role of ordered set matches the role of item. // Returns false otherwise. bool AXNode::SetRoleMatchesItemRole(const AXNode* ordered_set) const { ax::mojom::Role item_role = GetRole(); // Switch on role of ordered set switch (ordered_set->GetRole()) { case ax::mojom::Role::kFeed: return item_role == ax::mojom::Role::kArticle; case ax::mojom::Role::kList: return item_role == ax::mojom::Role::kListItem; case ax::mojom::Role::kGroup: return item_role == ax::mojom::Role::kComment || item_role == ax::mojom::Role::kListItem || item_role == ax::mojom::Role::kMenuItem || item_role == ax::mojom::Role::kMenuItemRadio || item_role == ax::mojom::Role::kListBoxOption || item_role == ax::mojom::Role::kTreeItem; case ax::mojom::Role::kMenu: return item_role == ax::mojom::Role::kMenuItem || item_role == ax::mojom::Role::kMenuItemRadio || item_role == ax::mojom::Role::kMenuItemCheckBox; case ax::mojom::Role::kMenuBar: return item_role == ax::mojom::Role::kMenuItem || item_role == ax::mojom::Role::kMenuItemRadio || item_role == ax::mojom::Role::kMenuItemCheckBox; case ax::mojom::Role::kTabList: return item_role == ax::mojom::Role::kTab; case ax::mojom::Role::kTree: return item_role == ax::mojom::Role::kTreeItem; case ax::mojom::Role::kListBox: return item_role == ax::mojom::Role::kListBoxOption; case ax::mojom::Role::kMenuListPopup: return item_role == ax::mojom::Role::kMenuListOption || item_role == ax::mojom::Role::kMenuItem || item_role == ax::mojom::Role::kMenuItemRadio || item_role == ax::mojom::Role::kMenuItemCheckBox; case ax::mojom::Role::kRadioGroup: return item_role == ax::mojom::Role::kRadioButton; case ax::mojom::Role::kDescriptionList: // Only the term for each description list entry should receive posinset // and setsize. return item_role == ax::mojom::Role::kDescriptionListTerm || item_role == ax::mojom::Role::kTerm; case ax::mojom::Role::kPopUpButton: // kPopUpButtons can wrap a kMenuListPopUp. return item_role == ax::mojom::Role::kMenuListPopup; default: return false; } } bool AXNode::IsIgnoredContainerForOrderedSet() const { return IsIgnored() || IsEmbeddedGroup() || GetRole() == ax::mojom::Role::kLabelText || GetRole() == ax::mojom::Role::kListItem || GetRole() == ax::mojom::Role::kGenericContainer || GetRole() == ax::mojom::Role::kUnknown; } int AXNode::UpdateUnignoredCachedValuesRecursive(int startIndex) { int count = 0; for (AXNode* child : children()) { if (child->IsIgnored()) { child->unignored_index_in_parent_ = 0; count += child->UpdateUnignoredCachedValuesRecursive(startIndex + count); } else { child->unignored_index_in_parent_ = startIndex + count++; } } unignored_child_count_ = count; return count; } // Finds ordered set that contains node. // Is not required for set's role to match node's role. AXNode* AXNode::GetOrderedSet() const { AXNode* result = GetParent(); // Continue walking up while parent is invalid, ignored, a generic container, // unknown, or embedded group. while (result && result->IsIgnoredContainerForOrderedSet()) { result = result->GetParent(); } return result; } AXNode* AXNode::ComputeLastUnignoredChildRecursive() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); if (children().empty()) return nullptr; for (int i = static_cast(children().size()) - 1; i >= 0; --i) { AXNode* child = children_[i]; if (!child->IsIgnored()) return child; AXNode* descendant = child->ComputeLastUnignoredChildRecursive(); if (descendant) return descendant; } return nullptr; } AXNode* AXNode::ComputeFirstUnignoredChildRecursive() const { DCHECK(!tree_->GetTreeUpdateInProgressState()); for (size_t i = 0; i < children().size(); i++) { AXNode* child = children_[i]; if (!child->IsIgnored()) return child; AXNode* descendant = child->ComputeFirstUnignoredChildRecursive(); if (descendant) return descendant; } return nullptr; } std::string AXNode::GetTextForRangeValue() const { DCHECK(data().IsRangeValueSupported()); std::string range_value = GetStringAttribute(ax::mojom::StringAttribute::kValue); float numeric_value; if (range_value.empty() && GetFloatAttribute(ax::mojom::FloatAttribute::kValueForRange, &numeric_value)) { // This method of number to string conversion creates a localized string // and avoids padding with extra zeros after the decimal point. // For example, 3.5 is converted to ""3.5"" rather than ""3.50000"". return base::StringPrintf(""%g"", numeric_value); } return range_value; } std::string AXNode::GetValueForColorWell() const { DCHECK_EQ(GetRole(), ax::mojom::Role::kColorWell); // static cast because SkColor is a 4-byte unsigned int unsigned int color = static_cast( GetIntAttribute(ax::mojom::IntAttribute::kColorValue)); unsigned int red = SkColorGetR(color); unsigned int green = SkColorGetG(color); unsigned int blue = SkColorGetB(color); return base::StringPrintf(""%d%% red %d%% green %d%% blue"", red * 100 / 255, green * 100 / 255, blue * 100 / 255); } std::string AXNode::GetValueForTextField() const { DCHECK(data().IsTextField()); std::string value = GetStringAttribute(ax::mojom::StringAttribute::kValue); // Some screen readers like Jaws and VoiceOver require a value to be set in // text fields with rich content, even though the same information is // available on the children. if (value.empty() && data().IsNonAtomicTextField()) return GetInnerText(); return value; } bool AXNode::IsIgnored() const { // If the focus has moved, then it could make a previously ignored node // unignored or vice versa. We never ignore focused nodes otherwise users of // assistive software might be unable to interact with the webpage. return AXTree::ComputeNodeIsIgnored(&tree_->data(), data()); } bool AXNode::IsIgnoredForTextNavigation() const { if (GetRole() == ax::mojom::Role::kSplitter) return true; // A generic container without any unignored children that is not editable // should not be used for text-based navigation. Such nodes don't make sense // for screen readers to land on, since no text will be announced and no // action is possible. if (GetRole() == ax::mojom::Role::kGenericContainer && !GetUnignoredChildCount() && !HasState(ax::mojom::State::kEditable)) { return true; } return false; } bool AXNode::IsInvisibleOrIgnored() const { return id() != tree_->data().focus_id && (IsIgnored() || data_.IsInvisible()); } bool AXNode::IsChildOfLeaf() const { for (const AXNode* ancestor = GetUnignoredParent(); ancestor; ancestor = ancestor->GetUnignoredParent()) { if (ancestor->IsLeaf()) return true; } return false; } bool AXNode::IsEmptyLeaf() const { if (!IsLeaf()) return false; if (GetUnignoredChildCountCrossingTreeBoundary()) return !GetInnerTextLength(); // Text exposed by ignored leaf (text) nodes is not exposed to the platforms' // accessibility layer, hence such leaf nodes are in effect empty. return IsIgnored() || !GetInnerTextLength(); } bool AXNode::IsLeaf() const { // A node is a leaf if it has no descendants, i.e. if it is at the bottom of // the tree, regardless whether it is ignored or not. if (!GetChildCountCrossingTreeBoundary()) return true; // Ignored nodes with any kind of descendants, (ignored or unignored), cannot // be leaves because: A) If some of their descendants are unignored then those // descendants need to be exposed to the platform layer, and B) If all of // their descendants are ignored they are still not at the bottom of the tree. if (IsIgnored()) return false; // An unignored node is a leaf if all of its descendants are ignored. int child_count = GetUnignoredChildCountCrossingTreeBoundary(); if (!child_count) return true; #if defined(OS_WIN) // On Windows, we want to hide the subtree of a collapsed will cause // different return values here, even though 'contenteditable' has no effect. // This needs to be modified from the Blink side, so 'kRichlyEditable' isn't // added in this case. if (data().IsAtomicTextField() || IsText()) return true; // Roles whose children are only presentational according to the ARIA and // HTML5 Specs should be hidden from screen readers. switch (GetRole()) { // According to the ARIA and Core-AAM specs: // https://w3c.github.io/aria/#button, // https://www.w3.org/TR/core-aam-1.1/#exclude_elements // buttons' children are presentational only and should be hidden from // screen readers. However, we cannot enforce the leafiness of buttons // because they may contain many rich, interactive descendants such as a day // in a calendar, and screen readers will need to interact with these // contents. See https://crbug.com/689204. // So we decided to not enforce the leafiness of buttons and expose all // children. case ax::mojom::Role::kButton: return false; case ax::mojom::Role::kImage: { // Images are not leaves when they are image maps. Therefore, do not // truncate descendants except in the case where ARIA role=img. std::string role = GetStringAttribute(ax::mojom::StringAttribute::kRole); return role == ""img"" || role == ""image""; } case ax::mojom::Role::kDocCover: case ax::mojom::Role::kGraphicsSymbol: case ax::mojom::Role::kMeter: case ax::mojom::Role::kScrollBar: case ax::mojom::Role::kSpinButton: case ax::mojom::Role::kSlider: case ax::mojom::Role::kSplitter: case ax::mojom::Role::kProgressIndicator: return true; case ax::mojom::Role::kCheckBox: case ax::mojom::Role::kListBoxOption: // role=""math"" is flat. But always return false for kMathMLMath since the // children of a tag should be exposed to make MathML accessible. case ax::mojom::Role::kMath: case ax::mojom::Role::kMenuListOption: case ax::mojom::Role::kMenuItem: case ax::mojom::Role::kMenuItemCheckBox: case ax::mojom::Role::kMenuItemRadio: case ax::mojom::Role::kPopUpButton: case ax::mojom::Role::kToggleButton: case ax::mojom::Role::kRadioButton: case ax::mojom::Role::kSwitch: case ax::mojom::Role::kTab: { // For historical reasons, truncate the children of these roles when they // have a single text child and are not editable. // TODO(accessibility) Consider removing this in the future, and exposing // all descendants, as it seems ATs do a good job of avoiding redundant // speech even if they have a text child. Removing this rule would allow // AT users to select any text visible in the page, and ensure that all // text is available to ATs that use the position of objects on the // screen. This has been manually tested in JAWS, NVDA, VoiceOver, Orca // and ChromeVox. // Note that the ARIA spec says, ""User agents SHOULD NOT expose // descendants of this element through the platform accessibility API. If // user agents do not hide the descendant nodes, some information may be // read twice."" However, this is not a MUST, and in non-simple cases // Chrome and Firefox already expose descendants, without causing issues. // Allow up to 2 text nodes so that list items with bullets are leaves. if (child_count > 2 || HasState(ax::mojom::State::kEditable)) return false; AXNode* child1 = GetFirstUnignoredChildCrossingTreeBoundary(); if (!child1 || child1->GetRole() != ax::mojom::Role::kStaticText) return false; AXNode* child2 = child1->GetNextSibling(); return !child2 || child2->GetRole() == ax::mojom::Role::kStaticText; } default: return false; } } bool AXNode::IsInListMarker() const { if (GetRole() == ax::mojom::Role::kListMarker) return true; // The children of a list marker node can only be text nodes. if (!IsText()) return false; // There is no need to iterate over all the ancestors of the current node // since a list marker has descendants that are only 2 levels deep, i.e.: // AXLayoutObject role=kListMarker // ++StaticText // ++++InlineTextBox AXNode* parent_node = GetUnignoredParent(); if (!parent_node) return false; if (parent_node->GetRole() == ax::mojom::Role::kListMarker) return true; AXNode* grandparent_node = parent_node->GetUnignoredParent(); return grandparent_node && grandparent_node->GetRole() == ax::mojom::Role::kListMarker; } bool AXNode::IsCollapsedMenuListPopUpButton() const { if (GetRole() != ax::mojom::Role::kPopUpButton || !HasState(ax::mojom::State::kCollapsed)) { return false; } // When a popup button contains a menu list popup, its only child is unignored // and is a menu list popup. AXNode* node = GetFirstUnignoredChild(); if (!node) return false; return node->GetRole() == ax::mojom::Role::kMenuListPopup; } AXNode* AXNode::GetCollapsedMenuListPopUpButtonAncestor() const { AXNode* node = GetOrderedSet(); if (!node) return nullptr; // The ordered set returned is either the popup element child of the popup // button (e.g., the AXMenuListPopup) or the popup button itself. We need // |node| to point to the popup button itself. if (node->GetRole() != ax::mojom::Role::kPopUpButton) { node = node->GetParent(); if (!node) return nullptr; } return node->IsCollapsedMenuListPopUpButton() ? node : nullptr; } bool AXNode::IsEmbeddedGroup() const { if (GetRole() != ax::mojom::Role::kGroup || !GetParent()) return false; return ui::IsSetLike(GetParent()->GetRole()); } AXNode* AXNode::GetLowestPlatformAncestor() const { AXNode* current_node = const_cast(this); AXNode* lowest_unignored_node = current_node; for (; lowest_unignored_node && lowest_unignored_node->IsIgnored(); lowest_unignored_node = lowest_unignored_node->GetParent()) { } // `highest_leaf_node` could be nullptr. AXNode* highest_leaf_node = lowest_unignored_node; // For the purposes of this method, a leaf node does not include leaves in the // internal accessibility tree, only in the platform exposed tree. for (AXNode* ancestor_node = lowest_unignored_node; ancestor_node; ancestor_node = ancestor_node->GetUnignoredParent()) { if (ancestor_node->IsLeaf()) highest_leaf_node = ancestor_node; } if (highest_leaf_node) return highest_leaf_node; if (lowest_unignored_node) return lowest_unignored_node; return current_node; } AXNode* AXNode::GetTextFieldAncestor() const { // The descendants of a text field usually have State::kEditable, however in // the case of Role::kSearchBox or Role::kSpinButton being the text field // ancestor, its immediate descendant can have Role::kGenericContainer without // State::kEditable. Same with inline text boxes and placeholder text. // TODO(nektar): Fix all such inconsistencies in Blink. for (AXNode* ancestor = const_cast(this); ancestor && (ancestor->HasState(ax::mojom::State::kEditable) || ancestor->GetRole() == ax::mojom::Role::kGenericContainer || ancestor->IsText()); ancestor = ancestor->GetUnignoredParent()) { if (ancestor->data().IsTextField()) return ancestor; } return nullptr; } AXNode* AXNode::GetSelectionContainer() const { for (AXNode* ancestor = const_cast(this); ancestor; ancestor = ancestor->GetUnignoredParent()) { if (IsContainerWithSelectableChildren(ancestor->GetRole())) return ancestor; } return nullptr; } AXNode* AXNode::GetTableAncestor() const { for (AXNode* ancestor = const_cast(this); ancestor; ancestor = ancestor->GetUnignoredParent()) { if (ancestor->IsTable()) return ancestor; } return nullptr; } bool AXNode::IsDescendantOfAtomicTextField() const { AXNode* text_field_node = GetTextFieldAncestor(); return text_field_node && text_field_node->data().IsAtomicTextField(); } } // namespace ui ",16267,True,2776.628679562398,median ":spring-data-commons-ref: https://docs.spring.io/spring-data/data-commons/docs/current/reference/html == Spring Data Cloud Spanner https://projects.spring.io/spring-data/[Spring Data] is an abstraction for storing and retrieving POJOs in numerous storage technologies. Spring Cloud GCP adds Spring Data support for https://cloud.google.com/spanner/[Google Cloud Spanner]. Maven coordinates for this module only, using <>: [source,xml] ---- org.springframework.cloud spring-cloud-gcp-data-spanner ---- Gradle coordinates: [source] ---- dependencies { compile group: 'org.springframework.cloud', name: 'spring-cloud-gcp-data-spanner' } ---- We provide a link:../spring-cloud-gcp-starters/spring-cloud-gcp-starter-data-spanner[Spring Boot Starter for Spring Data Spanner], with which you can leverage our recommended auto-configuration setup. To use the starter, see the coordinates see below. Maven: [source,xml] ---- org.springframework.cloud spring-cloud-gcp-starter-data-spanner ---- Gradle: [source,subs=""normal""] ---- dependencies { compile group: 'org.springframework.cloud', name: 'spring-cloud-gcp-starter-data-spanner' } ---- This setup takes care of bringing in the latest compatible version of Cloud Java Cloud Spanner libraries as well. === Configuration To setup Spring Data Cloud Spanner, you have to configure the following: * Setup the connection details to Google Cloud Spanner. * Enable Spring Data Repositories (optional). ==== Cloud Spanner settings You can the use link:../spring-cloud-gcp-starters/spring-cloud-gcp-starter-data-spanner[Spring Boot Starter for Spring Data Spanner] to autoconfigure Google Cloud Spanner in your Spring application. It contains all the necessary setup that makes it easy to authenticate with your Google Cloud project. The following configuration options are available: |=== | Name | Description | Required | Default value | `spring.cloud.gcp.spanner.instance-id` | Cloud Spanner instance to use | Yes | | `spring.cloud.gcp.spanner.database` | Cloud Spanner database to use | Yes | | `spring.cloud.gcp.spanner.project-id` | GCP project ID where the Google Cloud Spanner API is hosted, if different from the one in the <> | No | | `spring.cloud.gcp.spanner.credentials.location` | OAuth2 credentials for authenticating with the Google Cloud Spanner API, if different from the ones in the <> | No | | `spring.cloud.gcp.spanner.credentials.encoded-key` | Base64-encoded OAuth2 credentials for authenticating with the Google Cloud Spanner API, if different from the ones in the <> | No | | `spring.cloud.gcp.spanner.credentials.scopes` | https://developers.google.com/identity/protocols/googlescopes[OAuth2 scope] for Spring Cloud GCP Cloud Spanner credentials | No | https://www.googleapis.com/auth/spanner.data | `spring.cloud.gcp.spanner.createInterleavedTableDdlOnDeleteCascade` | If `true`, then schema statements generated by `SpannerSchemaUtils` for tables with interleaved parent-child relationships will be ""ON DELETE CASCADE"". The schema for the tables will be ""ON DELETE NO ACTION"" if `false`. | No | `true` | `spring.cloud.gcp.spanner.numRpcChannels` | Number of gRPC channels used to connect to Cloud Spanner | No | 4 - Determined by Cloud Spanner client library | `spring.cloud.gcp.spanner.prefetchChunks` | Number of chunks prefetched by Cloud Spanner for read and query | No | 4 - Determined by Cloud Spanner client library | `spring.cloud.gcp.spanner.minSessions` | Minimum number of sessions maintained in the session pool | No | 0 - Determined by Cloud Spanner client library | `spring.cloud.gcp.spanner.maxSessions` | Maximum number of sessions session pool can have | No | 400 - Determined by Cloud Spanner client library | `spring.cloud.gcp.spanner.maxIdleSessions` | Maximum number of idle sessions session pool will maintain | No | 0 - Determined by Cloud Spanner client library | `spring.cloud.gcp.spanner.writeSessionsFraction` | Fraction of sessions to be kept prepared for write transactions | No | 0.2 - Determined by Cloud Spanner client library | `spring.cloud.gcp.spanner.keepAliveIntervalMinutes` | How long to keep idle sessions alive | No | 30 - Determined by Cloud Spanner client library | `spring.cloud.gcp.spanner.failIfPoolExhausted` | If all sessions are in use, fail the request by throwing an exception. Otherwise, by default, block until a session becomes available. | No | `false` | `spring.cloud.gcp.spanner.emulator.enabled` | Enables the usage of an emulator. If this is set to true, then you should set the `spring.cloud.gcp.spanner.emulator-host` to the host:port of your locally running emulator instance. | No | `false` | `spring.cloud.gcp.spanner.emulator-host` | The host and port of the Spanner emulator; can be overridden to specify connecting to an already-running https://cloud.google.com/spanner/docs/emulator#installing_and_running_the_emulator[Spanner emulator] instance. | No | `localhost:9010` |=== ==== Repository settings Spring Data Repositories can be configured via the `@EnableSpannerRepositories` annotation on your main `@Configuration` class. With our Spring Boot Starter for Spring Data Cloud Spanner, `@EnableSpannerRepositories` is automatically added. It is not required to add it to any other class, unless there is a need to override finer grain configuration parameters provided by https://github.com/spring-cloud/spring-cloud-gcp/blob/master/spring-cloud-gcp-data-spanner/src/main/java/org/springframework/cloud/gcp/data/spanner/repository/config/EnableSpannerRepositories.java[`@EnableSpannerRepositories`]. ==== Autoconfiguration Our Spring Boot autoconfiguration creates the following beans available in the Spring application context: - an instance of `SpannerTemplate` - an instance of `SpannerDatabaseAdminTemplate` for generating table schemas from object hierarchies and creating and deleting tables and databases - an instance of all user-defined repositories extending `SpannerRepository`, `CrudRepository`, `PagingAndSortingRepository`, when repositories are enabled - an instance of `DatabaseClient` from the Google Cloud Java Client for Spanner, for convenience and lower level API access === Object Mapping Spring Data Cloud Spanner allows you to map domain POJOs to Cloud Spanner tables via annotations: [source,java] ---- @Table(name = ""traders"") public class Trader { @PrimaryKey @Column(name = ""trader_id"") String traderId; String firstName; String lastName; @NotMapped Double temporaryNumber; } ---- Spring Data Cloud Spanner will ignore any property annotated with `@NotMapped`. These properties will not be written to or read from Spanner. ==== Constructors Simple constructors are supported on POJOs. The constructor arguments can be a subset of the persistent properties. Every constructor argument needs to have the same name and type as a persistent property on the entity and the constructor should set the property from the given argument. Arguments that are not directly set to properties are not supported. [source,java] ---- @Table(name = ""traders"") public class Trader { @PrimaryKey @Column(name = ""trader_id"") String traderId; String firstName; String lastName; @NotMapped Double temporaryNumber; public Trader(String traderId, String firstName) { this.traderId = traderId; this.firstName = firstName; } } ---- ==== Table The `@Table` annotation can provide the name of the Cloud Spanner table that stores instances of the annotated class, one per row. This annotation is optional, and if not given, the name of the table is inferred from the class name with the first character uncapitalized. ===== SpEL expressions for table names In some cases, you might want the `@Table` table name to be determined dynamically. To do that, you can use https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#expressions[Spring Expression Language]. For example: [source, java] ---- @Table(name = ""trades_#{tableNameSuffix}"") public class Trade { // ... } ---- The table name will be resolved only if the `tableNameSuffix` value/bean in the Spring application context is defined. For example, if `tableNameSuffix` has the value ""123"", the table name will resolve to `trades_123`. ==== Primary Keys For a simple table, you may only have a primary key consisting of a single column. Even in that case, the `@PrimaryKey` annotation is required. `@PrimaryKey` identifies the one or more ID properties corresponding to the primary key. Spanner has first class support for composite primary keys of multiple columns. You have to annotate all of your POJO's fields that the primary key consists of with `@PrimaryKey` as below: [source,java] ---- @Table(name = ""trades"") public class Trade { @PrimaryKey(keyOrder = 2) @Column(name = ""trade_id"") private String tradeId; @PrimaryKey(keyOrder = 1) @Column(name = ""trader_id"") private String traderId; private String action; private BigDecimal price; private Double shares; private String symbol; } ---- The `keyOrder` parameter of `@PrimaryKey` identifies the properties corresponding to the primary key columns in order, starting with 1 and increasing consecutively. Order is important and must reflect the order defined in the Cloud Spanner schema. In our example the DDL to create the table and its primary key is as follows: [source,sql] ---- CREATE TABLE trades ( trader_id STRING(MAX), trade_id STRING(MAX), action STRING(15), symbol STRING(10), price NUMERIC, shares FLOAT64 ) PRIMARY KEY (trader_id, trade_id) ---- Spanner does not have automatic ID generation. For most use-cases, sequential IDs should be used with caution to avoid creating data hotspots in the system. Read https://cloud.google.com/spanner/docs/schema-and-data-model#primary_keys[Spanner Primary Keys documentation] for a better understanding of primary keys and recommended practices. ==== Columns All accessible properties on POJOs are automatically recognized as a Cloud Spanner column. Column naming is generated by the `PropertyNameFieldNamingStrategy` by default defined on the `SpannerMappingContext` bean. The `@Column` annotation optionally provides a different column name than that of the property and some other settings: - `name` is the optional name of the column - `spannerTypeMaxLength` specifies for `STRING` and `BYTES` columns the maximum length. This setting is only used when generating DDL schema statements based on domain types. - `nullable` specifies if the column is created as `NOT NULL`. This setting is only used when generating DDL schema statements based on domain types. - `spannerType` is the Cloud Spanner column type you can optionally specify. If this is not specified then a compatible column type is inferred from the Java property type. - `spannerCommitTimestamp` is a boolean specifying if this property corresponds to an auto-populated commit timestamp column. Any value set in this property will be ignored when writing to Cloud Spanner. ==== Embedded Objects If an object of type `B` is embedded as a property of `A`, then the columns of `B` will be saved in the same Cloud Spanner table as those of `A`. If `B` has primary key columns, those columns will be included in the primary key of `A`. `B` can also have embedded properties. Embedding allows reuse of columns between multiple entities, and can be useful for implementing parent-child situations, because Cloud Spanner requires child tables to include the key columns of their parents. For example: [source,java] ---- class X { @PrimaryKey String grandParentId; long age; } class A { @PrimaryKey @Embedded X grandParent; @PrimaryKey(keyOrder = 2) String parentId; String value; } @Table(name = ""items"") class B { @PrimaryKey @Embedded A parent; @PrimaryKey(keyOrder = 2) String id; @Column(name = ""child_value"") String value; } ---- Entities of `B` can be stored in a table defined as: [source,sql] ---- CREATE TABLE items ( grandParentId STRING(MAX), parentId STRING(MAX), id STRING(MAX), value STRING(MAX), child_value STRING(MAX), age INT64 ) PRIMARY KEY (grandParentId, parentId, id) ---- Note that embedded properties' column names must all be unique. ==== Relationships Spring Data Cloud Spanner supports parent-child relationships using the Cloud Spanner https://cloud.google.com/spanner/docs/schema-and-data-model#creating-interleaved-tables[parent-child interleaved table mechanism]. Cloud Spanner interleaved tables enforce the one-to-many relationship and provide efficient queries and operations on entities of a single domain parent entity. These relationships can be up to 7 levels deep. Cloud Spanner also provides automatic cascading delete or enforces the deletion of child entities before parents. While one-to-one and many-to-many relationships can be implemented in Cloud Spanner and Spring Data Cloud Spanner using constructs of interleaved parent-child tables, only the parent-child relationship is natively supported. Cloud Spanner does not support the foreign key constraint, though the parent-child key constraint enforces a similar requirement when used with interleaved tables. For example, the following Java entities: [source,java] ---- @Table(name = ""Singers"") class Singer { @PrimaryKey long SingerId; String FirstName; String LastName; byte[] SingerInfo; @Interleaved List albums; } @Table(name = ""Albums"") class Album { @PrimaryKey long SingerId; @PrimaryKey(keyOrder = 2) long AlbumId; String AlbumTitle; } ---- These classes can correspond to an existing pair of interleaved tables. The `@Interleaved` annotation may be applied to `Collection` properties and the inner type is resolved as the child entity type. The schema needed to create them can also be generated using the `SpannerSchemaUtils` and run by using the `SpannerDatabaseAdminTemplate`: [source,java] ---- @Autowired SpannerSchemaUtils schemaUtils; @Autowired SpannerDatabaseAdminTemplate databaseAdmin; ... // Get the create statmenets for all tables in the table structure rooted at Singer List createStrings = this.schemaUtils.getCreateTableDdlStringsForInterleavedHierarchy(Singer.class); // Create the tables and also create the database if necessary this.databaseAdmin.executeDdlStrings(createStrings, true); ---- The `createStrings` list contains table schema statements using column names and types compatible with the provided Java type and any resolved child relationship types contained within based on the configured custom converters. [source,sql] ---- CREATE TABLE Singers ( SingerId INT64 NOT NULL, FirstName STRING(1024), LastName STRING(1024), SingerInfo BYTES(MAX), ) PRIMARY KEY (SingerId); CREATE TABLE Albums ( SingerId INT64 NOT NULL, AlbumId INT64 NOT NULL, AlbumTitle STRING(MAX), ) PRIMARY KEY (SingerId, AlbumId), INTERLEAVE IN PARENT Singers ON DELETE CASCADE; ---- The `ON DELETE CASCADE` clause indicates that Cloud Spanner will delete all Albums of a singer if the Singer is deleted. The alternative is `ON DELETE NO ACTION`, where a Singer cannot be deleted until all of its Albums have already been deleted. When using `SpannerSchemaUtils` to generate the schema strings, the `spring.cloud.gcp.spanner.createInterleavedTableDdlOnDeleteCascade` boolean setting determines if these schema are generated as `ON DELETE CASCADE` for `true` and `ON DELETE NO ACTION` for `false`. Cloud Spanner restricts these relationships to 7 child layers. A table may have multiple child tables. On updating or inserting an object to Cloud Spanner, all of its referenced children objects are also updated or inserted in the same request, respectively. On read, all of the interleaved child rows are also all read. ===== Lazy Fetch `@Interleaved` properties are retrieved eagerly by default, but can be fetched lazily for performance in both read and write: [source,java] ---- @Interleaved(lazy = true) List albums; ---- Lazily-fetched interleaved properties are retrieved upon the first interaction with the property. If a property marked for lazy fetching is never retrieved, then it is also skipped when saving the parent entity. If used inside a transaction, subsequent operations on lazily-fetched properties use the same transaction context as that of the original parent entity. ===== Declarative Filtering with `@Where` The `@Where` annotation could be applied to an entity class or to an interleaved property. This annotation provides an SQL where clause that will be applied at the fetching of interleaved collections or the entity itself. Let's say we have an `Agreement` with a list of `Participants` which could be assigned to it. We would like to fetch a list of currently active participants. For security reasons, all records should remain in the database forever, even if participants become inactive. That can be easily achieved with the `@Where` annotation, which is demonstrated by this example: [source, java] ---- @Table(name = ""participants"") public class Participant { //... boolean active; //... } @Table(name = ""agreements"") public class Agreement { //... @Interleaved @Where(""active = true"") List participants; Person person; //... } ---- ==== Supported Types Spring Data Cloud Spanner natively supports the following types for regular fields but also utilizes custom converters (detailed in following sections) and dozens of pre-defined Spring Data custom converters to handle other common Java types. Natively supported types: * `com.google.cloud.ByteArray` * `com.google.cloud.Date` * `com.google.cloud.Timestamp` * `java.lang.Boolean`, `boolean` * `java.lang.Double`, `double` * `java.lang.Long`, `long` * `java.lang.Integer`, `int` * `java.lang.String` * `double[]` * `long[]` * `boolean[]` * `java.util.Date` * `java.time.Instant` * `java.sql.Date` * `java.time.LocalDate` * `java.time.LocalDateTime` ==== Lists Spanner supports `ARRAY` types for columns. `ARRAY` columns are mapped to `List` fields in POJOS. Example: [source,java] ---- List curve; ---- The types inside the lists can be any singular property type. ==== Lists of Structs Cloud Spanner queries can https://cloud.google.com/spanner/docs/query-syntax#using-structs-with-select[construct STRUCT values] that appear as columns in the result. Cloud Spanner requires STRUCT values appear in ARRAYs at the root level: `SELECT ARRAY(SELECT STRUCT(1 as val1, 2 as val2)) as pair FROM Users`. Spring Data Cloud Spanner will attempt to read the column STRUCT values into a property that is an `Iterable` of an entity type compatible with the schema of the column STRUCT value. For the previous array-select example, the following property can be mapped with the constructed `ARRAY` column: `List pair;` where the `TwoInts` type is defined: [source, java] ---- class TwoInts { int val1; int val2; } ---- ==== Custom types Custom converters can be used to extend the type support for user defined types. . Converters need to implement the `org.springframework.core.convert.converter.Converter` interface in both directions. . The user defined type needs to be mapped to one of the basic types supported by Spanner: * `com.google.cloud.ByteArray` * `com.google.cloud.Date` * `com.google.cloud.Timestamp` * `java.lang.Boolean`, `boolean` * `java.lang.Double`, `double` * `java.lang.Long`, `long` * `java.lang.String` * `double[]` * `long[]` * `boolean[]` * `enum` types . An instance of both Converters needs to be passed to a `ConverterAwareMappingSpannerEntityProcessor`, which then has to be made available as a `@Bean` for `SpannerEntityProcessor`. For example: We would like to have a field of type `Person` on our `Trade` POJO: [source, java] ---- @Table(name = ""trades"") public class Trade { //... Person person; //... } ---- Where Person is a simple class: [source, java] ---- public class Person { public String firstName; public String lastName; } ---- We have to define the two converters: [source, java] ---- public class PersonWriteConverter implements Converter { @Override public String convert(Person person) { return person.firstName + "" "" + person.lastName; } } public class PersonReadConverter implements Converter { @Override public Person convert(String s) { Person person = new Person(); person.firstName = s.split("" "")[0]; person.lastName = s.split("" "")[1]; return person; } } ---- That will be configured in our `@Configuration` file: [source, java] ---- @Configuration public class ConverterConfiguration { @Bean public SpannerEntityProcessor spannerEntityProcessor(SpannerMappingContext spannerMappingContext) { return new ConverterAwareMappingSpannerEntityProcessor(spannerMappingContext, Arrays.asList(new PersonWriteConverter()), Arrays.asList(new PersonReadConverter())); } } ---- ==== Custom Converter for Struct Array Columns If a `Converter` is provided, then properties of type `List` can be used in your entity types. === Spanner Operations & Template `SpannerOperations` and its implementation, `SpannerTemplate`, provides the Template pattern familiar to Spring developers. It provides: - Resource management - One-stop-shop to Spanner operations with the Spring Data POJO mapping and conversion features - Exception conversion Using the `autoconfigure` provided by our Spring Boot Starter for Spanner, your Spring application context will contain a fully configured `SpannerTemplate` object that you can easily autowire in your application: [source,java] ---- @SpringBootApplication public class SpannerTemplateExample { @Autowired SpannerTemplate spannerTemplate; public void doSomething() { this.spannerTemplate.delete(Trade.class, KeySet.all()); //... Trade t = new Trade(); //... this.spannerTemplate.insert(t); //... List tradesByAction = spannerTemplate.findAll(Trade.class); //... } } ---- The Template API provides convenience methods for: - https://cloud.google.com/spanner/docs/reads[Reads], and by providing SpannerReadOptions and SpannerQueryOptions ** Stale read ** Read with secondary indices ** Read with limits and offsets ** Read with sorting - https://cloud.google.com/spanner/docs/reads#execute_a_query[Queries] - DML operations (delete, insert, update, upsert) - Partial reads ** You can define a set of columns to be read into your entity - Partial writes ** Persist only a few properties from your entity - Read-only transactions - Locking read-write transactions ==== SQL Query Cloud Spanner has SQL support for running read-only queries. All the query related methods start with `query` on `SpannerTemplate`. By using `SpannerTemplate`, you can run SQL queries that map to POJOs: [source,java] ---- List trades = this.spannerTemplate.query(Trade.class, Statement.of(""SELECT * FROM trades"")); ---- ==== Read Spanner exposes a https://cloud.google.com/spanner/docs/reads[Read API] for reading single row or multiple rows in a table or in a secondary index. Using `SpannerTemplate` you can run reads, as the following example shows: [source,java] ---- List trades = this.spannerTemplate.readAll(Trade.class); ---- Main benefit of reads over queries is reading multiple rows of a certain pattern of keys is much easier using the features of the https://github.com/GoogleCloudPlatform/google-cloud-java/blob/master/google-cloud-spanner/src/main/java/com/google/cloud/spanner/KeySet.java[`KeySet`] class. ==== Advanced reads ===== Stale read All reads and queries are *strong reads* by default. A *strong read* is a read at a current time and is guaranteed to see all data that has been committed up until the start of this read. An *exact staleness read* is read at a timestamp in the past. Cloud Spanner allows you to determine how current the data should be when you read data. With `SpannerTemplate` you can specify the `Timestamp` by setting it on `SpannerQueryOptions` or `SpannerReadOptions` to the appropriate read or query methods: Reads: [source,java] ---- // a read with options: SpannerReadOptions spannerReadOptions = new SpannerReadOptions().setTimestamp(myTimestamp); List trades = this.spannerTemplate.readAll(Trade.class, spannerReadOptions); ---- Queries: [source,java] ---- // a query with options: SpannerQueryOptions spannerQueryOptions = new SpannerQueryOptions().setTimestamp(myTimestamp); List trades = this.spannerTemplate.query(Trade.class, Statement.of(""SELECT * FROM trades""), spannerQueryOptions); ---- You can also read with https://cloud.google.com/spanner/docs/timestamp-bounds[*bounded staleness*] by setting `.setTimestampBound(TimestampBound.ofMinReadTimestamp(myTimestamp))` on the query and read options objects. Bounded staleness lets Cloud Spanner choose any point in time later than or equal to the given timestampBound, but it cannot be used inside transactions. ===== Read from a secondary index Using a https://cloud.google.com/spanner/docs/secondary-indexes[secondary index] is available for Reads via the Template API and it is also implicitly available via SQL for Queries. The following shows how to read rows from a table using a https://cloud.google.com/spanner/docs/secondary-indexes[secondary index] simply by setting `index` on `SpannerReadOptions`: [source,java] ---- SpannerReadOptions spannerReadOptions = new SpannerReadOptions().setIndex(""TradesByTrader""); List trades = this.spannerTemplate.readAll(Trade.class, spannerReadOptions); ---- ===== Read with offsets and limits Limits and offsets are only supported by Queries. The following will get only the first two rows of the query: [source,java] ---- SpannerQueryOptions spannerQueryOptions = new SpannerQueryOptions().setLimit(2).setOffset(3); List trades = this.spannerTemplate.query(Trade.class, Statement.of(""SELECT * FROM trades""), spannerQueryOptions); ---- Note that the above is equivalent of running `SELECT * FROM trades LIMIT 2 OFFSET 3`. ===== Sorting Reads by keys do not support sorting. However, queries on the Template API support sorting through standard SQL and also via Spring Data Sort API: [source,java] ---- List trades = this.spannerTemplate.queryAll(Trade.class, Sort.by(""action"")); ---- If the provided sorted field name is that of a property of the domain type, then the column name corresponding to that property will be used in the query. Otherwise, the given field name is assumed to be the name of the column in the Cloud Spanner table. Sorting on columns of Cloud Spanner types STRING and BYTES can be done while ignoring case: [source,java] ---- Sort.by(Order.desc(""action"").ignoreCase()) ---- ===== Partial read Partial read is only possible when using Queries. In case the rows returned by the query have fewer columns than the entity that it will be mapped to, Spring Data will map the returned columns only. This setting also applies to nested structs and their corresponding nested POJO properties. [source,java] ---- List trades = this.spannerTemplate.query(Trade.class, Statement.of(""SELECT action, symbol FROM trades""), new SpannerQueryOptions().setAllowMissingResultSetColumns(true)); ---- If the setting is set to `false`, then an exception will be thrown if there are missing columns in the query result. ===== Summary of options for Query vs Read |=== | Feature | Query supports it | Read supports it | SQL | yes | no | Partial read | yes | no | Limits | yes | no | Offsets | yes | no | Secondary index | yes | yes | Read using index range | no | yes | Sorting | yes | no |=== ==== Write / Update The write methods of `SpannerOperations` accept a POJO and writes all of its properties to Spanner. The corresponding Spanner table and entity metadata is obtained from the given object's actual type. If a POJO was retrieved from Spanner and its primary key properties values were changed and then written or updated, the operation will occur as if against a row with the new primary key values. The row with the original primary key values will not be affected. ===== Insert The `insert` method of `SpannerOperations` accepts a POJO and writes all of its properties to Spanner, which means the operation will fail if a row with the POJO's primary key already exists in the table. [source, java] ---- Trade t = new Trade(); this.spannerTemplate.insert(t); ---- ===== Update The `update` method of `SpannerOperations` accepts a POJO and writes all of its properties to Spanner, which means the operation will fail if the POJO's primary key does not already exist in the table. [source, java] ---- // t was retrieved from a previous operation this.spannerTemplate.update(t); ---- ===== Upsert The `upsert` method of `SpannerOperations` accepts a POJO and writes all of its properties to Spanner using update-or-insert. [source, java] ---- // t was retrieved from a previous operation or it's new this.spannerTemplate.upsert(t); ---- ===== Partial Update The update methods of `SpannerOperations` operate by default on all properties within the given object, but also accept `String[]` and `Optional>` of column names. If the `Optional` of set of column names is empty, then all columns are written to Spanner. However, if the Optional is occupied by an empty set, then no columns will be written. [source, java] ---- // t was retrieved from a previous operation or it's new this.spannerTemplate.update(t, ""symbol"", ""action""); ---- ==== DML DML statements can be run by using `SpannerOperations.executeDmlStatement`. Inserts, updates, and deletions can affect any number of rows and entities. You can run https://cloud.google.com/spanner/docs/dml-partitioned[partitioned DML] updates by using the `executePartitionedDmlStatement` method. Partitioned DML queries have performance benefits but also have restrictions and cannot be used inside transactions. ==== Transactions `SpannerOperations` provides methods to run `java.util.Function` objects within a single transaction while making available the read and write methods from `SpannerOperations`. ===== Read/Write Transaction Read and write transactions are provided by `SpannerOperations` via the `performReadWriteTransaction` method: [source,java] ---- @Autowired SpannerOperations mySpannerOperations; public String doWorkInsideTransaction() { return mySpannerOperations.performReadWriteTransaction( transActionSpannerOperations -> { // Work with transActionSpannerOperations here. // It is also a SpannerOperations object. return ""transaction completed""; } ); } ---- The `performReadWriteTransaction` method accepts a `Function` that is provided an instance of a `SpannerOperations` object. The final returned value and type of the function is determined by the user. You can use this object just as you would a regular `SpannerOperations` with a few exceptions: - Its read functionality cannot perform stale reads, because all reads and writes happen at the single point in time of the transaction. - It cannot perform sub-transactions via `performReadWriteTransaction` or `performReadOnlyTransaction`. As these read-write transactions are locking, it is recommended that you use the `performReadOnlyTransaction` if your function does not perform any writes. ===== Read-only Transaction The `performReadOnlyTransaction` method is used to perform read-only transactions using a `SpannerOperations`: [source,java] ---- @Autowired SpannerOperations mySpannerOperations; public String doWorkInsideTransaction() { return mySpannerOperations.performReadOnlyTransaction( transActionSpannerOperations -> { // Work with transActionSpannerOperations here. // It is also a SpannerOperations object. return ""transaction completed""; } ); } ---- The `performReadOnlyTransaction` method accepts a `Function` that is provided an instance of a `SpannerOperations` object. This method also accepts a `ReadOptions` object, but the only attribute used is the timestamp used to determine the snapshot in time to perform the reads in the transaction. If the timestamp is not set in the read options the transaction is run against the current state of the database. The final returned value and type of the function is determined by the user. You can use this object just as you would a regular `SpannerOperations` with a few exceptions: - Its read functionality cannot perform stale reads (other than the staleness set on the entire transaction), because all reads happen at the single point in time of the transaction. - It cannot perform sub-transactions via `performReadWriteTransaction` or `performReadOnlyTransaction` - It cannot perform any write operations. Because read-only transactions are non-locking and can be performed on points in time in the past, these are recommended for functions that do not perform write operations. ===== Declarative Transactions with @Transactional Annotation This feature requires a bean of `SpannerTransactionManager`, which is provided when using `spring-cloud-gcp-starter-data-spanner`. `SpannerTemplate` and `SpannerRepository` support running methods with the `@Transactional` https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#transaction-declarative[annotation] as transactions. If a method annotated with `@Transactional` calls another method also annotated, then both methods will work within the same transaction. `performReadOnlyTransaction` and `performReadWriteTransaction` cannot be used in `@Transactional` annotated methods because Cloud Spanner does not support transactions within transactions. ==== DML Statements `SpannerTemplate` supports https://cloud.google.com/spanner/docs/dml-tasks:[DML] `Statements`. DML statements can also be run in transactions by using `performReadWriteTransaction` or by using the `@Transactional` annotation. === Repositories {spring-data-commons-ref}/#repositories[Spring Data Repositories] are a powerful abstraction that can save you a lot of boilerplate code. For example: [source,java] ---- public interface TraderRepository extends SpannerRepository { } ---- Spring Data generates a working implementation of the specified interface, which can be conveniently autowired into an application. The `Trader` type parameter to `SpannerRepository` refers to the underlying domain type. The second type parameter, `String` in this case, refers to the type of the key of the domain type. For POJOs with a composite primary key, this ID type parameter can be any descendant of `Object[]` compatible with all primary key properties, any descendant of `Iterable`, or `com.google.cloud.spanner.Key`. If the domain POJO type only has a single primary key column, then the primary key property type can be used or the `Key` type. For example in case of Trades, that belong to a Trader, `TradeRepository` would look like this: [source,java] ---- public interface TradeRepository extends SpannerRepository { } ---- [source,java] ---- public class MyApplication { @Autowired SpannerTemplate spannerTemplate; @Autowired StudentRepository studentRepository; public void demo() { this.tradeRepository.deleteAll(); String traderId = ""demo_trader""; Trade t = new Trade(); t.symbol = stock; t.action = action; t.traderId = traderId; t.price = new BigDecimal(""100.0""); t.shares = 12345.6; this.spannerTemplate.insert(t); Iterable allTrades = this.tradeRepository.findAll(); int count = this.tradeRepository.countByAction(""BUY""); } } ---- ==== CRUD Repository `CrudRepository` methods work as expected, with one thing Spanner specific: the `save` and `saveAll` methods work as update-or-insert. ==== Paging and Sorting Repository You can also use `PagingAndSortingRepository` with Spanner Spring Data. The sorting and pageable `findAll` methods available from this interface operate on the current state of the Spanner database. As a result, beware that the state of the database (and the results) might change when moving page to page. ==== Spanner Repository The `SpannerRepository` extends the `PagingAndSortingRepository`, but adds the read-only and the read-write transaction functionality provided by Spanner. These transactions work very similarly to those of `SpannerOperations`, but is specific to the repository's domain type and provides repository functions instead of template functions. For example, this is a read-only transaction: [source,java] ---- @Autowired SpannerRepository myRepo; public String doWorkInsideTransaction() { return myRepo.performReadOnlyTransaction( transactionSpannerRepo -> { // Work with the single-transaction transactionSpannerRepo here. // This is a SpannerRepository object. return ""transaction completed""; } ); } ---- When creating custom repositories for your own domain types and query methods, you can extend `SpannerRepository` to access Cloud Spanner-specific features as well as all features from `PagingAndSortingRepository` and `CrudRepository`. === Query Methods `SpannerRepository` supports Query Methods. Described in the following sections, these are methods residing in your custom repository interfaces of which implementations are generated based on their names and annotations. Query Methods can read, write, and delete entities in Cloud Spanner. Parameters to these methods can be any Cloud Spanner data type supported directly or via custom configured converters. Parameters can also be of type `Struct` or POJOs. If a POJO is given as a parameter, it will be converted to a `Struct` with the same type-conversion logic as used to create write mutations. Comparisons using Struct parameters are limited to https://cloud.google.com/spanner/docs/data-types#limited-comparisons-for-struct[what is available with Cloud Spanner]. ==== Query methods by convention [source, java] ---- public interface TradeRepository extends SpannerRepository { List findByAction(String action); int countByAction(String action); // Named methods are powerful, but can get unwieldy List findTop3DistinctByActionAndSymbolIgnoreCaseOrTraderIdOrderBySymbolDesc( String action, String symbol, String traderId); } ---- In the example above, the {spring-data-commons-ref}/#repositories.query-methods[query methods] in `TradeRepository` are generated based on the name of the methods, using the {spring-data-commons-ref}#repositories.query-methods.query-creation[Spring Data Query creation naming convention]. `List findByAction(String action)` would translate to a `SELECT * FROM trades WHERE action = ?`. The function `List findTop3DistinctByActionAndSymbolIgnoreCaseOrTraderIdOrderBySymbolDesc(String action, String symbol, String traderId);` will be translated as the equivalent of this SQL query: [source, sql] ---- SELECT DISTINCT * FROM trades WHERE ACTION = ? AND LOWER(SYMBOL) = LOWER(?) AND TRADER_ID = ? ORDER BY SYMBOL DESC LIMIT 3 ---- The following filter options are supported: * Equality * Greater than or equals * Greater than * Less than or equals * Less than * Is null * Is not null * Is true * Is false * Like a string * Not like a string * Contains a string * Not contains a string * In * Not in Note that the phrase `SymbolIgnoreCase` is translated to `LOWER(SYMBOL) = LOWER(?)` indicating a non-case-sensitive matching. The `IgnoreCase` phrase may only be appended to fields that correspond to columns of type STRING or BYTES. The Spring Data ""AllIgnoreCase"" phrase appended at the end of the method name is not supported. The `Like` or `NotLike` naming conventions: [source, java] ---- List findBySymbolLike(String symbolFragment); ---- The param `symbolFragment` can contain https://cloud.google.com/spanner/docs/functions-and-operators#comparison-operators[wildcard characters] for string matching such as `_` and `%`. The `Contains` and `NotContains` naming conventions: [source, java] ---- List findBySymbolContains(String symbolFragment); ---- The param `symbolFragment` is a https://cloud.google.com/spanner/docs/functions-and-operators#regexp_contains[regular expression] that is checked for occurrences. The `In` and `NotIn` keywords must be used with `Iterable` corresponding parameters. Delete queries are also supported. For example, query methods such as `deleteByAction` or `removeByAction` delete entities found by `findByAction`. The delete operation happens in a single transaction. Delete queries can have the following return types: * An integer type that is the number of entities deleted * A collection of entities that were deleted * `void` ==== Custom SQL/DML query methods The example above for `List fetchByActionNamedQuery(String action)` does not match the {spring-data-commons-ref}#repositories.query-methods.query-creation[Spring Data Query creation naming convention], so we have to map a parametrized Spanner SQL query to it. The SQL query for the method can be mapped to repository methods in one of two ways: * `namedQueries` properties file * using the `@Query` annotation The names of the tags of the SQL correspond to the `@Param` annotated names of the method parameters. Interleaved properties are loaded eagerly, unless they are annotated with `@Interleaved(lazy = true)`. Custom SQL query methods can accept a single `Sort` or `Pageable` parameter that is applied on top of the specified custom query. It is the recommended way to control the sort order of the results, which is not guaranteed by the `ORDER BY` clause in the SQL query. This is due to the fact that the user-provided query is used as a sub-query, and Cloud Spanner doesn't preserve order in subquery results. You might want to use `ORDER BY` with `LIMIT` to obtain the top records, according to a specified order. However, to ensure the correct sort order of the final result set, sort options have to be passed in with a `Pageable`. [source, java] ---- @Query(""SELECT * FROM trades"") List fetchTrades(Pageable pageable); @Query(""SELECT * FROM trades ORDER BY price DESC LIMIT 1"") Trade topTrade(Pageable pageable); ---- This can be used: [source, java] ---- List customSortedTrades = tradeRepository.fetchTrades(PageRequest .of(2, 2, org.springframework.data.domain.Sort.by(Order.asc(""id"")))); ---- The results would be sorted by ""id"" in ascending order. Your query method can also return non-entity types: [source, java] ---- @Query(""SELECT COUNT(1) FROM trades WHERE action = @action"") int countByActionQuery(String action); @Query(""SELECT EXISTS(SELECT COUNT(1) FROM trades WHERE action = @action)"") boolean existsByActionQuery(String action); @Query(""SELECT action FROM trades WHERE action = @action LIMIT 1"") String getFirstString(@Param(""action"") String action); @Query(""SELECT action FROM trades WHERE action = @action"") List getFirstStringList(@Param(""action"") String action); ---- DML statements can also be run by query methods, but the only possible return value is a `long` representing the number of affected rows. The `dmlStatement` boolean setting must be set on `@Query` to indicate that the query method is run as a DML statement. [source, java] ---- @Query(value = ""DELETE FROM trades WHERE action = @action"", dmlStatement = true) long deleteByActionQuery(String action); ---- ===== Query methods with named queries properties By default, the `namedQueriesLocation` attribute on `@EnableSpannerRepositories` points to the `META-INF/spanner-named-queries.properties` file. You can specify the query for a method in the properties file by providing the SQL as the value for the ""interface.method"" property: [source, properties] ---- Trade.fetchByActionNamedQuery=SELECT * FROM trades WHERE trades.action = @tag0 ---- [source, java] ---- public interface TradeRepository extends SpannerRepository { // This method uses the query from the properties file instead of one generated based on name. List fetchByActionNamedQuery(@Param(""tag0"") String action); } ---- ===== Query methods with annotation Using the `@Query` annotation: [source, java] ---- public interface TradeRepository extends SpannerRepository { @Query(""SELECT * FROM trades WHERE trades.action = @tag0"") List fetchByActionNamedQuery(@Param(""tag0"") String action); } ---- Table names can be used directly. For example, ""trades"" in the above example. Alternatively, table names can be resolved from the `@Table` annotation on domain classes as well. In this case, the query should refer to table names with fully qualified class names between `:` characters: `:fully.qualified.ClassName:`. A full example would look like: [source, java] ---- @Query(""SELECT * FROM :com.example.Trade: WHERE trades.action = @tag0"") List fetchByActionNamedQuery(String action); ---- This allows table names evaluated with SpEL to be used in custom queries. SpEL can also be used to provide SQL parameters: [source, java] ---- @Query(""SELECT * FROM :com.example.Trade: WHERE trades.action = @tag0 AND price > #{#priceRadius * -1} AND price < #{#priceRadius * 2}"") List fetchByActionNamedQuery(String action, Double priceRadius); ---- When using the `IN` SQL clause, remember to use `IN UNNEST(@iterableParam)` to specify a single `Iterable` parameter. You can also use a fixed number of singular parameters such as `IN (@stringParam1, @stringParam2)`. ==== Projections Spring Data Spanner supports {spring-data-commons-ref}/#projections[projections]. You can define projection interfaces based on domain types and add query methods that return them in your repository: [source, java] ---- public interface TradeProjection { String getAction(); @Value(""#{target.symbol + ' ' + target.action}"") String getSymbolAndAction(); } public interface TradeRepository extends SpannerRepository { List findByTraderId(String traderId); List findByAction(String action); @Query(""SELECT action, symbol FROM trades WHERE action = @action"") List findByQuery(String action); } ---- Projections can be provided by name-convention-based query methods as well as by custom SQL queries. If using custom SQL queries, you can further restrict the columns retrieved from Spanner to just those required by the projection to improve performance. Properties of projection types defined using SpEL use the fixed name `target` for the underlying domain object. As a result accessing underlying properties take the form `target.`. ==== Empty result handling in repository methods Java `java.util.Optional` can be used to indicate the potential absence of a return value. Alternatively, query methods can return the result without a wrapper. In that case the absence of a query result is indicated by returning `null`. Repository methods returning collections are guaranteed never to return `null` but rather the corresponding empty collection. NOTE: You can enable nullability checks. For more details please see https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#null-safety[Spring Framework’s nullability docs]. ==== REST Repositories When running with Spring Boot, repositories can be exposed as REST services by simply adding this dependency to your pom file: [source,xml] ---- org.springframework.boot spring-boot-starter-data-rest ---- If you prefer to configure parameters (such as path), you can use `@RepositoryRestResource` annotation: [source,java] ---- @RepositoryRestResource(collectionResourceRel = ""trades"", path = ""trades"") public interface TradeRepository extends SpannerRepository { } ---- NOTE: For classes that have composite keys (multiple `@PrimaryKey` fields), only the `Key` type is supported for the repository ID type. For example, you can retrieve all `Trade` objects in the repository by using `curl \\http://:/trades`, or any specific trade via `curl \\http://:/trades/,`. The separator between your primary key components, `id` and `trader_id` in this case, is a comma by default, but can be configured to any string not found in your key values by extending the `SpannerKeyIdConverter` class: [source,java] ---- @Component class MySpecialIdConverter extends SpannerKeyIdConverter { @Override protected String getUrlIdSeparator() { return "":""; } } ---- You can also write trades using `curl -XPOST -H""Content-Type: application/json"" -d@test.json \\http://:/trades/` where the file `test.json` holds the JSON representation of a `Trade` object. === Database and Schema Admin Databases and tables inside Spanner instances can be created automatically from `SpannerPersistentEntity` objects: [source,java] ---- @Autowired private SpannerSchemaUtils spannerSchemaUtils; @Autowired private SpannerDatabaseAdminTemplate spannerDatabaseAdminTemplate; public void createTable(SpannerPersistentEntity entity) { if(!spannerDatabaseAdminTemplate.tableExists(entity.tableName()){ // The boolean parameter indicates that the database will be created if it does not exist. spannerDatabaseAdminTemplate.executeDdlStrings(Arrays.asList( spannerSchemaUtils.getCreateTableDDLString(entity.getType())), true); } } ---- Schemas can be generated for entire object hierarchies with interleaved relationships and composite keys. === Events Spring Data Cloud Spanner publishes events extending the Spring Framework's `ApplicationEvent` to the context that can be received by `ApplicationListener` beans you register. [options=""header""] |=== | Type| Description | Contents | `AfterReadEvent`|Published immediately after entities are read by key from Cloud Spanner by `SpannerTemplate`| The entities loaded. The read options and key-set originally specified for the load operation. | `AfterQueryEvent`|Published immediately after entities are read by query from Cloud Spanner by `SpannerTemplate`| The entities loaded. The query options and query statement originally specified for the load operation. | `BeforeExecuteDmlEvent`|Published immediately before DML statements are executed by `SpannerTemplate`| The DML statement to execute. | `AfterExecuteDmlEvent`|Published immediately after DML statements are executed by `SpannerTemplate`| The DML statement to execute and the number of rows affected by the operation as reported by Cloud Spanner. | `BeforeSaveEvent`|Published immediately before upsert/update/insert operations are executed by `SpannerTemplate`| The mutations to be sent to Cloud Spanner, the entities to be saved, and optionally the properties in those entities to save. | `AfterSaveEvent`|Published immediately after upsert/update/insert operations are executed by `SpannerTemplate`| The mutations sent to Cloud Spanner, the entities to be saved, and optionally the properties in those entities to save. | `BeforeDeleteEvent`|Published immediately before delete operations are executed by `SpannerTemplate`| The mutations to be sent to Cloud Spanner. The target entities, keys, or entity type originally specified for the delete operation. | `AfterDeleteEvent`|Published immediately after delete operations are executed by `SpannerTemplate`| The mutations sent to Cloud Spanner. The target entities, keys, or entity type originally specified for the delete operation. |=== === Auditing Spring Data Cloud Spanner supports the `@LastModifiedDate` and `@LastModifiedBy` auditing annotations for properties: [source,java] ---- @Table public class SimpleEntity { @PrimaryKey String id; @LastModifiedBy String lastUser; @LastModifiedDate DateTime lastTouched; } ---- Upon insert, update, or save, these properties will be set automatically by the framework before mutations are generated and saved to Cloud Spanner. To take advantage of these features, add the `@EnableSpannerAuditing` annotation to your configuration class and provide a bean for an `AuditorAware` implementation where the type `A` is the desired property type annotated by `@LastModifiedBy`: [source,java] ---- @Configuration @EnableSpannerAuditing public class Config { @Bean public AuditorAware auditorProvider() { return () -> Optional.of(""YOUR_USERNAME_HERE""); } } ---- The `AuditorAware` interface contains a single method that supplies the value for fields annotated by `@LastModifiedBy` and can be of any type. One alternative is to use Spring Security's `User` type: [source,java] ---- class SpringSecurityAuditorAware implements AuditorAware { public Optional getCurrentAuditor() { return Optional.ofNullable(SecurityContextHolder.getContext()) .map(SecurityContext::getAuthentication) .filter(Authentication::isAuthenticated) .map(Authentication::getPrincipal) .map(User.class::cast); } } ---- You can also set a custom provider for properties annotated `@LastModifiedDate` by providing a bean for `DateTimeProvider` and providing the bean name to `@EnableSpannerAuditing(dateTimeProviderRef = ""customDateTimeProviderBean"")`. === Multi-Instance Usage Your application can be configured to use multiple Cloud Spanner instances or databases by providing a custom bean for `DatabaseIdProvider`. The default bean uses the instance ID, database name, and project ID options you configured in `application.properties`. [source,java] ---- @Bean public DatabaseIdProvider databaseIdProvider() { // return custom connection options provider } ---- The `DatabaseId` given by this provider is used as the target database name and instance of each operation Spring Data Cloud Spanner executes. By providing a custom implementation of this bean (for example, supplying a thread-local `DatabaseId`), you can direct your application to use multiple instances or databases. Database administrative operations, such as creating tables using `SpannerDatabaseAdminTemplate`, will also utilize the provided `DatabaseId`. If you would like to configure every aspect of each connection (such as pool size and retry settings), you can supply a bean for `Supplier`. === Cloud Spanner Emulator The https://cloud.google.com/sdk[Cloud SDK] provides a local, in-memory emulator for Cloud Spanner, which you can use to develop and test your application. As the emulator stores data only in memory, it will not persist data across runs. It is intended to help you use Cloud Spanner for local development and testing, not for production deployments. In order to set up and start the emulator, you can follow https://cloud.google.com/spanner/docs/emulator[these steps]. This command can be used to create Cloud Spanner instances: ---- $ gcloud spanner instances create --config=emulator-config --description="""" --nodes=1 ---- Once the Spanner emulator is running, ensure that the following properties are set in your `application.properties` of your Spring application: ---- spring.cloud.gcp.spanner.emulator.enabled=true spring.cloud.gcp.spanner.emulator-host=${EMULATOR_HOSTPORT} ---- === Sample A https://github.com/spring-cloud/spring-cloud-gcp/tree/master/spring-cloud-gcp-samples/spring-cloud-gcp-data-spanner-sample[sample application] is available. ",12214,False,2035.7212360528429,median "// Module included in the following assemblies: // // * installing/installing_aws/installing-aws-customizations.adoc // * installing/installing_aws/installing-aws-government-region.adoc // * installing/installing_aws/installing-aws-network-customizations.adoc // * installing/installing_aws/installing-aws-private.adoc // * installing/installing_aws/installing-aws-vpc.adoc // * installing/installing_aws/installing-restricted-networks-aws-installer-provisioned.adoc // * installing/installing_azure/installing-azure-customizations.adoc // * installing/installing_azure/installing-azure-government-region.adoc // * installing/installing_azure/installing-azure-network-customizations.adoc // * installing/installing_azure/installing-azure-private.adoc // * installing/installing_azure/installing-azure-vnet.adoc // * installing/installing_bare_metal/installing-bare-metal.adoc // * installing/installing_gcp/installing-gcp-customizations.adoc // * installing/installing_gcp/installing-gcp-private.adoc // * installing/installing_gcp/installing-gcp-network-customizations.adoc // * installing/installing_gcp/installing-gcp-vpc.adoc // * installing/installing_gcp/installing-restricted-networks-gcp-installer-provisioned.adoc // * installing/installing_openstack/installing-openstack-installer-custom.adoc // * installing/installing_openstack/installing-openstack-installer-kuryr.adoc // * installing/installing_openstack/installing-openstack-user.adoc // * installing/installing_openstack/installing-openstack-user-kuryr.adoc // * installing/installing_rhv/installing-rhv-custom.adoc // * installing/installing_vmc/installing-vmc-customizations.adoc // * installing/installing_vmc/installing-vmc-network-customizations.adoc // * installing/installing_vmc/installing-restricted-networks-vmc.adoc // * installing/installing_vsphere/installing-vsphere-installer-provisioned-customizations.adoc // * installing/installing_vsphere/installing-vsphere-installer-provisioned-network-customizations.adoc // * installing/installing_vsphere/installing-restricted-networks-installer-provisioned-vsphere.adoc ifeval::[""{context}"" == ""installing-aws-customizations""] :aws: endif::[] ifeval::[""{context}"" == ""installing-aws-government-region""] :aws: endif::[] ifeval::[""{context}"" == ""installing-aws-network-customizations""] :aws: endif::[] ifeval::[""{context}"" == ""installing-aws-private""] :aws: endif::[] ifeval::[""{context}"" == ""installing-aws-vpc""] :aws: endif::[] ifeval::[""{context}"" == ""installing-restricted-networks-aws-installer-provisioned""] :aws: endif::[] ifeval::[""{context}"" == ""installing-azure-customizations""] :azure: endif::[] ifeval::[""{context}"" == ""installing-azure-government-region""] :azure: endif::[] ifeval::[""{context}"" == ""installing-azure-network-customizations""] :azure: endif::[] ifeval::[""{context}"" == ""installing-azure-private""] :azure: endif::[] ifeval::[""{context}"" == ""installing-azure-vnet""] :azure: endif::[] ifeval::[""{context}"" == ""installing-gcp-customizations""] :gcp: endif::[] // OSDOCS-1640 - IPv4/IPv6 dual-stack bare metal only ifeval::[""{context}"" == ""installing-bare-metal""] :bare: endif::[] // OSDOCS-1640 - IPv4/IPv6 dual-stack bare metal only ifeval::[""{context}"" == ""installing-bare-metal-network-customizations""] :bare: endif::[] // OSDOCS-1640 - IPv4/IPv6 dual-stack bare metal only ifeval::[""{context}"" == ""installing-restricted-networks-bare-metal""] :bare: endif::[] ifeval::[""{context}"" == ""installing-gcp-private""] :gcp: endif::[] ifeval::[""{context}"" == ""installing-gcp-network-customizations""] :gcp: endif::[] ifeval::[""{context}"" == ""installing-gcp-vpc""] :gcp: endif::[] ifeval::[""{context}"" == ""installing-restricted-networks-gcp-installer-provisioned""] :gcp: endif::[] ifeval::[""{context}"" == ""installing-aws-customizations""] :aws: endif::[] ifeval::[""{context}"" == ""installing-openstack-installer-custom""] :osp: :osp-custom: endif::[] ifeval::[""{context}"" == ""installing-openstack-installer-kuryr""] :osp: :osp-kuryr: endif::[] ifeval::[""{context}"" == ""installing-openstack-user""] :osp: :osp-custom: endif::[] ifeval::[""{context}"" == ""installing-openstack-user-kuryr""] :osp: :osp-kuryr: endif::[] ifeval::[""{context}"" == ""installing-openstack-user-sr-iov""] :osp: :osp-custom: endif::[] ifeval::[""{context}"" == ""installing-openstack-user-sr-iov-kuryr""] :osp: :osp-kuryr: endif::[] ifeval::[""{context}"" == ""installing-rhv-customizations""] :rhv: endif::[] ifeval::[""{context}"" == ""installing-vsphere-installer-provisioned-customizations""] :vsphere: endif::[] ifeval::[""{context}"" == ""installing-vsphere-installer-provisioned-network-customizations""] :vsphere: endif::[] ifeval::[""{context}"" == ""installing-vmc-customizations""] :vmc: endif::[] ifeval::[""{context}"" == ""installing-vmc-network-customizations""] :vmc: endif::[] ifeval::[""{context}"" == ""installing-restricted-networks-vmc""] :vmc: endif::[] ifeval::[""{context}"" == ""installing-openstack-installer-restricted""] :osp: :osp-custom: endif::[] ifeval::[""{context}"" == ""installing-restricted-networks-installer-provisioned-vsphere""] :vsphere: endif::[] [id=""installation-configuration-parameters_{context}""] = Installation configuration parameters // If install-config.yaml is generated by openshift-install ifndef::bare[] Before you deploy an {product-title} cluster, you provide parameter values to describe your account on the cloud platform that hosts your cluster and optionally customize your cluster's platform. When you create the `install-config.yaml` installation configuration file, you provide values for the required parameters through the command line. If you customize your cluster, you can modify the `install-config.yaml` file to provide more details about the platform. endif::bare[] // If the user manually creates install-config.yaml ifdef::bare[] Before you deploy an {product-title} cluster, you provide a customized `install-config.yaml` installation configuration file that describes the details for your environment. endif::bare[] [NOTE] ==== After installation, you cannot modify these parameters in the `install-config.yaml` file. ==== [IMPORTANT] ==== The `openshift-install` command does not validate field names for parameters. If an incorrect name is specified, the related file or object is not created, and no error is reported. Ensure that the field names for any parameters that are specified are correct. ==== [id=""installation-configuration-parameters-required_{context}""] == Required configuration parameters Required installation configuration parameters are described in the following table: .Required parameters [cols="".^2,.^3,.^5a"",options=""header""] |==== |Parameter|Description|Values |`apiVersion` |The API version for the `install-config.yaml` content. The current version is `v1`. The installer may also support older API versions. |String |`baseDomain` |The base domain of your cloud provider. The base domain is used to create routes to your {product-title} cluster components. The full DNS name for your cluster is a combination of the `baseDomain` and `metadata.name` parameter values that uses the `.` format. |A fully-qualified domain or subdomain name, such as `example.com`. |`metadata` |Kubernetes resource `ObjectMeta`, from which only the `name` parameter is consumed. |Object |`metadata.name` |The name of the cluster. DNS records for the cluster are all subdomains of `{{.metadata.name}}.{{.baseDomain}}`. |String of lowercase letters, hyphens (`-`), and periods (`.`), such as `dev`. ifdef::osp[] The string must be 14 characters or fewer long. endif::osp[] |`platform` |The configuration for the specific platform upon which to perform the installation: `aws`, `baremetal`, `azure`, `openstack`, `ovirt`, `vsphere`. For additional information about `platform.` parameters, consult the table for your specific platform that follows. |Object ifndef::openshift-origin[] |`pullSecret` |Get a pull secret from link:https://cloud.redhat.com/openshift/install/pull-secret[] to authenticate downloading container images for {product-title} components from services such as Quay.io. | [source,json] ---- { ""auths"":{ ""cloud.openshift.com"":{ ""auth"":""b3Blb="", ""email"":""you@example.com"" }, ""quay.io"":{ ""auth"":""b3Blb="", ""email"":""you@example.com"" } } } ---- endif::[] |==== [id=""installation-configuration-parameters-network_{context}""] == Network configuration parameters You can customize your installation configuration based on the requirements of your existing network infrastructure. For example, you can expand the IP address block for the cluster network or provide different IP address blocks than the defaults. ifndef::bare[] Only IPv4 addresses are supported. endif::bare[] ifdef::bare[] If you use the OVN-Kubernetes cluster network provider, both IPv4 and IPv6 address families are supported. If you use the OpenShift SDN cluster network provider, only the IPv4 address family is supported. If you configure your cluster to use both IP address families, you must specify IPv4 and IPv6 addresses in the same order for all network configuration parameters. For example, in the following configuration IPv4 addresses are listed before IPv6 addresses. [source,yaml] ---- networking: clusterNetwork: - cidr: 10.128.0.0/14 hostPrefix: 23 - cidr: fd00:10:128::/56 hostPrefix: 64 serviceNetwork: - 172.30.0.0/16 - fd00:172:16::/112 ---- endif::bare[] .Network parameters [cols="".^2,.^3a,.^3a"",options=""header""] |==== |Parameter|Description|Values |`networking` |The configuration for the cluster network. |Object [NOTE] ==== You cannot modify parameters specified by the `networking` object after installation. ==== |`networking.networkType` |The cluster network provider Container Network Interface (CNI) plug-in to install. | ifdef::openshift-origin[] Either `OpenShiftSDN` or `OVNKubernetes`. The default value is `OVNKubernetes`. endif::openshift-origin[] ifndef::openshift-origin[] Either `OpenShiftSDN` or `OVNKubernetes`. The default value is `OpenShiftSDN`. endif::openshift-origin[] |`networking.clusterNetwork` | The IP address blocks for pods. The default value is `10.128.0.0/14` with a host prefix of `/23`. If you specify multiple IP address blocks, the blocks must not overlap. |An array of objects. For example: [source,yaml] ---- ifndef::bare[] networking: clusterNetwork: - cidr: 10.128.0.0/14 hostPrefix: 23 endif::bare[] ifdef::bare[] networking: clusterNetwork: - cidr: 10.128.0.0/14 hostPrefix: 23 - cidr: fd01::/48 hostPrefix: 64 endif::bare[] ---- |`networking.clusterNetwork.cidr` | Required if you use `networking.clusterNetwork`. An IP address block. ifndef::bare[] An IPv4 network. endif::bare[] ifdef::bare[] If you use the OpenShift SDN network provider, specify an IPv4 network. If you use the OVN-Kubernetes network provider, you can specify IPv4 and IPv6 networks. endif::bare[] | An IP address block in Classless Inter-Domain Routing (CIDR) notation. The prefix length for an IPv4 block is between `0` and `32`. ifdef::bare[] The prefix length for an IPv6 block is between `0` and `128`. For example, `10.128.0.0/14` or `fd01::/48`. endif::bare[] |`networking.clusterNetwork.hostPrefix` |The subnet prefix length to assign to each individual node. For example, if `hostPrefix` is set to `23` then each node is assigned a `/23` subnet out of the given `cidr`. A `hostPrefix` value of `23` provides 510 (2^(32 - 23) - 2) pod IP addresses. | A subnet prefix. ifndef::bare[] The default value is `23`. endif::bare[] ifdef::bare[] For an IPv4 network the default value is `23`. For an IPv6 network the default value is `64`. The default value is also the minimum value for IPv6. endif::bare[] |`networking.serviceNetwork` | The IP address block for services. The default value is `172.30.0.0/16`. The OpenShift SDN and OVN-Kubernetes network providers support only a single IP address block for the service network. ifdef::bare[] If you use the OVN-Kubernetes network provider, you can specify an IP address block for both of the IPv4 and IPv6 address families. endif::bare[] | An array with an IP address block in CIDR format. For example: [source,yaml] ---- ifndef::bare[] networking: serviceNetwork: - 172.30.0.0/16 endif::bare[] ifdef::bare[] networking: serviceNetwork: - 172.30.0.0/16 - fd02::/112 endif::bare[] ---- |`networking.machineNetwork` | The IP address blocks for machines. If you specify multiple IP address blocks, the blocks must not overlap. |An array of objects. For example: [source,yaml] ---- networking: machineNetwork: - cidr: 10.0.0.0/16 ---- |`networking.machineNetwork.cidr` | Required if you use `networking.machineNetwork`. An IP address block. The default value is `10.0.0.0/16` for all platforms other than libvirt. For libvirt, the default value is `192.168.126.0/24`. | An IP network block in CIDR notation. ifndef::bare[] For example, `10.0.0.0/16`. endif::bare[] ifdef::bare[] For example, `10.0.0.0/16` or `fd00::/48`. endif::bare[] [NOTE] ==== Set the `networking.machineNetwork` to match the CIDR that the preferred NIC resides in. ==== |==== [id=""installation-configuration-parameters-optional_{context}""] == Optional configuration parameters Optional installation configuration parameters are described in the following table: .Optional parameters [cols="".^2,.^3a,.^3a"",options=""header""] |==== |Parameter|Description|Values |`additionalTrustBundle` |A PEM-encoded X.509 certificate bundle that is added to the nodes' trusted certificate store. This trust bundle may also be used when a proxy has been configured. |String |`compute` |The configuration for the machines that comprise the compute nodes. |Array of `MachinePool` objects. For details, see the following ""Machine-pool"" table. |`compute.architecture` |Determines the instruction set architecture of the machines in the pool. Currently, heteregeneous clusters are not supported, so all pools must specify the same architecture. Valid values are `amd64` (the default). |String |`compute.hyperthreading` |Whether to enable or disable simultaneous multithreading, or `hyperthreading`, on compute machines. By default, simultaneous multithreading is enabled to increase the performance of your machines' cores. [IMPORTANT] ==== If you disable simultaneous multithreading, ensure that your capacity planning accounts for the dramatically decreased machine performance. ==== |`Enabled` or `Disabled` |`compute.name` |Required if you use `compute`. The name of the machine pool. |`worker` |`compute.platform` |Required if you use `compute`. Use this parameter to specify the cloud provider to host the worker machines. This parameter value must match the `controlPlane.platform` parameter value. |`aws`, `azure`, `gcp`, `openstack`, `ovirt`, `vsphere`, or `{}` |`compute.replicas` |The number of compute machines, which are also known as worker machines, to provision. |A positive integer greater than or equal to `2`. The default value is `3`. |`controlPlane` |The configuration for the machines that comprise the control plane. |Array of `MachinePool` objects. For details, see the following ""Machine-pool"" table. |`controlPlane.architecture` |Determines the instruction set architecture of the machines in the pool. Currently, heterogeneous clusters are not supported, so all pools must specify the same architecture. Valid values are `amd64` (the default). |String |`controlPlane.hyperthreading` |Whether to enable or disable simultaneous multithreading, or `hyperthreading`, on control plane machines. By default, simultaneous multithreading is enabled to increase the performance of your machines' cores. [IMPORTANT] ==== If you disable simultaneous multithreading, ensure that your capacity planning accounts for the dramatically decreased machine performance. ==== |`Enabled` or `Disabled` |`controlPlane.name` |Required if you use `controlPlane`. The name of the machine pool. |`master` |`controlPlane.platform` |Required if you use `controlPlane`. Use this parameter to specify the cloud provider that hosts the control plane machines. This parameter value must match the `compute.platform` parameter value. |`aws`, `azure`, `gcp`, `openstack`, `ovirt`, `vsphere`, or `{}` |`controlPlane.replicas` |The number of control plane machines to provision. |The only supported value is `3`, which is the default value. |`credentialsMode` |The Cloud Credential Operator (CCO) mode. If no mode is specified, the CCO dynamically tries to determine the capabilities of the provided credentials, with a preference for mint mode on the platforms where multiple modes are supported. [NOTE] ==== Not all CCO modes are supported for all cloud providers. For more information on CCO modes, see the _Cloud Credential Operator_ entry in the _Red Hat Operators reference_ content. ==== |`Mint`, `Passthrough`, `Manual`, or an empty string (`""""`). ifndef::openshift-origin[] |`fips` |Enable or disable FIPS mode. The default is `false` (disabled). If FIPS mode is enabled, the {op-system-first} machines that {product-title} runs on bypass the default Kubernetes cryptography suite and use the cryptography modules that are provided with {op-system} instead. [IMPORTANT] ==== The use of FIPS Validated / Modules in Process cryptographic libraries is only supported on {product-title} deployments on the `x86_64` architecture. ==== [NOTE] ==== If you are using Azure File storage, you cannot enable FIPS mode. ==== |`false` or `true` endif::openshift-origin[] |`imageContentSources` |Sources and repositories for the release-image content. |Array of objects. Includes a `source` and, optionally, `mirrors`, as described in the following rows of this table. |`imageContentSources.source` |Required if you use `imageContentSources`. Specify the repository that users refer to, for example, in image pull specifications. |String |`imageContentSources.mirrors` |Specify one or more repositories that may also contain the same images. |Array of strings |`publish` |How to publish or expose the user-facing endpoints of your cluster, such as the Kubernetes API, OpenShift routes. | ifdef::aws,azure,gcp[] `Internal` or `External`. To deploy a private cluster, which cannot be accessed from the internet, set `publish` to `Internal`. The default value is `External`. endif::[] ifndef::aws,azure,gcp[] `Internal` or `External`. The default value is `External`. Setting this field to `Internal` is not supported on non-cloud platforms. ifeval::[{product-version} <= 4.7] [IMPORTANT] ==== If the value of the field is set to `Internal`, the cluster will become non-functional. For more information, refer to link:https://bugzilla.redhat.com/show_bug.cgi?id=1953035[BZ#1953035]. ==== endif::[] endif::[] |`sshKey` | The SSH key to authenticate access to your cluster machines. [NOTE] ==== For production {product-title} clusters on which you want to perform installation debugging or disaster recovery, specify an SSH key that your `ssh-agent` process uses. ==== a|For example, `sshKey: ssh-ed25519 AAAA..`. |==== ifdef::aws[] [id=""installation-configuration-parameters-optional-aws_{context}""] == Optional AWS configuration parameters Optional AWS configuration parameters are described in the following table: .Optional AWS parameters [cols="".^2,.^3,.^5a"",options=""header""] |==== |Parameter|Description|Values |`compute.platform.aws.amiID` |The AWS AMI used to boot compute machines for the cluster. This is required for regions that require a custom {op-system} AMI. |Any published or custom {op-system} AMI that belongs to the set AWS region. |`compute.platform.aws.iamRole` |A pre-existing AWS IAM role applied to the compute machine pool instance profiles. You can use these fields to match naming schemes and include predefined permissions boundaries for your IAM roles. If undefined, the installation program creates a new IAM role. |The name of a valid AWS IAM role. |`compute.platform.aws.rootVolume.iops` |The Input/Output Operations Per Second (IOPS) that is reserved for the root volume. |Integer, for example `4000`. |`compute.platform.aws.rootVolume.size` |The size in GiB of the root volume. |Integer, for example `500`. |`compute.platform.aws.rootVolume.type` |The instance type of the root volume. |Valid link:https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSVolumeTypes.html[AWS EBS instance type], such as `io1`. |`compute.platform.aws.type` |The EC2 instance type for the compute machines. |Valid AWS instance type, such as `m4.2xlarge`. See the *Instance types for machines* table that follows. //add an xref when possible. |`compute.platform.aws.zones` |The availability zones where the installation program creates machines for the compute machine pool. If you provide your own VPC, you must provide a subnet in that availability zone. |A list of valid AWS availability zones, such as `us-east-1c`, in a link:https://yaml.org/spec/1.2/spec.html#sequence//[YAML sequence]. |`compute.aws.region` |The AWS region that the installation program creates compute resources in. |Any valid link:https://docs.aws.amazon.com/general/latest/gr/rande.html[AWS region], such as `us-east-1`. |`controlPlane.platform.aws.amiID` |The AWS AMI used to boot control plane machines for the cluster. This is required for regions that require a custom {op-system} AMI. |Any published or custom {op-system} AMI that belongs to the set AWS region. |`controlPlane.platform.aws.iamRole` |A pre-existing AWS IAM role applied to the control plane machine pool instance profiles. You can use these fields to match naming schemes and include predefined permissions boundaries for your IAM roles. If undefined, the installation program creates a new IAM role. |The name of a valid AWS IAM role. |`controlPlane.platform.aws.type` |The EC2 instance type for the control plane machines. |Valid AWS instance type, such as `m5.xlarge`. See the *Instance types for machines* table that follows. //add an xref when possible |`controlPlane.platform.aws.zones` |The availability zones where the installation program creates machines for the control plane machine pool. |A list of valid AWS availability zones, such as `us-east-1c`, in a link:https://yaml.org/spec/1.2/spec.html#sequence//[YAML sequence]. |`controlPlane.aws.region` |The AWS region that the installation program creates control plane resources in. |Valid link:https://docs.aws.amazon.com/general/latest/gr/rande.html[AWS region], such as `us-east-1`. |`platform.aws.amiID` |The AWS AMI used to boot all machines for the cluster. If set, the AMI must belong to the same region as the cluster. This is required for regions that require a custom {op-system} AMI. |Any published or custom {op-system} AMI that belongs to the set AWS region. |`platform.aws.hostedZone` |An existing Route 53 private hosted zone for the cluster. You can only use a pre-existing hosted zone when also supplying your own VPC. The hosted zone must already be associated with the user-provided VPC before installation. Also, the domain of the hosted zone must be the cluster domain or a parent of the cluster domain. If undefined, the installation program creates a new hosted zone. |String, for example `Z3URY6TWQ91KVV`. |`platform.aws.serviceEndpoints.name` |The AWS service endpoint name. Custom endpoints are only required for cases where alternative AWS endpoints, like FIPS, must be used. Custom API endpoints can be specified for EC2, S3, IAM, Elastic Load Balancing, Tagging, Route 53, and STS AWS services. |Valid link:https://docs.aws.amazon.com/general/latest/gr/rande.html[AWS service endpoint] name. |`platform.aws.serviceEndpoints.url` |The AWS service endpoint URL. The URL must use the `https` protocol and the host must trust the certificate. |Valid link:https://docs.aws.amazon.com/general/latest/gr/rande.html[AWS service endpoint] URL. |`platform.aws.userTags` |A map of keys and values that the installation program adds as tags to all resources that it creates. |Any valid YAML map, such as key value pairs in the `: ` format. For more information about AWS tags, see link:https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html[Tagging Your Amazon EC2 Resources] in the AWS documentation. |`platform.aws.subnets` |If you provide the VPC instead of allowing the installation program to create the VPC for you, specify the subnet for the cluster to use. The subnet must be part of the same `machineNetwork[].cidr` ranges that you specify. For a standard cluster, specify a public and a private subnet for each availability zone. For a private cluster, specify a private subnet for each availability zone. |Valid subnet IDs. |==== endif::aws[] ifdef::osp[] [id=""installation-configuration-parameters-additional-osp_{context}""] == Additional {rh-openstack-first} configuration parameters Additional {rh-openstack} configuration parameters are described in the following table: .Additional {rh-openstack} parameters [cols="".^2m,.^3a,^5a"",options=""header""] |==== |Parameter|Description|Values |`compute.platform.openstack.rootVolume.size` |For compute machines, the size in gigabytes of the root volume. If you do not set this value, machines use ephemeral storage. |Integer, for example `30`. |`compute.platform.openstack.rootVolume.type` |For compute machines, the root volume's type. |String, for example `performance`. |`controlPlane.platform.openstack.rootVolume.size` |For control plane machines, the size in gigabytes of the root volume. If you do not set this value, machines use ephemeral storage. |Integer, for example `30`. |`controlPlane.platform.openstack.rootVolume.type` |For control plane machines, the root volume's type. |String, for example `performance`. |`platform.openstack.cloud` |The name of the {rh-openstack} cloud to use from the list of clouds in the `clouds.yaml` file. |String, for example `MyCloud`. |`platform.openstack.externalNetwork` |The {rh-openstack} external network name to be used for installation. |String, for example `external`. |`platform.openstack.computeFlavor` |The {rh-openstack} flavor to use for control plane and compute machines. This property is deprecated. To use a flavor as the default for all machine pools, add it as the value of the `type` key in the `platform.openstack.defaultMachinePlatform` property. You can also set a flavor value for each machine pool individually. |String, for example `m1.xlarge`. |==== [id=""installation-configuration-parameters-optional-osp_{context}""] == Optional {rh-openstack} configuration parameters Optional {rh-openstack} configuration parameters are described in the following table: .Optional {rh-openstack} parameters [%header, cols="".^2,.^3,.^5a""] |==== |Parameter|Description|Values |`compute.platform.openstack.additionalNetworkIDs` |Additional networks that are associated with compute machines. Allowed address pairs are not created for additional networks. |A list of one or more UUIDs as strings. For example, `fa806b2f-ac49-4bce-b9db-124bc64209bf`. |`compute.platform.openstack.additionalSecurityGroupIDs` |Additional security groups that are associated with compute machines. |A list of one or more UUIDs as strings. For example, `7ee219f3-d2e9-48a1-96c2-e7429f1b0da7`. |`compute.platform.openstack.zones` |{rh-openstack} Compute (Nova) availability zones (AZs) to install machines on. If this parameter is not set, the installer relies on the default settings for Nova that the {rh-openstack} administrator configured. On clusters that use Kuryr, {rh-openstack} Octavia does not support availability zones. Load balancers and, if you are using the Amphora provider driver, {product-title} services that rely on Amphora VMs, are not created according to the value of this property. |A list of strings. For example, `[""zone-1"", ""zone-2""]`. |`compute.platform.openstack.rootVolume.zones` |For compute machines, the availability zone to install root volumes on. If you do not set a value for this parameter, the installer selects the default availability zone. |A list of strings, for example `[""zone-1"", ""zone-2""]`. |`controlPlane.platform.openstack.additionalNetworkIDs` |Additional networks that are associated with control plane machines. Allowed address pairs are not created for additional networks. |A list of one or more UUIDs as strings. For example, `fa806b2f-ac49-4bce-b9db-124bc64209bf`. |`controlPlane.platform.openstack.additionalSecurityGroupIDs` |Additional security groups that are associated with control plane machines. |A list of one or more UUIDs as strings. For example, `7ee219f3-d2e9-48a1-96c2-e7429f1b0da7`. |`controlPlane.platform.openstack.zones` |{rh-openstack} Compute (Nova) availability zones (AZs) to install machines on. If this parameter is not set, the installer relies on the default settings for Nova that the {rh-openstack} administrator configured. On clusters that use Kuryr, {rh-openstack} Octavia does not support availability zones. Load balancers and, if you are using the Amphora provider driver, {product-title} services that rely on Amphora VMs, are not created according to the value of this property. |A list of strings. For example, `[""zone-1"", ""zone-2""]`. |`controlPlane.platform.openstack.rootVolume.zones` |For control plane machines, the availability zone to install root volumes on. If you do not set this value, the installer selects the default availability zone. |A list of strings, for example `[""zone-1"", ""zone-2""]`. |`platform.openstack.clusterOSImage` |The location from which the installer downloads the {op-system} image. You must set this parameter to perform an installation in a restricted network. |An HTTP or HTTPS URL, optionally with an SHA-256 checksum. For example, `\\http://mirror.example.com/images/rhcos-43.81.201912131630.0-openstack.x86_64.qcow2.gz?sha256=ffebbd68e8a1f2a245ca19522c16c86f67f9ac8e4e0c1f0a812b068b16f7265d`. The value can also be the name of an existing Glance image, for example `my-rhcos`. |`platform.openstack.clusterOSImageProperties` |Properties to add to the installer-uploaded ClusterOSImage in Glance. This property is ignored if `platform.openstack.clusterOSImage` is set to an existing Glance image. You can use this property to exceed the default persistent volume (PV) limit for {rh-openstack} of 26 PVs per node. To exceed the limit, set the `hw_scsi_model` property value to `virtio-scsi` and the `hw_disk_bus` value to `scsi`. You can also use this property to enable the QEMU guest agent by including the `hw_qemu_guest_agent` property with a value of `yes`. |A list of key-value string pairs. For example, `[""hw_scsi_model"": ""virtio-scsi"", ""hw_disk_bus"": ""scsi""]`. |`platform.openstack.defaultMachinePlatform` |The default machine pool platform configuration. | [source,json] ---- { ""type"": ""ml.large"", ""rootVolume"": { ""size"": 30, ""type"": ""performance"" } } ---- |`platform.openstack.ingressFloatingIP` |An existing floating IP address to associate with the Ingress port. To use this property, you must also define the `platform.openstack.externalNetwork` property. |An IP address, for example `128.0.0.1`. |`platform.openstack.apiFloatingIP` |An existing floating IP address to associate with the API load balancer. To use this property, you must also define the `platform.openstack.externalNetwork` property. |An IP address, for example `128.0.0.1`. |`platform.openstack.externalDNS` |IP addresses for external DNS servers that cluster instances use for DNS resolution. |A list of IP addresses as strings. For example, `[""8.8.8.8"", ""192.168.1.12""]`. |`platform.openstack.machinesSubnet` |The UUID of a {rh-openstack} subnet that the cluster's nodes use. Nodes and virtual IP (VIP) ports are created on this subnet. The first item in `networking.machineNetwork` must match the value of `machinesSubnet`. If you deploy to a custom subnet, you cannot specify an external DNS server to the {product-title} installer. Instead, link:https://access.redhat.com/documentation/en-us/red_hat_openstack_platform/16.0/html/command_line_interface_reference/subnet[add DNS to the subnet in {rh-openstack}]. |A UUID as a string. For example, `fa806b2f-ac49-4bce-b9db-124bc64209bf`. |==== endif::osp[] ifdef::azure[] [id=""installation-configuration-parameters-additional-azure_{context}""] == Additional Azure configuration parameters Additional Azure configuration parameters are described in the following table: .Additional Azure parameters [cols="".^2,.^3a,.^3a"",options=""header""] |==== |Parameter|Description|Values |`controlPlane.platform.azure.osDisk.diskSizeGB` |The Azure disk size for the VM. |Integer that represents the size of the disk in GB. The minimum supported disk size is `1024`. |`platform.azure.baseDomainResourceGroupName` |The name of the resource group that contains the DNS zone for your base domain. |String, for example `production_cluster`. |`platform.azure.resourceGroupName` | The name of an already existing resource group to install your cluster to. This resource group must be empty and only used for this specific cluster; the cluster components assume ownership of all resources in the resource group. If you limit the service principal scope of the installation program to this resource group, you must ensure all other resources used by the installation program in your environment have the necessary permissions, such as the public DNS zone and virtual network. Destroying the cluster using the installation program deletes this resource group. |String, for example `existing_resource_group`. |`platform.azure.outboundType` |The outbound routing strategy used to connect your cluster to the internet. If you are using user-defined routing, you must have pre-existing networking available where the outbound routing has already been configured prior to installing a cluster. The installation program is not responsible for configuring user-defined routing. |`LoadBalancer` or `UserDefinedRouting`. The default is `LoadBalancer`. |`platform.azure.region` |The name of the Azure region that hosts your cluster. |Any valid region name, such as `centralus`. |`platform.azure.zone` |List of availability zones to place machines in. For high availability, specify at least two zones. |List of zones, for example `[""1"", ""2"", ""3""]`. |`platform.azure.networkResourceGroupName` |The name of the resource group that contains the existing VNet that you want to deploy your cluster to. This name cannot be the same as the `platform.azure.baseDomainResourceGroupName`. |String. |`platform.azure.virtualNetwork` |The name of the existing VNet that you want to deploy your cluster to. |String. |`platform.azure.controlPlaneSubnet` |The name of the existing subnet in your VNet that you want to deploy your control plane machines to. |Valid CIDR, for example `10.0.0.0/16`. |`platform.azure.computeSubnet` |The name of the existing subnet in your VNet that you want to deploy your compute machines to. |Valid CIDR, for example `10.0.0.0/16`. |`platform.azure.cloudName` |The name of the Azure cloud environment that is used to configure the Azure SDK with the appropriate Azure API endpoints. If empty, the default value `AzurePublicCloud` is used. |Any valid cloud environment, such as `AzurePublicCloud` or `AzureUSGovernmentCloud`. |==== [NOTE] ==== You cannot customize link:https://azure.microsoft.com/en-us/global-infrastructure/availability-zones/[Azure Availability Zones] or link:https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-using-tags[Use tags to organize your Azure resources] with an Azure cluster. ==== endif::azure[] ifdef::gcp[] [id=""installation-configuration-parameters-additional-gcp_{context}""] == Additional Google Cloud Platform (GCP) configuration parameters Additional GCP configuration parameters are described in the following table: .Additional GCP parameters [cols="".^2,.^3a,.^3a"",options=""header""] |==== |Parameter|Description|Values |`platform.gcp.network` |The name of the existing VPC that you want to deploy your cluster to. |String. |`platform.gcp.type` |The link:https://cloud.google.com/compute/docs/machine-types[GCP machine type]. |The GCP machine type. |`platform.gcp.zones` |The availability zones where the installation program creates machines for the specified MachinePool. |A list of valid link:https://cloud.google.com/compute/docs/regions-zones#available[GCP availability zones], such as `us-central1-a`, in a link:https://yaml.org/spec/1.2/spec.html#sequence//[YAML sequence]. |`platform.gcp.controlPlaneSubnet` |The name of the existing subnet in your VPC that you want to deploy your control plane machines to. |The subnet name. |`platform.gcp.computeSubnet` |The name of the existing subnet in your VPC that you want to deploy your compute machines to. |The subnet name. |`controlPlane.platform.gcp.osDisk.encryptionKey.kmsKey.name` |The name of the customer managed encryption key to be used for control plane machine disk encryption. |The encryption key name. |`controlPlane.platform.gcp.osDisk.encryptionKey.kmsKey.keyRing` |For control plane machines, the name of the KMS key ring to which the KMS key belongs. |The KMS key ring name. |`controlPlane.platform.gcp.osDisk.encryptionKey.kmsKey.location` |For control plane machines, the GCP location in which the key ring exists. For more information on KMS locations, see Google's documentation on link:https://cloud.google.com/kms/docs/locations[Cloud KMS locations]. |The GCP location for the key ring. |`controlPlane.platform.gcp.osDisk.encryptionKey.kmsKey.projectID` |For control plane machines, the ID of the project in which the KMS key ring exists. This value defaults to the VM project ID if not set. |The GCP project ID. //// `controlPlane.platform.gcp.osDisk.encryptionKey.kmsKeyServiceAccount` The GCP Compute Engine System service account used for the encryption request for the given KMS key. The Compute Engine default service account is always used for control plane machines during installation, which follows this pattern: `service-@compute-system.iam.gserviceaccount.com`. The default service account must have access to the KMS key specified for the control plane machines. The custom service account defined is available for use during post-installation operations. For more information on GCP service accounts, see Google's documentation on link:https://cloud.google.com/iam/docs/service-accounts#types[Types of service accounts]. The GCP Compute Engine System service account email, like `@.iam.gserviceaccount.com`. //// // kmsKeyServiceAccount not yet fully supported in 4.7. Re-add when more stable. |`compute.platform.gcp.osDisk.encryptionKey.kmsKey.name` |The name of the customer managed encryption key to be used for compute machine disk encryption. |The encryption key name. |`compute.platform.gcp.osDisk.encryptionKey.kmsKey.keyRing` |For compute machines, the name of the KMS key ring to which the KMS key belongs. |The KMS key ring name. |`compute.platform.gcp.osDisk.encryptionKey.kmsKey.location` |For compute machines, the GCP location in which the key ring exists. For more information on KMS locations, see Google's documentation on link:https://cloud.google.com/kms/docs/locations[Cloud KMS locations]. |The GCP location for the key ring. |`compute.platform.gcp.osDisk.encryptionKey.kmsKey.projectID` |For compute machines, the ID of the project in which the KMS key ring exists. This value defaults to the VM project ID if not set. |The GCP project ID. //// `compute.platform.gcp.osDisk.encryptionKey.kmsKeyServiceAccount` For compute machines, the GCP Compute Engine System service account used for the encryption request for the given KMS key. If left undefined, the Compute Engine default service account is used, which follows this pattern: `service-@compute-system.iam.gserviceaccount.com`. For more information on GCP service accounts, see Google's documentation on link:https://cloud.google.com/iam/docs/service-accounts#types[Types of service accounts]. The GCP Compute Engine System service account email, like `@.iam.gserviceaccount.com`. //// // kmsKeyServiceAccount not yet fully supported in 4.7. Re-add when more stable. |==== endif::gcp[] ifdef::rhv[] [id=""installation-configuration-parameters-additional-rhv_{context}""] == Additional {rh-virtualization-first} configuration parameters Additional {rh-virtualization} configuration parameters are described in the following table: .Additional {rh-virtualization} parameters for clusters [cols="".^2,.^3a,.^3a"",options=""header""] |==== |Parameter|Description|Values |`platform.ovirt.ovirt_cluster_id` |Required. The Cluster where the VMs will be created. |String. For example: `68833f9f-e89c-4891-b768-e2ba0815b76b` |`platform.ovirt.ovirt_storage_domain_id` |Required. The Storage Domain ID where the VM disks will be created. |String. For example: `ed7b0f4e-0e96-492a-8fff-279213ee1468` |`platform.ovirt.ovirt_network_name` |Required. The network name where the VM nics will be created. |String. For example: `ocpcluster` |`platform.ovirt.vnicProfileID` |Required. The vNIC profile ID of the VM network interfaces. This can be inferred if the cluster network has a single profile. |String. For example: `3fa86930-0be5-4052-b667-b79f0a729692` |`platform.ovirt.api_vip` |Required. An IP address on the machine network that will be assigned to the API virtual IP (VIP). You can access the OpenShift API at this endpoint. |String. Example: `10.46.8.230` |`platform.ovirt.ingress_vip` |Required. An IP address on the machine network that will be assigned to the Ingress virtual IP (VIP). |String. Example: `10.46.8.232` |==== [id=""installation-configuration-parameters-additional-machine_{context}""] == Additional {rh-virtualization} parameters for machine pools Additional {rh-virtualization} configuration parameters for machine pools are described in the following table: .Additional {rh-virtualization} parameters for machine pools [cols="".^2,.^3a,.^3a"",options=""header""] |==== |Parameter|Description|Values |`.platform.ovirt.cpu` |Optional. Defines the CPU of the VM. |Object |`.platform.ovirt.cpu.cores` |Required if you use `.platform.ovirt.cpu`. The number of cores. Total virtual CPUs (vCPUs) is cores * sockets. |Integer |`.platform.ovirt.cpu.sockets` |Required if you use `.platform.ovirt.cpu`. The number of sockets per core. Total virtual CPUs (vCPUs) is cores * sockets. |Integer |`.platform.ovirt.memoryMB` |Optional. Memory of the VM in MiB. |Integer |`.platform.ovirt.instanceTypeID` |Optional. An instance type UUID, such as `00000009-0009-0009-0009-0000000000f1`, which you can get from the `https:///ovirt-engine/api/instancetypes` endpoint. |String of UUID |`.platform.ovirt.osDisk` |Optional. Defines the first and bootable disk of the VM. |String |`.platform.ovirt.osDisk.sizeGB` |Required if you use `.platform.ovirt.osDisk`. Size of the disk in GiB. |Number |`.platform.ovirt.vmType` |Optional. The VM workload type, such as `high-performance`, `server`, or `desktop`. |String |==== [NOTE] ==== You can replace `` with `controlPlane` or `compute`. ==== endif::rhv[] ifdef::vsphere,vmc[] [id=""installation-configuration-parameters-additional-vsphere_{context}""] == Additional VMware vSphere configuration parameters Additional VMware vSphere configuration parameters are described in the following table: .Additional VMware vSphere cluster parameters [cols="".^2,.^3a,.^3a"",options=""header""] |==== |Parameter|Description|Values |`platform.vsphere.vCenter` |The fully-qualified hostname or IP address of the vCenter server. |String |`platform.vsphere.username` |The user name to use to connect to the vCenter instance with. This user must have at least the roles and privileges that are required for link:https://vmware.github.io/vsphere-storage-for-kubernetes/documentation/vcp-roles.html[static or dynamic persistent volume provisioning] in vSphere. |String |`platform.vsphere.password` |The password for the vCenter user name. |String |`platform.vsphere.datacenter` |The name of the datacenter to use in the vCenter instance. |String |`platform.vsphere.defaultDatastore` |The name of the default datastore to use for provisioning volumes. |String |`platform.vsphere.folder` |_Optional_. The absolute path of an existing folder where the installation program creates the virtual machines. If you do not provide this value, the installation program creates a folder that is named with the infrastructure ID in the datacenter virtual machine folder. |String, for example, `//vm//`. |`platform.vsphere.network` |The network in the vCenter instance that contains the virtual IP addresses and DNS records that you configured. |String |`platform.vsphere.cluster` |The vCenter cluster to install the {product-title} cluster in. |String |`platform.vsphere.apiVIP` |The virtual IP (VIP) address that you configured for control plane API access. |An IP address, for example `128.0.0.1`. |`platform.vsphere.ingressVIP` |The virtual IP (VIP) address that you configured for cluster ingress. |An IP address, for example `128.0.0.1`. |==== [id=""installation-configuration-parameters-optional-vsphere_{context}""] == Optional VMware vSphere machine pool configuration parameters Optional VMware vSphere machine pool configuration parameters are described in the following table: .Optional VMware vSphere machine pool parameters [cols="".^2,.^3a,.^3a"",options=""header""] |==== |Parameter|Description|Values |`platform.vsphere.clusterOSImage` |The location from which the installer downloads the {op-system} image. You must set this parameter to perform an installation in a restricted network. |An HTTP or HTTPS URL, optionally with a SHA-256 checksum. For example, `\\https://mirror.openshift.com/images/rhcos--vmware..ova`. |`platform.vsphere.osDisk.diskSizeGB` |The size of the disk in gigabytes. |Integer |`platform.vsphere.cpus` |The total number of virtual processor cores to assign a virtual machine. |Integer |`platform.vsphere.coresPerSocket` |The number of cores per socket in a virtual machine. The number of virtual CPUs (vCPUs) on the virtual machine is `platform.vsphere.cpus`/`platform.vsphere.coresPerSocket`. The default value is `1` |Integer |`platform.vsphere.memoryMB` |The size of a virtual machine's memory in megabytes. |Integer |==== endif::vsphere,vmc[] ifdef::bare[] :!bare: endif::bare[] ifeval::[""{context}"" == ""installing-aws-customizations""] :!aws: endif::[] ifeval::[""{context}"" == ""installing-aws-government-region""] :!aws: endif::[] ifeval::[""{context}"" == ""installing-aws-network-customizations""] :!aws: endif::[] ifeval::[""{context}"" == ""installing-aws-private""] :!aws: endif::[] ifeval::[""{context}"" == ""installing-aws-vpc""] :!aws: endif::[] ifeval::[""{context}"" == ""installing-restricted-networks-aws-installer-provisioned""] :!aws: endif::[] ifeval::[""{context}"" == ""installing-azure-customizations""] :!azure: endif::[] ifeval::[""{context}"" == ""installing-azure-government-region""] :!azure: endif::[] ifeval::[""{context}"" == ""installing-azure-network-customizations""] :!azure: endif::[] ifeval::[""{context}"" == ""installing-azure-private""] :!azure: endif::[] ifeval::[""{context}"" == ""installing-azure-vnet""] :!azure: endif::[] ifeval::[""{context}"" == ""installing-gcp-customizations""] :!gcp: endif::[] ifeval::[""{context}"" == ""installing-gcp-private""] :!gcp: endif::[] ifeval::[""{context}"" == ""installing-gcp-network-customizations""] :!gcp: endif::[] ifeval::[""{context}"" == ""installing-gcp-vpc""] :!gcp: endif::[] ifeval::[""{context}"" == ""installing-restricted-networks-gcp-installer-provisioned""] :!gcp: endif::[] ifeval::[""{context}"" == ""installing-aws-customizations""] :!aws: endif::[] ifeval::[""{context}"" == ""installing-openstack-installer-custom""] :!osp: :!osp-custom: endif::[] ifeval::[""{context}"" == ""installing-openstack-installer-kuryr""] :!osp: :!osp-kuryr: endif::[] ifeval::[""{context}"" == ""installing-openstack-user""] :!osp: :!osp-custom: endif::[] ifeval::[""{context}"" == ""installing-openstack-user-kuryr""] :!osp: :!osp-kuryr: endif::[] ifeval::[""{context}"" == ""installing-openstack-user-sr-iov""] :!osp: :!osp-custom: endif::[] ifeval::[""{context}"" == ""installing-openstack-user-sr-iov-kuryr""] :!osp: :!osp-kuryr: endif::[] ifeval::[""{context}"" == ""installing-rhv-customizations""] :!rhv: endif::[] ifeval::[""{context}"" == ""installing-vsphere-installer-provisioned-customizations""] :!vsphere: endif::[] ifeval::[""{context}"" == ""installing-vsphere-installer-provisioned-network-customizations""] :!vsphere: endif::[] ifeval::[""{context}"" == ""installing-vmc-customizations""] :!vmc: endif::[] ifeval::[""{context}"" == ""installing-vmc-network-customizations""] :!vmc: endif::[] ifeval::[""{context}"" == ""installing-restricted-networks-vmc""] :!vmc: endif::[] ifeval::[""{context}"" == ""installing-openstack-installer-restricted""] :!osp: :!osp-custom: endif::[] ifeval::[""{context}"" == ""installing-restricted-networks-installer-provisioned-vsphere""] :!vsphere: endif::[] ",12478,False,2303.155592323616,median "[[install-config-upgrading-manual-upgrades]] = Performing Manual In-place Cluster Upgrades {product-author} {product-version} :latest-tag: v3.6.173.0.5 :latest-int-tag: v3.6 :data-uri: :icons: :experimental: :toc: macro :toc-title: :prewrap!: toc::[] == Overview [IMPORTANT] ==== An etcd performance issue has been discovered on new and upgraded {product-title} ifdef::openshift-enterprise[] 3.6 endif::[] ifdef::openshift-origin[] 1.4+ endif::[] clusters. See the following Knowledgebase Solution for further details: https://access.redhat.com/solutions/2916381[] + (link:https://bugzilla.redhat.com/show_bug.cgi?id=1415839[*BZ#1415839*]) ==== As an alternative to performing an xref:../../install_config/upgrading/automated_upgrades.adoc#install-config-upgrading-automated-upgrades[automated upgrade], you can manually upgrade your OpenShift cluster. To manually upgrade without disruption, it is important to upgrade each component as documented in this topic. Before you begin your upgrade, familiarize yourself now with the entire procedure. xref:additional-instructions-per-release[Specific releases may require additional steps] to be performed at key points before or during the standard upgrade process. [IMPORTANT] ==== Ensure that you have met all xref:../../install_config/install/prerequisites.adoc#install-config-install-prerequisites[prerequisites] before proceeding with an upgrade. Failure to do so can result in a failed upgrade. ==== [[preparing-for-a-manual-upgrade]] == Preparing for a Manual Upgrade [NOTE] ==== Before upgrading your cluster to {product-title} 3.6, the cluster must be already upgraded to the link:https://docs.openshift.com/container-platform/3.5/release_notes/ocp_3_5_release_notes.html#ocp-35-asynchronous-errata-updates[latest asynchronous release of version 3.5]. Cluster upgrades cannot span more than one minor version at a time, so if your cluster is at a version earlier than 3.5, you must first upgrade incrementally (e.g., 3.3 to 3.4, then 3.4 to 3.5). ==== [NOTE] ==== Before attempting the upgrade, follow the steps in xref:manual-upgrades-verifying-the-upgrade[Verifying the Upgrade] to verify the cluster's health. This will confirm that nodes are in the *Ready* state, running the expected starting version, and will ensure that there are no diagnostic errors or warnings. ==== To prepare for a manual upgrade, follow these steps: ifdef::openshift-enterprise[] . If you are upgrading from {product-title} 3.5 to 3.6, manually disable the 3.5 channel and enable the 3.6 channel on each host: + ---- # subscription-manager repos --disable=""rhel-7-server-ose-3.5-rpms"" \\ --enable=""rhel-7-server-ose-3.6-rpms"" \\ --enable=""rhel-7-server-extras-rpms"" \\ --enable=""rhel-7-fast-datapath-rpms"" ---- + On RHEL 7 systems, also clear the *yum* cache: + ---- # yum clean all ---- endif::[] . Install or update to the latest available version of the *atomic-openshift-utils* package on each RHEL 7 system, which provides files that will be used in later sections: + ---- # yum install atomic-openshift-utils ---- .. When installing or updating *atomic-openshift-utils*, *_/usr/share/openshift/examples/_* does not get updated with the latest templates. To update the file: + ---- # mkdir /usr/share/openshift/examples # cp -R /usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/* /usr/share/openshift/examples/ ---- . Install or update to the following latest available **-excluder* packages on each RHEL 7 system, which helps ensure your systems stay on the correct versions of *atomic-openshift* and *docker* packages when you are not trying to upgrade, according to the {product-title} version: + ---- # yum install atomic-openshift-excluder atomic-openshift-docker-excluder ---- + These packages add entries to the `exclude` directive in the host's *_/etc/yum.conf_* file. . Create an *etcd* backup on each master. The *etcd* package is required, even if using embedded etcd, for access to the `etcdctl` command to make the backup. + [NOTE] ==== The *etcd* package is installed by default for RHEL Atomic Host 7 systems. If the master is a RHEL 7 system and *etcd* is not already installed, install it now: ---- # yum install etcd ---- ==== + To create the backup, run: + ---- # ETCD_DATA_DIR=/var/lib/origin/openshift.local.etcd <1> # etcdctl backup \\ --data-dir $ETCD_DATA_DIR \\ --backup-dir $ETCD_DATA_DIR.bak. <2> ---- <1> This directory is for embedded etcd. For external etcd, use *_/var/lib/etcd_* instead. <2> Use the date of the backup, or some unique identifier, for ``. The command will not make a backup if the `--backup-dir` location already exists. . For any upgrade path, ensure that you are running the latest kernel on each RHEL 7 system: + ---- # yum update kernel ---- [[upgrading-masters]] == Upgrading Master Components Before upgrading any stand-alone nodes, upgrade the master components (which provide the _control plane_ for the cluster). . Run the following command on each master to remove the *atomic-openshift* packages from the list of yum excludes on the host: + ---- # atomic-openshift-excluder unexclude ---- . Upgrade *etcd* on all master hosts and any external etcd hosts. .. For RHEL 7 systems using the RPM-based method: ... Upgrade the *etcd* package: + ---- # yum update etcd ---- ... Restart the *etcd* service and review the logs to ensure it restarts successfully: + ---- # systemctl restart etcd # journalctl -r -u etcd ---- .. For RHEL Atomic Host 7 systems and RHEL 7 systems using the containerized method: ... Pull the latest *rhel7/etcd* image: + ---- # docker pull registry.access.redhat.com/rhel7/etcd ---- ... Restart the *etcd_container* service and review the logs to ensure it restarts successfully: + ---- # systemctl restart etcd_container # journalctl -r -u etcd_container ---- ifdef::openshift-origin[] . On each master host, upgrade the *origin-master* package: + ---- # yum upgrade origin-master ---- . If you are upgrading from OpenShift Origin 1.0 to 1.1: .. Create the following master proxy client certificates: + ---- # cd /etc/origin/master/ # oadm ca create-master-certs --cert-dir=/etc/origin/master/ \\ --master=https://:8443 \\ --public-master=https://:8443 \\ --hostnames=,,localhost,127.0.0.1,,kubernetes.default.local \\ --overwrite=false ---- + This creates files at *_/etc/origin/master/master.proxy-client.{crt,key}_*. Then, add the master proxy client certificates to the *_/etc/origin/master/master-config.yml_* file on each master: + ---- kubernetesMasterConfig: proxyClientInfo: certFile: master.proxy-client.crt keyFile: master.proxy-client.key ---- .. Enable the following renamed service(s) on master hosts. + For single master clusters: + ---- # systemctl enable origin-master ---- + For multi-master clusters: + ---- # systemctl enable origin-master-api # systemctl enable origin-master-controllers ---- . Restart the master service(s) on each master and review logs to ensure they restart successfully. + For single master clusters: + ---- # systemctl restart origin-master # journalctl -r -u origin-master ---- + For multi-master clusters: + ---- # systemctl restart origin-master-controllers # systemctl restart origin-master-api # journalctl -r -u origin-master-controllers # journalctl -r -u origin-master-api ---- . Because masters also have node components running on them in order to be configured as part of the OpenShift SDN, restart the *origin-node* and *openvswitch* services: + ---- # systemctl restart openvswitch # systemctl restart origin-node # journalctl -r -u openvswitch # journalctl -r -u origin-node ---- endif::[] ifdef::openshift-enterprise[] . On each master host, upgrade the *atomic-openshift* packages or related images. .. For masters using the RPM-based method on a RHEL 7 system, upgrade all installed *atomic-openshift* packages and the *openvswitch* package: + ---- # yum upgrade atomic-openshift\\* openvswitch ---- .. For masters using the containerized method on a RHEL 7 or RHEL Atomic Host 7 system, set the `*IMAGE_VERSION*` parameter to the version you are upgrading to in the following files: + -- - *_/etc/sysconfig/atomic-openshift-master_* (single master clusters only) - *_/etc/sysconfig/atomic-openshift-master-controllers_* (multi-master clusters only) - *_/etc/sysconfig/atomic-openshift-master-api_* (multi-master clusters only) - *_/etc/sysconfig/atomic-openshift-node_* - *_/etc/sysconfig/atomic-openshift-openvswitch_* -- + For example: + ---- IMAGE_VERSION= ---- + Replace `` with `{latest-tag}` for the latest version. . Restart the master service(s) on each master and review logs to ensure they restart successfully. + For single master clusters: + ---- # systemctl restart atomic-openshift-master # journalctl -r -u atomic-openshift-master ---- + For multi-master clusters: + ---- # systemctl restart atomic-openshift-master-controllers # systemctl restart atomic-openshift-master-api # journalctl -r -u atomic-openshift-master-controllers # journalctl -r -u atomic-openshift-master-api ---- . Because masters also have node components running on them in order to be configured as part of the OpenShift SDN, restart the *atomic-openshift-node* and *openvswitch* services: + ---- # systemctl restart openvswitch # systemctl restart atomic-openshift-node # journalctl -r -u openvswitch # journalctl -r -u atomic-openshift-node ---- endif::[] . If you are performing a cluster upgrade that requires updating Docker to version 1.12, you must also perform the following steps if you are not already on Docker 1.12: + [IMPORTANT] ==== The node component on masters is set by default to unschedulable status during initial installation, so that pods are not deployed to them. However, it is possible to set them schedulable during the initial installation or manually thereafter. If any of your masters are also configured as a schedulable node, skip the following Docker upgrade steps for those masters and instead run all steps described in xref:upgrading-nodes[Upgrading Nodes] when you get to that section for those hosts as well. ==== .. Upgrade the *docker* package. ... For RHEL 7 systems: + ---- # yum update docker ---- + Then, restart the *docker* service and review the logs to ensure it restarts successfully: + ---- # systemctl restart docker # journalctl -r -u docker ---- ... For RHEL Atomic Host 7 systems, upgrade to the latest Atomic tree if one is available: + [NOTE] ==== If upgrading to RHEL Atomic Host 7.3.2, this upgrades Docker to version 1.12. ==== + ---- # atomic host upgrade ---- .. After the upgrade is completed and prepared for the next boot, reboot the host and ensure the *docker* service starts successfully: + ---- # systemctl reboot # journalctl -r -u docker ---- .. Remove the following file, which is no longer required: + ---- # rm /etc/systemd/system/docker.service.d/docker-sdn-ovs.conf ---- . Run the following command on each master to add the *atomic-openshift* packages back to the list of yum excludes on the host: + ---- # atomic-openshift-excluder exclude ---- [NOTE] ==== During the cluster upgrade, it can sometimes be useful to take a master out of rotation since some DNS client libraries will not properly to the other masters for cluster DNS. In addition to stopping the master and controller services, you can remove the EndPoint from the Kubernetes service's `*subsets.addresses*`. ---- $ oc edit ep/kubernetes -n default ---- When the master is restarted, the Kubernetes service will be automatically updated. ==== [[updating-policy-definitions]] == Updating Policy Definitions After a cluster upgrade, the default roles xref:../../architecture/additional_concepts/authorization.adoc#roles[default cluster roles] are automatically updated. To check if all defaults are set as recommended for your environment, run: ---- # oadm policy reconcile-cluster-roles ---- [WARNING] ==== If you have customized default cluster roles and want to ensure a role reconciliation does not modify those customized roles, annotate them with `openshift.io/reconcile-protect` set to `true` when using the old Openshift policy format. When using the new RBAC roles, use `rbac.authorization.kubernetes.io/autoupdate` set to `false` instead. In doing so, you are responsible for manually updating those roles with any new or required permissions during upgrades. ==== This command outputs a list of roles that are out of date and their new proposed values. For example: ---- # oadm policy reconcile-cluster-roles apiVersion: v1 items: - apiVersion: v1 kind: ClusterRole metadata: creationTimestamp: null name: admin rules: - attributeRestrictions: null resources: - builds/custom ... ---- [NOTE] ==== Your output will vary based on the OpenShift version and any local customizations you have made. Review the proposed policy carefully. ==== You can either modify this output to re-apply any local policy changes you have made, or you can automatically apply the new policy using the following process: . Reconcile the cluster roles: + ---- # oadm policy reconcile-cluster-roles \\ --additive-only=true \\ --confirm ---- . Reconcile the cluster role bindings: + ---- # oadm policy reconcile-cluster-role-bindings \\ --exclude-groups=system:authenticated \\ --exclude-groups=system:authenticated:oauth \\ --exclude-groups=system:unauthenticated \\ --exclude-users=system:anonymous \\ --additive-only=true \\ --confirm ---- + Also run: + ---- # oadm policy reconcile-cluster-role-bindings \\ system:build-strategy-jenkinspipeline \\ --confirm \\ -o name ---- . Reconcile security context constraints: + ---- # oadm policy reconcile-sccs \\ --additive-only=true \\ --confirm ---- [[upgrading-nodes]] == Upgrading Nodes After upgrading your masters, you can upgrade your nodes. When restarting the ifdef::openshift-origin[] *origin-node* service, there will be a brief disruption of outbound network endif::[] ifdef::openshift-enterprise[] *atomic-openshift-node* service, there will be a brief disruption of outbound network endif::[] connectivity from running pods to services while the xref:../../architecture/infrastructure_components/kubernetes_infrastructure.adoc#service-proxy[service proxy] is restarted. The length of this disruption should be very short and scales based on the number of services in the entire cluster. [NOTE] ==== You can alternatively use the xref:../../install_config/upgrading/blue_green_deployments.adoc#upgrading-blue-green-deployments[blue-green deployment] method at this point to create a parallel environment for new nodes instead of upgrading them in place. ==== One at at time for each node that is not also a master, you must disable scheduling and evacuate its pods to other nodes, then upgrade packages and restart services. . Run the following command on each node to remove the *atomic-openshift* packages from the list of yum excludes on the host: + ---- # atomic-openshift-excluder unexclude ---- . As a user with *cluster-admin* privileges, disable scheduling for the node: + ---- # oadm manage-node --schedulable=false ---- . Evacuate pods on the node to other nodes: + [IMPORTANT] ==== The `--force` option deletes any pods that are not backed by a replication controller. ==== + ---- # oadm drain --force --delete-local-data --ignore-daemonsets ---- ifdef::openshift-origin[] . On the node host, upgrade all *origin* packages: + ---- # yum upgrade origin\\* ---- . If you are upgrading from OpenShift Origin 1.0 to 1.1, enable the following renamed service on the node host: + ---- # systemctl enable origin-node ---- . Restart the *origin-node* and *openvswitch* services and review the logs to ensure they restart successfully: + ---- # systemctl restart openvswitch # systemctl restart origin-node # journalctl -r -u origin-node # journalctl -r -u openvswitch ---- endif::[] ifdef::openshift-enterprise[] . Upgrade the node component packages or related images. .. For nodes using the RPM-based method on a RHEL 7 system, upgrade all installed *atomic-openshift* packages and the *openvswitch* package: + ---- # yum upgrade atomic-openshift\\* openvswitch ---- .. For nodes using the containerized method on a RHEL 7 or RHEL Atomic Host 7 system, set the `*IMAGE_VERSION*` parameter in the *_/etc/sysconfig/atomic-openshift-node_* and *_/etc/sysconfig/openvswitch_* files to the version you are upgrading to. For example: + ---- IMAGE_VERSION= ---- + Replace `` with `{latest-tag}` for the latest version. . Restart the *atomic-openshift-node* and *openvswitch* services and review the logs to ensure they restart successfully: + ---- # systemctl restart openvswitch # systemctl restart atomic-openshift-node # journalctl -r -u atomic-openshift-node # journalctl -r -u openvswitch ---- endif::[] . If you are performing a cluster upgrade that requires updating Docker to version 1.12, you must also perform the following steps if you are not already on Docker 1.12: .. Upgrade the *docker* package. ... For RHEL 7 systems: + ---- # yum update docker ---- + Then, restart the *docker* service and review the logs to ensure it restarts successfully: + ---- # systemctl restart docker # journalctl -r -u docker ---- + After Docker is restarted, restart the *atomic-openshift-node* service again and review the logs to ensure it restarts successfully: + ---- # systemctl restart atomic-openshift-node # journalctl -r -u atomic-openshift-node ---- ... For RHEL Atomic Host 7 systems, upgrade to the latest Atomic tree if one is available: + [NOTE] ==== If upgrading to RHEL Atomic Host 7.3.2, this upgrades Docker to version 1.12. ==== + ---- # atomic host upgrade ---- + After the upgrade is completed and prepared for the next boot, reboot the host and ensure the *docker* service starts successfully: + ---- # systemctl reboot # journalctl -r -u docker ---- .. Remove the following file, which is no longer required: + ---- # rm /etc/systemd/system/docker.service.d/docker-sdn-ovs.conf ---- . Re-enable scheduling for the node: + ---- # oadm manage-node --schedulable ---- . Run the following command on each node to add the *atomic-openshift* packages back to the list of yum excludes on the host: + ---- # atomic-openshift-excluder exclude ---- . Repeat the previous steps on the next node, and continue repeating these steps until all nodes have been upgraded. . After all nodes have been upgraded, as a user with *cluster-admin* privileges, verify that all nodes are showing as *Ready*: + ---- # oc get nodes NAME STATUS AGE master.example.com Ready,SchedulingDisabled 165d node1.example.com Ready 165d node2.example.com Ready 165d ---- [[upgrading-the-router]] == Upgrading the Router If you have previously xref:../../install_config/router/index.adoc#install-config-router-overview[deployed a router], the router deployment configuration must be upgraded to apply updates contained in the router image. To upgrade your router without disrupting services, you must have previously deployed a xref:../../admin_guide/high_availability.adoc#configuring-a-highly-available-service[highly-available routing service]. ifdef::openshift-origin[] [IMPORTANT] ==== If you are upgrading to OpenShift Origin 1.0.4 or 1.0.5, first see the xref:additional-instructions-per-release[Additional Manual Instructions per Release] section for important steps specific to your upgrade, then continue with the router upgrade as described in this section. ==== endif::[] Edit your router's deployment configuration. For example, if it has the default *router* name: ---- # oc edit dc/router ---- Apply the following changes: ---- ... spec: template: spec: containers: - env: ... ifdef::openshift-enterprise[] image: registry.access.redhat.com/openshift3/ose-haproxy-router: <1> endif::[] ifdef::openshift-origin[] image: openshift/origin-haproxy-router:v1.0.6 <1> endif::[] imagePullPolicy: IfNotPresent ... ---- <1> Adjust `` to match the version you are upgrading to (use `{latest-tag}` for the latest version). You should see one router pod updated and then the next. [[upgrading-the-registry]] == Upgrading the Registry The registry must also be upgraded for changes to take effect in the registry image. If you have used a `*PersistentVolumeClaim*` or a host mount point, you may restart the registry without losing the contents of your registry. xref:../../install_config/registry/deploy_registry_existing_clusters.adoc#storage-for-the-registry[Storage for the Registry] details how to configure persistent storage for the registry. Edit your registry's deployment configuration: ---- # oc edit dc/docker-registry ---- Apply the following changes: ---- ... spec: template: spec: containers: - env: ... ifdef::openshift-enterprise[] image: registry.access.redhat.com/openshift3/ose-docker-registry: <1> endif::[] ifdef::openshift-origin[] image: openshift/origin-docker-registry:v1.0.4 <1> endif::[] imagePullPolicy: IfNotPresent ... ---- <1> Adjust `` to match the version you are upgrading to (use `{latest-tag}` for the latest version). ifdef::openshift-enterprise[] If the registry console is deployed, edit its deployment configuration: ---- # oc edit dc/registry-console ---- Apply the following changes: ---- ... spec: template: spec: containers: - env: ... image: registry.access.redhat.com/openshift3/registry-console:v3.6 imagePullPolicy: IfNotPresent ... ---- endif::[] [IMPORTANT] ==== Images that are being pushed or pulled from the internal registry at the time of upgrade will fail and should be restarted automatically. This will not disrupt pods that are already running. ==== ifdef::openshift-origin[] [[updating-the-registry-configuration-file]] === Updating Custom Registry Configuration Files [NOTE] ==== You may safely skip this part if you do not use a custom registry configuration file. ==== The internal Docker registry version 1.4.0 and higher requires following entries in the xref:../registry/extended_registry_configuration.adoc#docker-registry-configuration-reference-middleware[middleware section] of the configuration file: [source,yaml] ---- middleware: registry: - name: openshift repository: - name: openshift storage: - name: openshift ---- . Edit your custom configuration file, adding the missing entries. . xref:../registry/extended_registry_configuration.adoc#advanced-overriding-the-registry-configuration[Deploy your updated configuration]. . Append the `--overwrite` flag to `oc volume dc/docker-registry --add` to replace a volume mount of your previous secret. . You can safely remove the old secret. [[enforcing-quota-in-the-registry]] === Enforcing Quota in the Registry Quota must be enforced to prevent layer blobs that exceed the size limit from being written to the registry's storage. This can be achieved via a xref:../registry/extended_registry_configuration.adoc#registry-configuration-reference[configuration file]: ---- ... middleware: repository: - name: openshift options: enforcequota: true ... ---- Alternatively, use the `*REGISTRY_MIDDLEWARE_REPOSITORY_OPENSHIFT_ENFORCEQUOTA*` environment variable, which is set to `*true*` for the new registry deployments by default. Existing deployments need to be modified using: ---- # oc set env dc/docker-registry REGISTRY_MIDDLEWARE_REPOSITORY_OPENSHIFT_ENFORCEQUOTA=true ---- endif::[] [[updating-the-default-image-streams-and-templates]] == Updating the Default Image Streams and Templates ifdef::openshift-origin[] By default, the xref:../../install_config/install/advanced_install.adoc#install-config-install-advanced-install[advanced installation] method automatically creates default image streams, InstantApp templates, and database service templates in the *openshift* project, which is a default project to which all users have view access. These objects were created during installation from the JSON files located under *_/usr/share/openshift/examples_*. To update these objects: . Ensure that you have the latest *openshift-ansible* code checked out, which provides the example JSON files: + ---- # cd ~/openshift-ansible # git pull https://github.com/openshift/openshift-ansible master ---- endif::[] ifdef::openshift-enterprise[] By default, the xref:../../install_config/install/quick_install.adoc#install-config-install-quick-install[quick] and xref:../../install_config/install/advanced_install.adoc#install-config-install-advanced-install[advanced installation] methods automatically create default image streams, InstantApp templates, and database service templates in the *openshift* project, which is a default project to which all users have view access. These objects were created during installation from the JSON files located under the *_/usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/_* directory. [NOTE] ==== Because RHEL Atomic Host 7 cannot use *yum* to update packages, the following steps must take place on a RHEL 7 system. ==== Update the packages that provide the example JSON files. On a subscribed Red Hat Enterprise Linux 7 system where you can run the CLI as a user with *cluster-admin* permissions, install or update to the latest version of the *atomic-openshift-utils* package, which should also update the *openshift-ansible-* packages: ---- # yum update atomic-openshift-utils ---- To persist *_/usr/share/openshift/examples/_* on the first master: ---- scp -R /usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/* user@master1:/usr/share/openshift/examples/ ---- To persist *_/usr/share/openshift/examples/_* on all masters: ---- mkdir /usr/share/openshift/examples scp -R /usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/* user@masterx:/usr/share/openshift/examples ---- The *openshift-ansible-roles* package provides the latest example JSON files. endif::[] . After a manual upgrade, get the latest templates from *openshift-ansible-roles*: + ---- rpm -ql openshift-ansible-roles | grep examples | grep v3.6 ---- + In this example, *_/usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/image-streams/image-streams-rhel7.json_* is the latest file that you want in the latest *openshift-ansible-roles* package. + *_/usr/share/openshift/examples/image-streams/image-streams-rhel7.json_* is not owned by a package, but is updated by Ansible. If you are upgrading outside of Ansible. you need to get the latest .json files on the system where you are running `oc`, which can run anywhere that has access to the master. . Install *atomic-openshift-utils* and its dependencies to install the new content into *_/usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/_*.: + ---- $ oc create -n openshift -f /usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/image-streams/image-streams-rhel7.json $ oc create -n openshift -f /usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/image-streams/dotnet_imagestreams.json $ oc replace -n openshift -f /usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/image-streams/image-streams-rhel7.json $ oc replace -n openshift -f /usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/image-streams/dotnet_imagestreams.json ---- . Update the templates: + ---- $ oc create -n openshift -f /usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/quickstart-templates/ $ oc create -n openshift -f /usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/db-templates/ $ oc create -n openshift -f /usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/infrastructure-templates/ $ oc create -n openshift -f /usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/xpaas-templates/ $ oc create -n openshift -f /usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/xpaas-streams/ $ oc replace -n openshift -f /usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/quickstart-templates/ $ oc replace -n openshift -f /usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/db-templates/ $ oc replace -n openshift -f /usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/infrastructure-templates/ $ oc replace -n openshift -f /usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/xpaas-templates/ $ oc replace -n openshift -f /usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/xpaas-streams/ ---- + Errors are generated for items that already exist. This is expected behavior: + ---- # oc create -n openshift -f /usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/quickstart-templates/ Error from server: error when creating ""/usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/quickstart-templates/cakephp-mysql.json"": templates ""cakephp-mysql-example"" already exists Error from server: error when creating ""/usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/quickstart-templates/cakephp.json"": templates ""cakephp-example"" already exists Error from server: error when creating ""/usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/quickstart-templates/dancer-mysql.json"": templates ""dancer-mysql-example"" already exists Error from server: error when creating ""/usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/quickstart-templates/dancer.json"": templates ""dancer-example"" already exists Error from server: error when creating ""/usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/quickstart-templates/django-postgresql.json"": templates ""django-psql-example"" already exists ---- Now, content can be updated. Without running the automated upgrade playbooks, the content is not updated in *_/usr/share/openshift/_*. [[importing-the-latest-images]] == Importing the Latest Images After xref:updating-the-default-image-streams-and-templates[updating the default image streams], you may also want to ensure that the images within those streams are updated. For each image stream in the default *openshift* project, you can run: ---- # oc import-image -n openshift ---- For example, get the list of all image streams in the default *openshift* project: ==== ---- # oc get is -n openshift NAME DOCKER REPO TAGS UPDATED mongodb registry.access.redhat.com/openshift3/mongodb-24-rhel7 2.4,latest,v3.1.1.6 16 hours ago mysql registry.access.redhat.com/openshift3/mysql-55-rhel7 5.5,latest,v3.1.1.6 16 hours ago nodejs registry.access.redhat.com/openshift3/nodejs-010-rhel7 0.10,latest,v3.1.1.6 16 hours ago ... ---- ==== Update each image stream one at a time: ==== ---- # oc import-image -n openshift nodejs The import completed successfully. Name: nodejs Created: 10 seconds ago Labels: Annotations: openshift.io/image.dockerRepositoryCheck=2016-07-05T19:20:30Z Docker Pull Spec: 172.30.204.22:5000/openshift/nodejs Tag Spec Created PullSpec Image latest 4 9 seconds ago registry.access.redhat.com/rhscl/nodejs-4-rhel7:latest 570ad8ed927fd5c2c9554ef4d9534cef808dfa05df31ec491c0969c3bd372b05 4 registry.access.redhat.com/rhscl/nodejs-4-rhel7:latest 9 seconds ago 570ad8ed927fd5c2c9554ef4d9534cef808dfa05df31ec491c0969c3bd372b05 0.10 registry.access.redhat.com/openshift3/nodejs-010-rhel7:latest 9 seconds ago a1ef33be788a28ec2bdd48a9a5d174ebcfbe11c8e986d2996b77f5bccaaa4774 ---- ==== [IMPORTANT] ==== In order to update your S2I-based applications, you must manually trigger a new build of those applications after importing the new images using `oc start-build `. ==== ifdef::openshift-origin[] :sect: manual // tag::30to31updatingcerts[] [id='{sect}-updating-master-and-node-certificates'] == Updating Master and Node Certificates The following steps may be required for any OpenShift cluster that was originally installed prior to the https://github.com/openshift/origin/releases[OpenShift Origin 1.0.8 release]. This may include any and all updates from that version. [id='{sect}-updating-node-certificates'] === Node Certificates With the 1.0.8 release, certificates for each of the kubelet nodes were updated to include the IP address of the node. Any node certificates generated before the 1.0.8 release may not contain the IP address of the node. If a node is missing the IP address as part of its certificate, clients may refuse to connect to the kubelet endpoint. Usually this will result in errors regarding the certificate not containing an `IP SAN`. In order to remedy this situation, you may need to manually update the certificates for your node. [id='{sect}-checking-the-nodes-certificate'] ==== Checking the Node's Certificate The following command can be used to determine which Subject Alternative Names (SANs) are present in the node's serving certificate. In this example, the Subject Alternative Names are *mynode*, *mynode.mydomain.com*, and *1.2.3.4*: ==== ---- # openssl x509 -in /etc/origin/node/server.crt -text -noout | grep -A 1 ""Subject Alternative Name"" X509v3 Subject Alternative Name: DNS:mynode, DNS:mynode.mydomain.com, IP: 1.2.3.4 ---- ==== Ensure that the `*nodeIP*` value set in the *_/etc/origin/node/node-config.yaml_* file is present in the IP values from the Subject Alternative Names listed in the node's serving certificate. If the `*nodeIP*` is not present, then it will need to be added to the node's certificate. If the `*nodeIP*` value is already contained within the Subject Alternative Names, then no further steps are required. You will need to know the Subject Alternative Names and `*nodeIP*` value for the following steps. [id='{sect}-generating-a-new-node-certificate'] ==== Generating a New Node Certificate If your current node certificate does not contain the proper IP address, then you must regenerate a new certificate for your node. [IMPORTANT] ==== Node certificates will be regenerated on the master (or first master) and are then copied into place on node systems. ==== . Create a temporary directory in which to perform the following steps: + ---- # mkdir /tmp/node_certificate_update # cd /tmp/node_certificate_update ---- . Export the signing options: + ---- # export signing_opts=""--signer-cert=/etc/origin/master/ca.crt \\ --signer-key=/etc/origin/master/ca.key \\ --signer-serial=/etc/origin/master/ca.serial.txt"" ---- . Generate the new certificate: + ---- # oadm ca create-server-cert --cert=server.crt \\ --key=server.key $signing_opts \\ --hostnames=, ---- + For example, if the Subject Alternative Names from before were *mynode*, *mynode.mydomain.com*, and *1.2.3.4*, and the `*nodeIP*` was 10.10.10.1, then you would need to run the following command: + ---- # oadm ca create-server-cert --cert=server.crt \\ --key=server.key $signing_opts \\ --hostnames=mynode,mynode.mydomain.com,1.2.3.4,10.10.10.1 ---- [id='{sect}-replace-node-serving-certificates'] ==== Replace Node Serving Certificates Back up the existing *_/etc/origin/node/server.crt_* and *_/etc/origin/node/server.key_* files for your node: ---- # mv /etc/origin/node/server.crt /etc/origin/node/server.crt.bak # mv /etc/origin/node/server.key /etc/origin/node/server.key.bak ---- You must now copy the new *_server.crt_* and *_server.key_* created in the temporary directory during the previous step: ---- # mv /tmp/node_certificate_update/server.crt /etc/origin/node/server.crt # mv /tmp/node_certificate_update/server.key /etc/origin/node/server.key ---- After you have replaced the node's certificate, restart the node service: ---- # systemctl restart origin-node ---- [id='{sect}-updating-master-certificates'] === Master Certificates With the 1.0.8 release, certificates for each of the masters were updated to include all names that pods may use to communicate with masters. Any master certificates generated before the 1.0.8 release may not contain these additional service names. [id='{sect}-checking-the-masters-certificate'] ==== Checking the Master's Certificate The following command can be used to determine which Subject Alternative Names (SANs) are present in the master's serving certificate. In this example, the Subject Alternative Names are *mymaster*, *mymaster.mydomain.com*, and *1.2.3.4*: ---- # openssl x509 -in /etc/origin/master/master.server.crt -text -noout | grep -A 1 ""Subject Alternative Name"" X509v3 Subject Alternative Name: DNS:mymaster, DNS:mymaster.mydomain.com, IP: 1.2.3.4 ---- Ensure that the following entries are present in the Subject Alternative Names for the master's serving certificate: [options=""header""] |=== |Entry |Example |Kubernetes service IP address |172.30.0.1 |All master host names |*master1.example.com* |All master IP addresses |192.168.122.1 |Public master host name in clustered environments |*public-master.example.com* |*kubernetes* | |*kubernetes.default* | |*kubernetes.default.svc* | |*kubernetes.default.svc.cluster.local* | |*openshift* | |*openshift.default* | |*openshift.default.svc* | |*openshift.default.svc.cluster.local* | |=== If these names are already contained within the Subject Alternative Names, then no further steps are required. [id='{sect}-generating-a-new-master-certificate'] ==== Generating a New Master Certificate If your current master certificate does not contain all names from the list above, then you must generate a new certificate for your master: . Back up the existing *_/etc/origin/master/master.server.crt_* and *_/etc/origin/master/master.server.key_* files for your master: + ---- # mv /etc/origin/master/master.server.crt /etc/origin/master/master.server.crt.bak # mv /etc/origin/master/master.server.key /etc/origin/master/master.server.key.bak ---- . Export the service names. These names will be used when generating the new certificate: + ---- # export service_names=""kubernetes,kubernetes.default,kubernetes.default.svc,kubernetes.default.svc.cluster.local,openshift,openshift.default,openshift.default.svc,openshift.default.svc.cluster.local"" ---- . You will need the first IP in the services subnet (the *kubernetes* service IP) as well as the values of `*masterIP*`, `*masterURL*` and `*publicMasterURL*` contained in the *_/etc/origin/master/master-config.yaml_* file for the following steps. + The *kubernetes* service IP can be obtained with: + ---- # oc get svc/kubernetes --template='{{.spec.clusterIP}}' ---- . Generate the new certificate: + ==== ---- # oadm ca create-master-certs \\ --hostnames=,,,$service_names \\ <1> <2> <3> --master= \\ <4> --public-master= \\ <5> --cert-dir=/etc/origin/master/ \\ --overwrite=false ---- <1> Adjust `` to match your master host name. In a clustered environment, add all master host names. <2> Adjust `` to match the value of `*masterIP*`. In a clustered environment, add all master IP addresses. <3> Adjust `` to the first IP in the *kubernetes* services subnet. <4> Adjust `` to match the value of `*masterURL*`. <5> Adjust `` to match the value of `*masterPublicURL*`. ==== . Restart master services. For single master deployments: + ---- # systemctl restart origin-master ---- + For native HA multiple master deployments: + ---- # systemctl restart origin-master-api # systemctl restart origin-master-controllers ---- + After the service restarts, the certificate update is complete. // end::30to31updatingcerts[] endif::[] [[manual-upgrading-efk-logging-stack]] == Upgrading the EFK Logging Stack [NOTE] ==== Manual upgrade steps for logging deployments are no longer available starting in {product-title} ifdef::openshift-enterprise[] 3.5. endif::[] ifdef::openshift-origin[] 1.5. endif::[] ==== include::install_config/upgrading/automated_upgrades.adoc[tag=automated-logging-upgrade-steps] [[manual-upgrading-cluster-metrics]] == Upgrading Cluster Metrics [NOTE] ==== Manual upgrade steps for metrics deployments are no longer available starting in {product-title} ifdef::openshift-enterprise[] 3.5. endif::[] ifdef::openshift-origin[] 1.5. endif::[] ==== include::install_config/upgrading/automated_upgrades.adoc[tag=automated-metrics-upgrade-steps] [[additional-instructions-per-release]] == Additional Manual Steps Per Release Some {product-title} releases may have additional instructions specific to that release that must be performed to fully apply the updates across the cluster. ifdef::openshift-enterprise[] This section will be updated over time as new asynchronous updates are released for {product-title} 3.6. See the xref:../../release_notes/ocp_3_6_release_notes.adoc#release-notes-ocp-3-6-release-notes[{product-title} 3.6 Release Notes] to review the latest release notes. ifdef::openshift-origin[] Read through the following sections carefully depending on your upgrade path, as you may be required to perform certain steps at key points during the standard upgrade process described earlier in this topic. [[openshift-origin-1-0-4]] === OpenShift Origin 1.0.4 The following steps are required for the https://github.com/openshift/origin/releases/tag/v1.0.4[OpenShift Origin 1.0.4 release]. *Creating a Service Account for the Router* The default HAProxy router was updated to utilize host ports and requires that a service account be created and made a member of the privileged xref:../../admin_guide/manage_scc.adoc#admin-guide-manage-scc[security context constraint] (SCC). Additionally, ""down-then-up"" rolling upgrades have been added and is now the preferred strategy for upgrading routers. After upgrading your master and nodes but before updating to the newer router, you must create a service account for the router. As a cluster administrator, ensure you are operating on the *default* project: ==== ---- # oc project default ---- ==== Delete any existing *router* service account and create a new one: ==== ---- # oc delete serviceaccount/router serviceaccounts/router # echo '{""kind"":""ServiceAccount"",""apiVersion"":""v1"",""metadata"":{""name"":""router""}}' | oc create -f - serviceaccounts/router ---- ==== Edit the *privileged* SCC: ==== ---- # oc edit scc privileged ---- ==== Apply the following changes: ==== ---- allowHostDirVolumePlugin: true allowHostNetwork: true <1> allowHostPorts: true <2> allowPrivilegedContainer: true ... users: - system:serviceaccount:openshift-infra:build-controller - system:serviceaccount:default:router <3> ---- <1> Add or update `allowHostNetwork: true`. <2> Add or update `allowHostPorts: true`. <3> Add the service account you created to the `*users*` list at the end of the file. ==== Edit your router's deployment configuration: ---- # oc edit dc/router ---- Apply the following changes: ---- ... spec: replicas: 2 selector: router: router strategy: resources: {} rollingParams: intervalSeconds: 1 timeoutSeconds: 120 updatePeriodSeconds: 1 updatePercent: -10 <1> type: Rolling ... template: ... spec: ... dnsPolicy: ClusterFirst restartPolicy: Always serviceAccount: router <2> serviceAccountName: router <3> ... ---- <1> Add `updatePercent: -10` to allow down-then-up rolling upgrades. <2> Add `serviceAccount: router` to the template `*spec*`. <3> Add `serviceAccountName: router` to the template `*spec*`. Now upgrade your router per the xref:upgrading-the-router[standard router upgrade steps]. [[openshift-origin-1-0-5]] === OpenShift Origin 1.0.5 The following steps are required for the https://github.com/openshift/origin/releases[OpenShift Origin 1.0.5 release]. *Switching the Router to Use the Host Network Stack* The default HAProxy router was updated to use the host networking stack by default instead of the former behavior of xref:../../install_config/router/default_haproxy_router.adoc#using-the-container-network-stack[using the container network stack], which proxied traffic to the router, which in turn proxied the traffic to the target service and container. This new default behavior benefits performance because network traffic from remote clients no longer needs to take multiple hops through user space in order to reach the target service and container. Additionally, the new default behavior enables the router to get the actual source IP address of the remote connection. This is useful for defining ingress rules based on the originating IP, supporting sticky sessions, and monitoring traffic, among other uses. Existing router deployments will continue to use the container network stack unless modified to switch to using the host network stack. To switch the router to use the host network stack, edit your router's deployment configuration: ==== ---- # oc edit dc/router ---- ==== Apply the following changes: ==== ---- ... spec: replicas: 2 selector: router: router ... template: ... spec: ... ports: - containerPort: 80 <1> hostPort: 80 protocol: TCP - containerPort: 443 <1> hostPort: 443 protocol: TCP - containerPort: 1936 <1> hostPort: 1936 name: stats protocol: TCP resources: {} terminationMessagePath: /dev/termination-log dnsPolicy: ClusterFirst hostNetwork: true <2> restartPolicy: Always ... ---- ==== <1> For host networking, ensure that the `*containerPort*` value matches the `*hostPort*` values for each of the ports. <2> Add `*hostNetwork: true*` to the template `*spec*`. Now upgrade your router per the xref:upgrading-the-router[standard router upgrade steps]. *Configuring serviceNetworkCIDR for the SDN* Add the `*serviceNetworkCIDR*` parameter to the `*networkConfig*` section in *_/etc/origin/master/master-config.yaml_*. This value should match the `*servicesSubnet*` value in the `*kubernetesMasterConfig*` section: ==== ---- kubernetesMasterConfig: servicesSubnet: 172.30.0.0/16 ... networkConfig: serviceNetworkCIDR: 172.30.0.0/16 ---- ==== *Adding the Scheduler Configuration API Version* The scheduler configuration file incorrectly lacked `*kind*` and `*apiVersion*` fields when deployed using the quick or advanced installation methods. This will affect future upgrades, so it is important to add those values if they do not exist. Modify the *_/etc/origin/master/scheduler.json_* file to add the `*kind*` and `*apiVersion*` fields: ==== ---- { ""kind"": ""Policy"", <1> ""apiVersion"": ""v1"", <2> ""predicates"": [ ... } ---- ==== <1> Add `*""kind"": ""Policy"",*` <2> Add `*""apiVersion"": ""v1"",*` [[openshift-origin-1-1-0]] === OpenShift Origin 1.1.0 There are no additional manual steps for this release that are not already mentioned inline during the xref:preparing-for-a-manual-upgrade[standard manual upgrade process]. [[openshift-origin-1-5-0]] === OpenShift Origin 1.5.0 With deprecation of the `extensions/v1beta1.Job` resource, you must migrate all `Job` resources to use the `batch/v1.Job` instead. To verify which objects will be migrated, run: ---- $ oadm migrate storage --include=jobs ---- You can also increase the log level using the `--loglevel` flag. When you are ready to perform the actual migration, add the `--confirm` option: ---- $ oadm migrate storage --include=jobs --confirm ---- endif::[] [[manual-upgrades-verifying-the-upgrade]] == Verifying the Upgrade To verify the upgrade: . Check that all nodes are marked as *Ready*: + ---- # oc get nodes NAME STATUS AGE master.example.com Ready,SchedulingDisabled 165d node1.example.com Ready 165d node2.example.com Ready 165d ---- . Verify that you are running the expected versions of the *docker-registry* and *router* images, if deployed. ifdef::openshift-enterprise[] Replace `` with `{latest-tag}` for the latest version. endif::[] + ---- ifdef::openshift-enterprise[] # oc get -n default dc/docker-registry -o json | grep \\""image\\"" ""image"": ""openshift3/ose-docker-registry:"", # oc get -n default dc/router -o json | grep \\""image\\"" ""image"": ""openshift3/ose-haproxy-router:"", endif::[] ifdef::openshift-origin[] # oc get -n default dc/docker-registry -o json | grep \\""image\\"" ""image"": ""openshift/origin-docker-registry:v1.0.6"", # oc get -n default dc/router -o json | grep \\""image\\"" ""image"": ""openshift/origin-haproxy-router:v1.0.6"", endif::[] ---- ifdef::openshift-origin[] . If you upgraded from Origin 1.0 to Origin 1.1, verify in your old *_/etc/sysconfig/openshift-master_* and *_/etc/sysconfig/openshift-node_* files that any custom configuration is added to your new *_/etc/sysconfig/origin-master_* and *_/etc/sysconfig/origin-node_* files. endif::[] . Use the diagnostics tool on the master to look for common issues: + ---- # oadm diagnostics ... [Note] Summary of diagnostics execution: [Note] Completed with no errors or warnings seen. ---- ",12469,False,2163.2058288000094,median "[[install-config-upgrading-manual-upgrades]] = Performing Manual In-place Cluster Upgrades {product-author} {product-version} :latest-tag: v3.6.173.0.5 :latest-int-tag: v3.6 :data-uri: :icons: :experimental: :toc: macro :toc-title: :prewrap!: toc::[] == Overview [IMPORTANT] ==== An etcd performance issue has been discovered on new and upgraded {product-title} ifdef::openshift-enterprise[] 3.6 endif::[] ifdef::openshift-origin[] 1.4+ endif::[] clusters. See the following Knowledgebase Solution for further details: https://access.redhat.com/solutions/2916381[] + (link:https://bugzilla.redhat.com/show_bug.cgi?id=1415839[*BZ#1415839*]) ==== As an alternative to performing an xref:../../install_config/upgrading/automated_upgrades.adoc#install-config-upgrading-automated-upgrades[automated upgrade], you can manually upgrade your OpenShift cluster. To manually upgrade without disruption, it is important to upgrade each component as documented in this topic. Before you begin your upgrade, familiarize yourself now with the entire procedure. xref:additional-instructions-per-release[Specific releases may require additional steps] to be performed at key points before or during the standard upgrade process. [IMPORTANT] ==== Ensure that you have met all xref:../../install_config/install/prerequisites.adoc#install-config-install-prerequisites[prerequisites] before proceeding with an upgrade. Failure to do so can result in a failed upgrade. ==== [[preparing-for-a-manual-upgrade]] == Preparing for a Manual Upgrade [NOTE] ==== Before upgrading your cluster to {product-title} 3.6, the cluster must be already upgraded to the link:https://docs.openshift.com/container-platform/3.5/release_notes/ocp_3_5_release_notes.html#ocp-35-asynchronous-errata-updates[latest asynchronous release of version 3.5]. Cluster upgrades cannot span more than one minor version at a time, so if your cluster is at a version earlier than 3.5, you must first upgrade incrementally (e.g., 3.3 to 3.4, then 3.4 to 3.5). ==== [NOTE] ==== Before attempting the upgrade, follow the steps in xref:manual-upgrades-verifying-the-upgrade[Verifying the Upgrade] to verify the cluster's health. This will confirm that nodes are in the *Ready* state, running the expected starting version, and will ensure that there are no diagnostic errors or warnings. ==== To prepare for a manual upgrade, follow these steps: ifdef::openshift-enterprise[] . If you are upgrading from {product-title} 3.5 to 3.6, manually disable the 3.5 channel and enable the 3.6 channel on each host: + ---- # subscription-manager repos --disable=""rhel-7-server-ose-3.5-rpms"" \\ --enable=""rhel-7-server-ose-3.6-rpms"" \\ --enable=""rhel-7-server-extras-rpms"" \\ --enable=""rhel-7-fast-datapath-rpms"" ---- + On RHEL 7 systems, also clear the *yum* cache: + ---- # yum clean all ---- endif::[] . Install or update to the latest available version of the *atomic-openshift-utils* package on each RHEL 7 system, which provides files that will be used in later sections: + ---- # yum install atomic-openshift-utils ---- . Install or update to the following latest available **-excluder* packages on each RHEL 7 system, which helps ensure your systems stay on the correct versions of *atomic-openshift* and *docker* packages when you are not trying to upgrade, according to the {product-title} version: + ---- # yum install atomic-openshift-excluder atomic-openshift-docker-excluder ---- + These packages add entries to the `exclude` directive in the host's *_/etc/yum.conf_* file. . Create an *etcd* backup on each master. The *etcd* package is required, even if using embedded etcd, for access to the `etcdctl` command to make the backup. + [NOTE] ==== The *etcd* package is installed by default for RHEL Atomic Host 7 systems. If the master is a RHEL 7 system and *etcd* is not already installed, install it now: ---- # yum install etcd ---- ==== + To create the backup, run: + ---- # ETCD_DATA_DIR=/var/lib/origin/openshift.local.etcd <1> # etcdctl backup \\ --data-dir $ETCD_DATA_DIR \\ --backup-dir $ETCD_DATA_DIR.bak. <2> ---- <1> This directory is for embedded etcd. For external etcd, use *_/var/lib/etcd_* instead. <2> Use the date of the backup, or some unique identifier, for ``. The command will not make a backup if the `--backup-dir` location already exists. . For any upgrade path, ensure that you are running the latest kernel on each RHEL 7 system: + ---- # yum update kernel ---- [[upgrading-masters]] == Upgrading Master Components Before upgrading any stand-alone nodes, upgrade the master components (which provide the _control plane_ for the cluster). . Run the following command on each master to remove the *atomic-openshift* packages from the list of yum excludes on the host: + ---- # atomic-openshift-excluder unexclude ---- . Upgrade *etcd* on all master hosts and any external etcd hosts. .. For RHEL 7 systems using the RPM-based method: ... Upgrade the *etcd* package: + ---- # yum update etcd ---- ... Restart the *etcd* service and review the logs to ensure it restarts successfully: + ---- # systemctl restart etcd # journalctl -r -u etcd ---- .. For RHEL Atomic Host 7 systems and RHEL 7 systems using the containerized method: ... Pull the latest *rhel7/etcd* image: + ---- # docker pull registry.access.redhat.com/rhel7/etcd ---- ... Restart the *etcd_container* service and review the logs to ensure it restarts successfully: + ---- # systemctl restart etcd_container # journalctl -r -u etcd_container ---- ifdef::openshift-origin[] . On each master host, upgrade the *origin-master* package: + ---- # yum upgrade origin-master ---- . If you are upgrading from OpenShift Origin 1.0 to 1.1: .. Create the following master proxy client certificates: + ---- # cd /etc/origin/master/ # oadm ca create-master-certs --cert-dir=/etc/origin/master/ \\ --master=https://:8443 \\ --public-master=https://:8443 \\ --hostnames=,,localhost,127.0.0.1,,kubernetes.default.local \\ --overwrite=false ---- + This creates files at *_/etc/origin/master/master.proxy-client.{crt,key}_*. Then, add the master proxy client certificates to the *_/etc/origin/master/master-config.yml_* file on each master: + ---- kubernetesMasterConfig: proxyClientInfo: certFile: master.proxy-client.crt keyFile: master.proxy-client.key ---- .. Enable the following renamed service(s) on master hosts. + For single master clusters: + ---- # systemctl enable origin-master ---- + For multi-master clusters: + ---- # systemctl enable origin-master-api # systemctl enable origin-master-controllers ---- . Restart the master service(s) on each master and review logs to ensure they restart successfully. + For single master clusters: + ---- # systemctl restart origin-master # journalctl -r -u origin-master ---- + For multi-master clusters: + ---- # systemctl restart origin-master-controllers # systemctl restart origin-master-api # journalctl -r -u origin-master-controllers # journalctl -r -u origin-master-api ---- . Because masters also have node components running on them in order to be configured as part of the OpenShift SDN, restart the *origin-node* and *openvswitch* services: + ---- # systemctl restart openvswitch # systemctl restart origin-node # journalctl -r -u openvswitch # journalctl -r -u origin-node ---- endif::[] ifdef::openshift-enterprise[] . On each master host, upgrade the *atomic-openshift* packages or related images. .. For masters using the RPM-based method on a RHEL 7 system, upgrade all installed *atomic-openshift* packages and the *openvswitch* package: + ---- # yum upgrade atomic-openshift\\* openvswitch ---- .. For masters using the containerized method on a RHEL 7 or RHEL Atomic Host 7 system, set the `*IMAGE_VERSION*` parameter to the version you are upgrading to in the following files: + -- - *_/etc/sysconfig/atomic-openshift-master_* (single master clusters only) - *_/etc/sysconfig/atomic-openshift-master-controllers_* (multi-master clusters only) - *_/etc/sysconfig/atomic-openshift-master-api_* (multi-master clusters only) - *_/etc/sysconfig/atomic-openshift-node_* - *_/etc/sysconfig/atomic-openshift-openvswitch_* -- + For example: + ---- IMAGE_VERSION= ---- + Replace `` with `{latest-tag}` for the latest version. . Restart the master service(s) on each master and review logs to ensure they restart successfully. + For single master clusters: + ---- # systemctl restart atomic-openshift-master # journalctl -r -u atomic-openshift-master ---- + For multi-master clusters: + ---- # systemctl restart atomic-openshift-master-controllers # systemctl restart atomic-openshift-master-api # journalctl -r -u atomic-openshift-master-controllers # journalctl -r -u atomic-openshift-master-api ---- . Because masters also have node components running on them in order to be configured as part of the OpenShift SDN, restart the *atomic-openshift-node* and *openvswitch* services: + ---- # systemctl restart openvswitch # systemctl restart atomic-openshift-node # journalctl -r -u openvswitch # journalctl -r -u atomic-openshift-node ---- endif::[] . If you are performing a cluster upgrade that requires updating Docker to version 1.12, you must also perform the following steps if you are not already on Docker 1.12: + [IMPORTANT] ==== The node component on masters is set by default to unschedulable status during initial installation, so that pods are not deployed to them. However, it is possible to set them schedulable during the initial installation or manually thereafter. If any of your masters are also configured as a schedulable node, skip the following Docker upgrade steps for those masters and instead run all steps described in xref:upgrading-nodes[Upgrading Nodes] when you get to that section for those hosts as well. ==== .. Upgrade the *docker* package. ... For RHEL 7 systems: + ---- # yum update docker ---- + Then, restart the *docker* service and review the logs to ensure it restarts successfully: + ---- # systemctl restart docker # journalctl -r -u docker ---- ... For RHEL Atomic Host 7 systems, upgrade to the latest Atomic tree if one is available: + [NOTE] ==== If upgrading to RHEL Atomic Host 7.3.2, this upgrades Docker to version 1.12. ==== + ---- # atomic host upgrade ---- .. After the upgrade is completed and prepared for the next boot, reboot the host and ensure the *docker* service starts successfully: + ---- # systemctl reboot # journalctl -r -u docker ---- .. Remove the following file, which is no longer required: + ---- # rm /etc/systemd/system/docker.service.d/docker-sdn-ovs.conf ---- . Run the following command on each master to add the *atomic-openshift* packages back to the list of yum excludes on the host: + ---- # atomic-openshift-excluder exclude ---- [NOTE] ==== During the cluster upgrade, it can sometimes be useful to take a master out of rotation since some DNS client libraries will not properly to the other masters for cluster DNS. In addition to stopping the master and controller services, you can remove the EndPoint from the Kubernetes service's `*subsets.addresses*`. ---- $ oc edit ep/kubernetes -n default ---- When the master is restarted, the Kubernetes service will be automatically updated. ==== [[updating-policy-definitions]] == Updating Policy Definitions After a cluster upgrade, the recommended xref:../../architecture/additional_concepts/authorization.adoc#roles[default cluster roles] may be updated. To check if an update is recommended for your environment, you can run: ---- # oadm policy reconcile-cluster-roles ---- [WARNING] ==== If you have customized default cluster roles and want to ensure a role reconciliation does not modify those customized roles, annotate them with `openshift.io/reconcile-protect` set to `true`. Doing so means you are responsible for manually updating those roles with any new or required permissions during upgrades. ==== This command outputs a list of roles that are out of date and their new proposed values. For example: ---- # oadm policy reconcile-cluster-roles apiVersion: v1 items: - apiVersion: v1 kind: ClusterRole metadata: creationTimestamp: null name: admin rules: - attributeRestrictions: null resources: - builds/custom ... ---- [NOTE] ==== Your output will vary based on the OpenShift version and any local customizations you have made. Review the proposed policy carefully. ==== You can either modify this output to re-apply any local policy changes you have made, or you can automatically apply the new policy using the following process: . Reconcile the cluster roles: + ---- # oadm policy reconcile-cluster-roles \\ --additive-only=true \\ --confirm ---- . Reconcile the cluster role bindings: + ---- # oadm policy reconcile-cluster-role-bindings \\ --exclude-groups=system:authenticated \\ --exclude-groups=system:authenticated:oauth \\ --exclude-groups=system:unauthenticated \\ --exclude-users=system:anonymous \\ --additive-only=true \\ --confirm ---- + Also run: + ---- # oadm policy reconcile-cluster-role-bindings \\ system:build-strategy-jenkinspipeline \\ --confirm \\ -o name ---- . Reconcile security context constraints: + ---- # oadm policy reconcile-sccs \\ --additive-only=true \\ --confirm ---- [[upgrading-nodes]] == Upgrading Nodes After upgrading your masters, you can upgrade your nodes. When restarting the ifdef::openshift-origin[] *origin-node* service, there will be a brief disruption of outbound network endif::[] ifdef::openshift-enterprise[] *atomic-openshift-node* service, there will be a brief disruption of outbound network endif::[] connectivity from running pods to services while the xref:../../architecture/infrastructure_components/kubernetes_infrastructure.adoc#service-proxy[service proxy] is restarted. The length of this disruption should be very short and scales based on the number of services in the entire cluster. [NOTE] ==== You can alternatively use the xref:../../install_config/upgrading/blue_green_deployments.adoc#upgrading-blue-green-deployments[blue-green deployment] method at this point to create a parallel environment for new nodes instead of upgrading them in place. ==== One at at time for each node that is not also a master, you must disable scheduling and evacuate its pods to other nodes, then upgrade packages and restart services. . Run the following command on each node to remove the *atomic-openshift* packages from the list of yum excludes on the host: + ---- # atomic-openshift-excluder unexclude ---- . As a user with *cluster-admin* privileges, disable scheduling for the node: + ---- # oadm manage-node --schedulable=false ---- . Evacuate pods on the node to other nodes: + [IMPORTANT] ==== The `--force` option deletes any pods that are not backed by a replication controller. ==== + ---- # oadm drain --force --delete-local-data --ignore-daemonsets ---- ifdef::openshift-origin[] . On the node host, upgrade all *origin* packages: + ---- # yum upgrade origin\\* ---- . If you are upgrading from OpenShift Origin 1.0 to 1.1, enable the following renamed service on the node host: + ---- # systemctl enable origin-node ---- . Restart the *origin-node* and *openvswitch* services and review the logs to ensure they restart successfully: + ---- # systemctl restart openvswitch # systemctl restart origin-node # journalctl -r -u origin-node # journalctl -r -u openvswitch ---- endif::[] ifdef::openshift-enterprise[] . Upgrade the node component packages or related images. .. For nodes using the RPM-based method on a RHEL 7 system, upgrade all installed *atomic-openshift* packages and the *openvswitch* package: + ---- # yum upgrade atomic-openshift\\* openvswitch ---- .. For nodes using the containerized method on a RHEL 7 or RHEL Atomic Host 7 system, set the `*IMAGE_VERSION*` parameter in the *_/etc/sysconfig/atomic-openshift-node_* and *_/etc/sysconfig/openvswitch_* files to the version you are upgrading to. For example: + ---- IMAGE_VERSION= ---- + Replace `` with `{latest-tag}` for the latest version. . Restart the *atomic-openshift-node* and *openvswitch* services and review the logs to ensure they restart successfully: + ---- # systemctl restart openvswitch # systemctl restart atomic-openshift-node # journalctl -r -u atomic-openshift-node # journalctl -r -u openvswitch ---- endif::[] . If you are performing a cluster upgrade that requires updating Docker to version 1.12, you must also perform the following steps if you are not already on Docker 1.12: .. Upgrade the *docker* package. ... For RHEL 7 systems: + ---- # yum update docker ---- + Then, restart the *docker* service and review the logs to ensure it restarts successfully: + ---- # systemctl restart docker # journalctl -r -u docker ---- + After Docker is restarted, restart the *atomic-openshift-node* service again and review the logs to ensure it restarts successfully: + ---- # systemctl restart atomic-openshift-node # journalctl -r -u atomic-openshift-node ---- ... For RHEL Atomic Host 7 systems, upgrade to the latest Atomic tree if one is available: + [NOTE] ==== If upgrading to RHEL Atomic Host 7.3.2, this upgrades Docker to version 1.12. ==== + ---- # atomic host upgrade ---- + After the upgrade is completed and prepared for the next boot, reboot the host and ensure the *docker* service starts successfully: + ---- # systemctl reboot # journalctl -r -u docker ---- .. Remove the following file, which is no longer required: + ---- # rm /etc/systemd/system/docker.service.d/docker-sdn-ovs.conf ---- . Re-enable scheduling for the node: + ---- # oadm manage-node --schedulable ---- . Run the following command on each node to add the *atomic-openshift* packages back to the list of yum excludes on the host: + ---- # atomic-openshift-excluder exclude ---- . Repeat the previous steps on the next node, and continue repeating these steps until all nodes have been upgraded. . After all nodes have been upgraded, as a user with *cluster-admin* privileges, verify that all nodes are showing as *Ready*: + ---- # oc get nodes NAME STATUS AGE master.example.com Ready,SchedulingDisabled 165d node1.example.com Ready 165d node2.example.com Ready 165d ---- [[upgrading-the-router]] == Upgrading the Router If you have previously xref:../../install_config/router/index.adoc#install-config-router-overview[deployed a router], the router deployment configuration must be upgraded to apply updates contained in the router image. To upgrade your router without disrupting services, you must have previously deployed a xref:../../admin_guide/high_availability.adoc#configuring-a-highly-available-service[highly-available routing service]. ifdef::openshift-origin[] [IMPORTANT] ==== If you are upgrading to OpenShift Origin 1.0.4 or 1.0.5, first see the xref:additional-instructions-per-release[Additional Manual Instructions per Release] section for important steps specific to your upgrade, then continue with the router upgrade as described in this section. ==== endif::[] Edit your router's deployment configuration. For example, if it has the default *router* name: ---- # oc edit dc/router ---- Apply the following changes: ---- ... spec: template: spec: containers: - env: ... ifdef::openshift-enterprise[] image: registry.access.redhat.com/openshift3/ose-haproxy-router: <1> endif::[] ifdef::openshift-origin[] image: openshift/origin-haproxy-router:v1.0.6 <1> endif::[] imagePullPolicy: IfNotPresent ... ---- <1> Adjust `` to match the version you are upgrading to (use `{latest-tag}` for the latest version). You should see one router pod updated and then the next. [[upgrading-the-registry]] == Upgrading the Registry The registry must also be upgraded for changes to take effect in the registry image. If you have used a `*PersistentVolumeClaim*` or a host mount point, you may restart the registry without losing the contents of your registry. xref:../../install_config/registry/deploy_registry_existing_clusters.adoc#storage-for-the-registry[Storage for the Registry] details how to configure persistent storage for the registry. Edit your registry's deployment configuration: ---- # oc edit dc/docker-registry ---- Apply the following changes: ---- ... spec: template: spec: containers: - env: ... ifdef::openshift-enterprise[] image: registry.access.redhat.com/openshift3/ose-docker-registry: <1> endif::[] ifdef::openshift-origin[] image: openshift/origin-docker-registry:v1.0.4 <1> endif::[] imagePullPolicy: IfNotPresent ... ---- <1> Adjust `` to match the version you are upgrading to (use `{latest-tag}` for the latest version). ifdef::openshift-enterprise[] If the registry console is deployed, edit its deployment configuration: ---- # oc edit dc/registry-console ---- Apply the following changes: ---- ... spec: template: spec: containers: - env: ... image: registry.access.redhat.com/openshift3/registry-console:v3.6 imagePullPolicy: IfNotPresent ... ---- endif::[] [IMPORTANT] ==== Images that are being pushed or pulled from the internal registry at the time of upgrade will fail and should be restarted automatically. This will not disrupt pods that are already running. ==== ifdef::openshift-origin[] [[updating-the-registry-configuration-file]] === Updating Custom Registry Configuration Files [NOTE] ==== You may safely skip this part if you do not use a custom registry configuration file. ==== The internal Docker registry version 1.4.0 and higher requires following entries in the xref:../registry/extended_registry_configuration.adoc#docker-registry-configuration-reference-middleware[middleware section] of the configuration file: [source,yaml] ---- middleware: registry: - name: openshift repository: - name: openshift storage: - name: openshift ---- . Edit your custom configuration file, adding the missing entries. . xref:../registry/extended_registry_configuration.adoc#advanced-overriding-the-registry-configuration[Deploy your updated configuration]. . Append the `--overwrite` flag to `oc volume dc/docker-registry --add` to replace a volume mount of your previous secret. . You can safely remove the old secret. [[enforcing-quota-in-the-registry]] === Enforcing Quota in the Registry Quota must be enforced to prevent layer blobs that exceed the size limit from being written to the registry's storage. This can be achieved via a xref:../registry/extended_registry_configuration.adoc#registry-configuration-reference[configuration file]: ---- ... middleware: repository: - name: openshift options: enforcequota: true ... ---- Alternatively, use the `*REGISTRY_MIDDLEWARE_REPOSITORY_OPENSHIFT_ENFORCEQUOTA*` environment variable, which is set to `*true*` for the new registry deployments by default. Existing deployments need to be modified using: ---- # oc set env dc/docker-registry REGISTRY_MIDDLEWARE_REPOSITORY_OPENSHIFT_ENFORCEQUOTA=true ---- endif::[] [[updating-the-default-image-streams-and-templates]] == Updating the Default Image Streams and Templates ifdef::openshift-origin[] By default, the xref:../../install_config/install/advanced_install.adoc#install-config-install-advanced-install[advanced installation] method automatically creates default image streams, InstantApp templates, and database service templates in the *openshift* project, which is a default project to which all users have view access. These objects were created during installation from the JSON files located under *_/usr/share/openshift/examples_*. To update these objects: . Ensure that you have the latest *openshift-ansible* code checked out, which provides the example JSON files: + ---- # cd ~/openshift-ansible # git pull https://github.com/openshift/openshift-ansible master ---- endif::[] ifdef::openshift-enterprise[] By default, the xref:../../install_config/install/quick_install.adoc#install-config-install-quick-install[quick] and xref:../../install_config/install/advanced_install.adoc#install-config-install-advanced-install[advanced installation] methods automatically create default image streams, InstantApp templates, and database service templates in the *openshift* project, which is a default project to which all users have view access. These objects were created during installation from the JSON files located under the *_/usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/_* directory. [NOTE] ==== Because RHEL Atomic Host 7 cannot use *yum* to update packages, the following steps must take place on a RHEL 7 system. ==== . Update the packages that provide the example JSON files. On a subscribed Red Hat Enterprise Linux 7 system where you can run the CLI as a user with *cluster-admin* permissions, install or update to the latest version of the *atomic-openshift-utils* package, which should also update the *openshift-ansible-* packages: + ---- # yum update atomic-openshift-utils ---- + The *openshift-ansible-roles* package provides the latest example JSON files. endif::[] . After a manual upgrade, get the latest templates from *openshift-ansible-roles*: + ---- rpm -ql openshift-ansible-roles | grep examples | grep v3.6 ---- + In this example, *_/usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/image-streams/image-streams-rhel7.json_* is the latest file that you want in the latest *openshift-ansible-roles* package. + *_/usr/share/openshift/examples/image-streams/image-streams-rhel7.json_* is not owned by a package, but is updated by Ansible. If you are upgrading outside of Ansible. you need to get the latest .json files on the system where you are running `oc`, which can run anywhere that has access to the master. . Install *atomic-openshift-utils* and its dependencies to install the new content into *_/usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/_*.: + ---- $ oc create -n openshift -f /usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/image-streams/image-streams-rhel7.json $ oc create -n openshift -f /usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/image-streams/dotnet_imagestreams.json $ oc replace -n openshift -f /usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/image-streams/image-streams-rhel7.json $ oc replace -n openshift -f /usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/image-streams/dotnet_imagestreams.json ---- . Update the templates: + ---- $ oc create -n openshift -f /usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/quickstart-templates/ $ oc create -n openshift -f /usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/db-templates/ $ oc create -n openshift -f /usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/infrastructure-templates/ $ oc create -n openshift -f /usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/xpaas-templates/ $ oc create -n openshift -f /usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/xpaas-streams/ $ oc replace -n openshift -f /usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/quickstart-templates/ $ oc replace -n openshift -f /usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/db-templates/ $ oc replace -n openshift -f /usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/infrastructure-templates/ $ oc replace -n openshift -f /usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/xpaas-templates/ $ oc replace -n openshift -f /usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/xpaas-streams/ ---- + Errors are generated for items that already exist. This is expected behavior: + ---- # oc create -n openshift -f /usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/quickstart-templates/ Error from server: error when creating ""/usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/quickstart-templates/cakephp-mysql.json"": templates ""cakephp-mysql-example"" already exists Error from server: error when creating ""/usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/quickstart-templates/cakephp.json"": templates ""cakephp-example"" already exists Error from server: error when creating ""/usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/quickstart-templates/dancer-mysql.json"": templates ""dancer-mysql-example"" already exists Error from server: error when creating ""/usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/quickstart-templates/dancer.json"": templates ""dancer-example"" already exists Error from server: error when creating ""/usr/share/ansible/openshift-ansible/roles/openshift_examples/files/examples/v3.6/quickstart-templates/django-postgresql.json"": templates ""django-psql-example"" already exists ---- Now, content can be updated. Without running the automated upgrade playbooks, the content is not updated in *_/usr/share/openshift/_*. [[importing-the-latest-images]] == Importing the Latest Images After xref:updating-the-default-image-streams-and-templates[updating the default image streams], you may also want to ensure that the images within those streams are updated. For each image stream in the default *openshift* project, you can run: ---- # oc import-image -n openshift ---- For example, get the list of all image streams in the default *openshift* project: ==== ---- # oc get is -n openshift NAME DOCKER REPO TAGS UPDATED mongodb registry.access.redhat.com/openshift3/mongodb-24-rhel7 2.4,latest,v3.1.1.6 16 hours ago mysql registry.access.redhat.com/openshift3/mysql-55-rhel7 5.5,latest,v3.1.1.6 16 hours ago nodejs registry.access.redhat.com/openshift3/nodejs-010-rhel7 0.10,latest,v3.1.1.6 16 hours ago ... ---- ==== Update each image stream one at a time: ==== ---- # oc import-image -n openshift nodejs The import completed successfully. Name: nodejs Created: 10 seconds ago Labels: Annotations: openshift.io/image.dockerRepositoryCheck=2016-07-05T19:20:30Z Docker Pull Spec: 172.30.204.22:5000/openshift/nodejs Tag Spec Created PullSpec Image latest 4 9 seconds ago registry.access.redhat.com/rhscl/nodejs-4-rhel7:latest 570ad8ed927fd5c2c9554ef4d9534cef808dfa05df31ec491c0969c3bd372b05 4 registry.access.redhat.com/rhscl/nodejs-4-rhel7:latest 9 seconds ago 570ad8ed927fd5c2c9554ef4d9534cef808dfa05df31ec491c0969c3bd372b05 0.10 registry.access.redhat.com/openshift3/nodejs-010-rhel7:latest 9 seconds ago a1ef33be788a28ec2bdd48a9a5d174ebcfbe11c8e986d2996b77f5bccaaa4774 ---- ==== [IMPORTANT] ==== In order to update your S2I-based applications, you must manually trigger a new build of those applications after importing the new images using `oc start-build `. ==== ifdef::openshift-origin[] :sect: manual // tag::30to31updatingcerts[] [id='{sect}-updating-master-and-node-certificates'] == Updating Master and Node Certificates The following steps may be required for any OpenShift cluster that was originally installed prior to the https://github.com/openshift/origin/releases[OpenShift Origin 1.0.8 release]. This may include any and all updates from that version. [id='{sect}-updating-node-certificates'] === Node Certificates With the 1.0.8 release, certificates for each of the kubelet nodes were updated to include the IP address of the node. Any node certificates generated before the 1.0.8 release may not contain the IP address of the node. If a node is missing the IP address as part of its certificate, clients may refuse to connect to the kubelet endpoint. Usually this will result in errors regarding the certificate not containing an `IP SAN`. In order to remedy this situation, you may need to manually update the certificates for your node. [id='{sect}-checking-the-nodes-certificate'] ==== Checking the Node's Certificate The following command can be used to determine which Subject Alternative Names (SANs) are present in the node's serving certificate. In this example, the Subject Alternative Names are *mynode*, *mynode.mydomain.com*, and *1.2.3.4*: ==== ---- # openssl x509 -in /etc/origin/node/server.crt -text -noout | grep -A 1 ""Subject Alternative Name"" X509v3 Subject Alternative Name: DNS:mynode, DNS:mynode.mydomain.com, IP: 1.2.3.4 ---- ==== Ensure that the `*nodeIP*` value set in the *_/etc/origin/node/node-config.yaml_* file is present in the IP values from the Subject Alternative Names listed in the node's serving certificate. If the `*nodeIP*` is not present, then it will need to be added to the node's certificate. If the `*nodeIP*` value is already contained within the Subject Alternative Names, then no further steps are required. You will need to know the Subject Alternative Names and `*nodeIP*` value for the following steps. [id='{sect}-generating-a-new-node-certificate'] ==== Generating a New Node Certificate If your current node certificate does not contain the proper IP address, then you must regenerate a new certificate for your node. [IMPORTANT] ==== Node certificates will be regenerated on the master (or first master) and are then copied into place on node systems. ==== . Create a temporary directory in which to perform the following steps: + ---- # mkdir /tmp/node_certificate_update # cd /tmp/node_certificate_update ---- . Export the signing options: + ---- # export signing_opts=""--signer-cert=/etc/origin/master/ca.crt \\ --signer-key=/etc/origin/master/ca.key \\ --signer-serial=/etc/origin/master/ca.serial.txt"" ---- . Generate the new certificate: + ---- # oadm ca create-server-cert --cert=server.crt \\ --key=server.key $signing_opts \\ --hostnames=, ---- + For example, if the Subject Alternative Names from before were *mynode*, *mynode.mydomain.com*, and *1.2.3.4*, and the `*nodeIP*` was 10.10.10.1, then you would need to run the following command: + ---- # oadm ca create-server-cert --cert=server.crt \\ --key=server.key $signing_opts \\ --hostnames=mynode,mynode.mydomain.com,1.2.3.4,10.10.10.1 ---- [id='{sect}-replace-node-serving-certificates'] ==== Replace Node Serving Certificates Back up the existing *_/etc/origin/node/server.crt_* and *_/etc/origin/node/server.key_* files for your node: ---- # mv /etc/origin/node/server.crt /etc/origin/node/server.crt.bak # mv /etc/origin/node/server.key /etc/origin/node/server.key.bak ---- You must now copy the new *_server.crt_* and *_server.key_* created in the temporary directory during the previous step: ---- # mv /tmp/node_certificate_update/server.crt /etc/origin/node/server.crt # mv /tmp/node_certificate_update/server.key /etc/origin/node/server.key ---- After you have replaced the node's certificate, restart the node service: ---- # systemctl restart origin-node ---- [id='{sect}-updating-master-certificates'] === Master Certificates With the 1.0.8 release, certificates for each of the masters were updated to include all names that pods may use to communicate with masters. Any master certificates generated before the 1.0.8 release may not contain these additional service names. [id='{sect}-checking-the-masters-certificate'] ==== Checking the Master's Certificate The following command can be used to determine which Subject Alternative Names (SANs) are present in the master's serving certificate. In this example, the Subject Alternative Names are *mymaster*, *mymaster.mydomain.com*, and *1.2.3.4*: ---- # openssl x509 -in /etc/origin/master/master.server.crt -text -noout | grep -A 1 ""Subject Alternative Name"" X509v3 Subject Alternative Name: DNS:mymaster, DNS:mymaster.mydomain.com, IP: 1.2.3.4 ---- Ensure that the following entries are present in the Subject Alternative Names for the master's serving certificate: [options=""header""] |=== |Entry |Example |Kubernetes service IP address |172.30.0.1 |All master host names |*master1.example.com* |All master IP addresses |192.168.122.1 |Public master host name in clustered environments |*public-master.example.com* |*kubernetes* | |*kubernetes.default* | |*kubernetes.default.svc* | |*kubernetes.default.svc.cluster.local* | |*openshift* | |*openshift.default* | |*openshift.default.svc* | |*openshift.default.svc.cluster.local* | |=== If these names are already contained within the Subject Alternative Names, then no further steps are required. [id='{sect}-generating-a-new-master-certificate'] ==== Generating a New Master Certificate If your current master certificate does not contain all names from the list above, then you must generate a new certificate for your master: . Back up the existing *_/etc/origin/master/master.server.crt_* and *_/etc/origin/master/master.server.key_* files for your master: + ---- # mv /etc/origin/master/master.server.crt /etc/origin/master/master.server.crt.bak # mv /etc/origin/master/master.server.key /etc/origin/master/master.server.key.bak ---- . Export the service names. These names will be used when generating the new certificate: + ---- # export service_names=""kubernetes,kubernetes.default,kubernetes.default.svc,kubernetes.default.svc.cluster.local,openshift,openshift.default,openshift.default.svc,openshift.default.svc.cluster.local"" ---- . You will need the first IP in the services subnet (the *kubernetes* service IP) as well as the values of `*masterIP*`, `*masterURL*` and `*publicMasterURL*` contained in the *_/etc/origin/master/master-config.yaml_* file for the following steps. + The *kubernetes* service IP can be obtained with: + ---- # oc get svc/kubernetes --template='{{.spec.clusterIP}}' ---- . Generate the new certificate: + ==== ---- # oadm ca create-master-certs \\ --hostnames=,,,$service_names \\ <1> <2> <3> --master= \\ <4> --public-master= \\ <5> --cert-dir=/etc/origin/master/ \\ --overwrite=false ---- <1> Adjust `` to match your master host name. In a clustered environment, add all master host names. <2> Adjust `` to match the value of `*masterIP*`. In a clustered environment, add all master IP addresses. <3> Adjust `` to the first IP in the *kubernetes* services subnet. <4> Adjust `` to match the value of `*masterURL*`. <5> Adjust `` to match the value of `*masterPublicURL*`. ==== . Restart master services. For single master deployments: + ---- # systemctl restart origin-master ---- + For native HA multiple master deployments: + ---- # systemctl restart origin-master-api # systemctl restart origin-master-controllers ---- + After the service restarts, the certificate update is complete. // end::30to31updatingcerts[] endif::[] [[manual-upgrading-efk-logging-stack]] == Upgrading the EFK Logging Stack [NOTE] ==== Manual upgrade steps for logging deployments are no longer available starting in {product-title} ifdef::openshift-enterprise[] 3.5. endif::[] ifdef::openshift-origin[] 1.5. endif::[] ==== include::install_config/upgrading/automated_upgrades.adoc[tag=automated-logging-upgrade-steps] [[manual-upgrading-cluster-metrics]] == Upgrading Cluster Metrics [NOTE] ==== Manual upgrade steps for metrics deployments are no longer available starting in {product-title} ifdef::openshift-enterprise[] 3.5. endif::[] ifdef::openshift-origin[] 1.5. endif::[] ==== include::install_config/upgrading/automated_upgrades.adoc[tag=automated-metrics-upgrade-steps] [[additional-instructions-per-release]] == Additional Manual Steps Per Release Some {product-title} releases may have additional instructions specific to that release that must be performed to fully apply the updates across the cluster. ifdef::openshift-enterprise[] This section will be updated over time as new asynchronous updates are released for {product-title} 3.6. See the xref:../../release_notes/ocp_3_6_release_notes.adoc#release-notes-ocp-3-6-release-notes[{product-title} 3.6 Release Notes] to review the latest release notes. ifdef::openshift-origin[] Read through the following sections carefully depending on your upgrade path, as you may be required to perform certain steps at key points during the standard upgrade process described earlier in this topic. [[openshift-origin-1-0-4]] === OpenShift Origin 1.0.4 The following steps are required for the https://github.com/openshift/origin/releases/tag/v1.0.4[OpenShift Origin 1.0.4 release]. *Creating a Service Account for the Router* The default HAProxy router was updated to utilize host ports and requires that a service account be created and made a member of the privileged xref:../../admin_guide/manage_scc.adoc#admin-guide-manage-scc[security context constraint] (SCC). Additionally, ""down-then-up"" rolling upgrades have been added and is now the preferred strategy for upgrading routers. After upgrading your master and nodes but before updating to the newer router, you must create a service account for the router. As a cluster administrator, ensure you are operating on the *default* project: ==== ---- # oc project default ---- ==== Delete any existing *router* service account and create a new one: ==== ---- # oc delete serviceaccount/router serviceaccounts/router # echo '{""kind"":""ServiceAccount"",""apiVersion"":""v1"",""metadata"":{""name"":""router""}}' | oc create -f - serviceaccounts/router ---- ==== Edit the *privileged* SCC: ==== ---- # oc edit scc privileged ---- ==== Apply the following changes: ==== ---- allowHostDirVolumePlugin: true allowHostNetwork: true <1> allowHostPorts: true <2> allowPrivilegedContainer: true ... users: - system:serviceaccount:openshift-infra:build-controller - system:serviceaccount:default:router <3> ---- <1> Add or update `allowHostNetwork: true`. <2> Add or update `allowHostPorts: true`. <3> Add the service account you created to the `*users*` list at the end of the file. ==== Edit your router's deployment configuration: ---- # oc edit dc/router ---- Apply the following changes: ---- ... spec: replicas: 2 selector: router: router strategy: resources: {} rollingParams: intervalSeconds: 1 timeoutSeconds: 120 updatePeriodSeconds: 1 updatePercent: -10 <1> type: Rolling ... template: ... spec: ... dnsPolicy: ClusterFirst restartPolicy: Always serviceAccount: router <2> serviceAccountName: router <3> ... ---- <1> Add `updatePercent: -10` to allow down-then-up rolling upgrades. <2> Add `serviceAccount: router` to the template `*spec*`. <3> Add `serviceAccountName: router` to the template `*spec*`. Now upgrade your router per the xref:upgrading-the-router[standard router upgrade steps]. [[openshift-origin-1-0-5]] === OpenShift Origin 1.0.5 The following steps are required for the https://github.com/openshift/origin/releases[OpenShift Origin 1.0.5 release]. *Switching the Router to Use the Host Network Stack* The default HAProxy router was updated to use the host networking stack by default instead of the former behavior of xref:../../install_config/router/default_haproxy_router.adoc#using-the-container-network-stack[using the container network stack], which proxied traffic to the router, which in turn proxied the traffic to the target service and container. This new default behavior benefits performance because network traffic from remote clients no longer needs to take multiple hops through user space in order to reach the target service and container. Additionally, the new default behavior enables the router to get the actual source IP address of the remote connection. This is useful for defining ingress rules based on the originating IP, supporting sticky sessions, and monitoring traffic, among other uses. Existing router deployments will continue to use the container network stack unless modified to switch to using the host network stack. To switch the router to use the host network stack, edit your router's deployment configuration: ==== ---- # oc edit dc/router ---- ==== Apply the following changes: ==== ---- ... spec: replicas: 2 selector: router: router ... template: ... spec: ... ports: - containerPort: 80 <1> hostPort: 80 protocol: TCP - containerPort: 443 <1> hostPort: 443 protocol: TCP - containerPort: 1936 <1> hostPort: 1936 name: stats protocol: TCP resources: {} terminationMessagePath: /dev/termination-log dnsPolicy: ClusterFirst hostNetwork: true <2> restartPolicy: Always ... ---- ==== <1> For host networking, ensure that the `*containerPort*` value matches the `*hostPort*` values for each of the ports. <2> Add `*hostNetwork: true*` to the template `*spec*`. Now upgrade your router per the xref:upgrading-the-router[standard router upgrade steps]. *Configuring serviceNetworkCIDR for the SDN* Add the `*serviceNetworkCIDR*` parameter to the `*networkConfig*` section in *_/etc/origin/master/master-config.yaml_*. This value should match the `*servicesSubnet*` value in the `*kubernetesMasterConfig*` section: ==== ---- kubernetesMasterConfig: servicesSubnet: 172.30.0.0/16 ... networkConfig: serviceNetworkCIDR: 172.30.0.0/16 ---- ==== *Adding the Scheduler Configuration API Version* The scheduler configuration file incorrectly lacked `*kind*` and `*apiVersion*` fields when deployed using the quick or advanced installation methods. This will affect future upgrades, so it is important to add those values if they do not exist. Modify the *_/etc/origin/master/scheduler.json_* file to add the `*kind*` and `*apiVersion*` fields: ==== ---- { ""kind"": ""Policy"", <1> ""apiVersion"": ""v1"", <2> ""predicates"": [ ... } ---- ==== <1> Add `*""kind"": ""Policy"",*` <2> Add `*""apiVersion"": ""v1"",*` [[openshift-origin-1-1-0]] === OpenShift Origin 1.1.0 There are no additional manual steps for this release that are not already mentioned inline during the xref:preparing-for-a-manual-upgrade[standard manual upgrade process]. [[openshift-origin-1-5-0]] === OpenShift Origin 1.5.0 With deprecation of the `extensions/v1beta1.Job` resource, you must migrate all `Job` resources to use the `batch/v1.Job` instead. To verify which objects will be migrated, run: ---- $ oadm migrate storage --include=jobs ---- You can also increase the log level using the `--loglevel` flag. When you are ready to perform the actual migration, add the `--confirm` option: ---- $ oadm migrate storage --include=jobs --confirm ---- endif::[] [[manual-upgrades-verifying-the-upgrade]] == Verifying the Upgrade To verify the upgrade: . Check that all nodes are marked as *Ready*: + ---- # oc get nodes NAME STATUS AGE master.example.com Ready,SchedulingDisabled 165d node1.example.com Ready 165d node2.example.com Ready 165d ---- . Verify that you are running the expected versions of the *docker-registry* and *router* images, if deployed. ifdef::openshift-enterprise[] Replace `` with `{latest-tag}` for the latest version. endif::[] + ---- ifdef::openshift-enterprise[] # oc get -n default dc/docker-registry -o json | grep \\""image\\"" ""image"": ""openshift3/ose-docker-registry:"", # oc get -n default dc/router -o json | grep \\""image\\"" ""image"": ""openshift3/ose-haproxy-router:"", endif::[] ifdef::openshift-origin[] # oc get -n default dc/docker-registry -o json | grep \\""image\\"" ""image"": ""openshift/origin-docker-registry:v1.0.6"", # oc get -n default dc/router -o json | grep \\""image\\"" ""image"": ""openshift/origin-haproxy-router:v1.0.6"", endif::[] ---- ifdef::openshift-origin[] . If you upgraded from Origin 1.0 to Origin 1.1, verify in your old *_/etc/sysconfig/openshift-master_* and *_/etc/sysconfig/openshift-node_* files that any custom configuration is added to your new *_/etc/sysconfig/origin-master_* and *_/etc/sysconfig/origin-node_* files. endif::[] . Use the diagnostics tool on the master to look for common issues: + ---- # oadm diagnostics ... [Note] Summary of diagnostics execution: [Note] Completed with no errors or warnings seen. ----",12223,False,2089.210753603027,median "/* Open Asset Import Library (assimp) ---------------------------------------------------------------------- Copyright (c) 2006-2021, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------- */ #if !defined(ASSIMP_BUILD_NO_GLTF_IMPORTER) && !defined(ASSIMP_BUILD_NO_GLTF2_IMPORTER) #include ""AssetLib/glTF2/glTF2Importer.h"" #include ""PostProcessing/MakeVerboseFormat.h"" #include ""AssetLib/glTF2/glTF2Asset.h"" #if !defined(ASSIMP_BUILD_NO_EXPORT) #include ""AssetLib/glTF2/glTF2AssetWriter.h"" #endif #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace Assimp; using namespace glTF2; using namespace glTFCommon; namespace { // generate bi-tangents from normals and tangents according to spec struct Tangent { aiVector3D xyz; ai_real w; }; } // namespace // // glTF2Importer // static const aiImporterDesc desc = { ""glTF2 Importer"", """", """", """", aiImporterFlags_SupportTextFlavour | aiImporterFlags_SupportBinaryFlavour | aiImporterFlags_LimitedSupport | aiImporterFlags_Experimental, 0, 0, 0, 0, ""gltf glb"" }; glTF2Importer::glTF2Importer() : BaseImporter(), meshOffsets(), embeddedTexIdxs(), mScene(nullptr) { // empty } glTF2Importer::~glTF2Importer() { // empty } const aiImporterDesc *glTF2Importer::GetInfo() const { return &desc; } bool glTF2Importer::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool /* checkSig */) const { const std::string &extension = GetExtension(pFile); if (extension != ""gltf"" && extension != ""glb"") { return false; } if (pIOHandler) { glTF2::Asset asset(pIOHandler); asset.Load(pFile, extension == ""glb""); std::string version = asset.asset.version; return !version.empty() && version[0] == '2'; } return false; } static aiTextureMapMode ConvertWrappingMode(SamplerWrap gltfWrapMode) { switch (gltfWrapMode) { case SamplerWrap::Mirrored_Repeat: return aiTextureMapMode_Mirror; case SamplerWrap::Clamp_To_Edge: return aiTextureMapMode_Clamp; case SamplerWrap::UNSET: case SamplerWrap::Repeat: default: return aiTextureMapMode_Wrap; } } inline void SetMaterialColorProperty(Asset & /*r*/, vec4 &prop, aiMaterial *mat, const char *pKey, unsigned int type, unsigned int idx) { aiColor4D col; CopyValue(prop, col); mat->AddProperty(&col, 1, pKey, type, idx); } inline void SetMaterialColorProperty(Asset & /*r*/, vec3 &prop, aiMaterial *mat, const char *pKey, unsigned int type, unsigned int idx) { aiColor4D col; glTFCommon::CopyValue(prop, col); mat->AddProperty(&col, 1, pKey, type, idx); } inline void SetMaterialTextureProperty(std::vector &embeddedTexIdxs, Asset & /*r*/, glTF2::TextureInfo prop, aiMaterial *mat, aiTextureType texType, unsigned int texSlot = 0) { if (prop.texture && prop.texture->source) { aiString uri(prop.texture->source->uri); int texIdx = embeddedTexIdxs[prop.texture->source.GetIndex()]; if (texIdx != -1) { // embedded // setup texture reference string (copied from ColladaLoader::FindFilenameForEffectTexture) uri.data[0] = '*'; uri.length = 1 + ASSIMP_itoa10(uri.data + 1, MAXLEN - 1, texIdx); } mat->AddProperty(&uri, AI_MATKEY_TEXTURE(texType, texSlot)); const int uvIndex = static_cast(prop.texCoord); mat->AddProperty(&uvIndex, 1, AI_MATKEY_UVWSRC(texType, texSlot)); if (prop.textureTransformSupported) { aiUVTransform transform; transform.mScaling.x = prop.TextureTransformExt_t.scale[0]; transform.mScaling.y = prop.TextureTransformExt_t.scale[1]; transform.mRotation = -prop.TextureTransformExt_t.rotation; // must be negated // A change of coordinates is required to map glTF UV transformations into the space used by // Assimp. In glTF all UV origins are at 0,1 (top left of texture) in Assimp space. In Assimp // rotation occurs around the image center (0.5,0.5) where as in glTF rotation is around the // texture origin. All three can be corrected for solely by a change of the translation since // the transformations available are shape preserving. Note the importer already flips the V // coordinate of the actual meshes during import. const ai_real rcos(cos(-transform.mRotation)); const ai_real rsin(sin(-transform.mRotation)); transform.mTranslation.x = (static_cast( 0.5 ) * transform.mScaling.x) * (-rcos + rsin + 1) + prop.TextureTransformExt_t.offset[0]; transform.mTranslation.y = ((static_cast( 0.5 ) * transform.mScaling.y) * (rsin + rcos - 1)) + 1 - transform.mScaling.y - prop.TextureTransformExt_t.offset[1];; mat->AddProperty(&transform, 1, _AI_MATKEY_UVTRANSFORM_BASE, texType, texSlot); } if (prop.texture->sampler) { Ref sampler = prop.texture->sampler; aiString name(sampler->name); aiString id(sampler->id); mat->AddProperty(&name, AI_MATKEY_GLTF_MAPPINGNAME(texType, texSlot)); mat->AddProperty(&id, AI_MATKEY_GLTF_MAPPINGID(texType, texSlot)); aiTextureMapMode wrapS = ConvertWrappingMode(sampler->wrapS); aiTextureMapMode wrapT = ConvertWrappingMode(sampler->wrapT); mat->AddProperty(&wrapS, 1, AI_MATKEY_MAPPINGMODE_U(texType, texSlot)); mat->AddProperty(&wrapT, 1, AI_MATKEY_MAPPINGMODE_V(texType, texSlot)); if (sampler->magFilter != SamplerMagFilter::UNSET) { mat->AddProperty(&sampler->magFilter, 1, AI_MATKEY_GLTF_MAPPINGFILTER_MAG(texType, texSlot)); } if (sampler->minFilter != SamplerMinFilter::UNSET) { mat->AddProperty(&sampler->minFilter, 1, AI_MATKEY_GLTF_MAPPINGFILTER_MIN(texType, texSlot)); } } else { // Use glTFv2 default sampler const aiTextureMapMode default_wrap = aiTextureMapMode_Wrap; mat->AddProperty(&default_wrap, 1, AI_MATKEY_MAPPINGMODE_U(texType, texSlot)); mat->AddProperty(&default_wrap, 1, AI_MATKEY_MAPPINGMODE_V(texType, texSlot)); } } } inline void SetMaterialTextureProperty(std::vector &embeddedTexIdxs, Asset &r, glTF2::NormalTextureInfo &prop, aiMaterial *mat, aiTextureType texType, unsigned int texSlot = 0) { SetMaterialTextureProperty(embeddedTexIdxs, r, (glTF2::TextureInfo)prop, mat, texType, texSlot); if (prop.texture && prop.texture->source) { mat->AddProperty(&prop.scale, 1, AI_MATKEY_GLTF_TEXTURE_SCALE(texType, texSlot)); } } inline void SetMaterialTextureProperty(std::vector &embeddedTexIdxs, Asset &r, glTF2::OcclusionTextureInfo &prop, aiMaterial *mat, aiTextureType texType, unsigned int texSlot = 0) { SetMaterialTextureProperty(embeddedTexIdxs, r, (glTF2::TextureInfo)prop, mat, texType, texSlot); if (prop.texture && prop.texture->source) { mat->AddProperty(&prop.strength, 1, AI_MATKEY_GLTF_TEXTURE_STRENGTH(texType, texSlot)); } } static aiMaterial *ImportMaterial(std::vector &embeddedTexIdxs, Asset &r, Material &mat) { aiMaterial *aimat = new aiMaterial(); try { if (!mat.name.empty()) { aiString str(mat.name); aimat->AddProperty(&str, AI_MATKEY_NAME); } // Set Assimp DIFFUSE and BASE COLOR to the pbrMetallicRoughness base color and texture for backwards compatibility // Technically should not load any pbrMetallicRoughness if extensionsRequired contains KHR_materials_pbrSpecularGlossiness SetMaterialColorProperty(r, mat.pbrMetallicRoughness.baseColorFactor, aimat, AI_MATKEY_COLOR_DIFFUSE); SetMaterialColorProperty(r, mat.pbrMetallicRoughness.baseColorFactor, aimat, AI_MATKEY_BASE_COLOR); SetMaterialTextureProperty(embeddedTexIdxs, r, mat.pbrMetallicRoughness.baseColorTexture, aimat, aiTextureType_DIFFUSE); SetMaterialTextureProperty(embeddedTexIdxs, r, mat.pbrMetallicRoughness.baseColorTexture, aimat, aiTextureType_BASE_COLOR); SetMaterialTextureProperty(embeddedTexIdxs, r, mat.pbrMetallicRoughness.metallicRoughnessTexture, aimat, AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLICROUGHNESS_TEXTURE); aimat->AddProperty(&mat.pbrMetallicRoughness.metallicFactor, 1, AI_MATKEY_METALLIC_FACTOR); aimat->AddProperty(&mat.pbrMetallicRoughness.roughnessFactor, 1, AI_MATKEY_ROUGHNESS_FACTOR); float roughnessAsShininess = 1 - mat.pbrMetallicRoughness.roughnessFactor; roughnessAsShininess *= roughnessAsShininess * 1000; aimat->AddProperty(&roughnessAsShininess, 1, AI_MATKEY_SHININESS); SetMaterialTextureProperty(embeddedTexIdxs, r, mat.normalTexture, aimat, aiTextureType_NORMALS); SetMaterialTextureProperty(embeddedTexIdxs, r, mat.occlusionTexture, aimat, aiTextureType_LIGHTMAP); SetMaterialTextureProperty(embeddedTexIdxs, r, mat.emissiveTexture, aimat, aiTextureType_EMISSIVE); SetMaterialColorProperty(r, mat.emissiveFactor, aimat, AI_MATKEY_COLOR_EMISSIVE); aimat->AddProperty(&mat.doubleSided, 1, AI_MATKEY_TWOSIDED); aimat->AddProperty(&mat.pbrMetallicRoughness.baseColorFactor[3], 1, AI_MATKEY_OPACITY); aiString alphaMode(mat.alphaMode); aimat->AddProperty(&alphaMode, AI_MATKEY_GLTF_ALPHAMODE); aimat->AddProperty(&mat.alphaCutoff, 1, AI_MATKEY_GLTF_ALPHACUTOFF); //pbrSpecularGlossiness if (mat.pbrSpecularGlossiness.isPresent) { PbrSpecularGlossiness &pbrSG = mat.pbrSpecularGlossiness.value; SetMaterialColorProperty(r, pbrSG.diffuseFactor, aimat, AI_MATKEY_COLOR_DIFFUSE); SetMaterialColorProperty(r, pbrSG.specularFactor, aimat, AI_MATKEY_COLOR_SPECULAR); float glossinessAsShininess = pbrSG.glossinessFactor * 1000.0f; aimat->AddProperty(&glossinessAsShininess, 1, AI_MATKEY_SHININESS); aimat->AddProperty(&pbrSG.glossinessFactor, 1, AI_MATKEY_GLOSSINESS_FACTOR); SetMaterialTextureProperty(embeddedTexIdxs, r, pbrSG.diffuseTexture, aimat, aiTextureType_DIFFUSE); SetMaterialTextureProperty(embeddedTexIdxs, r, pbrSG.specularGlossinessTexture, aimat, aiTextureType_SPECULAR); } // glTFv2 is either PBR or Unlit aiShadingMode shadingMode = aiShadingMode_PBR_BRDF; if (mat.unlit) { shadingMode = aiShadingMode_Unlit; } aimat->AddProperty(&shadingMode, 1, AI_MATKEY_SHADING_MODEL); // KHR_materials_sheen if (mat.materialSheen.isPresent) { MaterialSheen &sheen = mat.materialSheen.value; // Default value {0,0,0} disables Sheen if (sheen.sheenColorFactor != defaultSheenFactor) { SetMaterialColorProperty(r, sheen.sheenColorFactor, aimat, AI_MATKEY_SHEEN_COLOR_FACTOR); aimat->AddProperty(&sheen.sheenRoughnessFactor, 1, AI_MATKEY_SHEEN_ROUGHNESS_FACTOR); SetMaterialTextureProperty(embeddedTexIdxs, r, sheen.sheenColorTexture, aimat, AI_MATKEY_SHEEN_COLOR_TEXTURE); SetMaterialTextureProperty(embeddedTexIdxs, r, sheen.sheenRoughnessTexture, aimat, AI_MATKEY_SHEEN_ROUGHNESS_TEXTURE); } } // KHR_materials_clearcoat if (mat.materialClearcoat.isPresent) { MaterialClearcoat &clearcoat = mat.materialClearcoat.value; // Default value 0.0 disables clearcoat if (clearcoat.clearcoatFactor != 0.0f) { aimat->AddProperty(&clearcoat.clearcoatFactor, 1, AI_MATKEY_CLEARCOAT_FACTOR); aimat->AddProperty(&clearcoat.clearcoatRoughnessFactor, 1, AI_MATKEY_CLEARCOAT_ROUGHNESS_FACTOR); SetMaterialTextureProperty(embeddedTexIdxs, r, clearcoat.clearcoatTexture, aimat, AI_MATKEY_CLEARCOAT_TEXTURE); SetMaterialTextureProperty(embeddedTexIdxs, r, clearcoat.clearcoatRoughnessTexture, aimat, AI_MATKEY_CLEARCOAT_ROUGHNESS_TEXTURE); SetMaterialTextureProperty(embeddedTexIdxs, r, clearcoat.clearcoatNormalTexture, aimat, AI_MATKEY_CLEARCOAT_NORMAL_TEXTURE); } } // KHR_materials_transmission if (mat.materialTransmission.isPresent) { MaterialTransmission &transmission = mat.materialTransmission.value; aimat->AddProperty(&transmission.transmissionFactor, 1, AI_MATKEY_TRANSMISSION_FACTOR); SetMaterialTextureProperty(embeddedTexIdxs, r, transmission.transmissionTexture, aimat, AI_MATKEY_TRANSMISSION_TEXTURE); } return aimat; } catch (...) { delete aimat; throw; } } void glTF2Importer::ImportMaterials(glTF2::Asset &r) { const unsigned int numImportedMaterials = unsigned(r.materials.Size()); ASSIMP_LOG_DEBUG(""Importing "", numImportedMaterials, "" materials""); Material defaultMaterial; mScene->mNumMaterials = numImportedMaterials + 1; mScene->mMaterials = new aiMaterial *[mScene->mNumMaterials]; std::fill(mScene->mMaterials, mScene->mMaterials + mScene->mNumMaterials, nullptr); mScene->mMaterials[numImportedMaterials] = ImportMaterial(embeddedTexIdxs, r, defaultMaterial); for (unsigned int i = 0; i < numImportedMaterials; ++i) { mScene->mMaterials[i] = ImportMaterial(embeddedTexIdxs, r, r.materials[i]); } } static inline void SetFaceAndAdvance1(aiFace*& face, unsigned int numVertices, unsigned int a) { if (a >= numVertices) { return; } face->mNumIndices = 1; face->mIndices = new unsigned int[1]; face->mIndices[0] = a; ++face; } static inline void SetFaceAndAdvance2(aiFace*& face, unsigned int numVertices, unsigned int a, unsigned int b) { if ((a >= numVertices) || (b >= numVertices)) { return; } face->mNumIndices = 2; face->mIndices = new unsigned int[2]; face->mIndices[0] = a; face->mIndices[1] = b; ++face; } static inline void SetFaceAndAdvance3(aiFace*& face, unsigned int numVertices, unsigned int a, unsigned int b, unsigned int c) { if ((a >= numVertices) || (b >= numVertices) || (c >= numVertices)) { return; } face->mNumIndices = 3; face->mIndices = new unsigned int[3]; face->mIndices[0] = a; face->mIndices[1] = b; face->mIndices[2] = c; ++face; } #ifdef ASSIMP_BUILD_DEBUG static inline bool CheckValidFacesIndices(aiFace *faces, unsigned nFaces, unsigned nVerts) { for (unsigned i = 0; i < nFaces; ++i) { for (unsigned j = 0; j < faces[i].mNumIndices; ++j) { unsigned idx = faces[i].mIndices[j]; if (idx >= nVerts) { return false; } } } return true; } #endif // ASSIMP_BUILD_DEBUG template aiColor4D* GetVertexColorsForType(glTF2::Ref input) { float max = std::numeric_limits::max(); aiColor4t* colors; input->ExtractData(colors); auto output = new aiColor4D[input->count]; for (size_t i = 0; i < input->count; i++) { output[i] = aiColor4D( colors[i].r / max, colors[i].g / max, colors[i].b / max, colors[i].a / max ); } delete[] colors; return output; } void glTF2Importer::ImportMeshes(glTF2::Asset &r) { ASSIMP_LOG_DEBUG(""Importing "", r.meshes.Size(), "" meshes""); std::vector> meshes; unsigned int k = 0; meshOffsets.clear(); for (unsigned int m = 0; m < r.meshes.Size(); ++m) { Mesh &mesh = r.meshes[m]; meshOffsets.push_back(k); k += unsigned(mesh.primitives.size()); for (unsigned int p = 0; p < mesh.primitives.size(); ++p) { Mesh::Primitive &prim = mesh.primitives[p]; aiMesh *aim = new aiMesh(); meshes.push_back(std::unique_ptr(aim)); aim->mName = mesh.name.empty() ? mesh.id : mesh.name; if (mesh.primitives.size() > 1) { ai_uint32 &len = aim->mName.length; aim->mName.data[len] = '-'; len += 1 + ASSIMP_itoa10(aim->mName.data + len + 1, unsigned(MAXLEN - len - 1), p); } switch (prim.mode) { case PrimitiveMode_POINTS: aim->mPrimitiveTypes |= aiPrimitiveType_POINT; break; case PrimitiveMode_LINES: case PrimitiveMode_LINE_LOOP: case PrimitiveMode_LINE_STRIP: aim->mPrimitiveTypes |= aiPrimitiveType_LINE; break; case PrimitiveMode_TRIANGLES: case PrimitiveMode_TRIANGLE_STRIP: case PrimitiveMode_TRIANGLE_FAN: aim->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE; break; } Mesh::Primitive::Attributes &attr = prim.attributes; if (attr.position.size() > 0 && attr.position[0]) { aim->mNumVertices = static_cast(attr.position[0]->count); attr.position[0]->ExtractData(aim->mVertices); } if (attr.normal.size() > 0 && attr.normal[0]) { if (attr.normal[0]->count != aim->mNumVertices) { DefaultLogger::get()->warn(""Normal count in mesh \\"""", mesh.name, ""\\"" does not match the vertex count, normals ignored.""); } else { attr.normal[0]->ExtractData(aim->mNormals); // only extract tangents if normals are present if (attr.tangent.size() > 0 && attr.tangent[0]) { if (attr.tangent[0]->count != aim->mNumVertices) { DefaultLogger::get()->warn(""Tangent count in mesh \\"""", mesh.name, ""\\"" does not match the vertex count, tangents ignored.""); } else { // generate bitangents from normals and tangents according to spec Tangent *tangents = nullptr; attr.tangent[0]->ExtractData(tangents); aim->mTangents = new aiVector3D[aim->mNumVertices]; aim->mBitangents = new aiVector3D[aim->mNumVertices]; for (unsigned int i = 0; i < aim->mNumVertices; ++i) { aim->mTangents[i] = tangents[i].xyz; aim->mBitangents[i] = (aim->mNormals[i] ^ tangents[i].xyz) * tangents[i].w; } delete[] tangents; } } } } for (size_t c = 0; c < attr.color.size() && c < AI_MAX_NUMBER_OF_COLOR_SETS; ++c) { if (attr.color[c]->count != aim->mNumVertices) { DefaultLogger::get()->warn(""Color stream size in mesh \\"""", mesh.name, ""\\"" does not match the vertex count""); continue; } auto componentType = attr.color[c]->componentType; if (componentType == glTF2::ComponentType_FLOAT) { attr.color[c]->ExtractData(aim->mColors[c]); } else { if (componentType == glTF2::ComponentType_UNSIGNED_BYTE) { aim->mColors[c] = GetVertexColorsForType(attr.color[c]); } else if (componentType == glTF2::ComponentType_UNSIGNED_SHORT) { aim->mColors[c] = GetVertexColorsForType(attr.color[c]); } } } for (size_t tc = 0; tc < attr.texcoord.size() && tc < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++tc) { if (!attr.texcoord[tc]) { DefaultLogger::get()->warn(""Texture coordinate accessor not found or non-contiguous texture coordinate sets.""); continue; } if (attr.texcoord[tc]->count != aim->mNumVertices) { DefaultLogger::get()->warn(""Texcoord stream size in mesh \\"""", mesh.name, ""\\"" does not match the vertex count""); continue; } attr.texcoord[tc]->ExtractData(aim->mTextureCoords[tc]); aim->mNumUVComponents[tc] = attr.texcoord[tc]->GetNumComponents(); aiVector3D *values = aim->mTextureCoords[tc]; for (unsigned int i = 0; i < aim->mNumVertices; ++i) { values[i].y = 1 - values[i].y; // Flip Y coords } } std::vector &targets = prim.targets; if (targets.size() > 0) { aim->mNumAnimMeshes = (unsigned int)targets.size(); aim->mAnimMeshes = new aiAnimMesh *[aim->mNumAnimMeshes]; std::fill(aim->mAnimMeshes, aim->mAnimMeshes + aim->mNumAnimMeshes, nullptr); for (size_t i = 0; i < targets.size(); i++) { bool needPositions = targets[i].position.size() > 0; bool needNormals = (targets[i].normal.size() > 0) && aim->HasNormals(); bool needTangents = (targets[i].tangent.size() > 0) && aim->HasTangentsAndBitangents(); // GLTF morph does not support colors and texCoords aim->mAnimMeshes[i] = aiCreateAnimMesh(aim, needPositions, needNormals, needTangents, false, false); aiAnimMesh &aiAnimMesh = *(aim->mAnimMeshes[i]); Mesh::Primitive::Target &target = targets[i]; if (needPositions) { if (target.position[0]->count != aim->mNumVertices) { ASSIMP_LOG_WARN(""Positions of target "", i, "" in mesh \\"""", mesh.name, ""\\"" does not match the vertex count""); } else { aiVector3D *positionDiff = nullptr; target.position[0]->ExtractData(positionDiff); for (unsigned int vertexId = 0; vertexId < aim->mNumVertices; vertexId++) { aiAnimMesh.mVertices[vertexId] += positionDiff[vertexId]; } delete[] positionDiff; } } if (needNormals) { if (target.normal[0]->count != aim->mNumVertices) { ASSIMP_LOG_WARN(""Normals of target "", i, "" in mesh \\"""", mesh.name, ""\\"" does not match the vertex count""); } else { aiVector3D *normalDiff = nullptr; target.normal[0]->ExtractData(normalDiff); for (unsigned int vertexId = 0; vertexId < aim->mNumVertices; vertexId++) { aiAnimMesh.mNormals[vertexId] += normalDiff[vertexId]; } delete[] normalDiff; } } if (needTangents) { if (target.tangent[0]->count != aim->mNumVertices) { ASSIMP_LOG_WARN(""Tangents of target "", i, "" in mesh \\"""", mesh.name, ""\\"" does not match the vertex count""); } else { Tangent *tangent = nullptr; attr.tangent[0]->ExtractData(tangent); aiVector3D *tangentDiff = nullptr; target.tangent[0]->ExtractData(tangentDiff); for (unsigned int vertexId = 0; vertexId < aim->mNumVertices; ++vertexId) { tangent[vertexId].xyz += tangentDiff[vertexId]; aiAnimMesh.mTangents[vertexId] = tangent[vertexId].xyz; aiAnimMesh.mBitangents[vertexId] = (aiAnimMesh.mNormals[vertexId] ^ tangent[vertexId].xyz) * tangent[vertexId].w; } delete[] tangent; delete[] tangentDiff; } } if (mesh.weights.size() > i) { aiAnimMesh.mWeight = mesh.weights[i]; } if (mesh.targetNames.size() > i) { aiAnimMesh.mName = mesh.targetNames[i]; } } } aiFace *faces = nullptr; aiFace *facePtr = nullptr; size_t nFaces = 0; if (prim.indices) { size_t count = prim.indices->count; Accessor::Indexer data = prim.indices->GetIndexer(); if (!data.IsValid()) { throw DeadlyImportError(""GLTF: Invalid accessor without data in mesh "", getContextForErrorMessages(mesh.id, mesh.name)); } switch (prim.mode) { case PrimitiveMode_POINTS: { nFaces = count; facePtr = faces = new aiFace[nFaces]; for (unsigned int i = 0; i < count; ++i) { SetFaceAndAdvance1(facePtr, aim->mNumVertices, data.GetUInt(i)); } break; } case PrimitiveMode_LINES: { nFaces = count / 2; if (nFaces * 2 != count) { ASSIMP_LOG_WARN(""The number of vertices was not compatible with the LINES mode. Some vertices were dropped.""); count = nFaces * 2; } facePtr = faces = new aiFace[nFaces]; for (unsigned int i = 0; i < count; i += 2) { SetFaceAndAdvance2(facePtr, aim->mNumVertices, data.GetUInt(i), data.GetUInt(i + 1)); } break; } case PrimitiveMode_LINE_LOOP: case PrimitiveMode_LINE_STRIP: { nFaces = count - ((prim.mode == PrimitiveMode_LINE_STRIP) ? 1 : 0); facePtr = faces = new aiFace[nFaces]; SetFaceAndAdvance2(facePtr, aim->mNumVertices, data.GetUInt(0), data.GetUInt(1)); for (unsigned int i = 2; i < count; ++i) { SetFaceAndAdvance2(facePtr, aim->mNumVertices, data.GetUInt(i - 1), data.GetUInt(i)); } if (prim.mode == PrimitiveMode_LINE_LOOP) { // close the loop SetFaceAndAdvance2(facePtr, aim->mNumVertices, data.GetUInt(static_cast(count) - 1), faces[0].mIndices[0]); } break; } case PrimitiveMode_TRIANGLES: { nFaces = count / 3; if (nFaces * 3 != count) { ASSIMP_LOG_WARN(""The number of vertices was not compatible with the TRIANGLES mode. Some vertices were dropped.""); count = nFaces * 3; } facePtr = faces = new aiFace[nFaces]; for (unsigned int i = 0; i < count; i += 3) { SetFaceAndAdvance3(facePtr, aim->mNumVertices, data.GetUInt(i), data.GetUInt(i + 1), data.GetUInt(i + 2)); } break; } case PrimitiveMode_TRIANGLE_STRIP: { nFaces = count - 2; facePtr = faces = new aiFace[nFaces]; for (unsigned int i = 0; i < nFaces; ++i) { //The ordering is to ensure that the triangles are all drawn with the same orientation if ((i + 1) % 2 == 0) { //For even n, vertices n + 1, n, and n + 2 define triangle n SetFaceAndAdvance3(facePtr, aim->mNumVertices, data.GetUInt(i + 1), data.GetUInt(i), data.GetUInt(i + 2)); } else { //For odd n, vertices n, n+1, and n+2 define triangle n SetFaceAndAdvance3(facePtr, aim->mNumVertices, data.GetUInt(i), data.GetUInt(i + 1), data.GetUInt(i + 2)); } } break; } case PrimitiveMode_TRIANGLE_FAN: nFaces = count - 2; facePtr = faces = new aiFace[nFaces]; SetFaceAndAdvance3(facePtr, aim->mNumVertices, data.GetUInt(0), data.GetUInt(1), data.GetUInt(2)); for (unsigned int i = 1; i < nFaces; ++i) { SetFaceAndAdvance3(facePtr, aim->mNumVertices, data.GetUInt(0), data.GetUInt(i + 1), data.GetUInt(i + 2)); } break; } } else { // no indices provided so directly generate from counts // use the already determined count as it includes checks unsigned int count = aim->mNumVertices; switch (prim.mode) { case PrimitiveMode_POINTS: { nFaces = count; facePtr = faces = new aiFace[nFaces]; for (unsigned int i = 0; i < count; ++i) { SetFaceAndAdvance1(facePtr, aim->mNumVertices, i); } break; } case PrimitiveMode_LINES: { nFaces = count / 2; if (nFaces * 2 != count) { ASSIMP_LOG_WARN(""The number of vertices was not compatible with the LINES mode. Some vertices were dropped.""); count = (unsigned int)nFaces * 2; } facePtr = faces = new aiFace[nFaces]; for (unsigned int i = 0; i < count; i += 2) { SetFaceAndAdvance2(facePtr, aim->mNumVertices, i, i + 1); } break; } case PrimitiveMode_LINE_LOOP: case PrimitiveMode_LINE_STRIP: { nFaces = count - ((prim.mode == PrimitiveMode_LINE_STRIP) ? 1 : 0); facePtr = faces = new aiFace[nFaces]; SetFaceAndAdvance2(facePtr, aim->mNumVertices, 0, 1); for (unsigned int i = 2; i < count; ++i) { SetFaceAndAdvance2(facePtr, aim->mNumVertices, i - 1, i); } if (prim.mode == PrimitiveMode_LINE_LOOP) { // close the loop SetFaceAndAdvance2(facePtr, aim->mNumVertices, count - 1, 0); } break; } case PrimitiveMode_TRIANGLES: { nFaces = count / 3; if (nFaces * 3 != count) { ASSIMP_LOG_WARN(""The number of vertices was not compatible with the TRIANGLES mode. Some vertices were dropped.""); count = (unsigned int)nFaces * 3; } facePtr = faces = new aiFace[nFaces]; for (unsigned int i = 0; i < count; i += 3) { SetFaceAndAdvance3(facePtr, aim->mNumVertices, i, i + 1, i + 2); } break; } case PrimitiveMode_TRIANGLE_STRIP: { nFaces = count - 2; facePtr = faces = new aiFace[nFaces]; for (unsigned int i = 0; i < nFaces; ++i) { //The ordering is to ensure that the triangles are all drawn with the same orientation if ((i + 1) % 2 == 0) { //For even n, vertices n + 1, n, and n + 2 define triangle n SetFaceAndAdvance3(facePtr, aim->mNumVertices, i + 1, i, i + 2); } else { //For odd n, vertices n, n+1, and n+2 define triangle n SetFaceAndAdvance3(facePtr, aim->mNumVertices, i, i + 1, i + 2); } } break; } case PrimitiveMode_TRIANGLE_FAN: nFaces = count - 2; facePtr = faces = new aiFace[nFaces]; SetFaceAndAdvance3(facePtr, aim->mNumVertices, 0, 1, 2); for (unsigned int i = 1; i < nFaces; ++i) { SetFaceAndAdvance3(facePtr, aim->mNumVertices, 0, i + 1, i + 2); } break; } } if (faces) { aim->mFaces = faces; const unsigned int actualNumFaces = static_cast(facePtr - faces); if (actualNumFaces < nFaces) { ASSIMP_LOG_WARN(""Some faces had out-of-range indices. Those faces were dropped.""); } if (actualNumFaces == 0) { throw DeadlyImportError(""Mesh \\"""", aim->mName.C_Str(), ""\\"" has no faces""); } aim->mNumFaces = actualNumFaces; ai_assert(CheckValidFacesIndices(faces, actualNumFaces, aim->mNumVertices)); } if (prim.material) { aim->mMaterialIndex = prim.material.GetIndex(); } else { aim->mMaterialIndex = mScene->mNumMaterials - 1; } } } meshOffsets.push_back(k); CopyVector(meshes, mScene->mMeshes, mScene->mNumMeshes); } void glTF2Importer::ImportCameras(glTF2::Asset &r) { if (!r.cameras.Size()) return; const unsigned int numCameras = r.cameras.Size(); ASSIMP_LOG_DEBUG(""Importing "", numCameras, "" cameras""); mScene->mNumCameras = numCameras; mScene->mCameras = new aiCamera *[numCameras]; std::fill(mScene->mCameras, mScene->mCameras + numCameras, nullptr); for (size_t i = 0; i < numCameras; ++i) { Camera &cam = r.cameras[i]; aiCamera *aicam = mScene->mCameras[i] = new aiCamera(); // cameras point in -Z by default, rest is specified in node transform aicam->mLookAt = aiVector3D(0.f, 0.f, -1.f); if (cam.type == Camera::Perspective) { aicam->mAspect = cam.cameraProperties.perspective.aspectRatio; aicam->mHorizontalFOV = cam.cameraProperties.perspective.yfov * ((aicam->mAspect == 0.f) ? 1.f : aicam->mAspect); aicam->mClipPlaneFar = cam.cameraProperties.perspective.zfar; aicam->mClipPlaneNear = cam.cameraProperties.perspective.znear; } else { aicam->mClipPlaneFar = cam.cameraProperties.ortographic.zfar; aicam->mClipPlaneNear = cam.cameraProperties.ortographic.znear; aicam->mHorizontalFOV = 0.0; aicam->mOrthographicWidth = cam.cameraProperties.ortographic.xmag; aicam->mAspect = 1.0f; if (0.f != cam.cameraProperties.ortographic.ymag) { aicam->mAspect = cam.cameraProperties.ortographic.xmag / cam.cameraProperties.ortographic.ymag; } } } } void glTF2Importer::ImportLights(glTF2::Asset &r) { if (!r.lights.Size()) return; const unsigned int numLights = r.lights.Size(); ASSIMP_LOG_DEBUG(""Importing "", numLights, "" lights""); mScene->mNumLights = numLights; mScene->mLights = new aiLight *[numLights]; std::fill(mScene->mLights, mScene->mLights + numLights, nullptr); for (size_t i = 0; i < numLights; ++i) { Light &light = r.lights[i]; aiLight *ail = mScene->mLights[i] = new aiLight(); switch (light.type) { case Light::Directional: ail->mType = aiLightSource_DIRECTIONAL; break; case Light::Point: ail->mType = aiLightSource_POINT; break; case Light::Spot: ail->mType = aiLightSource_SPOT; break; } if (ail->mType != aiLightSource_POINT) { ail->mDirection = aiVector3D(0.0f, 0.0f, -1.0f); ail->mUp = aiVector3D(0.0f, 1.0f, 0.0f); } vec3 colorWithIntensity = { light.color[0] * light.intensity, light.color[1] * light.intensity, light.color[2] * light.intensity }; CopyValue(colorWithIntensity, ail->mColorAmbient); CopyValue(colorWithIntensity, ail->mColorDiffuse); CopyValue(colorWithIntensity, ail->mColorSpecular); if (ail->mType == aiLightSource_DIRECTIONAL) { ail->mAttenuationConstant = 1.0; ail->mAttenuationLinear = 0.0; ail->mAttenuationQuadratic = 0.0; } else { //in PBR attenuation is calculated using inverse square law which can be expressed //using assimps equation: 1/(att0 + att1 * d + att2 * d*d) with the following parameters //this is correct equation for the case when range (see //https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual) //is not present. When range is not present it is assumed that it is infinite and so numerator is 1. //When range is present then numerator might be any value in range [0,1] and then assimps equation //will not suffice. In this case range is added into metadata in ImportNode function //and its up to implementation to read it when it wants to ail->mAttenuationConstant = 0.0; ail->mAttenuationLinear = 0.0; ail->mAttenuationQuadratic = 1.0; } if (ail->mType == aiLightSource_SPOT) { ail->mAngleInnerCone = light.innerConeAngle; ail->mAngleOuterCone = light.outerConeAngle; } } } static void GetNodeTransform(aiMatrix4x4 &matrix, const glTF2::Node &node) { if (node.matrix.isPresent) { CopyValue(node.matrix.value, matrix); } else { if (node.translation.isPresent) { aiVector3D trans; CopyValue(node.translation.value, trans); aiMatrix4x4 t; aiMatrix4x4::Translation(trans, t); matrix = matrix * t; } if (node.rotation.isPresent) { aiQuaternion rot; CopyValue(node.rotation.value, rot); matrix = matrix * aiMatrix4x4(rot.GetMatrix()); } if (node.scale.isPresent) { aiVector3D scal(1.f); CopyValue(node.scale.value, scal); aiMatrix4x4 s; aiMatrix4x4::Scaling(scal, s); matrix = matrix * s; } } } static void BuildVertexWeightMapping(Mesh::Primitive &primitive, std::vector> &map) { Mesh::Primitive::Attributes &attr = primitive.attributes; if (attr.weight.empty() || attr.joint.empty()) { return; } if (attr.weight[0]->count != attr.joint[0]->count) { return; } size_t num_vertices = attr.weight[0]->count; struct Weights { float values[4]; }; Weights *weights = nullptr; attr.weight[0]->ExtractData(weights); struct Indices8 { uint8_t values[4]; }; struct Indices16 { uint16_t values[4]; }; Indices8 *indices8 = nullptr; Indices16 *indices16 = nullptr; if (attr.joint[0]->GetElementSize() == 4) { attr.joint[0]->ExtractData(indices8); } else { attr.joint[0]->ExtractData(indices16); } // if (nullptr == indices8 && nullptr == indices16) { // Something went completely wrong! ai_assert(false); return; } for (size_t i = 0; i < num_vertices; ++i) { for (int j = 0; j < 4; ++j) { const unsigned int bone = (indices8 != nullptr) ? indices8[i].values[j] : indices16[i].values[j]; const float weight = weights[i].values[j]; if (weight > 0 && bone < map.size()) { map[bone].reserve(8); map[bone].emplace_back(static_cast(i), weight); } } } delete[] weights; delete[] indices8; delete[] indices16; } static std::string GetNodeName(const Node &node) { return node.name.empty() ? node.id : node.name; } void ParseExtensions(aiMetadata *metadata, const CustomExtension &extension) { if (extension.mStringValue.isPresent) { metadata->Add(extension.name.c_str(), aiString(extension.mStringValue.value)); } else if (extension.mDoubleValue.isPresent) { metadata->Add(extension.name.c_str(), extension.mDoubleValue.value); } else if (extension.mUint64Value.isPresent) { metadata->Add(extension.name.c_str(), extension.mUint64Value.value); } else if (extension.mInt64Value.isPresent) { metadata->Add(extension.name.c_str(), static_cast(extension.mInt64Value.value)); } else if (extension.mBoolValue.isPresent) { metadata->Add(extension.name.c_str(), extension.mBoolValue.value); } else if (extension.mValues.isPresent) { aiMetadata val; for (auto const & subExtension : extension.mValues.value) { ParseExtensions(&val, subExtension); } metadata->Add(extension.name.c_str(), val); } } void ParseExtras(aiMetadata *metadata, const CustomExtension &extension) { if (extension.mValues.isPresent) { for (auto const & subExtension : extension.mValues.value) { ParseExtensions(metadata, subExtension); } } } aiNode *ImportNode(aiScene *pScene, glTF2::Asset &r, std::vector &meshOffsets, glTF2::Ref &ptr) { Node &node = *ptr; aiNode *ainode = new aiNode(GetNodeName(node)); try { if (!node.children.empty()) { ainode->mNumChildren = unsigned(node.children.size()); ainode->mChildren = new aiNode *[ainode->mNumChildren]; std::fill(ainode->mChildren, ainode->mChildren + ainode->mNumChildren, nullptr); for (unsigned int i = 0; i < ainode->mNumChildren; ++i) { aiNode *child = ImportNode(pScene, r, meshOffsets, node.children[i]); child->mParent = ainode; ainode->mChildren[i] = child; } } if (node.customExtensions || node.extras) { ainode->mMetaData = new aiMetadata; if (node.customExtensions) { ParseExtensions(ainode->mMetaData, node.customExtensions); } if (node.extras) { ParseExtras(ainode->mMetaData, node.extras); } } GetNodeTransform(ainode->mTransformation, node); if (!node.meshes.empty()) { // GLTF files contain at most 1 mesh per node. if (node.meshes.size() > 1) { throw DeadlyImportError(""GLTF: Invalid input, found "", node.meshes.size(), "" meshes in "", getContextForErrorMessages(node.id, node.name), "", but only 1 mesh per node allowed.""); } int mesh_idx = node.meshes[0].GetIndex(); int count = meshOffsets[mesh_idx + 1] - meshOffsets[mesh_idx]; ainode->mNumMeshes = count; ainode->mMeshes = new unsigned int[count]; if (node.skin) { for (int primitiveNo = 0; primitiveNo < count; ++primitiveNo) { aiMesh *mesh = pScene->mMeshes[meshOffsets[mesh_idx] + primitiveNo]; unsigned int numBones =static_cast(node.skin->jointNames.size()); std::vector> weighting(numBones); BuildVertexWeightMapping(node.meshes[0]->primitives[primitiveNo], weighting); mesh->mNumBones = static_cast(numBones); mesh->mBones = new aiBone *[mesh->mNumBones]; std::fill(mesh->mBones, mesh->mBones + mesh->mNumBones, nullptr); // GLTF and Assimp choose to store bone weights differently. // GLTF has each vertex specify which bones influence the vertex. // Assimp has each bone specify which vertices it has influence over. // To convert this data, we first read over the vertex data and pull // out the bone-to-vertex mapping. Then, when creating the aiBones, // we copy the bone-to-vertex mapping into the bone. This is unfortunate // both because it's somewhat slow and because, for many applications, // we then need to reconvert the data back into the vertex-to-bone // mapping which makes things doubly-slow. mat4 *pbindMatrices = nullptr; node.skin->inverseBindMatrices->ExtractData(pbindMatrices); for (uint32_t i = 0; i < numBones; ++i) { const std::vector &weights = weighting[i]; aiBone *bone = new aiBone(); Ref joint = node.skin->jointNames[i]; if (!joint->name.empty()) { bone->mName = joint->name; } else { // Assimp expects each bone to have a unique name. static const std::string kDefaultName = ""bone_""; char postfix[10] = { 0 }; ASSIMP_itoa10(postfix, i); bone->mName = (kDefaultName + postfix); } GetNodeTransform(bone->mOffsetMatrix, *joint); CopyValue(pbindMatrices[i], bone->mOffsetMatrix); bone->mNumWeights = static_cast(weights.size()); if (bone->mNumWeights > 0) { bone->mWeights = new aiVertexWeight[bone->mNumWeights]; memcpy(bone->mWeights, weights.data(), bone->mNumWeights * sizeof(aiVertexWeight)); } else { // Assimp expects all bones to have at least 1 weight. bone->mWeights = new aiVertexWeight[1]; bone->mNumWeights = 1; bone->mWeights->mVertexId = 0; bone->mWeights->mWeight = 0.f; } mesh->mBones[i] = bone; } if (pbindMatrices) { delete[] pbindMatrices; } } } int k = 0; for (unsigned int j = meshOffsets[mesh_idx]; j < meshOffsets[mesh_idx + 1]; ++j, ++k) { ainode->mMeshes[k] = j; } } if (node.camera) { pScene->mCameras[node.camera.GetIndex()]->mName = ainode->mName; if (node.translation.isPresent) { aiVector3D trans; CopyValue(node.translation.value, trans); pScene->mCameras[node.camera.GetIndex()]->mPosition = trans; } } if (node.light) { pScene->mLights[node.light.GetIndex()]->mName = ainode->mName; //range is optional - see https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual //it is added to meta data of parent node, because there is no other place to put it if (node.light->range.isPresent) { if (!ainode->mMetaData) { ainode->mMetaData = aiMetadata::Alloc(1); ainode->mMetaData->Set(0, ""PBR_LightRange"", node.light->range.value); } else { ainode->mMetaData->Add(""PBR_LightRange"", node.light->range.value); } } } return ainode; } catch (...) { delete ainode; throw; } } void glTF2Importer::ImportNodes(glTF2::Asset &r) { if (!r.scene) { throw DeadlyImportError(""GLTF: No scene""); } ASSIMP_LOG_DEBUG(""Importing nodes""); std::vector> rootNodes = r.scene->nodes; // The root nodes unsigned int numRootNodes = unsigned(rootNodes.size()); if (numRootNodes == 1) { // a single root node: use it mScene->mRootNode = ImportNode(mScene, r, meshOffsets, rootNodes[0]); } else if (numRootNodes > 1) { // more than one root node: create a fake root aiNode *root = mScene->mRootNode = new aiNode(""ROOT""); root->mChildren = new aiNode *[numRootNodes]; std::fill(root->mChildren, root->mChildren + numRootNodes, nullptr); for (unsigned int i = 0; i < numRootNodes; ++i) { aiNode *node = ImportNode(mScene, r, meshOffsets, rootNodes[i]); node->mParent = root; root->mChildren[root->mNumChildren++] = node; } } else { mScene->mRootNode = new aiNode(""ROOT""); } } struct AnimationSamplers { AnimationSamplers() : translation(nullptr), rotation(nullptr), scale(nullptr), weight(nullptr) { // empty } Animation::Sampler *translation; Animation::Sampler *rotation; Animation::Sampler *scale; Animation::Sampler *weight; }; aiNodeAnim *CreateNodeAnim(glTF2::Asset&, Node &node, AnimationSamplers &samplers) { aiNodeAnim *anim = new aiNodeAnim(); try { anim->mNodeName = GetNodeName(node); static const float kMillisecondsFromSeconds = 1000.f; if (samplers.translation && samplers.translation->input && samplers.translation->output) { float *times = nullptr; samplers.translation->input->ExtractData(times); aiVector3D *values = nullptr; samplers.translation->output->ExtractData(values); anim->mNumPositionKeys = static_cast(samplers.translation->input->count); anim->mPositionKeys = new aiVectorKey[anim->mNumPositionKeys]; unsigned int ii = (samplers.translation->interpolation == Interpolation_CUBICSPLINE) ? 1 : 0; for (unsigned int i = 0; i < anim->mNumPositionKeys; ++i) { anim->mPositionKeys[i].mTime = times[i] * kMillisecondsFromSeconds; anim->mPositionKeys[i].mValue = values[ii]; ii += (samplers.translation->interpolation == Interpolation_CUBICSPLINE) ? 3 : 1; } delete[] times; delete[] values; } else if (node.translation.isPresent) { anim->mNumPositionKeys = 1; anim->mPositionKeys = new aiVectorKey[anim->mNumPositionKeys]; anim->mPositionKeys->mTime = 0.f; anim->mPositionKeys->mValue.x = node.translation.value[0]; anim->mPositionKeys->mValue.y = node.translation.value[1]; anim->mPositionKeys->mValue.z = node.translation.value[2]; } if (samplers.rotation && samplers.rotation->input && samplers.rotation->output) { float *times = nullptr; samplers.rotation->input->ExtractData(times); aiQuaternion *values = nullptr; samplers.rotation->output->ExtractData(values); anim->mNumRotationKeys = static_cast(samplers.rotation->input->count); anim->mRotationKeys = new aiQuatKey[anim->mNumRotationKeys]; unsigned int ii = (samplers.rotation->interpolation == Interpolation_CUBICSPLINE) ? 1 : 0; for (unsigned int i = 0; i < anim->mNumRotationKeys; ++i) { anim->mRotationKeys[i].mTime = times[i] * kMillisecondsFromSeconds; anim->mRotationKeys[i].mValue.x = values[ii].w; anim->mRotationKeys[i].mValue.y = values[ii].x; anim->mRotationKeys[i].mValue.z = values[ii].y; anim->mRotationKeys[i].mValue.w = values[ii].z; ii += (samplers.rotation->interpolation == Interpolation_CUBICSPLINE) ? 3 : 1; } delete[] times; delete[] values; } else if (node.rotation.isPresent) { anim->mNumRotationKeys = 1; anim->mRotationKeys = new aiQuatKey[anim->mNumRotationKeys]; anim->mRotationKeys->mTime = 0.f; anim->mRotationKeys->mValue.x = node.rotation.value[0]; anim->mRotationKeys->mValue.y = node.rotation.value[1]; anim->mRotationKeys->mValue.z = node.rotation.value[2]; anim->mRotationKeys->mValue.w = node.rotation.value[3]; } if (samplers.scale && samplers.scale->input && samplers.scale->output) { float *times = nullptr; samplers.scale->input->ExtractData(times); aiVector3D *values = nullptr; samplers.scale->output->ExtractData(values); anim->mNumScalingKeys = static_cast(samplers.scale->input->count); anim->mScalingKeys = new aiVectorKey[anim->mNumScalingKeys]; unsigned int ii = (samplers.scale->interpolation == Interpolation_CUBICSPLINE) ? 1 : 0; for (unsigned int i = 0; i < anim->mNumScalingKeys; ++i) { anim->mScalingKeys[i].mTime = times[i] * kMillisecondsFromSeconds; anim->mScalingKeys[i].mValue = values[ii]; ii += (samplers.scale->interpolation == Interpolation_CUBICSPLINE) ? 3 : 1; } delete[] times; delete[] values; } else if (node.scale.isPresent) { anim->mNumScalingKeys = 1; anim->mScalingKeys = new aiVectorKey[anim->mNumScalingKeys]; anim->mScalingKeys->mTime = 0.f; anim->mScalingKeys->mValue.x = node.scale.value[0]; anim->mScalingKeys->mValue.y = node.scale.value[1]; anim->mScalingKeys->mValue.z = node.scale.value[2]; } return anim; } catch (...) { delete anim; throw; } } aiMeshMorphAnim *CreateMeshMorphAnim(glTF2::Asset&, Node &node, AnimationSamplers &samplers) { aiMeshMorphAnim *anim = new aiMeshMorphAnim(); try { anim->mName = GetNodeName(node); static const float kMillisecondsFromSeconds = 1000.f; if (samplers.weight && samplers.weight->input && samplers.weight->output) { float *times = nullptr; samplers.weight->input->ExtractData(times); float *values = nullptr; samplers.weight->output->ExtractData(values); anim->mNumKeys = static_cast(samplers.weight->input->count); // for Interpolation_CUBICSPLINE can have more outputs const unsigned int weightStride = (unsigned int)samplers.weight->output->count / anim->mNumKeys; const unsigned int numMorphs = (samplers.weight->interpolation == Interpolation_CUBICSPLINE) ? weightStride - 2 : weightStride; anim->mKeys = new aiMeshMorphKey[anim->mNumKeys]; unsigned int ii = (samplers.weight->interpolation == Interpolation_CUBICSPLINE) ? 1 : 0; for (unsigned int i = 0u; i < anim->mNumKeys; ++i) { unsigned int k = weightStride * i + ii; anim->mKeys[i].mTime = times[i] * kMillisecondsFromSeconds; anim->mKeys[i].mNumValuesAndWeights = numMorphs; anim->mKeys[i].mValues = new unsigned int[numMorphs]; anim->mKeys[i].mWeights = new double[numMorphs]; for (unsigned int j = 0u; j < numMorphs; ++j, ++k) { anim->mKeys[i].mValues[j] = j; anim->mKeys[i].mWeights[j] = (0.f > values[k]) ? 0.f : values[k]; } } delete[] times; delete[] values; } return anim; } catch (...) { delete anim; throw; } } std::unordered_map GatherSamplers(Animation &anim) { std::unordered_map samplers; for (unsigned int c = 0; c < anim.channels.size(); ++c) { Animation::Channel &channel = anim.channels[c]; if (channel.sampler < 0 || channel.sampler >= static_cast(anim.samplers.size())) { continue; } auto& animsampler = anim.samplers[channel.sampler]; if (animsampler.input->count > animsampler.output->count) { ASSIMP_LOG_WARN(""Animation "", anim.name, "": Number of keyframes in sampler input "", animsampler.input->count, "" exceeds number of keyframes in sampler output "", animsampler.output->count); continue; } const unsigned int node_index = channel.target.node.GetIndex(); AnimationSamplers &sampler = samplers[node_index]; if (channel.target.path == AnimationPath_TRANSLATION) { sampler.translation = &anim.samplers[channel.sampler]; } else if (channel.target.path == AnimationPath_ROTATION) { sampler.rotation = &anim.samplers[channel.sampler]; } else if (channel.target.path == AnimationPath_SCALE) { sampler.scale = &anim.samplers[channel.sampler]; } else if (channel.target.path == AnimationPath_WEIGHTS) { sampler.weight = &anim.samplers[channel.sampler]; } } return samplers; } void glTF2Importer::ImportAnimations(glTF2::Asset &r) { if (!r.scene) return; const unsigned numAnimations = r.animations.Size(); ASSIMP_LOG_DEBUG(""Importing "", numAnimations, "" animations""); mScene->mNumAnimations = numAnimations; if (mScene->mNumAnimations == 0) { return; } mScene->mAnimations = new aiAnimation *[numAnimations]; std::fill(mScene->mAnimations, mScene->mAnimations + numAnimations, nullptr); for (unsigned int i = 0; i < numAnimations; ++i) { aiAnimation *ai_anim = mScene->mAnimations[i] = new aiAnimation(); Animation &anim = r.animations[i]; ai_anim->mName = anim.name; ai_anim->mDuration = 0; ai_anim->mTicksPerSecond = 0; std::unordered_map samplers = GatherSamplers(anim); uint32_t numChannels = 0u; uint32_t numMorphMeshChannels = 0u; for (auto &iter : samplers) { if ((nullptr != iter.second.rotation) || (nullptr != iter.second.scale) || (nullptr != iter.second.translation)) { ++numChannels; } if (nullptr != iter.second.weight) { ++numMorphMeshChannels; } } ai_anim->mNumChannels = numChannels; if (ai_anim->mNumChannels > 0) { ai_anim->mChannels = new aiNodeAnim *[ai_anim->mNumChannels]; std::fill(ai_anim->mChannels, ai_anim->mChannels + ai_anim->mNumChannels, nullptr); int j = 0; for (auto &iter : samplers) { if ((nullptr != iter.second.rotation) || (nullptr != iter.second.scale) || (nullptr != iter.second.translation)) { ai_anim->mChannels[j] = CreateNodeAnim(r, r.nodes[iter.first], iter.second); ++j; } } } ai_anim->mNumMorphMeshChannels = numMorphMeshChannels; if (ai_anim->mNumMorphMeshChannels > 0) { ai_anim->mMorphMeshChannels = new aiMeshMorphAnim *[ai_anim->mNumMorphMeshChannels]; std::fill(ai_anim->mMorphMeshChannels, ai_anim->mMorphMeshChannels + ai_anim->mNumMorphMeshChannels, nullptr); int j = 0; for (auto &iter : samplers) { if (nullptr != iter.second.weight) { ai_anim->mMorphMeshChannels[j] = CreateMeshMorphAnim(r, r.nodes[iter.first], iter.second); ++j; } } } // Use the latest keyframe for the duration of the animation double maxDuration = 0; unsigned int maxNumberOfKeys = 0; for (unsigned int j = 0; j < ai_anim->mNumChannels; ++j) { auto chan = ai_anim->mChannels[j]; if (chan->mNumPositionKeys) { auto lastPosKey = chan->mPositionKeys[chan->mNumPositionKeys - 1]; if (lastPosKey.mTime > maxDuration) { maxDuration = lastPosKey.mTime; } maxNumberOfKeys = std::max(maxNumberOfKeys, chan->mNumPositionKeys); } if (chan->mNumRotationKeys) { auto lastRotKey = chan->mRotationKeys[chan->mNumRotationKeys - 1]; if (lastRotKey.mTime > maxDuration) { maxDuration = lastRotKey.mTime; } maxNumberOfKeys = std::max(maxNumberOfKeys, chan->mNumRotationKeys); } if (chan->mNumScalingKeys) { auto lastScaleKey = chan->mScalingKeys[chan->mNumScalingKeys - 1]; if (lastScaleKey.mTime > maxDuration) { maxDuration = lastScaleKey.mTime; } maxNumberOfKeys = std::max(maxNumberOfKeys, chan->mNumScalingKeys); } } for (unsigned int j = 0; j < ai_anim->mNumMorphMeshChannels; ++j) { const auto *const chan = ai_anim->mMorphMeshChannels[j]; if (0u != chan->mNumKeys) { const auto &lastKey = chan->mKeys[chan->mNumKeys - 1u]; if (lastKey.mTime > maxDuration) { maxDuration = lastKey.mTime; } maxNumberOfKeys = std::max(maxNumberOfKeys, chan->mNumKeys); } } ai_anim->mDuration = maxDuration; ai_anim->mTicksPerSecond = 1000.0; } } void glTF2Importer::ImportEmbeddedTextures(glTF2::Asset &r) { embeddedTexIdxs.resize(r.images.Size(), -1); int numEmbeddedTexs = 0; for (size_t i = 0; i < r.images.Size(); ++i) { if (r.images[i].HasData()) { numEmbeddedTexs += 1; } } if (numEmbeddedTexs == 0) { return; } ASSIMP_LOG_DEBUG(""Importing "", numEmbeddedTexs, "" embedded textures""); mScene->mTextures = new aiTexture *[numEmbeddedTexs]; std::fill(mScene->mTextures, mScene->mTextures + numEmbeddedTexs, nullptr); // Add the embedded textures for (size_t i = 0; i < r.images.Size(); ++i) { Image &img = r.images[i]; if (!img.HasData()) { continue; } int idx = mScene->mNumTextures++; embeddedTexIdxs[i] = idx; aiTexture *tex = mScene->mTextures[idx] = new aiTexture(); size_t length = img.GetDataLength(); void *data = img.StealData(); tex->mFilename = img.name; tex->mWidth = static_cast(length); tex->mHeight = 0; tex->pcData = reinterpret_cast(data); if (!img.mimeType.empty()) { const char *ext = strchr(img.mimeType.c_str(), '/') + 1; if (ext) { if (strcmp(ext, ""jpeg"") == 0) { ext = ""jpg""; } else if(strcmp(ext, ""ktx2"") == 0) { //basisu: ktx remains ext = ""kx2""; } else if(strcmp(ext, ""basis"") == 0) { //basisu ext = ""bu""; } size_t len = strlen(ext); if (len <= 3) { strcpy(tex->achFormatHint, ext); } } } } } void glTF2Importer::ImportCommonMetadata(glTF2::Asset& a) { ASSIMP_LOG_DEBUG(""Importing metadata""); ai_assert(mScene->mMetaData == nullptr); const bool hasVersion = !a.asset.version.empty(); const bool hasGenerator = !a.asset.generator.empty(); const bool hasCopyright = !a.asset.copyright.empty(); const bool hasSceneMetadata = a.scene->customExtensions; if (hasVersion || hasGenerator || hasCopyright || hasSceneMetadata) { mScene->mMetaData = new aiMetadata; if (hasVersion) { mScene->mMetaData->Add(AI_METADATA_SOURCE_FORMAT_VERSION, aiString(a.asset.version)); } if (hasGenerator) { mScene->mMetaData->Add(AI_METADATA_SOURCE_GENERATOR, aiString(a.asset.generator)); } if (hasCopyright) { mScene->mMetaData->Add(AI_METADATA_SOURCE_COPYRIGHT, aiString(a.asset.copyright)); } if (hasSceneMetadata) { ParseExtensions(mScene->mMetaData, a.scene->customExtensions); } } } void glTF2Importer::InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler) { ASSIMP_LOG_DEBUG(""Reading GLTF2 file""); // clean all member arrays meshOffsets.clear(); embeddedTexIdxs.clear(); this->mScene = pScene; // read the asset file glTF2::Asset asset(pIOHandler); asset.Load(pFile, GetExtension(pFile) == ""glb""); if (asset.scene) { pScene->mName = asset.scene->name; } // // Copy the data out // ImportEmbeddedTextures(asset); ImportMaterials(asset); ImportMeshes(asset); ImportCameras(asset); ImportLights(asset); ImportNodes(asset); ImportAnimations(asset); ImportCommonMetadata(asset); if (pScene->mNumMeshes == 0) { pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE; } } #endif // ASSIMP_BUILD_NO_GLTF_IMPORTER ",16203,True,2545.452184663529,median "[[smpp-component]] = SMPP Component :page-source: components/camel-smpp/src/main/docs/smpp-component.adoc *Since Camel 2.2* // HEADER START *Both producer and consumer is supported* // HEADER END This component provides access to an SMSC (Short Message Service Center) over the http://smsforum.net/SMPP_v3_4_Issue1_2.zip[SMPP] protocol to send and receive SMS. The http://jsmpp.org[JSMPP] library is used for the protocol implementation. The Camel component currently operates as an http://en.wikipedia.org/wiki/ESME[ESME] (External Short Messaging Entity) and not as an SMSC itself. You are also able to execute ReplaceSm, QuerySm, SubmitMulti, CancelSm and DataSm. Maven users will need to add the following dependency to their `pom.xml` for this component: [source,xml] ------------------------------------------------------------ org.apache.camel camel-smpp x.x.x ------------------------------------------------------------ == SMS limitations SMS is neither reliable or secure. Users who require reliable and secure delivery may want to consider using the XMPP or SIP components instead, combined with a smartphone app supporting the chosen protocol. * Reliability: although the SMPP standard offers a range of feedback mechanisms to indicate errors, non-delivery and confirmation of delivery it is not uncommon for mobile networks to hide or simulate these responses. For example, some networks automatically send a delivery confirmation for every message even if the destination number is invalid or not switched on. Some networks silently drop messages if they think they are spam. Spam detection rules in the network may be very crude, sometimes more than 100 messages per day from a single sender may be considered spam. * Security: there is basic encryption for the last hop from the radio tower down to the recipient handset. SMS messages are not encrypted or authenticated in any other part of the network. Some operators allow staff in retail outlets or call centres to browse through the SMS message histories of their customers. Message sender identity can be easily forged. Regulators and even the mobile telephone industry itself has cautioned against the use of SMS in two-factor authentication schemes and other purposes where security is important. While the Camel component makes it as easy as possible to send messages to the SMS network, it can not offer an easy solution to these problems. == Data coding, alphabet and international character sets Data coding and alphabet can be specified on a per-message basis. Default values can be specified for the endpoint. It is important to understand the relationship between these options and the way the component acts when more than one value is set. Data coding is an 8 bit field in the SMPP wire format. Alphabet corresponds to bits 0-3 of the data coding field. For some types of message, where a message class is used (by setting bit 5 of the data coding field), the lower two bits of the data coding field are not interpreted as alphabet and only bits 2 and 3 impact the alphabet. Furthermore, current version of the JSMPP library only seems to support bits 2 and 3, assuming that bits 0 and 1 are used for message class. This is why the Alphabet class in JSMPP doesn't support the value 3 (binary 0011) which indicates ISO-8859-1. Although JSMPP provides a representation of the message class parameter, the Camel component doesn't currently provide a way to set it other than manually setting the corresponding bits in the data coding field. When setting the data coding field in the outgoing message, the Camel component considers the following values and uses the first one it can find: * the data coding specified in a header * the alphabet specified in a header * the data coding specified in the endpoint configuration (URI parameter) Older versions of Camel had bugs in support for international character sets. This feature only worked when a single encoding was used for all messages and was troublesome when users wanted to change it on a per-message basis. Users who require this to work should ensure their version of Camel includes the fix for JIRA Issues Macro: com.atlassian.sal.api.net.ResponseStatusException: Unexpected response received. Status code: 404 . In addition to trying to send the data coding value to the SMSC, the Camel component also tries to analyze the message body, convert it to a Java String (Unicode) and convert that to a byte array in the corresponding alphabet When deciding which alphabet to use in the byte array, the Camel SMPP component does not consider the data coding value (header or configuration), it only considers the specified alphabet (from either the header or endpoint parameter). If some characters in the String can't be represented in the chosen alphabet, they may be replaced by the question mark ( ? ) symbol. Users of the API may want to consider checking if their message body can be converted to ISO-8859-1 before passing it to the component and if not, setting the alphabet header to request UCS-2 encoding. If the alphabet and data coding options are not specified at all then the component may try to detect the required encoding and set the data coding for you. The list of alphabet codes are specified in the SMPP specification v3.4, section 5.2.19. One notable limitation of the SMPP specification is that there is no alphabet code for explicitly requesting use of the GSM 3.38 (7 bit) character set. Choosing the value 0 for the alphabet selects the SMSC _default_ alphabet, this usually means GSM 3.38 but it is not guaranteed. The SMPP gateway Nexmo https://help.nexmo.com/hc/en-us/articles/204015813-How-to-change-the-character-encoding-in-SMPP-[actually allows the default to be mapped to any other character set with a control panel option]. It is suggested that users check with their SMSC operator to confirm exactly which character set is being used as the default. == Message splitting and throttling After transforming a message body from a String to a byte array, the Camel component is also responsible for splitting the message into parts (within the 140 byte SMS size limit) before passing it to JSMPP. This is completed automatically. If the GSM 3.38 alphabet is used, the component will pack up to 160 characters into the 140 byte message body. If an 8 bit character set is used (e.g. ISO-8859-1 for western Europe) then 140 characters will be allowed within the 140 byte message body. If 16 bit UCS-2 encoding is used then just 70 characters fit into each 140 byte message. Some SMSC providers implement throttling rules. Each part of a message that has been split may be counted separately by the provider's throttling mechanism. The Camel Throttler component can be useful for throttling messages in the SMPP route before handing them to the SMSC. == URI format [source,java] -------------------------------------------- smpp://[username@]hostname[:port][?options] smpps://[username@]hostname[:port][?options] -------------------------------------------- If no *username* is provided, then Camel will provide the default value `smppclient`. + If no *port* number is provided, then Camel will provide the default value `2775`. + If the protocol name is ""smpps"", camel-smpp with try to use SSLSocket to init a connection to the server. You can append query options to the URI in the following format, `?option=value&option=value&...` == URI Options // component options: START The SMPP component supports 4 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *configuration* (advanced) | To use the shared SmppConfiguration as configuration. | | SmppConfiguration | *basicPropertyBinding* (advanced) | Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean |=== // component options: END // endpoint options: START The SMPP endpoint is configured using URI syntax: ---- smpp:host:port ---- with the following path and query parameters: === Path Parameters (2 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *host* | Hostname for the SMSC server to use. | localhost | String | *port* | Port number for the SMSC server to use. | 2775 | Integer |=== === Query Parameters (40 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *initialReconnectDelay* (common) | Defines the initial delay in milliseconds after the consumer/producer tries to reconnect to the SMSC, after the connection was lost. | 5000 | long | *maxReconnect* (common) | Defines the maximum number of attempts to reconnect to the SMSC, if SMSC returns a negative bind response | 2147483647 | int | *reconnectDelay* (common) | Defines the interval in milliseconds between the reconnect attempts, if the connection to the SMSC was lost and the previous was not succeed. | 5000 | long | *splittingPolicy* (common) | You can specify a policy for handling long messages: ALLOW - the default, long messages are split to 140 bytes per message TRUNCATE - long messages are split and only the first fragment will be sent to the SMSC. Some carriers drop subsequent fragments so this reduces load on the SMPP connection sending parts of a message that will never be delivered. REJECT - if a message would need to be split, it is rejected with an SMPP NegativeResponseException and the reason code signifying the message is too long. | ALLOW | SmppSplittingPolicy | *systemType* (common) | This parameter is used to categorize the type of ESME (External Short Message Entity) that is binding to the SMSC (max. 13 characters). | | String | *addressRange* (consumer) | You can specify the address range for the SmppConsumer as defined in section 5.2.7 of the SMPP 3.4 specification. The SmppConsumer will receive messages only from SMSC's which target an address (MSISDN or IP address) within this range. | | String | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *exceptionHandler* (consumer) | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | | ExceptionHandler | *exchangePattern* (consumer) | Sets the exchange pattern when the consumer creates an exchange. | | ExchangePattern | *destAddr* (producer) | Defines the destination SME address. For mobile terminated messages, this is the directory number of the recipient MS. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. | 1717 | String | *destAddrNpi* (producer) | Defines the type of number (TON) to be used in the SME destination address parameters. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. The following NPI values are defined: 0: Unknown 1: ISDN (E163/E164) 2: Data (X.121) 3: Telex (F.69) 6: Land Mobile (E.212) 8: National 9: Private 10: ERMES 13: Internet (IP) 18: WAP Client Id (to be defined by WAP Forum) | | byte | *destAddrTon* (producer) | Defines the type of number (TON) to be used in the SME destination address parameters. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. The following TON values are defined: 0: Unknown 1: International 2: National 3: Network Specific 4: Subscriber Number 5: Alphanumeric 6: Abbreviated | | byte | *lazySessionCreation* (producer) | Sessions can be lazily created to avoid exceptions, if the SMSC is not available when the Camel producer is started. Camel will check the in message headers 'CamelSmppSystemId' and 'CamelSmppPassword' of the first exchange. If they are present, Camel will use these data to connect to the SMSC. | false | boolean | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *numberingPlanIndicator* (producer) | Defines the numeric plan indicator (NPI) to be used in the SME. The following NPI values are defined: 0: Unknown 1: ISDN (E163/E164) 2: Data (X.121) 3: Telex (F.69) 6: Land Mobile (E.212) 8: National 9: Private 10: ERMES 13: Internet (IP) 18: WAP Client Id (to be defined by WAP Forum) | | byte | *priorityFlag* (producer) | Allows the originating SME to assign a priority level to the short message. Only for SubmitSm and SubmitMulti. Four Priority Levels are supported: 0: Level 0 (lowest) priority 1: Level 1 priority 2: Level 2 priority 3: Level 3 (highest) priority | | byte | *protocolId* (producer) | The protocol id | | byte | *registeredDelivery* (producer) | Is used to request an SMSC delivery receipt and/or SME originated acknowledgements. The following values are defined: 0: No SMSC delivery receipt requested. 1: SMSC delivery receipt requested where final delivery outcome is success or failure. 2: SMSC delivery receipt requested where the final delivery outcome is delivery failure. | | byte | *replaceIfPresentFlag* (producer) | Used to request the SMSC to replace a previously submitted message, that is still pending delivery. The SMSC will replace an existing message provided that the source address, destination address and service type match the same fields in the new message. The following replace if present flag values are defined: 0: Don't replace 1: Replace | | byte | *serviceType* (producer) | The service type parameter can be used to indicate the SMS Application service associated with the message. The following generic service_types are defined: CMT: Cellular Messaging CPT: Cellular Paging VMN: Voice Mail Notification VMA: Voice Mail Alerting WAP: Wireless Application Protocol USSD: Unstructured Supplementary Services Data | | String | *sourceAddr* (producer) | Defines the address of SME (Short Message Entity) which originated this message. | 1616 | String | *sourceAddrNpi* (producer) | Defines the numeric plan indicator (NPI) to be used in the SME originator address parameters. The following NPI values are defined: 0: Unknown 1: ISDN (E163/E164) 2: Data (X.121) 3: Telex (F.69) 6: Land Mobile (E.212) 8: National 9: Private 10: ERMES 13: Internet (IP) 18: WAP Client Id (to be defined by WAP Forum) | | byte | *sourceAddrTon* (producer) | Defines the type of number (TON) to be used in the SME originator address parameters. The following TON values are defined: 0: Unknown 1: International 2: National 3: Network Specific 4: Subscriber Number 5: Alphanumeric 6: Abbreviated | | byte | *typeOfNumber* (producer) | Defines the type of number (TON) to be used in the SME. The following TON values are defined: 0: Unknown 1: International 2: National 3: Network Specific 4: Subscriber Number 5: Alphanumeric 6: Abbreviated | | byte | *basicPropertyBinding* (advanced) | Whether the endpoint should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean | *enquireLinkTimer* (advanced) | Defines the interval in milliseconds between the confidence checks. The confidence check is used to test the communication path between an ESME and an SMSC. | 5000 | Integer | *sessionStateListener* (advanced) | You can refer to a org.jsmpp.session.SessionStateListener in the Registry to receive callbacks when the session state changed. | | SessionStateListener | *synchronous* (advanced) | Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported). | false | boolean | *transactionTimer* (advanced) | Defines the maximum period of inactivity allowed after a transaction, after which an SMPP entity may assume that the session is no longer active. This timer may be active on either communicating SMPP entity (i.e. SMSC or ESME). | 10000 | Integer | *alphabet* (codec) | Defines encoding of data according the SMPP 3.4 specification, section 5.2.19. 0: SMSC Default Alphabet 4: 8 bit Alphabet 8: UCS2 Alphabet | | byte | *dataCoding* (codec) | Defines the data coding according the SMPP 3.4 specification, section 5.2.19. Example data encodings are: 0: SMSC Default Alphabet 3: Latin 1 (ISO-8859-1) 4: Octet unspecified (8-bit binary) 8: UCS2 (ISO/IEC-10646) 13: Extended Kanji JIS(X 0212-1990) | | byte | *encoding* (codec) | Defines the encoding scheme of the short message user data. Only for SubmitSm, ReplaceSm and SubmitMulti. | ISO-8859-1 | String | *httpProxyHost* (proxy) | If you need to tunnel SMPP through a HTTP proxy, set this attribute to the hostname or ip address of your HTTP proxy. | | String | *httpProxyPassword* (proxy) | If your HTTP proxy requires basic authentication, set this attribute to the password required for your HTTP proxy. | | String | *httpProxyPort* (proxy) | If you need to tunnel SMPP through a HTTP proxy, set this attribute to the port of your HTTP proxy. | 3128 | Integer | *httpProxyUsername* (proxy) | If your HTTP proxy requires basic authentication, set this attribute to the username required for your HTTP proxy. | | String | *proxyHeaders* (proxy) | These headers will be passed to the proxy server while establishing the connection. | | Map | *password* (security) | The password for connecting to SMSC server. | | String | *systemId* (security) | The system id (username) for connecting to SMSC server. | smppclient | String | *usingSSL* (security) | Whether using SSL with the smpps protocol | false | boolean |=== // endpoint options: END // spring-boot-auto-configure options: START == Spring Boot Auto-Configuration When using Spring Boot make sure to use the following Maven dependency to have support for auto configuration: [source,xml] ---- org.apache.camel.springboot camel-smpp-starter x.x.x ---- The component supports 40 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *camel.component.smpp.basic-property-binding* | Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | Boolean | *camel.component.smpp.bridge-error-handler* | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | Boolean | *camel.component.smpp.configuration.address-range* | You can specify the address range for the SmppConsumer as defined in section 5.2.7 of the SMPP 3.4 specification. The SmppConsumer will receive messages only from SMSC's which target an address (MSISDN or IP address) within this range. | | String | *camel.component.smpp.configuration.alphabet* | Defines encoding of data according the SMPP 3.4 specification, section 5.2.19.
  • 0: SMSC Default Alphabet
  • 4: 8 bit Alphabet
  • 8: UCS2 Alphabet
| | Byte | *camel.component.smpp.configuration.data-coding* | Defines the data coding according the SMPP 3.4 specification, section 5.2.19. Example data encodings are:
  • 0: SMSC Default Alphabet
  • 3: Latin 1 (ISO-8859-1)
  • 4: Octet unspecified (8-bit binary)
  • 8: UCS2 (ISO/IEC-10646)
  • 13: Extended Kanji JIS(X 0212-1990)
| | Byte | *camel.component.smpp.configuration.dest-addr* | Defines the destination SME address. For mobile terminated messages, this is the directory number of the recipient MS. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. | 1717 | String | *camel.component.smpp.configuration.dest-addr-npi* | Defines the type of number (TON) to be used in the SME destination address parameters. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. The following NPI values are defined:
  • 0: Unknown
  • 1: ISDN (E163/E164)
  • 2: Data (X.121)
  • 3: Telex (F.69)
  • 6: Land Mobile (E.212)
  • 8: National
  • 9: Private
  • 10: ERMES
  • 13: Internet (IP)
  • 18: WAP Client Id (to be defined by WAP Forum)
| | Byte | *camel.component.smpp.configuration.dest-addr-ton* | Defines the type of number (TON) to be used in the SME destination address parameters. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. The following TON values are defined:
  • 0: Unknown
  • 1: International
  • 2: National
  • 3: Network Specific
  • 4: Subscriber Number
  • 5: Alphanumeric
  • 6: Abbreviated
| | Byte | *camel.component.smpp.configuration.encoding* | Defines the encoding scheme of the short message user data. Only for SubmitSm, ReplaceSm and SubmitMulti. | ISO-8859-1 | String | *camel.component.smpp.configuration.enquire-link-timer* | Defines the interval in milliseconds between the confidence checks. The confidence check is used to test the communication path between an ESME and an SMSC. | 5000 | Integer | *camel.component.smpp.configuration.host* | Hostname for the SMSC server to use. | localhost | String | *camel.component.smpp.configuration.http-proxy-host* | If you need to tunnel SMPP through a HTTP proxy, set this attribute to the hostname or ip address of your HTTP proxy. | | String | *camel.component.smpp.configuration.http-proxy-password* | If your HTTP proxy requires basic authentication, set this attribute to the password required for your HTTP proxy. | | String | *camel.component.smpp.configuration.http-proxy-port* | If you need to tunnel SMPP through a HTTP proxy, set this attribute to the port of your HTTP proxy. | 3128 | Integer | *camel.component.smpp.configuration.http-proxy-username* | If your HTTP proxy requires basic authentication, set this attribute to the username required for your HTTP proxy. | | String | *camel.component.smpp.configuration.initial-reconnect-delay* | Defines the initial delay in milliseconds after the consumer/producer tries to reconnect to the SMSC, after the connection was lost. | 5000 | Long | *camel.component.smpp.configuration.lazy-session-creation* | Sessions can be lazily created to avoid exceptions, if the SMSC is not available when the Camel producer is started. Camel will check the in message headers 'CamelSmppSystemId' and 'CamelSmppPassword' of the first exchange. If they are present, Camel will use these data to connect to the SMSC. | false | Boolean | *camel.component.smpp.configuration.max-reconnect* | Defines the maximum number of attempts to reconnect to the SMSC, if SMSC returns a negative bind response | 2147483647 | Integer | *camel.component.smpp.configuration.numbering-plan-indicator* | Defines the numeric plan indicator (NPI) to be used in the SME. The following NPI values are defined:
  • 0: Unknown
  • 1: ISDN (E163/E164)
  • 2: Data (X.121)
  • 3: Telex (F.69)
  • 6: Land Mobile (E.212)
  • 8: National
  • 9: Private
  • 10: ERMES
  • 13: Internet (IP)
  • 18: WAP Client Id (to be defined by WAP Forum)
| | Byte | *camel.component.smpp.configuration.password* | Defines the encoding scheme of the short message user data. Only for SubmitSm, ReplaceSm and SubmitMulti. | | String | *camel.component.smpp.configuration.port* | Port number for the SMSC server to use. | 2775 | Integer | *camel.component.smpp.configuration.priority-flag* | Allows the originating SME to assign a priority level to the short message. Only for SubmitSm and SubmitMulti. Four Priority Levels are supported:
  • 0: Level 0 (lowest) priority
  • 1: Level 1 priority
  • 2: Level 2 priority
  • 3: Level 3 (highest) priority
| | Byte | *camel.component.smpp.configuration.protocol-id* | The protocol id | | Byte | *camel.component.smpp.configuration.proxy-headers* | These headers will be passed to the proxy server while establishing the connection. | | Map | *camel.component.smpp.configuration.reconnect-delay* | Defines the interval in milliseconds between the reconnect attempts, if the connection to the SMSC was lost and the previous was not succeed. | 5000 | Long | *camel.component.smpp.configuration.registered-delivery* | Is used to request an SMSC delivery receipt and/or SME originated acknowledgements. The following values are defined:
  • 0: No SMSC delivery receipt requested.
  • 1: SMSC delivery receipt requested where final delivery outcome is success or failure.
  • 2: SMSC delivery receipt requested where the final delivery outcome is delivery failure.
| | Byte | *camel.component.smpp.configuration.replace-if-present-flag* | Used to request the SMSC to replace a previously submitted message, that is still pending delivery. The SMSC will replace an existing message provided that the source address, destination address and service type match the same fields in the new message. The following replace if present flag values are defined:
  • 0: Don't replace
  • 1: Replace
| | Byte | *camel.component.smpp.configuration.service-type* | The service type parameter can be used to indicate the SMS Application service associated with the message. The following generic service_types are defined:
  • CMT: Cellular Messaging
  • CPT: Cellular Paging
  • VMN: Voice Mail Notification
  • VMA: Voice Mail Alerting
  • WAP: Wireless Application Protocol
  • USSD: Unstructured Supplementary Services Data
| | String | *camel.component.smpp.configuration.session-state-listener* | You can refer to a org.jsmpp.session.SessionStateListener in the Registry to receive callbacks when the session state changed. | | SessionStateListener | *camel.component.smpp.configuration.source-addr* | Defines the address of SME (Short Message Entity) which originated this message. | 1616 | String | *camel.component.smpp.configuration.source-addr-npi* | Defines the numeric plan indicator (NPI) to be used in the SME originator address parameters. The following NPI values are defined:
  • 0: Unknown
  • 1: ISDN (E163/E164)
  • 2: Data (X.121)
  • 3: Telex (F.69)
  • 6: Land Mobile (E.212)
  • 8: National
  • 9: Private
  • 10: ERMES
  • 13: Internet (IP)
  • 18: WAP Client Id (to be defined by WAP Forum)
| | Byte | *camel.component.smpp.configuration.source-addr-ton* | Defines the type of number (TON) to be used in the SME originator address parameters. The following TON values are defined:
  • 0: Unknown
  • 1: International
  • 2: National
  • 3: Network Specific
  • 4: Subscriber Number
  • 5: Alphanumeric
  • 6: Abbreviated
| | Byte | *camel.component.smpp.configuration.splitting-policy* | You can specify a policy for handling long messages:
  • ALLOW - the default, long messages are split to 140 bytes per message
  • TRUNCATE - long messages are split and only the first fragment will be sent to the SMSC. Some carriers drop subsequent fragments so this reduces load on the SMPP connection sending parts of a message that will never be delivered.
  • REJECT - if a message would need to be split, it is rejected with an SMPP NegativeResponseException and the reason code signifying the message is too long.
| | SmppSplittingPolicy | *camel.component.smpp.configuration.system-id* | The system id (username) for connecting to SMSC server. | smppclient | String | *camel.component.smpp.configuration.system-type* | This parameter is used to categorize the type of ESME (External Short Message Entity) that is binding to the SMSC (max. 13 characters). | | String | *camel.component.smpp.configuration.transaction-timer* | Defines the maximum period of inactivity allowed after a transaction, after which an SMPP entity may assume that the session is no longer active. This timer may be active on either communicating SMPP entity (i.e. SMSC or ESME). | 10000 | Integer | *camel.component.smpp.configuration.type-of-number* | Defines the type of number (TON) to be used in the SME. The following TON values are defined:
  • 0: Unknown
  • 1: International
  • 2: National
  • 3: Network Specific
  • 4: Subscriber Number
  • 5: Alphanumeric
  • 6: Abbreviated
| | Byte | *camel.component.smpp.configuration.using-s-s-l* | Whether using SSL with the smpps protocol | false | Boolean | *camel.component.smpp.enabled* | Enable smpp component | true | Boolean | *camel.component.smpp.lazy-start-producer* | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | Boolean |=== // spring-boot-auto-configure options: END You can have as many of these options as you like. [source,java] ------------------------------------------------------------------------------------------------------------------ smpp://smppclient@localhost:2775?password=password&enquireLinkTimer=3000&transactionTimer=5000&systemType=consumer ------------------------------------------------------------------------------------------------------------------ == Producer Message Headers The following message headers can be used to affect the behavior of the SMPP producer [width=""100%"",cols=""10%,10%,80%"",options=""header"",] |======================================================================= |Header |Type |Description |`CamelSmppDestAddr` |`List`/`String` |*only for SubmitSm, SubmitMulti, CancelSm and DataSm* Defines the destination SME address(es). For mobile terminated messages, this is the directory number of the recipient MS. Is must be a `List` for SubmitMulti and a `String` otherwise. |`CamelSmppDestAddrTon` |`Byte` |*only for SubmitSm, SubmitMulti, CancelSm and DataSm* Defines the type of number (TON) to be used in the SME destination address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppDestAddrNpi` |`Byte` |*only for SubmitSm, SubmitMulti, CancelSm and DataSm* Defines the numeric plan indicator (NPI) to be used in the SME destination address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppSourceAddr` |`String` |Defines the address of SME (Short Message Entity) which originated this message. |`CamelSmppSourceAddrTon` |`Byte` |Defines the type of number (TON) to be used in the SME originator address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppSourceAddrNpi` |`Byte` |Defines the numeric plan indicator (NPI) to be used in the SME originator address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppServiceType` |`String` |The service type parameter can be used to indicate the SMS Application service associated with the message. Use the URI option `serviceType` settings above. |`CamelSmppRegisteredDelivery` |`Byte` |*only for SubmitSm, ReplaceSm, SubmitMulti and DataSm* Is used to request an SMSC delivery receipt and/or SME originated acknowledgements. Use the URI option `registeredDelivery` settings above. |`CamelSmppPriorityFlag` |`Byte` |*only for SubmitSm and SubmitMulti* Allows the originating SME to assign a priority level to the short message. Use the URI option `priorityFlag` settings above. |`CamelSmppScheduleDeliveryTime` |`Date` |*only for SubmitSm, SubmitMulti and ReplaceSm* This parameter specifies the scheduled time at which the message delivery should be first attempted. It defines either the absolute date and time or relative time from the current SMSC time at which delivery of this message will be attempted by the SMSC. It can be specified in either absolute time format or relative time format. The encoding of a time format is specified in chapter 7.1.1. in the smpp specification v3.4. |`CamelSmppValidityPeriod` |`String`/`Date` |*only for SubmitSm, SubmitMulti and ReplaceSm* The validity period parameter indicates the SMSC expiration time, after which the message should be discarded if not delivered to the destination. If it's provided as `Date`, it's interpreted as absolute time or relative time format if you provide it as `String` as specified in chapter 7.1.1 in the smpp specification v3.4. |`CamelSmppReplaceIfPresentFlag` |`Byte` |*only for SubmitSm and SubmitMulti* The replace if present flag parameter is used to request the SMSC to replace a previously submitted message, that is still pending delivery. The SMSC will replace an existing message provided that the source address, destination address and service type match the same fields in the new message. The following values are defined: `0`, Don't replace and `1`, Replace |`CamelSmppAlphabet` / `CamelSmppDataCoding` |`Byte` |*For SubmitSm, SubmitMulti and ReplaceSm* The data coding according to the SMPP 3.4 specification, section 5.2.19. Use the URI option `alphabet` settings above. |`CamelSmppOptionalParameter` |`Map` |*only for SubmitSm, SubmitMulti and DataSm* The optional parameter which are send to the SMSC. The value is converted in the following way: `String` -> `org.jsmpp.bean.OptionalParameter.COctetString`, `byte[]` -> `org.jsmpp.bean.OptionalParameter.OctetString`, `Byte` -> `org.jsmpp.bean.OptionalParameter.Byte`, `Integer` -> `org.jsmpp.bean.OptionalParameter.Int`, `Short` -> `org.jsmpp.bean.OptionalParameter.Short`, `null` -> `org.jsmpp.bean.OptionalParameter.Null` |CamelSmppEncoding |String |*only for SubmitSm, SubmitMulti and DataSm*. Specifies the encoding (character set name) of the bytes in the message body. If the message body is a string then this is not relevant because Java Strings are always Unicode. If the body is a byte array then this header can be used to indicate that it is ISO-8859-1 or some other value. Default value is specified by the endpoint configuration parameter _encoding_ |CamelSmppSplittingPolicy |String |*only for SubmitSm, SubmitMulti and DataSm*. Specifies the policy for message splitting for this exchange. Possible values are described in the endpoint configuration parameter _splittingPolicy_ |======================================================================= The following message headers are used by the SMPP producer to set the response from the SMSC in the message header [width=""100%"",cols=""10%,10%,80%"",options=""header"",] |======================================================================= |Header |Type |Description |`CamelSmppId` |`List`/`String` |The id to identify the submitted short message(s) for later use. In case of a ReplaceSm, QuerySm, CancelSm and DataSm this header vaule is a `String`. In case of a SubmitSm or SubmitMultiSm this header vaule is a `List`. |`CamelSmppSentMessageCount` |`Integer` |*only for SubmitSm and SubmitMultiSm* The total number of messages which has been sent. |`CamelSmppError` |`Map>>` |*only for SubmitMultiSm* The errors which occurred by sending the short message(s) the form `Map>>` (messageID : (destAddr : address, error : errorCode)). |`CamelSmppOptionalParameter` |`Map` |*only for DataSm* The optional parameter which are returned from the SMSC by sending the message. The key is the `Short` code for the optional parameter. The value is converted in the following way: `org.jsmpp.bean.OptionalParameter.COctetString` -> `String`, `org.jsmpp.bean.OptionalParameter.OctetString` -> `byte[]`, `org.jsmpp.bean.OptionalParameter.Byte` -> `Byte`, `org.jsmpp.bean.OptionalParameter.Int` -> `Integer`, `org.jsmpp.bean.OptionalParameter.Short` -> `Short`, `org.jsmpp.bean.OptionalParameter.Null` -> `null` |======================================================================= == Consumer Message Headers The following message headers are used by the SMPP consumer to set the request data from the SMSC in the message header [width=""100%"",cols=""10%,10%,80%"",options=""header"",] |======================================================================= |Header |Type |Description |`CamelSmppSequenceNumber` |`Integer` |*only for AlertNotification, DeliverSm and DataSm* A sequence number allows a response PDU to be correlated with a request PDU. The associated SMPP response PDU must preserve this field. |`CamelSmppCommandId` |`Integer` |*only for AlertNotification, DeliverSm and DataSm* The command id field identifies the particular SMPP PDU. For the complete list of defined values see chapter 5.1.2.1 in the smpp specification v3.4. |`CamelSmppSourceAddr` |`String` |*only for AlertNotification, DeliverSm and DataSm* Defines the address of SME (Short Message Entity) which originated this message. |`CamelSmppSourceAddrNpi` |`Byte` |*only for AlertNotification and DataSm* Defines the numeric plan indicator (NPI) to be used in the SME originator address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppSourceAddrTon` |`Byte` |*only for AlertNotification and DataSm* Defines the type of number (TON) to be used in the SME originator address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppEsmeAddr` |`String` |*only for AlertNotification* Defines the destination ESME address. For mobile terminated messages, this is the directory number of the recipient MS. |`CamelSmppEsmeAddrNpi` |`Byte` |*only for AlertNotification* Defines the numeric plan indicator (NPI) to be used in the ESME originator address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppEsmeAddrTon` |`Byte` |*only for AlertNotification* Defines the type of number (TON) to be used in the ESME originator address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppId` |`String` |*only for smsc DeliveryReceipt and DataSm* The message ID allocated to the message by the SMSC when originally submitted. |`CamelSmppDelivered` |`Integer` |*only for smsc DeliveryReceipt* Number of short messages delivered. This is only relevant where the original message was submitted to a distribution list.The value is padded with leading zeros if necessary. |`CamelSmppDoneDate` |`Date` |*only for smsc DeliveryReceipt* The time and date at which the short message reached it's final state. The format is as follows: YYMMDDhhmm. |`CamelSmppStatus` |`DeliveryReceiptState` |*only for smsc DeliveryReceipt:* The final status of the message. The following values are defined: `DELIVRD`: Message is delivered to destination, `EXPIRED`: Message validity period has expired, `DELETED`: Message has been deleted, `UNDELIV`: Message is undeliverable, `ACCEPTD`: Message is in accepted state (i.e. has been manually read on behalf of the subscriber by customer service), `UNKNOWN`: Message is in invalid state, `REJECTD`: Message is in a rejected state |`CamelSmppCommandStatus` |`Integer` |*only for DataSm* The Command status of the message. |`CamelSmppError` |`String` |*only for smsc DeliveryReceipt* Where appropriate this may hold a Network specific error code or an SMSC error code for the attempted delivery of the message. These errors are Network or SMSC specific and are not included here. |`CamelSmppSubmitDate` |`Date` |*only for smsc DeliveryReceipt* The time and date at which the short message was submitted. In the case of a message which has been replaced, this is the date that the original message was replaced. The format is as follows: YYMMDDhhmm. |`CamelSmppSubmitted` |`Integer` |*only for smsc DeliveryReceipt* Number of short messages originally submitted. This is only relevant when the original message was submitted to a distribution list.The value is padded with leading zeros if necessary. |`CamelSmppDestAddr` |`String` |*only for DeliverSm and DataSm:* Defines the destination SME address. For mobile terminated messages, this is the directory number of the recipient MS. |`CamelSmppScheduleDeliveryTime` |`String` |*only for DeliverSm:* This parameter specifies the scheduled time at which the message delivery should be first attempted. It defines either the absolute date and time or relative time from the current SMSC time at which delivery of this message will be attempted by the SMSC. It can be specified in either absolute time format or relative time format. The encoding of a time format is specified in Section 7.1.1. in the smpp specification v3.4. |`CamelSmppValidityPeriod` |`String` |*only for DeliverSm* The validity period parameter indicates the SMSC expiration time, after which the message should be discarded if not delivered to the destination. It can be defined in absolute time format or relative time format. The encoding of absolute and relative time format is specified in Section 7.1.1 in the smpp specification v3.4. |`CamelSmppServiceType` |`String` |*only for DeliverSm and DataSm* The service type parameter indicates the SMS Application service associated with the message. |`CamelSmppRegisteredDelivery` |`Byte` |*only for DataSm* Is used to request an delivery receipt and/or SME originated acknowledgements. Same values as in Producer header list above. |`CamelSmppDestAddrNpi` |`Byte` |*only for DataSm* Defines the numeric plan indicator (NPI) in the destination address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppDestAddrTon` |`Byte` |*only for DataSm* Defines the type of number (TON) in the destination address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppMessageType` |`String` |Identifies the type of an incoming message: `AlertNotification`: an SMSC alert notification, `DataSm`: an SMSC data short message, `DeliveryReceipt`: an SMSC delivery receipt, `DeliverSm`: an SMSC deliver short message |`CamelSmppOptionalParameter` |`Map` |*only for DeliverSm* The optional parameters send back by the SMSC. The key is the `Short` code for the optional parameter. The value is converted in the following way: `org.jsmpp.bean.OptionalParameter.COctetString` -> `String`, `org.jsmpp.bean.OptionalParameter.OctetString` -> `byte[]`, `org.jsmpp.bean.OptionalParameter.Byte` -> `Byte`, `org.jsmpp.bean.OptionalParameter.Int` -> `Integer`, `org.jsmpp.bean.OptionalParameter.Short` -> `Short`, `org.jsmpp.bean.OptionalParameter.Null` -> `null` |======================================================================= TIP: *JSMPP library* See the documentation of the http://jsmpp.org[JSMPP Library] for more details about the underlying library. == Exception handling This component supports the general Camel exception handling capabilities When an error occurs sending a message with SubmitSm (the default action), the org.apache.camel.component.smpp.SmppException is thrown with a nested exception, org.jsmpp.extra.NegativeResponseException. Call NegativeResponseException.getCommandStatus() to obtain the exact SMPP negative response code, the values are explained in the SMPP specification 3.4, section 5.1.3. + When the SMPP consumer receives a `DeliverSm` or `DataSm` short message and the processing of these messages fails, you can also throw a `ProcessRequestException` instead of handle the failure. In this case, this exception is forwarded to the underlying http://jsmpp.org[JSMPP library] which will return the included error code to the SMSC. This feature is useful to e.g. instruct the SMSC to resend the short message at a later time. This could be done with the following lines of code: [source,java] -------------------------------------------------------------------------------------------------------------------------- from(""smpp://smppclient@localhost:2775?password=password&enquireLinkTimer=3000&transactionTimer=5000&systemType=consumer"") .doTry() .to(""bean:dao?method=updateSmsState"") .doCatch(Exception.class) .throwException(new ProcessRequestException(""update of sms state failed"", 100)) .end(); -------------------------------------------------------------------------------------------------------------------------- Please refer to the http://smsforum.net/SMPP_v3_4_Issue1_2.zip[SMPP specification] for the complete list of error codes and their meanings. == Samples A route which sends an SMS using the Java DSL: [source,java] ------------------------------------------------------------------------------------------ from(""direct:start"") .to(""smpp://smppclient@localhost:2775? password=password&enquireLinkTimer=3000&transactionTimer=5000&systemType=producer""); ------------------------------------------------------------------------------------------ A route which sends an SMS using the Spring XML DSL: [source,xml] ----------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------- A route which receives an SMS using the Java DSL: [source,java] -------------------------------------------------------------------------------------------------------------------------- from(""smpp://smppclient@localhost:2775?password=password&enquireLinkTimer=3000&transactionTimer=5000&systemType=consumer"") .to(""bean:foo""); -------------------------------------------------------------------------------------------------------------------------- A route which receives an SMS using the Spring XML DSL: [source,xml] ---------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------- TIP: *SMSC simulator* If you need an SMSC simulator for your test, you can use the simulator provided by http://opensmpp.logica.com/CommonPart/Download/download2.html#simulator[Logica]. == Debug logging This component has log level *DEBUG*, which can be helpful in debugging problems. If you use log4j, you can add the following line to your configuration: [source,java] -------------------------------------------------- log4j.logger.org.apache.camel.component.smpp=DEBUG -------------------------------------------------- ",12127,False,2372.5813171184336,median "/** * @copyright (C) 2017 Melexis N.V. * * 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. * */ #include #include ""mlx90640_driver.h"" #include #include #include #include #include #include #include #include #include #include #include #include ""mywidget.h"" #define MLX_I2C_ADDR 0x33 // I2C void MLX90640::registerCallback(MyWidget* mywidget) { mlx90640_callback = mywidget; } void MLX90640::start() { state = 0; std::cout << ""Starting...\\n""; static uint16_t eeMLX90640[832]; float emissivity = 1; uint16_t frame[834]; static float image[768]; static uint16_t data[768*sizeof(float)]; std::fstream fs; MLX90640_SetDeviceMode(MLX_I2C_ADDR, 0); MLX90640_SetSubPageRepeat(MLX_I2C_ADDR, 0); MLX90640_SetRefreshRate(MLX_I2C_ADDR, 0b010); MLX90640_SetChessMode(MLX_I2C_ADDR); //MLX90640_SetSubPage(MLX_I2C_ADDR, 0); std::cout << ""Configured...\\n""; MLX90640_DumpEE(MLX_I2C_ADDR, eeMLX90640); MLX90640_ExtractParameters(eeMLX90640, this); int refresh = MLX90640_GetRefreshRate(MLX_I2C_ADDR); std::cout << ""EE Dumped...\\n""; if (nullptr != daqThread) { std::cout << ""Thread in progress."" << std::endl; return; } daqThread = new std::thread(exec, this); } void MLX90640::run(){ int frames = 30; int subpage; static float mlx90640To[768]; running = 1; while (running){ state = !state; //std::cout << ""State: "" << state << std::endl; MLX90640_GetFrameData(MLX_I2C_ADDR, frame); // MLX90640_InterpolateOutliers(frame, eeMLX90640); eTa = MLX90640_GetTa(frame, this); subpage = MLX90640_GetSubPageNumber(frame); MLX90640_CalculateTo(frame, this, emissivity, eTa, mlx90640To); MLX90640_BadPixelsCorrection(this->brokenPixels, mlx90640To, 1, this); MLX90640_BadPixelsCorrection(this->outlierPixels, mlx90640To, 1, this); // std::cout << ""Subpage: "" << subpage <hasValue(mlx90640To); } } } void MLX90640::stop(void) { running = 0; if (nullptr != daqThread) { daqThread->join(); delete daqThread; daqThread = nullptr; } } int MLX90640::MLX90640_I2CRead(uint8_t slaveAddr, uint16_t startAddress, uint16_t nMemAddressRead, uint16_t *data) { if(!i2c_fd){ i2c_fd = open(i2c_device, O_RDWR); } int result; char cmd[2] = {(char)(startAddress >> 8), (char)(startAddress & 0xFF)}; char buf[1664]; uint16_t *p = data; struct i2c_msg i2c_messages[2]; struct i2c_rdwr_ioctl_data i2c_messageset[1]; i2c_messages[0].addr = slaveAddr; i2c_messages[0].flags = 0; i2c_messages[0].len = 2; i2c_messages[0].buf = (I2C_MSG_FMT*)cmd; i2c_messages[1].addr = slaveAddr; i2c_messages[1].flags = I2C_M_RD | I2C_M_NOSTART; i2c_messages[1].len = nMemAddressRead * 2; i2c_messages[1].buf = (I2C_MSG_FMT*)buf; // result = write(i2c_fd, cmd, 3); // result = read(i2c_fd, buf, nMemAddressRead*2); i2c_messageset[0].msgs = i2c_messages; i2c_messageset[0].nmsgs = 2; memset(buf, 0, nMemAddressRead * 2); if (ioctl(i2c_fd, I2C_RDWR, &i2c_messageset) < 0) { printf(""I2C Read Error!\\n""); return -1; } for(int count = 0; count < nMemAddressRead; count++){ int i = count << 1; *p++ = ((uint16_t)buf[i] << 8) | buf[i+1]; } return 0; } void MLX90640::MLX90640_I2CFreqSet(int freq) {} int MLX90640::MLX90640_I2CWrite(uint8_t slaveAddr, uint16_t writeAddress, uint16_t data) { char cmd[4] = {(char)(writeAddress >> 8), (char)(writeAddress & 0x00FF), (char)(data >> 8), (char)(data & 0x00FF)}; int result; struct i2c_msg i2c_messages[1]; struct i2c_rdwr_ioctl_data i2c_messageset[1]; i2c_messages[0].addr = slaveAddr; i2c_messages[0].flags = 0; i2c_messages[0].len = 4; i2c_messages[0].buf = (I2C_MSG_FMT*)cmd; i2c_messageset[0].msgs = i2c_messages; i2c_messageset[0].nmsgs = 1; if (ioctl(i2c_fd, I2C_RDWR, &i2c_messageset) < 0) { printf(""I2C Write Error!\\n""); return -1; } return 0; } // API int MLX90640::MLX90640_DumpEE(uint8_t slaveAddr, uint16_t *eeData) { return MLX90640_I2CRead(slaveAddr, 0x2400, 832, eeData); } int MLX90640::MLX90640_CheckInterrupt(uint8_t slaveAddr) { uint16_t statusRegister; MLX90640_I2CRead(slaveAddr, 0x8000, 1, &statusRegister); return (statusRegister & 0b1000) > 0; } void MLX90640::MLX90640_StartMeasurement(uint8_t slaveAddr, uint8_t subPage) { uint16_t controlRegister1; uint16_t statusRegister; MLX90640_I2CRead(slaveAddr, 0x800D, 1, &controlRegister1); controlRegister1 &= 0b1111111111101111; controlRegister1 |= subPage << 4; MLX90640_I2CWrite(slaveAddr, 0x800D, controlRegister1); MLX90640_I2CRead(slaveAddr, 0x8000, 1, &statusRegister); statusRegister &= 0b1111111111110111; // Clear b3: new data available in RAM statusRegister |= 0b0000000000110000; // Set b5: start of measurement // Set b4: enable RAM overwrite MLX90640_I2CWrite(slaveAddr, 0x8000, statusRegister); } void MLX90640::MLX90640_SetEmissivity(float em) { this->emissivity = em; } int MLX90640::MLX90640_GetData(uint8_t slaveAddr, uint16_t *frameData) { int error = 0; uint16_t statusRegister; uint16_t controlRegister1; // Get page data error = MLX90640_I2CRead(slaveAddr, 0x0400, 832, frameData); // Get status reguster MLX90640_I2CRead(slaveAddr, 0x8000, 1, &statusRegister); // Get control register MLX90640_I2CRead(slaveAddr, 0x800D, 1, &controlRegister1); frameData[832] = controlRegister1; frameData[833] = statusRegister & 0x0001; // Populate the subpage number } int MLX90640::MLX90640_InterpolateOutliers(uint16_t *frameData, uint16_t *eepromData) { for(int x = 0; x < 768; x++){ int broken = eepromData[64 + x] == 0; int outlier = eepromData[64 + x] & 0x0001; if (broken){ float val = 0; int count = 0; if(x - 33 > 0){ val += frameData[x - 33]; val += frameData[x - 31]; count += 2; } else if (x - 31 > 0){ val += frameData[x - 31]; count += 1; } if(x + 33 < 768){ val += frameData[x + 33]; val += frameData[x + 31]; count += 2; } else if (x + 31 < 768){ val += frameData[x + 31]; count += 1; } frameData[x] = (uint16_t)((float)(val / count) * 1.0003); } } return 0; } int MLX90640::MLX90640_GetFrameData(uint8_t slaveAddr, uint16_t *frameData) { uint16_t dataReady = 1; uint16_t controlRegister1; uint16_t statusRegister; int error = 1; uint8_t cnt = 0; auto t_start = std::chrono::system_clock::now(); dataReady = 0; while(dataReady == 0) { error = MLX90640_I2CRead(slaveAddr, 0x8000, 1, &statusRegister); if(error != 0) { return error; } dataReady = statusRegister & 0x0008; auto t_end = std::chrono::system_clock::now(); auto t_elapsed = std::chrono::duration_cast(t_end - t_start); if (t_elapsed.count() > 5) { printf(""frameData timeout error waiting for dataReady \\n""); return -1; } } while(dataReady != 0 && cnt < 5) { error = MLX90640_I2CWrite(slaveAddr, 0x8000, 0x0030); if(error == -1) { return error; } error = MLX90640_I2CRead(slaveAddr, 0x0400, 832, frameData); if(error != 0) { printf(""frameData read error \\n""); return error; } error = MLX90640_I2CRead(slaveAddr, 0x8000, 1, &statusRegister); if(error != 0) { return error; } dataReady = statusRegister & 0x0008; cnt = cnt + 1; } if(cnt > 4) { fprintf(stderr, ""cnt > 4 error \\n""); // return -8; } //printf(""count: %d \\n"", cnt); error = MLX90640_I2CRead(slaveAddr, 0x800D, 1, &controlRegister1); frameData[832] = controlRegister1; frameData[833] = statusRegister & 0x0001; if(error != 0) { return error; } return frameData[833]; } int MLX90640::MLX90640_ExtractParameters(uint16_t *eeData, MLX90640 *mlx90640) { int error = 0; ExtractVDDParameters(eeData, mlx90640); ExtractPTATParameters(eeData, mlx90640); ExtractGainParameters(eeData, mlx90640); ExtractTgcParameters(eeData, mlx90640); ExtractResolutionParameters(eeData, mlx90640); ExtractKsTaParameters(eeData, mlx90640); ExtractKsToParameters(eeData, mlx90640); ExtractCPParameters(eeData, mlx90640); ExtractAlphaParameters(eeData, mlx90640); ExtractOffsetParameters(eeData, mlx90640); ExtractKtaPixelParameters(eeData, mlx90640); ExtractKvPixelParameters(eeData, mlx90640); ExtractCILCParameters(eeData, mlx90640); error = ExtractDeviatingPixels(eeData, mlx90640); return error; } // Resolution Settings int MLX90640::MLX90640_SetResolution(uint8_t slaveAddr, uint8_t resolution) { uint16_t controlRegister1; int value; int error; value = (resolution & 0x03) << 10; error = MLX90640_I2CRead(slaveAddr, 0x800D, 1, &controlRegister1); if(error == 0) { value = (controlRegister1 & 0xF3FF) | value; error = MLX90640_I2CWrite(slaveAddr, 0x800D, value); } return error; } int MLX90640::MLX90640_GetCurResolution(uint8_t slaveAddr) { uint16_t controlRegister1; int resolutionRAM; int error; error = MLX90640_I2CRead(slaveAddr, 0x800D, 1, &controlRegister1); if(error != 0) { return error; } resolutionRAM = (controlRegister1 & 0x0C00) >> 10; return resolutionRAM; } int MLX90640::MLX90640_SetRefreshRate(uint8_t slaveAddr, uint8_t refreshRate) { uint16_t controlRegister1; int value; int error; value = (refreshRate & 0x07)<<7; error = MLX90640_I2CRead(slaveAddr, 0x800D, 1, &controlRegister1); if(error == 0) { value = (controlRegister1 & 0xFC7F) | value; error = MLX90640_I2CWrite(slaveAddr, 0x800D, value); } return error; } int MLX90640::MLX90640_GetRefreshRate(uint8_t slaveAddr) { uint16_t controlRegister1; int refreshRate; int error; error = MLX90640_I2CRead(slaveAddr, 0x800D, 1, &controlRegister1); if(error != 0) { return error; } refreshRate = (controlRegister1 & 0x0380) >> 7; return refreshRate; } int MLX90640::MLX90640_SetInterleavedMode(uint8_t slaveAddr) { uint16_t controlRegister1; int value; int error; error = MLX90640_I2CRead(slaveAddr, 0x800D, 1, &controlRegister1); if(error == 0) { value = (controlRegister1 & 0xEFFF); error = MLX90640_I2CWrite(slaveAddr, 0x800D, value); } return error; } int MLX90640::MLX90640_SetChessMode(uint8_t slaveAddr) { uint16_t controlRegister1; int value; int error; error = MLX90640_I2CRead(slaveAddr, 0x800D, 1, &controlRegister1); if(error == 0) { value = (controlRegister1 | 0x1000); error = MLX90640_I2CWrite(slaveAddr, 0x800D, value); } return error; } // Device mode settings int MLX90640::MLX90640_GetCurMode(uint8_t slaveAddr) { uint16_t controlRegister1; int modeRAM; int error; error = MLX90640_I2CRead(slaveAddr, 0x800D, 1, &controlRegister1); if(error != 0) { return error; } modeRAM = (controlRegister1 & 0x1000) >> 12; return modeRAM; } int MLX90640::MLX90640_SetDeviceMode(uint8_t slaveAddr, uint8_t deviceMode) { uint16_t controlRegister1; int value; int error; value = (deviceMode & 0x01)<<4; error = MLX90640_I2CRead(slaveAddr, 0x800D, 1, &controlRegister1); if(error == 0) { value = (controlRegister1 & 0b1111111111111101) | value; error = MLX90640_I2CWrite(slaveAddr, 0x800D, value); } return error; } int MLX90640::MLX90640_SetSubPageRepeat(uint8_t slaveAddr, uint8_t subPageRepeat) { uint16_t controlRegister1; int value; int error; value = (subPageRepeat & 0x01)<<3; error = MLX90640_I2CRead(slaveAddr, 0x800D, 1, &controlRegister1); if(error == 0) { value = (controlRegister1 & 0b1111111111110111) | value; error = MLX90640_I2CWrite(slaveAddr, 0x800D, value); } return error; } int MLX90640::MLX90640_SetSubPage(uint8_t slaveAddr, uint8_t subPage) { uint16_t controlRegister1; int value; int error; value = (subPage & 0x01)<<4; error = MLX90640_I2CRead(slaveAddr, 0x800D, 1, &controlRegister1); if(error == 0) { value = (controlRegister1 & 0b1111111110001111) | value; error = MLX90640_I2CWrite(slaveAddr, 0x800D, value); } return error; } // Key data processing void MLX90640::MLX90640_CalculateTo(uint16_t *frameData, const MLX90640 *params, float emissivity, float tr, float *result) { float vdd; float ta; float ta4; float tr4; float taTr; float gain; float irDataCP[2]; float irData; float alphaCompensated; uint8_t mode; int8_t ilPattern; int8_t chessPattern; int8_t pattern; int8_t conversionPattern; float Sx; float To; float alphaCorrR[4]; int8_t range; uint16_t subPage; float ktaScale; float kvScale; float alphaScale; float kta; float kv; subPage = frameData[833]; vdd = MLX90640_GetVdd(frameData, params); ta = MLX90640_GetTa(frameData, params); ta4 = (ta + 273.15); ta4 = ta4 * ta4; ta4 = ta4 * ta4; tr4 = (tr + 273.15); tr4 = tr4 * tr4; tr4 = tr4 * tr4; taTr = tr4 - (tr4-ta4)/emissivity; ktaScale = pow(2,(double)params->ktaScale); kvScale = pow(2,(double)params->kvScale); alphaScale = pow(2,(double)params->alphaScale); alphaCorrR[0] = 1 / (1 + params->ksTo[0] * 40); alphaCorrR[1] = 1 ; alphaCorrR[2] = (1 + params->ksTo[1] * params->ct[2]); alphaCorrR[3] = alphaCorrR[2] * (1 + params->ksTo[2] * (params->ct[3] - params->ct[2])); //------------------------- Gain calculation ----------------------------------- gain = frameData[778]; if(gain > 32767) { gain = gain - 65536; } gain = params->gainEE / gain; //------------------------- To calculation ------------------------------------- mode = (frameData[832] & 0x1000) >> 5; irDataCP[0] = frameData[776]; irDataCP[1] = frameData[808]; for( int i = 0; i < 2; i++) { if(irDataCP[i] > 32767) { irDataCP[i] = irDataCP[i] - 65536; } irDataCP[i] = irDataCP[i] * gain; } irDataCP[0] = irDataCP[0] - params->cpOffset[0] * (1 + params->cpKta * (ta - 25)) * (1 + params->cpKv * (vdd - 3.3)); if( mode == params->calibrationModeEE) { irDataCP[1] = irDataCP[1] - params->cpOffset[1] * (1 + params->cpKta * (ta - 25)) * (1 + params->cpKv * (vdd - 3.3)); } else { irDataCP[1] = irDataCP[1] - (params->cpOffset[1] + params->ilChessC[0]) * (1 + params->cpKta * (ta - 25)) * (1 + params->cpKv * (vdd - 3.3)); } for( int pixelNumber = 0; pixelNumber < 768; pixelNumber++) { ilPattern = pixelNumber / 32 - (pixelNumber / 64) * 2; chessPattern = ilPattern ^ (pixelNumber - (pixelNumber/2)*2); conversionPattern = ((pixelNumber + 2) / 4 - (pixelNumber + 3) / 4 + (pixelNumber + 1) / 4 - pixelNumber / 4) * (1 - 2 * ilPattern); if(mode == 0) { pattern = ilPattern; } else { pattern = chessPattern; } if(pattern == frameData[833]) { irData = frameData[pixelNumber]; if(irData > 32767) { irData = irData - 65536; } irData = irData * gain; kta = params->kta[pixelNumber]/ktaScale; kv = params->kv[pixelNumber]/kvScale; irData = irData - params->offset[pixelNumber]*(1 + kta*(ta - 25))*(1 + kv*(vdd - 3.3)); if(mode != params->calibrationModeEE) { irData = irData + params->ilChessC[2] * (2 * ilPattern - 1) - params->ilChessC[1] * conversionPattern; } irData = irData - params->tgc * irDataCP[subPage]; irData = irData / emissivity; alphaCompensated = SCALEALPHA*alphaScale/params->alpha[pixelNumber]; alphaCompensated = alphaCompensated*(1 + params->KsTa * (ta - 25)); Sx = alphaCompensated * alphaCompensated * alphaCompensated * (irData + alphaCompensated * taTr); Sx = sqrt(sqrt(Sx)) * params->ksTo[1]; To = sqrt(sqrt(irData/(alphaCompensated * (1 - params->ksTo[1] * 273.15) + Sx) + taTr)) - 273.15; if(To < params->ct[1]) { range = 0; } else if(To < params->ct[2]) { range = 1; } else if(To < params->ct[3]) { range = 2; } else { range = 3; } To = sqrt(sqrt(irData / (alphaCompensated * alphaCorrR[range] * (1 + params->ksTo[range] * (To - params->ct[range]))) + taTr)) - 273.15; result[pixelNumber] = To; } } } void MLX90640::MLX90640_GetImage(uint16_t *frameData, const MLX90640 *params, float *result) { float vdd; float ta; float gain; float irDataCP[2]; float irData; float alphaCompensated; uint8_t mode; int8_t ilPattern; int8_t chessPattern; int8_t pattern; int8_t conversionPattern; float image; uint16_t subPage; float ktaScale; float kvScale; float kta; float kv; subPage = frameData[833]; vdd = MLX90640_GetVdd(frameData, params); ta = MLX90640_GetTa(frameData, params); ktaScale = pow(2,(double)params->ktaScale); kvScale = pow(2,(double)params->kvScale); //------------------------- Gain calculation ----------------------------------- gain = frameData[778]; if(gain > 32767) { gain = gain - 65536; } gain = params->gainEE / gain; //------------------------- Image calculation ------------------------------------- mode = (frameData[832] & 0x1000) >> 5; irDataCP[0] = frameData[776]; irDataCP[1] = frameData[808]; for( int i = 0; i < 2; i++) { if(irDataCP[i] > 32767) { irDataCP[i] = irDataCP[i] - 65536; } irDataCP[i] = irDataCP[i] * gain; } irDataCP[0] = irDataCP[0] - params->cpOffset[0] * (1 + params->cpKta * (ta - 25)) * (1 + params->cpKv * (vdd - 3.3)); if( mode == params->calibrationModeEE) { irDataCP[1] = irDataCP[1] - params->cpOffset[1] * (1 + params->cpKta * (ta - 25)) * (1 + params->cpKv * (vdd - 3.3)); } else { irDataCP[1] = irDataCP[1] - (params->cpOffset[1] + params->ilChessC[0]) * (1 + params->cpKta * (ta - 25)) * (1 + params->cpKv * (vdd - 3.3)); } for( int pixelNumber = 0; pixelNumber < 768; pixelNumber++) { ilPattern = pixelNumber / 32 - (pixelNumber / 64) * 2; chessPattern = ilPattern ^ (pixelNumber - (pixelNumber/2)*2); conversionPattern = ((pixelNumber + 2) / 4 - (pixelNumber + 3) / 4 + (pixelNumber + 1) / 4 - pixelNumber / 4) * (1 - 2 * ilPattern); if(mode == 0) { pattern = ilPattern; } else { pattern = chessPattern; } if(pattern == frameData[833]) { irData = frameData[pixelNumber]; if(irData > 32767) { irData = irData - 65536; } irData = irData * gain; kta = params->kta[pixelNumber]/ktaScale; kv = params->kv[pixelNumber]/kvScale; irData = irData - params->offset[pixelNumber]*(1 + kta*(ta - 25))*(1 + kv*(vdd - 3.3)); if(mode != params->calibrationModeEE) { irData = irData + params->ilChessC[2] * (2 * ilPattern - 1) - params->ilChessC[1] * conversionPattern; } irData = irData - params->tgc * irDataCP[subPage]; alphaCompensated = params->alpha[pixelNumber]; image = irData*alphaCompensated; result[pixelNumber] = image; } } } float MLX90640::MLX90640_GetVdd(uint16_t *frameData, const MLX90640 *params) { float vdd; float resolutionCorrection; int resolutionRAM; vdd = frameData[810]; if(vdd > 32767) { vdd = vdd - 65536; } resolutionRAM = (frameData[832] & 0x0C00) >> 10; resolutionCorrection = pow(2, (double)params->resolutionEE) / pow(2, (double)resolutionRAM); vdd = (resolutionCorrection * vdd - params->vdd25) / params->kVdd + 3.3; return vdd; } float MLX90640::MLX90640_GetTa(uint16_t *frameData, const MLX90640 *params) { float ptat; float ptatArt; float vdd; float ta; vdd = MLX90640_GetVdd(frameData, params); ptat = frameData[800]; if(ptat > 32767) { ptat = ptat - 65536; } ptatArt = frameData[768]; if(ptatArt > 32767) { ptatArt = ptatArt - 65536; } ptatArt = (ptat / (ptat * params->alphaPTAT + ptatArt)) * pow(2, (double)18); ta = (ptatArt / (1 + params->KvPTAT * (vdd - 3.3)) - params->vPTAT25); ta = ta / params->KtPTAT + 25; return ta; } int MLX90640::MLX90640_GetSubPageNumber(uint16_t *frameData) { return frameData[833]; } void MLX90640::MLX90640_BadPixelsCorrection(uint16_t *pixels, float *to, int mode, MLX90640 *params) { float ap[4]; uint8_t pix; uint8_t line; uint8_t column; pix = 0; while(pixels[pix] != 0xFFFF) { line = pixels[pix]>>5; column = pixels[pix] - (line<<5); if(mode == 1) { if(line == 0) { if(column == 0) { to[pixels[pix]] = to[33]; } else if(column == 31) { to[pixels[pix]] = to[62]; } else { to[pixels[pix]] = (to[pixels[pix]+31] + to[pixels[pix]+33])/2.0; } } else if(line == 23) { if(column == 0) { to[pixels[pix]] = to[705]; } else if(column == 31) { to[pixels[pix]] = to[734]; } else { to[pixels[pix]] = (to[pixels[pix]-33] + to[pixels[pix]-31])/2.0; } } else if(column == 0) { to[pixels[pix]] = (to[pixels[pix]-31] + to[pixels[pix]+33])/2.0; } else if(column == 31) { to[pixels[pix]] = (to[pixels[pix]-33] + to[pixels[pix]+31])/2.0; } else { ap[0] = to[pixels[pix]-33]; ap[1] = to[pixels[pix]-31]; ap[2] = to[pixels[pix]+31]; ap[3] = to[pixels[pix]+33]; to[pixels[pix]] = GetMedian(ap,4); } } else { if(column == 0) { to[pixels[pix]] = to[pixels[pix]+1]; } else if(column == 1 || column == 30) { to[pixels[pix]] = (to[pixels[pix]-1]+to[pixels[pix]+1])/2.0; } else if(column == 31) { to[pixels[pix]] = to[pixels[pix]-1]; } else { if(IsPixelBad(pixels[pix]-2,params) == 0 && IsPixelBad(pixels[pix]+2,params) == 0) { ap[0] = to[pixels[pix]+1] - to[pixels[pix]+2]; ap[1] = to[pixels[pix]-1] - to[pixels[pix]-2]; if(fabs(ap[0]) > fabs(ap[1])) { to[pixels[pix]] = to[pixels[pix]-1] + ap[1]; } else { to[pixels[pix]] = to[pixels[pix]+1] + ap[0]; } } else { to[pixels[pix]] = (to[pixels[pix]-1]+to[pixels[pix]+1])/2.0; } } } pix = pix + 1; } } // Parameter extract void MLX90640::ExtractVDDParameters(uint16_t *eeData, MLX90640 *mlx90640) { int16_t kVdd; int16_t vdd25; kVdd = eeData[51]; kVdd = (eeData[51] & 0xFF00) >> 8; if(kVdd > 127) { kVdd = kVdd - 256; } kVdd = 32 * kVdd; vdd25 = eeData[51] & 0x00FF; vdd25 = ((vdd25 - 256) << 5) - 8192; mlx90640->kVdd = kVdd; mlx90640->vdd25 = vdd25; } void MLX90640::ExtractPTATParameters(uint16_t *eeData, MLX90640 *mlx90640) { float KvPTAT; float KtPTAT; int16_t vPTAT25; float alphaPTAT; KvPTAT = (eeData[50] & 0xFC00) >> 10; if(KvPTAT > 31) { KvPTAT = KvPTAT - 64; } KvPTAT = KvPTAT/4096; KtPTAT = eeData[50] & 0x03FF; if(KtPTAT > 511) { KtPTAT = KtPTAT - 1024; } KtPTAT = KtPTAT/8; vPTAT25 = eeData[49]; alphaPTAT = (eeData[16] & 0xF000) / pow(2, (double)14) + 8.0f; mlx90640->KvPTAT = KvPTAT; mlx90640->KtPTAT = KtPTAT; mlx90640->vPTAT25 = vPTAT25; mlx90640->alphaPTAT = alphaPTAT; } void MLX90640::ExtractGainParameters(uint16_t *eeData, MLX90640 *mlx90640) { int16_t _gainEE; _gainEE = eeData[48]; if(_gainEE > 32767) { _gainEE = _gainEE -65536; } mlx90640->gainEE = _gainEE; } void MLX90640::ExtractTgcParameters(uint16_t *eeData, MLX90640 *mlx90640) { float _tgc; _tgc = eeData[60] & 0x00FF; if(_tgc > 127) { _tgc = _tgc - 256; } _tgc = _tgc / 32.0f; mlx90640->tgc = _tgc; } void MLX90640::ExtractResolutionParameters(uint16_t *eeData, MLX90640 *mlx90640) { uint8_t _resolutionEE; _resolutionEE = (eeData[56] & 0x3000) >> 12; mlx90640->resolutionEE = _resolutionEE; } void MLX90640::ExtractKsTaParameters(uint16_t *eeData, MLX90640 *mlx90640) { float _KsTa; _KsTa = (eeData[60] & 0xFF00) >> 8; if(_KsTa > 127) { _KsTa = _KsTa -256; } _KsTa = _KsTa / 8192.0f; mlx90640->KsTa = _KsTa; } void MLX90640::ExtractKsToParameters(uint16_t *eeData, MLX90640 *mlx90640) { int KsToScale; int8_t step; step = ((eeData[63] & 0x3000) >> 12) * 10; mlx90640->ct[0] = -40; mlx90640->ct[1] = 0; mlx90640->ct[2] = (eeData[63] & 0x00F0) >> 4; mlx90640->ct[3] = (eeData[63] & 0x0F00) >> 8; mlx90640->ct[2] = mlx90640->ct[2]*step; mlx90640->ct[3] = mlx90640->ct[2] + mlx90640->ct[3]*step; mlx90640->ct[4] = 400; KsToScale = (eeData[63] & 0x000F) + 8; KsToScale = 1 << KsToScale; mlx90640->ksTo[0] = eeData[61] & 0x00FF; mlx90640->ksTo[1] = (eeData[61] & 0xFF00) >> 8; mlx90640->ksTo[2] = eeData[62] & 0x00FF; mlx90640->ksTo[3] = (eeData[62] & 0xFF00) >> 8; for(int i = 0; i < 4; i++) { if(mlx90640->ksTo[i] > 127) { mlx90640->ksTo[i] = mlx90640->ksTo[i] - 256; } mlx90640->ksTo[i] = mlx90640->ksTo[i] / KsToScale; } mlx90640->ksTo[4] = -0.0002; } void MLX90640::ExtractAlphaParameters(uint16_t *eeData, MLX90640 *mlx90640) { int accRow[24]; int accColumn[32]; int p = 0; int alphaRef; uint8_t _alphaScale; uint8_t accRowScale; uint8_t accColumnScale; uint8_t accRemScale; float alphaTemp[768]; float temp; accRemScale = eeData[32] & 0x000F; accColumnScale = (eeData[32] & 0x00F0) >> 4; accRowScale = (eeData[32] & 0x0F00) >> 8; _alphaScale = ((eeData[32] & 0xF000) >> 12) + 30; alphaRef = eeData[33]; for(int i = 0; i < 6; i++) { p = i * 4; accRow[p + 0] = (eeData[34 + i] & 0x000F); accRow[p + 1] = (eeData[34 + i] & 0x00F0) >> 4; accRow[p + 2] = (eeData[34 + i] & 0x0F00) >> 8; accRow[p + 3] = (eeData[34 + i] & 0xF000) >> 12; } for(int i = 0; i < 24; i++) { if (accRow[i] > 7) { accRow[i] = accRow[i] - 16; } } for(int i = 0; i < 8; i++) { p = i * 4; accColumn[p + 0] = (eeData[40 + i] & 0x000F); accColumn[p + 1] = (eeData[40 + i] & 0x00F0) >> 4; accColumn[p + 2] = (eeData[40 + i] & 0x0F00) >> 8; accColumn[p + 3] = (eeData[40 + i] & 0xF000) >> 12; } for(int i = 0; i < 32; i ++) { if (accColumn[i] > 7) { accColumn[i] = accColumn[i] - 16; } } for(int i = 0; i < 24; i++) { for(int j = 0; j < 32; j ++) { p = 32 * i +j; alphaTemp[p] = (eeData[64 + p] & 0x03F0) >> 4; if (alphaTemp[p] > 31) { alphaTemp[p] = alphaTemp[p] - 64; } alphaTemp[p] = alphaTemp[p]*(1 << accRemScale); alphaTemp[p] = (alphaRef + (accRow[i] << accRowScale) + (accColumn[j] << accColumnScale) + alphaTemp[p]); alphaTemp[p] = alphaTemp[p] / pow(2,(double)_alphaScale); alphaTemp[p] = alphaTemp[p] - mlx90640->tgc * (mlx90640->cpAlpha[0] + mlx90640->cpAlpha[1])/2; alphaTemp[p] = SCALEALPHA/alphaTemp[p]; } } temp = alphaTemp[0]; for(int i = 1; i < 768; i++) { if (alphaTemp[i] > temp) { temp = alphaTemp[i]; } } _alphaScale = 0; while(temp < 32768) { temp = temp*2; _alphaScale = _alphaScale + 1; } for(int i = 0; i < 768; i++) { temp = alphaTemp[i] * pow(2,(double)_alphaScale); mlx90640->alpha[i] = (temp + 0.5); } mlx90640->alphaScale = _alphaScale; } void MLX90640::ExtractOffsetParameters(uint16_t *eeData, MLX90640 *mlx90640) { int occRow[24]; int occColumn[32]; int p = 0; int16_t offsetRef; uint8_t occRowScale; uint8_t occColumnScale; uint8_t occRemScale; occRemScale = (eeData[16] & 0x000F); occColumnScale = (eeData[16] & 0x00F0) >> 4; occRowScale = (eeData[16] & 0x0F00) >> 8; offsetRef = eeData[17]; if (offsetRef > 32767) { offsetRef = offsetRef - 65536; } for(int i = 0; i < 6; i++) { p = i * 4; occRow[p + 0] = (eeData[18 + i] & 0x000F); occRow[p + 1] = (eeData[18 + i] & 0x00F0) >> 4; occRow[p + 2] = (eeData[18 + i] & 0x0F00) >> 8; occRow[p + 3] = (eeData[18 + i] & 0xF000) >> 12; } for(int i = 0; i < 24; i++) { if (occRow[i] > 7) { occRow[i] = occRow[i] - 16; } } for(int i = 0; i < 8; i++) { p = i * 4; occColumn[p + 0] = (eeData[24 + i] & 0x000F); occColumn[p + 1] = (eeData[24 + i] & 0x00F0) >> 4; occColumn[p + 2] = (eeData[24 + i] & 0x0F00) >> 8; occColumn[p + 3] = (eeData[24 + i] & 0xF000) >> 12; } for(int i = 0; i < 32; i ++) { if (occColumn[i] > 7) { occColumn[i] = occColumn[i] - 16; } } for(int i = 0; i < 24; i++) { for(int j = 0; j < 32; j ++) { p = 32 * i +j; mlx90640->offset[p] = (eeData[64 + p] & 0xFC00) >> 10; if (mlx90640->offset[p] > 31) { mlx90640->offset[p] = mlx90640->offset[p] - 64; } mlx90640->offset[p] = mlx90640->offset[p]*(1 << occRemScale); mlx90640->offset[p] = (offsetRef + (occRow[i] << occRowScale) + (occColumn[j] << occColumnScale) + mlx90640->offset[p]); } } } void MLX90640::ExtractKtaPixelParameters(uint16_t *eeData, MLX90640 *mlx90640) { int p = 0; int8_t KtaRC[4]; int8_t KtaRoCo; int8_t KtaRoCe; int8_t KtaReCo; int8_t KtaReCe; uint8_t ktaScale1; uint8_t ktaScale2; uint8_t split; float ktaTemp[768]; float temp; KtaRoCo = (eeData[54] & 0xFF00) >> 8; if (KtaRoCo > 127) { KtaRoCo = KtaRoCo - 256; } KtaRC[0] = KtaRoCo; KtaReCo = (eeData[54] & 0x00FF); if (KtaReCo > 127) { KtaReCo = KtaReCo - 256; } KtaRC[2] = KtaReCo; KtaRoCe = (eeData[55] & 0xFF00) >> 8; if (KtaRoCe > 127) { KtaRoCe = KtaRoCe - 256; } KtaRC[1] = KtaRoCe; KtaReCe = (eeData[55] & 0x00FF); if (KtaReCe > 127) { KtaReCe = KtaReCe - 256; } KtaRC[3] = KtaReCe; ktaScale1 = ((eeData[56] & 0x00F0) >> 4) + 8; ktaScale2 = (eeData[56] & 0x000F); for(int i = 0; i < 24; i++) { for(int j = 0; j < 32; j ++) { p = 32 * i +j; split = 2*(p/32 - (p/64)*2) + p%2; ktaTemp[p] = (eeData[64 + p] & 0x000E) >> 1; if (ktaTemp[p] > 3) { ktaTemp[p] = ktaTemp[p] - 8; } ktaTemp[p] = ktaTemp[p] * (1 << ktaScale2); ktaTemp[p] = KtaRC[split] + ktaTemp[p]; ktaTemp[p] = ktaTemp[p] / pow(2,(double)ktaScale1); //ktaTemp[p] = ktaTemp[p] * mlx90640->offset[p]; } } temp = fabs(ktaTemp[0]); for(int i = 1; i < 768; i++) { if (fabs(ktaTemp[i]) > temp) { temp = fabs(ktaTemp[i]); } } ktaScale1 = 0; while(temp < 64) { temp = temp*2; ktaScale1 = ktaScale1 + 1; } for(int i = 0; i < 768; i++) { temp = ktaTemp[i] * pow(2,(double)ktaScale1); if (temp < 0) { mlx90640->kta[i] = (temp - 0.5); } else { mlx90640->kta[i] = (temp + 0.5); } } mlx90640->ktaScale = ktaScale1; } void MLX90640::ExtractKvPixelParameters(uint16_t *eeData, MLX90640 *mlx90640) { int p = 0; int8_t KvT[4]; int8_t KvRoCo; int8_t KvRoCe; int8_t KvReCo; int8_t KvReCe; uint8_t _kvScale; uint8_t split; float kvTemp[768]; float temp; KvRoCo = (eeData[52] & 0xF000) >> 12; if (KvRoCo > 7) { KvRoCo = KvRoCo - 16; } KvT[0] = KvRoCo; KvReCo = (eeData[52] & 0x0F00) >> 8; if (KvReCo > 7) { KvReCo = KvReCo - 16; } KvT[2] = KvReCo; KvRoCe = (eeData[52] & 0x00F0) >> 4; if (KvRoCe > 7) { KvRoCe = KvRoCe - 16; } KvT[1] = KvRoCe; KvReCe = (eeData[52] & 0x000F); if (KvReCe > 7) { KvReCe = KvReCe - 16; } KvT[3] = KvReCe; _kvScale = (eeData[56] & 0x0F00) >> 8; for(int i = 0; i < 24; i++) { for(int j = 0; j < 32; j ++) { p = 32 * i +j; split = 2*(p/32 - (p/64)*2) + p%2; kvTemp[p] = KvT[split]; kvTemp[p] = kvTemp[p] / pow(2,(double)_kvScale); //kvTemp[p] = kvTemp[p] * mlx90640->offset[p]; } } temp = fabs(kvTemp[0]); for(int i = 1; i < 768; i++) { if (fabs(kvTemp[i]) > temp) { temp = fabs(kvTemp[i]); } } _kvScale = 0; while(temp < 64) { temp = temp*2; _kvScale = _kvScale + 1; } for(int i = 0; i < 768; i++) { temp = kvTemp[i] * pow(2,(double)_kvScale); if (temp < 0) { mlx90640->kv[i] = (temp - 0.5); } else { mlx90640->kv[i] = (temp + 0.5); } } mlx90640->kvScale = _kvScale; } void MLX90640::ExtractCPParameters(uint16_t *eeData, MLX90640 *mlx90640) { float alphaSP[2]; int16_t offsetSP[2]; float _cpKv; float _cpKta; uint8_t alphaScale; uint8_t ktaScale1; uint8_t kvScale; alphaScale = ((eeData[32] & 0xF000) >> 12) + 27; offsetSP[0] = (eeData[58] & 0x03FF); if (offsetSP[0] > 511) { offsetSP[0] = offsetSP[0] - 1024; } offsetSP[1] = (eeData[58] & 0xFC00) >> 10; if (offsetSP[1] > 31) { offsetSP[1] = offsetSP[1] - 64; } offsetSP[1] = offsetSP[1] + offsetSP[0]; alphaSP[0] = (eeData[57] & 0x03FF); if (alphaSP[0] > 511) { alphaSP[0] = alphaSP[0] - 1024; } alphaSP[0] = alphaSP[0] / pow(2,(double)alphaScale); alphaSP[1] = (eeData[57] & 0xFC00) >> 10; if (alphaSP[1] > 31) { alphaSP[1] = alphaSP[1] - 64; } alphaSP[1] = (1 + alphaSP[1]/128) * alphaSP[0]; _cpKta = (eeData[59] & 0x00FF); if (_cpKta > 127) { _cpKta = _cpKta - 256; } ktaScale1 = ((eeData[56] & 0x00F0) >> 4) + 8; mlx90640->cpKta = _cpKta / pow(2,(double)ktaScale1); _cpKv = (eeData[59] & 0xFF00) >> 8; if (_cpKv > 127) { _cpKv = _cpKv - 256; } kvScale = (eeData[56] & 0x0F00) >> 8; mlx90640->cpKv = _cpKv / pow(2,(double)kvScale); mlx90640->cpAlpha[0] = alphaSP[0]; mlx90640->cpAlpha[1] = alphaSP[1]; mlx90640->cpOffset[0] = offsetSP[0]; mlx90640->cpOffset[1] = offsetSP[1]; } void MLX90640::ExtractCILCParameters(uint16_t *eeData, MLX90640 *mlx90640) { float _ilChessC[3]; uint8_t calibrationModeEE; calibrationModeEE = (eeData[10] & 0x0800) >> 4; calibrationModeEE = calibrationModeEE ^ 0x80; _ilChessC[0] = (eeData[53] & 0x003F); if (_ilChessC[0] > 31) { _ilChessC[0] = _ilChessC[0] - 64; } _ilChessC[0] = _ilChessC[0] / 16.0f; _ilChessC[1] = (eeData[53] & 0x07C0) >> 6; if (_ilChessC[1] > 15) { _ilChessC[1] = _ilChessC[1] - 32; } _ilChessC[1] = _ilChessC[1] / 2.0f; _ilChessC[2] = (eeData[53] & 0xF800) >> 11; if (_ilChessC[2] > 15) { _ilChessC[2] = _ilChessC[2] - 32; } _ilChessC[2] = _ilChessC[2] / 8.0f; mlx90640->calibrationModeEE = calibrationModeEE; mlx90640->ilChessC[0] = _ilChessC[0]; mlx90640->ilChessC[1] = _ilChessC[1]; mlx90640->ilChessC[2] = _ilChessC[2]; } int MLX90640::ExtractDeviatingPixels(uint16_t *eeData, MLX90640 *mlx90640) { uint16_t pixCnt = 0; uint16_t brokenPixCnt = 0; uint16_t outlierPixCnt = 0; int warn = 0; int i; for(pixCnt = 0; pixCnt<5; pixCnt++) { mlx90640->brokenPixels[pixCnt] = 0xFFFF; mlx90640->outlierPixels[pixCnt] = 0xFFFF; } pixCnt = 0; while (pixCnt < 768 && brokenPixCnt < 5 && outlierPixCnt < 5) { if(eeData[pixCnt+64] == 0) { mlx90640->brokenPixels[brokenPixCnt] = pixCnt; brokenPixCnt = brokenPixCnt + 1; } else if((eeData[pixCnt+64] & 0x0001) != 0) { mlx90640->outlierPixels[outlierPixCnt] = pixCnt; outlierPixCnt = outlierPixCnt + 1; } pixCnt = pixCnt + 1; } if(brokenPixCnt > 4) { warn = -3; } else if(outlierPixCnt > 4) { warn = -4; } else if((brokenPixCnt + outlierPixCnt) > 4) { warn = -5; } else { for(pixCnt=0; pixCntbrokenPixels[pixCnt],mlx90640->brokenPixels[i]); if(warn != 0) { return warn; } } } for(pixCnt=0; pixCntoutlierPixels[pixCnt],mlx90640->outlierPixels[i]); if(warn != 0) { return warn; } } } for(pixCnt=0; pixCntbrokenPixels[pixCnt],mlx90640->outlierPixels[i]); if(warn != 0) { return warn; } } } } return warn; } // Bad Pixel int MLX90640::CheckAdjacentPixels(uint16_t pix1, uint16_t pix2) { int pixPosDif; pixPosDif = pix1 - pix2; if(pixPosDif > -34 && pixPosDif < -30) { return -6; } if(pixPosDif > -2 && pixPosDif < 2) { return -6; } if(pixPosDif > 30 && pixPosDif < 34) { return -6; } return 0; } float MLX90640::GetMedian(float *values, int n) { float temp; for(int i=0; ioutlierPixels[i] || pixel == params->brokenPixels[i]) { return 1; } } return 0; } ",16327,True,3033.395140997642,median "//===--- CodeCompletion.cpp - Code completion implementation --------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include ""swift/IDE/CodeCompletion.h"" #include ""CodeCompletionDiagnostics.h"" #include ""CodeCompletionResultBuilder.h"" #include ""ExprContextAnalysis.h"" #include ""swift/AST/ASTPrinter.h"" #include ""swift/AST/ASTWalker.h"" #include ""swift/AST/Comment.h"" #include ""swift/AST/GenericSignature.h"" #include ""swift/AST/ImportCache.h"" #include ""swift/AST/Initializer.h"" #include ""swift/AST/LazyResolver.h"" #include ""swift/AST/NameLookup.h"" #include ""swift/AST/ParameterList.h"" #include ""swift/AST/ProtocolConformance.h"" #include ""swift/AST/SourceFile.h"" #include ""swift/AST/SubstitutionMap.h"" #include ""swift/AST/USRGeneration.h"" #include ""swift/Basic/Defer.h"" #include ""swift/Basic/LLVM.h"" #include ""swift/ClangImporter/ClangImporter.h"" #include ""swift/ClangImporter/ClangModule.h"" #include ""swift/Frontend/FrontendOptions.h"" #include ""swift/IDE/CodeCompletionCache.h"" #include ""swift/IDE/CodeCompletionConsumer.h"" #include ""swift/IDE/CodeCompletionResultPrinter.h"" #include ""swift/IDE/CodeCompletionStringPrinter.h"" #include ""swift/IDE/CompletionLookup.h"" #include ""swift/IDE/CompletionOverrideLookup.h"" #include ""swift/IDE/DotExprCompletion.h"" #include ""swift/IDE/KeyPathCompletion.h"" #include ""swift/IDE/UnresolvedMemberCompletion.h"" #include ""swift/IDE/Utils.h"" #include ""swift/Parse/CodeCompletionCallbacks.h"" #include ""swift/Sema/CodeCompletionTypeChecking.h"" #include ""swift/Sema/IDETypeChecking.h"" #include ""swift/Strings.h"" #include ""swift/Subsystems.h"" #include ""swift/Syntax/SyntaxKind.h"" #include ""clang/AST/ASTContext.h"" #include ""clang/AST/Attr.h"" #include ""clang/AST/Comment.h"" #include ""clang/AST/CommentVisitor.h"" #include ""clang/AST/Decl.h"" #include ""clang/Basic/Module.h"" #include ""clang/Index/USRGeneration.h"" #include ""llvm/ADT/SmallString.h"" #include ""llvm/ADT/StringRef.h"" #include ""llvm/Support/Compiler.h"" #include ""llvm/Support/SaveAndRestore.h"" #include ""llvm/Support/raw_ostream.h"" #include #include using namespace swift; using namespace ide; std::string swift::ide::removeCodeCompletionTokens( StringRef Input, StringRef TokenName, unsigned *CompletionOffset) { assert(TokenName.size() >= 1); *CompletionOffset = ~0U; std::string CleanFile; CleanFile.reserve(Input.size()); const std::string Token = std::string(""#^"") + TokenName.str() + ""^#""; for (const char *Ptr = Input.begin(), *End = Input.end(); Ptr != End; ++Ptr) { const char C = *Ptr; if (C == '#' && Ptr <= End - Token.size() && StringRef(Ptr, Token.size()) == Token) { Ptr += Token.size() - 1; *CompletionOffset = CleanFile.size(); CleanFile += '\\0'; continue; } if (C == '#' && Ptr <= End - 2 && Ptr[1] == '^') { do { ++Ptr; } while (Ptr < End && *Ptr != '#'); if (Ptr == End) break; continue; } CleanFile += C; } return CleanFile; } namespace { class CodeCompletionCallbacksImpl : public CodeCompletionCallbacks { CodeCompletionContext &CompletionContext; CodeCompletionConsumer &Consumer; CodeCompletionExpr *CodeCompleteTokenExpr = nullptr; CompletionKind Kind = CompletionKind::None; Expr *ParsedExpr = nullptr; SourceLoc DotLoc; TypeLoc ParsedTypeLoc; DeclContext *CurDeclContext = nullptr; DeclAttrKind AttrKind; /// In situations when \\c SyntaxKind hints or determines /// completions, i.e. a precedence group attribute, this /// can be set and used to control the code completion scenario. SyntaxKind SyntxKind; int AttrParamIndex; bool IsInSil = false; bool HasSpace = false; bool ShouldCompleteCallPatternAfterParen = true; bool PreferFunctionReferencesToCalls = false; bool AttTargetIsIndependent = false; bool IsAtStartOfLine = false; Optional AttTargetDK; Optional ParentStmtKind; SmallVector ParsedKeywords; SourceLoc introducerLoc; std::vector> SubModuleNameVisibilityPairs; Optional> typeCheckParsedExpr() { assert(ParsedExpr && ""should have an expression""); // Figure out the kind of type-check we'll be performing. auto CheckKind = CompletionTypeCheckKind::Normal; if (Kind == CompletionKind::KeyPathExprObjC) CheckKind = CompletionTypeCheckKind::KeyPath; // If we've already successfully type-checked the expression for some // reason, just return the type. // FIXME: if it's ErrorType but we've already typechecked we shouldn't // typecheck again. rdar://21466394 if (CheckKind == CompletionTypeCheckKind::Normal && ParsedExpr->getType() && !ParsedExpr->getType()->is()) { return getReferencedDecl(ParsedExpr); } ConcreteDeclRef ReferencedDecl = nullptr; Expr *ModifiedExpr = ParsedExpr; if (auto T = getTypeOfCompletionContextExpr(P.Context, CurDeclContext, CheckKind, ModifiedExpr, ReferencedDecl)) { // FIXME: even though we don't apply the solution, the type checker may // modify the original expression. We should understand what effect that // may have on code completion. ParsedExpr = ModifiedExpr; return std::make_pair(*T, ReferencedDecl); } return None; } /// \\returns true on success, false on failure. bool typecheckParsedType() { assert(ParsedTypeLoc.getTypeRepr() && ""should have a TypeRepr""); if (ParsedTypeLoc.wasValidated() && !ParsedTypeLoc.isError()) { return true; } const auto ty = swift::performTypeResolution( ParsedTypeLoc.getTypeRepr(), P.Context, /*isSILMode=*/false, /*isSILType=*/false, CurDeclContext->getGenericEnvironmentOfContext(), /*GenericParams=*/nullptr, CurDeclContext, /*ProduceDiagnostics=*/false); if (!ty->hasError()) { ParsedTypeLoc.setType(CurDeclContext->mapTypeIntoContext(ty)); return true; } ParsedTypeLoc.setType(ty); // It doesn't type check as a type, so see if it's a qualifying module name. if (auto *ITR = dyn_cast(ParsedTypeLoc.getTypeRepr())) { const auto &componentRange = ITR->getComponentRange(); // If it has more than one component, it can't be a module name. if (std::distance(componentRange.begin(), componentRange.end()) != 1) return false; const auto &component = componentRange.front(); ImportPath::Module::Builder builder( component->getNameRef().getBaseIdentifier(), component->getLoc()); if (auto Module = Context.getLoadedModule(builder.get())) ParsedTypeLoc.setType(ModuleType::get(Module)); return true; } return false; } public: CodeCompletionCallbacksImpl(Parser &P, CodeCompletionContext &CompletionContext, CodeCompletionConsumer &Consumer) : CodeCompletionCallbacks(P), CompletionContext(CompletionContext), Consumer(Consumer) { } void setAttrTargetDeclKind(Optional DK) override { if (DK == DeclKind::PatternBinding) DK = DeclKind::Var; else if (DK == DeclKind::Param) // For params, consider the attribute is always for the decl. AttTargetIsIndependent = false; if (!AttTargetIsIndependent) AttTargetDK = DK; } void completeDotExpr(CodeCompletionExpr *E, SourceLoc DotLoc) override; void completeStmtOrExpr(CodeCompletionExpr *E) override; void completePostfixExprBeginning(CodeCompletionExpr *E) override; void completeForEachSequenceBeginning(CodeCompletionExpr *E) override; void completePostfixExpr(Expr *E, bool hasSpace) override; void completePostfixExprParen(Expr *E, Expr *CodeCompletionE) override; void completeExprKeyPath(KeyPathExpr *KPE, SourceLoc DotLoc) override; void completeTypeDeclResultBeginning() override; void completeTypeSimpleBeginning() override; void completeTypeIdentifierWithDot(IdentTypeRepr *ITR) override; void completeTypeIdentifierWithoutDot(IdentTypeRepr *ITR) override; void completeCaseStmtKeyword() override; void completeCaseStmtBeginning(CodeCompletionExpr *E) override; void completeDeclAttrBeginning(bool Sil, bool isIndependent) override; void completeDeclAttrParam(DeclAttrKind DK, int Index) override; void completeEffectsSpecifier(bool hasAsync, bool hasThrows) override; void completeInPrecedenceGroup(SyntaxKind SK) override; void completeNominalMemberBeginning( SmallVectorImpl &Keywords, SourceLoc introducerLoc) override; void completeAccessorBeginning(CodeCompletionExpr *E) override; void completePoundAvailablePlatform() override; void completeImportDecl(ImportPath::Builder &Path) override; void completeUnresolvedMember(CodeCompletionExpr *E, SourceLoc DotLoc) override; void completeCallArg(CodeCompletionExpr *E, bool isFirst) override; void completeLabeledTrailingClosure(CodeCompletionExpr *E, bool isAtStartOfLine) override; bool canPerformCompleteLabeledTrailingClosure() const override { return true; } void completeReturnStmt(CodeCompletionExpr *E) override; void completeYieldStmt(CodeCompletionExpr *E, Optional yieldIndex) override; void completeAfterPoundExpr(CodeCompletionExpr *E, Optional ParentKind) override; void completeAfterPoundDirective() override; void completePlatformCondition() override; void completeGenericRequirement() override; void completeAfterIfStmt(bool hasElse) override; void completeStmtLabel(StmtKind ParentKind) override; void completeForEachPatternBeginning(bool hasTry, bool hasAwait) override; void completeTypeAttrBeginning() override; void doneParsing() override; private: void addKeywords(CodeCompletionResultSink &Sink, bool MaybeFuncBody); bool trySolverCompletion(bool MaybeFuncBody); }; } // end anonymous namespace static void addSelectorModifierKeywords(CodeCompletionResultSink &sink) { auto addKeyword = [&](StringRef Name, CodeCompletionKeywordKind Kind) { CodeCompletionResultBuilder Builder(sink, CodeCompletionResultKind::Keyword, SemanticContextKind::None); Builder.setKeywordKind(Kind); Builder.addTextChunk(Name); Builder.addCallParameterColon(); Builder.addSimpleTypedParameter(""@objc property"", /*IsVarArg=*/false); }; addKeyword(""getter"", CodeCompletionKeywordKind::None); addKeyword(""setter"", CodeCompletionKeywordKind::None); } void CodeCompletionCallbacksImpl::completeDotExpr(CodeCompletionExpr *E, SourceLoc DotLoc) { assert(P.Tok.is(tok::code_complete)); // Don't produce any results in an enum element. if (InEnumElementRawValue) return; Kind = CompletionKind::DotExpr; if (ParseExprSelectorContext != ObjCSelectorContext::None) { PreferFunctionReferencesToCalls = true; CompleteExprSelectorContext = ParseExprSelectorContext; } ParsedExpr = E->getBase(); this->DotLoc = DotLoc; CurDeclContext = P.CurDeclContext; CodeCompleteTokenExpr = E; } void CodeCompletionCallbacksImpl::completeStmtOrExpr(CodeCompletionExpr *E) { assert(P.Tok.is(tok::code_complete)); Kind = CompletionKind::StmtOrExpr; CurDeclContext = P.CurDeclContext; CodeCompleteTokenExpr = E; } void CodeCompletionCallbacksImpl::completePostfixExprBeginning(CodeCompletionExpr *E) { assert(P.Tok.is(tok::code_complete)); // Don't produce any results in an enum element. if (InEnumElementRawValue) return; Kind = CompletionKind::PostfixExprBeginning; if (ParseExprSelectorContext != ObjCSelectorContext::None) { PreferFunctionReferencesToCalls = true; CompleteExprSelectorContext = ParseExprSelectorContext; if (CompleteExprSelectorContext == ObjCSelectorContext::MethodSelector) { addSelectorModifierKeywords(CompletionContext.getResultSink()); } } CurDeclContext = P.CurDeclContext; CodeCompleteTokenExpr = E; } void CodeCompletionCallbacksImpl::completeForEachSequenceBeginning( CodeCompletionExpr *E) { assert(P.Tok.is(tok::code_complete)); Kind = CompletionKind::ForEachSequence; CurDeclContext = P.CurDeclContext; CodeCompleteTokenExpr = E; } void CodeCompletionCallbacksImpl::completePostfixExpr(Expr *E, bool hasSpace) { assert(P.Tok.is(tok::code_complete)); // Don't produce any results in an enum element. if (InEnumElementRawValue) return; HasSpace = hasSpace; Kind = CompletionKind::PostfixExpr; if (ParseExprSelectorContext != ObjCSelectorContext::None) { PreferFunctionReferencesToCalls = true; CompleteExprSelectorContext = ParseExprSelectorContext; } ParsedExpr = E; CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completePostfixExprParen(Expr *E, Expr *CodeCompletionE) { assert(P.Tok.is(tok::code_complete)); // Don't produce any results in an enum element. if (InEnumElementRawValue) return; Kind = CompletionKind::PostfixExprParen; ParsedExpr = E; CurDeclContext = P.CurDeclContext; CodeCompleteTokenExpr = static_cast(CodeCompletionE); ShouldCompleteCallPatternAfterParen = true; if (CompletionContext.getCallPatternHeuristics()) { // Lookahead one token to decide what kind of call completions to provide. // When it appears that there is already code for the call present, just // complete values and/or argument labels. Otherwise give the entire call // pattern. Token next = P.peekToken(); if (!next.isAtStartOfLine() && !next.is(tok::eof) && !next.is(tok::r_paren)) { ShouldCompleteCallPatternAfterParen = false; } } } void CodeCompletionCallbacksImpl::completeExprKeyPath(KeyPathExpr *KPE, SourceLoc DotLoc) { Kind = (!KPE || KPE->isObjC()) ? CompletionKind::KeyPathExprObjC : CompletionKind::KeyPathExprSwift; ParsedExpr = KPE; this->DotLoc = DotLoc; CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completePoundAvailablePlatform() { Kind = CompletionKind::PoundAvailablePlatform; CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completeTypeDeclResultBeginning() { Kind = CompletionKind::TypeDeclResultBeginning; CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completeTypeSimpleBeginning() { Kind = CompletionKind::TypeSimpleBeginning; CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completeDeclAttrParam(DeclAttrKind DK, int Index) { Kind = CompletionKind::AttributeDeclParen; AttrKind = DK; AttrParamIndex = Index; CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completeEffectsSpecifier(bool hasAsync, bool hasThrows) { Kind = CompletionKind::EffectsSpecifier; CurDeclContext = P.CurDeclContext; ParsedKeywords.clear(); if (hasAsync) ParsedKeywords.emplace_back(""async""); if (hasThrows) ParsedKeywords.emplace_back(""throws""); } void CodeCompletionCallbacksImpl::completeDeclAttrBeginning( bool Sil, bool isIndependent) { Kind = CompletionKind::AttributeBegin; IsInSil = Sil; CurDeclContext = P.CurDeclContext; AttTargetIsIndependent = isIndependent; } void CodeCompletionCallbacksImpl::completeInPrecedenceGroup(SyntaxKind SK) { assert(P.Tok.is(tok::code_complete)); SyntxKind = SK; Kind = CompletionKind::PrecedenceGroup; CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completeTypeIdentifierWithDot( IdentTypeRepr *ITR) { if (!ITR) { completeTypeSimpleBeginning(); return; } Kind = CompletionKind::TypeIdentifierWithDot; ParsedTypeLoc = TypeLoc(ITR); CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completeTypeIdentifierWithoutDot( IdentTypeRepr *ITR) { assert(ITR); Kind = CompletionKind::TypeIdentifierWithoutDot; ParsedTypeLoc = TypeLoc(ITR); CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completeCaseStmtKeyword() { Kind = CompletionKind::CaseStmtKeyword; CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completeCaseStmtBeginning(CodeCompletionExpr *E) { assert(!InEnumElementRawValue); Kind = CompletionKind::CaseStmtBeginning; CurDeclContext = P.CurDeclContext; CodeCompleteTokenExpr = E; } void CodeCompletionCallbacksImpl::completeImportDecl( ImportPath::Builder &Path) { Kind = CompletionKind::Import; CurDeclContext = P.CurDeclContext; DotLoc = Path.empty() ? SourceLoc() : Path.back().Loc; if (DotLoc.isInvalid()) return; auto Importer = static_cast(CurDeclContext->getASTContext(). getClangModuleLoader()); std::vector SubNames; Importer->collectSubModuleNames(Path.get().getModulePath(false), SubNames); ASTContext &Ctx = CurDeclContext->getASTContext(); Path.push_back(Identifier()); for (StringRef Sub : SubNames) { Path.back().Item = Ctx.getIdentifier(Sub); SubModuleNameVisibilityPairs.push_back( std::make_pair(Sub.str(), Ctx.getLoadedModule(Path.get().getModulePath(false)))); } Path.pop_back(); } void CodeCompletionCallbacksImpl::completeUnresolvedMember(CodeCompletionExpr *E, SourceLoc DotLoc) { Kind = CompletionKind::UnresolvedMember; CurDeclContext = P.CurDeclContext; CodeCompleteTokenExpr = E; this->DotLoc = DotLoc; } void CodeCompletionCallbacksImpl::completeCallArg(CodeCompletionExpr *E, bool isFirst) { CurDeclContext = P.CurDeclContext; CodeCompleteTokenExpr = E; Kind = CompletionKind::CallArg; ShouldCompleteCallPatternAfterParen = false; if (isFirst) { ShouldCompleteCallPatternAfterParen = true; if (CompletionContext.getCallPatternHeuristics()) { // Lookahead one token to decide what kind of call completions to provide. // When it appears that there is already code for the call present, just // complete values and/or argument labels. Otherwise give the entire call // pattern. Token next = P.peekToken(); if (!next.isAtStartOfLine() && !next.is(tok::eof) && !next.is(tok::r_paren)) { ShouldCompleteCallPatternAfterParen = false; } } } } void CodeCompletionCallbacksImpl::completeLabeledTrailingClosure( CodeCompletionExpr *E, bool isAtStartOfLine) { CurDeclContext = P.CurDeclContext; CodeCompleteTokenExpr = E; Kind = CompletionKind::LabeledTrailingClosure; IsAtStartOfLine = isAtStartOfLine; } void CodeCompletionCallbacksImpl::completeReturnStmt(CodeCompletionExpr *E) { CurDeclContext = P.CurDeclContext; CodeCompleteTokenExpr = E; Kind = CompletionKind::ReturnStmtExpr; } void CodeCompletionCallbacksImpl::completeYieldStmt(CodeCompletionExpr *E, Optional index) { CurDeclContext = P.CurDeclContext; CodeCompleteTokenExpr = E; // TODO: use a different completion kind when completing without an index // in a multiple-value context. Kind = CompletionKind::YieldStmtExpr; } void CodeCompletionCallbacksImpl::completeAfterPoundExpr( CodeCompletionExpr *E, Optional ParentKind) { CurDeclContext = P.CurDeclContext; CodeCompleteTokenExpr = E; Kind = CompletionKind::AfterPoundExpr; ParentStmtKind = ParentKind; } void CodeCompletionCallbacksImpl::completeAfterPoundDirective() { CurDeclContext = P.CurDeclContext; Kind = CompletionKind::AfterPoundDirective; } void CodeCompletionCallbacksImpl::completePlatformCondition() { CurDeclContext = P.CurDeclContext; Kind = CompletionKind::PlatformConditon; } void CodeCompletionCallbacksImpl::completeAfterIfStmt(bool hasElse) { CurDeclContext = P.CurDeclContext; if (hasElse) { Kind = CompletionKind::AfterIfStmtElse; } else { Kind = CompletionKind::StmtOrExpr; } } void CodeCompletionCallbacksImpl::completeGenericRequirement() { CurDeclContext = P.CurDeclContext; Kind = CompletionKind::GenericRequirement; } void CodeCompletionCallbacksImpl::completeNominalMemberBeginning( SmallVectorImpl &Keywords, SourceLoc introducerLoc) { assert(!InEnumElementRawValue); this->introducerLoc = introducerLoc; ParsedKeywords.clear(); ParsedKeywords.append(Keywords.begin(), Keywords.end()); Kind = CompletionKind::NominalMemberBeginning; CurDeclContext = P.CurDeclContext; } void CodeCompletionCallbacksImpl::completeAccessorBeginning( CodeCompletionExpr *E) { Kind = CompletionKind::AccessorBeginning; CurDeclContext = P.CurDeclContext; CodeCompleteTokenExpr = E; } void CodeCompletionCallbacksImpl::completeStmtLabel(StmtKind ParentKind) { CurDeclContext = P.CurDeclContext; Kind = CompletionKind::StmtLabel; ParentStmtKind = ParentKind; } void CodeCompletionCallbacksImpl::completeForEachPatternBeginning( bool hasTry, bool hasAwait) { CurDeclContext = P.CurDeclContext; Kind = CompletionKind::ForEachPatternBeginning; ParsedKeywords.clear(); if (hasTry) ParsedKeywords.emplace_back(""try""); if (hasAwait) ParsedKeywords.emplace_back(""await""); } void CodeCompletionCallbacksImpl::completeTypeAttrBeginning() { CurDeclContext = P.CurDeclContext; Kind = CompletionKind::TypeAttrBeginning; } bool swift::ide::isDynamicLookup(Type T) { return T->getRValueType()->isAnyObject(); } static bool isClangSubModule(ModuleDecl *TheModule) { if (auto ClangMod = TheModule->findUnderlyingClangModule()) return ClangMod->isSubModule(); return false; } static void addKeyword(CodeCompletionResultSink &Sink, StringRef Name, CodeCompletionKeywordKind Kind, StringRef TypeAnnotation = """", CodeCompletionFlair Flair = {}) { CodeCompletionResultBuilder Builder(Sink, CodeCompletionResultKind::Keyword, SemanticContextKind::None); Builder.setKeywordKind(Kind); Builder.addKeyword(Name); Builder.addFlair(Flair); if (!TypeAnnotation.empty()) Builder.addTypeAnnotation(TypeAnnotation); Builder.setResultTypeNotApplicable(); } static void addDeclKeywords(CodeCompletionResultSink &Sink, DeclContext *DC, bool IsConcurrencyEnabled) { auto isTypeDeclIntroducer = [](CodeCompletionKeywordKind Kind, Optional DAK) -> bool { switch (Kind) { case CodeCompletionKeywordKind::kw_protocol: case CodeCompletionKeywordKind::kw_class: case CodeCompletionKeywordKind::kw_struct: case CodeCompletionKeywordKind::kw_enum: case CodeCompletionKeywordKind::kw_extension: return true; case CodeCompletionKeywordKind::None: if (DAK && *DAK == DeclAttrKind::DAK_Actor) { return true; } break; default: break; } return false; }; auto isTopLevelOnlyDeclIntroducer = [](CodeCompletionKeywordKind Kind, Optional DAK) -> bool { switch (Kind) { case CodeCompletionKeywordKind::kw_operator: case CodeCompletionKeywordKind::kw_precedencegroup: case CodeCompletionKeywordKind::kw_import: case CodeCompletionKeywordKind::kw_protocol: case CodeCompletionKeywordKind::kw_extension: return true; default: return false; } }; auto getFlair = [&](CodeCompletionKeywordKind Kind, Optional DAK) -> CodeCompletionFlair { if (isCodeCompletionAtTopLevelOfLibraryFile(DC)) { // Type decls are common in library file top-level. if (isTypeDeclIntroducer(Kind, DAK)) return CodeCompletionFlairBit::CommonKeywordAtCurrentPosition; } if (isa(DC)) { // Protocols cannot have nested type decls (other than 'typealias'). if (isTypeDeclIntroducer(Kind, DAK)) return CodeCompletionFlairBit::RareKeywordAtCurrentPosition; } if (DC->isTypeContext()) { // Top-level only decls are invalid in type context. if (isTopLevelOnlyDeclIntroducer(Kind, DAK)) return CodeCompletionFlairBit::RareKeywordAtCurrentPosition; } if (isCompletionDeclContextLocalContext(DC)) { // Local type decl are valid, but not common. if (isTypeDeclIntroducer(Kind, DAK)) return CodeCompletionFlairBit::RareKeywordAtCurrentPosition; // Top-level only decls are invalid in function body. if (isTopLevelOnlyDeclIntroducer(Kind, DAK)) return CodeCompletionFlairBit::RareKeywordAtCurrentPosition; // 'init', 'deinit' and 'subscript' are invalid in function body. // Access control modifiers are invalid in function body. switch (Kind) { case CodeCompletionKeywordKind::kw_init: case CodeCompletionKeywordKind::kw_deinit: case CodeCompletionKeywordKind::kw_subscript: case CodeCompletionKeywordKind::kw_private: case CodeCompletionKeywordKind::kw_fileprivate: case CodeCompletionKeywordKind::kw_internal: case CodeCompletionKeywordKind::kw_public: case CodeCompletionKeywordKind::kw_static: return CodeCompletionFlairBit::RareKeywordAtCurrentPosition; default: break; } // These modifiers are invalid for decls in function body. if (DAK) { switch (*DAK) { case DeclAttrKind::DAK_Lazy: case DeclAttrKind::DAK_Final: case DeclAttrKind::DAK_Infix: case DeclAttrKind::DAK_Frozen: case DeclAttrKind::DAK_Prefix: case DeclAttrKind::DAK_Postfix: case DeclAttrKind::DAK_Dynamic: case DeclAttrKind::DAK_Override: case DeclAttrKind::DAK_Optional: case DeclAttrKind::DAK_Required: case DeclAttrKind::DAK_Convenience: case DeclAttrKind::DAK_AccessControl: case DeclAttrKind::DAK_Nonisolated: return CodeCompletionFlairBit::RareKeywordAtCurrentPosition; default: break; } } } return None; }; auto AddDeclKeyword = [&](StringRef Name, CodeCompletionKeywordKind Kind, Optional DAK) { if (Name == ""let"" || Name == ""var"") { // Treat keywords that could be the start of a pattern specially. return; } // FIXME: This should use canUseAttributeOnDecl. // Remove user inaccessible keywords. if (DAK.hasValue() && DeclAttribute::isUserInaccessible(*DAK)) return; // Remove keywords only available when concurrency is enabled. if (DAK.hasValue() && !IsConcurrencyEnabled && DeclAttribute::isConcurrencyOnly(*DAK)) return; addKeyword(Sink, Name, Kind, /*TypeAnnotation=*/"""", getFlair(Kind, DAK)); }; #define DECL_KEYWORD(kw) \\ AddDeclKeyword(#kw, CodeCompletionKeywordKind::kw_##kw, None); #include ""swift/Syntax/TokenKinds.def"" // Context-sensitive keywords. auto AddCSKeyword = [&](StringRef Name, DeclAttrKind Kind) { AddDeclKeyword(Name, CodeCompletionKeywordKind::None, Kind); }; #define CONTEXTUAL_CASE(KW, CLASS) AddCSKeyword(#KW, DAK_##CLASS); #define CONTEXTUAL_DECL_ATTR(KW, CLASS, ...) CONTEXTUAL_CASE(KW, CLASS) #define CONTEXTUAL_DECL_ATTR_ALIAS(KW, CLASS) CONTEXTUAL_CASE(KW, CLASS) #define CONTEXTUAL_SIMPLE_DECL_ATTR(KW, CLASS, ...) CONTEXTUAL_CASE(KW, CLASS) #include #undef CONTEXTUAL_CASE } static void addStmtKeywords(CodeCompletionResultSink &Sink, DeclContext *DC, bool MaybeFuncBody) { CodeCompletionFlair flair; // Starting a statement at top-level in non-script files is invalid. if (isCodeCompletionAtTopLevelOfLibraryFile(DC)) { flair |= CodeCompletionFlairBit::ExpressionAtNonScriptOrMainFileScope; } auto AddStmtKeyword = [&](StringRef Name, CodeCompletionKeywordKind Kind) { if (!MaybeFuncBody && Kind == CodeCompletionKeywordKind::kw_return) return; addKeyword(Sink, Name, Kind, """", flair); }; #define STMT_KEYWORD(kw) AddStmtKeyword(#kw, CodeCompletionKeywordKind::kw_##kw); #include ""swift/Syntax/TokenKinds.def"" } static void addCaseStmtKeywords(CodeCompletionResultSink &Sink) { addKeyword(Sink, ""case"", CodeCompletionKeywordKind::kw_case); addKeyword(Sink, ""default"", CodeCompletionKeywordKind::kw_default); } static void addLetVarKeywords(CodeCompletionResultSink &Sink) { addKeyword(Sink, ""let"", CodeCompletionKeywordKind::kw_let); addKeyword(Sink, ""var"", CodeCompletionKeywordKind::kw_var); } static void addAccessorKeywords(CodeCompletionResultSink &Sink) { addKeyword(Sink, ""get"", CodeCompletionKeywordKind::None); addKeyword(Sink, ""set"", CodeCompletionKeywordKind::None); } static void addObserverKeywords(CodeCompletionResultSink &Sink) { addKeyword(Sink, ""willSet"", CodeCompletionKeywordKind::None); addKeyword(Sink, ""didSet"", CodeCompletionKeywordKind::None); } static void addExprKeywords(CodeCompletionResultSink &Sink, DeclContext *DC) { // Expression is invalid at top-level of non-script files. CodeCompletionFlair flair; if (isCodeCompletionAtTopLevelOfLibraryFile(DC)) { flair |= CodeCompletionFlairBit::ExpressionAtNonScriptOrMainFileScope; } // Expr keywords. addKeyword(Sink, ""try"", CodeCompletionKeywordKind::kw_try, """", flair); addKeyword(Sink, ""try!"", CodeCompletionKeywordKind::kw_try, """", flair); addKeyword(Sink, ""try?"", CodeCompletionKeywordKind::kw_try, """", flair); addKeyword(Sink, ""await"", CodeCompletionKeywordKind::None, """", flair); } static void addSuperKeyword(CodeCompletionResultSink &Sink, DeclContext *DC) { if (!DC) return; auto *TC = DC->getInnermostTypeContext(); if (!TC) return; auto *CD = TC->getSelfClassDecl(); if (!CD) return; Type ST = CD->getSuperclass(); if (ST.isNull() || ST->is()) return; CodeCompletionResultBuilder Builder(Sink, CodeCompletionResultKind::Keyword, SemanticContextKind::CurrentNominal); if (auto *AFD = dyn_cast(DC)) { if (AFD->getOverriddenDecl() != nullptr) { Builder.addFlair(CodeCompletionFlairBit::CommonKeywordAtCurrentPosition); } } Builder.setKeywordKind(CodeCompletionKeywordKind::kw_super); Builder.addKeyword(""super""); Builder.addTypeAnnotation(ST, PrintOptions()); } static void addOpaqueTypeKeyword(CodeCompletionResultSink &Sink) { addKeyword(Sink, ""some"", CodeCompletionKeywordKind::None, ""some""); } static void addAnyTypeKeyword(CodeCompletionResultSink &Sink, Type T) { CodeCompletionResultBuilder Builder(Sink, CodeCompletionResultKind::Keyword, SemanticContextKind::None); Builder.setKeywordKind(CodeCompletionKeywordKind::None); Builder.addKeyword(""Any""); Builder.addTypeAnnotation(T, PrintOptions()); } void CodeCompletionCallbacksImpl::addKeywords(CodeCompletionResultSink &Sink, bool MaybeFuncBody) { switch (Kind) { case CompletionKind::None: case CompletionKind::DotExpr: case CompletionKind::AttributeDeclParen: case CompletionKind::AttributeBegin: case CompletionKind::PoundAvailablePlatform: case CompletionKind::Import: case CompletionKind::UnresolvedMember: case CompletionKind::LabeledTrailingClosure: case CompletionKind::AfterPoundExpr: case CompletionKind::AfterPoundDirective: case CompletionKind::PlatformConditon: case CompletionKind::GenericRequirement: case CompletionKind::KeyPathExprObjC: case CompletionKind::KeyPathExprSwift: case CompletionKind::PrecedenceGroup: case CompletionKind::StmtLabel: case CompletionKind::TypeAttrBeginning: break; case CompletionKind::EffectsSpecifier: { if (!llvm::is_contained(ParsedKeywords, ""async"")) addKeyword(Sink, ""async"", CodeCompletionKeywordKind::None); if (!llvm::is_contained(ParsedKeywords, ""throws"")) addKeyword(Sink, ""throws"", CodeCompletionKeywordKind::kw_throws); break; } case CompletionKind::AccessorBeginning: { // TODO: Omit already declared or mutally exclusive accessors. // E.g. If 'get' is already declared, emit 'set' only. addAccessorKeywords(Sink); // Only 'var' for non-protocol context can have 'willSet' and 'didSet'. assert(ParsedDecl); VarDecl *var = dyn_cast(ParsedDecl); if (auto accessor = dyn_cast(ParsedDecl)) var = dyn_cast(accessor->getStorage()); if (var && !var->getDeclContext()->getSelfProtocolDecl()) addObserverKeywords(Sink); if (!isa(ParsedDecl)) break; MaybeFuncBody = true; LLVM_FALLTHROUGH; } case CompletionKind::StmtOrExpr: addDeclKeywords(Sink, CurDeclContext, Context.LangOpts.EnableExperimentalConcurrency); addStmtKeywords(Sink, CurDeclContext, MaybeFuncBody); LLVM_FALLTHROUGH; case CompletionKind::ReturnStmtExpr: case CompletionKind::YieldStmtExpr: case CompletionKind::PostfixExprBeginning: case CompletionKind::ForEachSequence: addSuperKeyword(Sink, CurDeclContext); addLetVarKeywords(Sink); addExprKeywords(Sink, CurDeclContext); addAnyTypeKeyword(Sink, CurDeclContext->getASTContext().TheAnyType); break; case CompletionKind::CallArg: case CompletionKind::PostfixExprParen: // Note that we don't add keywords here as the completion might be for // an argument list pattern. We instead add keywords later in // CodeCompletionCallbacksImpl::doneParsing when we know we're not // completing for a argument list pattern. break; case CompletionKind::CaseStmtKeyword: addCaseStmtKeywords(Sink); break; case CompletionKind::PostfixExpr: case CompletionKind::CaseStmtBeginning: case CompletionKind::TypeIdentifierWithDot: case CompletionKind::TypeIdentifierWithoutDot: break; case CompletionKind::TypeDeclResultBeginning: { auto DC = CurDeclContext; if (ParsedDecl && ParsedDecl == CurDeclContext->getAsDecl()) DC = ParsedDecl->getDeclContext(); if (!isa(DC)) if (DC->isTypeContext() || isa_and_nonnull(ParsedDecl)) addOpaqueTypeKeyword(Sink); LLVM_FALLTHROUGH; } case CompletionKind::TypeSimpleBeginning: addAnyTypeKeyword(Sink, CurDeclContext->getASTContext().TheAnyType); break; case CompletionKind::NominalMemberBeginning: { bool HasDeclIntroducer = llvm::find_if(ParsedKeywords, [this](const StringRef kw) { return llvm::StringSwitch(kw) .Case(""associatedtype"", true) .Case(""class"", !CurDeclContext || !isa(CurDeclContext)) .Case(""deinit"", true) .Case(""enum"", true) .Case(""extension"", true) .Case(""func"", true) .Case(""import"", true) .Case(""init"", true) .Case(""let"", true) .Case(""operator"", true) .Case(""precedencegroup"", true) .Case(""protocol"", true) .Case(""struct"", true) .Case(""subscript"", true) .Case(""typealias"", true) .Case(""var"", true) .Default(false); }) != ParsedKeywords.end(); if (!HasDeclIntroducer) { addDeclKeywords(Sink, CurDeclContext, Context.LangOpts.EnableExperimentalConcurrency); addLetVarKeywords(Sink); } break; } case CompletionKind::AfterIfStmtElse: addKeyword(Sink, ""if"", CodeCompletionKeywordKind::kw_if); break; case CompletionKind::ForEachPatternBeginning: if (!llvm::is_contained(ParsedKeywords, ""try"")) addKeyword(Sink, ""try"", CodeCompletionKeywordKind::kw_try); if (!llvm::is_contained(ParsedKeywords, ""await"")) addKeyword(Sink, ""await"", CodeCompletionKeywordKind::None); addKeyword(Sink, ""var"", CodeCompletionKeywordKind::kw_var); addKeyword(Sink, ""case"", CodeCompletionKeywordKind::kw_case); } } static void addPoundDirectives(CodeCompletionResultSink &Sink) { auto addWithName = [&](StringRef name, CodeCompletionKeywordKind K, llvm::function_ref consumer = nullptr) { CodeCompletionResultBuilder Builder(Sink, CodeCompletionResultKind::Keyword, SemanticContextKind::None); Builder.addBaseName(name); Builder.setKeywordKind(K); if (consumer) consumer(Builder); }; addWithName(""sourceLocation"", CodeCompletionKeywordKind::pound_sourceLocation, [&] (CodeCompletionResultBuilder &Builder) { Builder.addLeftParen(); Builder.addTextChunk(""file""); Builder.addCallParameterColon(); Builder.addSimpleTypedParameter(""String""); Builder.addComma(); Builder.addTextChunk(""line""); Builder.addCallParameterColon(); Builder.addSimpleTypedParameter(""Int""); Builder.addRightParen(); }); addWithName(""warning"", CodeCompletionKeywordKind::pound_warning, [&] (CodeCompletionResultBuilder &Builder) { Builder.addLeftParen(); Builder.addTextChunk(""\\""""); Builder.addSimpleNamedParameter(""message""); Builder.addTextChunk(""\\""""); Builder.addRightParen(); }); addWithName(""error"", CodeCompletionKeywordKind::pound_error, [&] (CodeCompletionResultBuilder &Builder) { Builder.addLeftParen(); Builder.addTextChunk(""\\""""); Builder.addSimpleNamedParameter(""message""); Builder.addTextChunk(""\\""""); Builder.addRightParen(); }); addWithName(""if "", CodeCompletionKeywordKind::pound_if, [&] (CodeCompletionResultBuilder &Builder) { Builder.addSimpleNamedParameter(""condition""); }); // FIXME: These directives are only valid in conditional completion block. addWithName(""elseif "", CodeCompletionKeywordKind::pound_elseif, [&] (CodeCompletionResultBuilder &Builder) { Builder.addSimpleNamedParameter(""condition""); }); addWithName(""else"", CodeCompletionKeywordKind::pound_else); addWithName(""endif"", CodeCompletionKeywordKind::pound_endif); } /// Add platform conditions used in '#if' and '#elseif' directives. static void addPlatformConditions(CodeCompletionResultSink &Sink) { auto addWithName = [&](StringRef Name, llvm::function_ref consumer) { CodeCompletionResultBuilder Builder( Sink, CodeCompletionResultKind::Pattern, // FIXME: SemanticContextKind::CurrentModule is not correct. // Use 'None' (and fix prioritization) or introduce a new context. SemanticContextKind::CurrentModule); Builder.addFlair(CodeCompletionFlairBit::ExpressionSpecific); Builder.addBaseName(Name); Builder.addLeftParen(); consumer(Builder); Builder.addRightParen(); }; addWithName(""os"", [](CodeCompletionResultBuilder &Builder) { Builder.addSimpleNamedParameter(""name""); }); addWithName(""arch"", [](CodeCompletionResultBuilder &Builder) { Builder.addSimpleNamedParameter(""name""); }); addWithName(""canImport"", [](CodeCompletionResultBuilder &Builder) { Builder.addSimpleNamedParameter(""module""); }); addWithName(""targetEnvironment"", [](CodeCompletionResultBuilder &Builder) { Builder.addTextChunk(""simulator""); }); addWithName(""swift"", [](CodeCompletionResultBuilder &Builder) { Builder.addTextChunk("">=""); Builder.addSimpleNamedParameter(""version""); }); addWithName(""swift"", [](CodeCompletionResultBuilder &Builder) { Builder.addTextChunk(""<""); Builder.addSimpleNamedParameter(""version""); }); addWithName(""compiler"", [](CodeCompletionResultBuilder &Builder) { Builder.addTextChunk("">=""); Builder.addSimpleNamedParameter(""version""); }); addWithName(""compiler"", [](CodeCompletionResultBuilder &Builder) { Builder.addTextChunk(""<""); Builder.addSimpleNamedParameter(""version""); }); addKeyword(Sink, ""true"", CodeCompletionKeywordKind::kw_true, ""Bool""); addKeyword(Sink, ""false"", CodeCompletionKeywordKind::kw_false, ""Bool""); } /// Add flags specified by '-D' to completion results. static void addConditionalCompilationFlags(ASTContext &Ctx, CodeCompletionResultSink &Sink) { for (auto Flag : Ctx.LangOpts.getCustomConditionalCompilationFlags()) { // TODO: Should we filter out some flags? CodeCompletionResultBuilder Builder( Sink, CodeCompletionResultKind::Keyword, // FIXME: SemanticContextKind::CurrentModule is not correct. // Use 'None' (and fix prioritization) or introduce a new context. SemanticContextKind::CurrentModule); Builder.addFlair(CodeCompletionFlairBit::ExpressionSpecific); Builder.addTextChunk(Flag); } } /// Add flairs to the each item in \\p results . /// /// If \\p Sink is passed, the pointer of the each result may be replaced with a /// pointer to the new item allocated in \\p Sink. /// If \\p Sink is nullptr, the pointee of each result may be modified in place. void swift::ide::postProcessCompletionResults( MutableArrayRef results, CompletionKind Kind, const DeclContext *DC, CodeCompletionResultSink *Sink) { for (CodeCompletionResult *&result : results) { bool modified = false; auto flair = result->getFlair(); // Starting a statement with a protocol name is not common. So protocol // names at non-type name position are ""rare"". if (result->getKind() == CodeCompletionResultKind::Declaration && result->getAssociatedDeclKind() == CodeCompletionDeclKind::Protocol && Kind != CompletionKind::TypeSimpleBeginning && Kind != CompletionKind::TypeIdentifierWithoutDot && Kind != CompletionKind::TypeIdentifierWithDot && Kind != CompletionKind::TypeDeclResultBeginning && Kind != CompletionKind::GenericRequirement) { flair |= CodeCompletionFlairBit::RareTypeAtCurrentPosition; modified = true; } // Starting a statement at top-level in non-script files is invalid. if (Kind == CompletionKind::StmtOrExpr && result->getKind() == CodeCompletionResultKind::Declaration && isCodeCompletionAtTopLevelOfLibraryFile(DC)) { flair |= CodeCompletionFlairBit::ExpressionAtNonScriptOrMainFileScope; modified = true; } if (!modified) continue; if (Sink) { // Replace the result with a new result with the flair. result = result->withFlair(flair, *Sink); } else { // 'Sink' == nullptr means the result is modifiable in place. result->setFlair(flair); } } } void swift::ide::deliverCompletionResults( CodeCompletionContext &CompletionContext, CompletionLookup &Lookup, DeclContext *DC, CodeCompletionConsumer &Consumer) { auto &SF = *DC->getParentSourceFile(); llvm::SmallPtrSet seenModuleNames; std::vector RequestedModules; SmallPtrSet explictlyImportedModules; { // Collect modules directly imported in this SourceFile. SmallVector directImport; SF.getImportedModules(directImport, {ModuleDecl::ImportFilterKind::Default, ModuleDecl::ImportFilterKind::ImplementationOnly}); for (auto import : directImport) explictlyImportedModules.insert(import.importedModule); // Exclude modules implicitly imported in the current module. auto implicitImports = SF.getParentModule()->getImplicitImports(); for (auto import : implicitImports.imports) explictlyImportedModules.erase(import.module.importedModule); // Consider the current module ""explicit"". explictlyImportedModules.insert(SF.getParentModule()); } for (auto &Request: Lookup.RequestedCachedResults) { llvm::DenseSet ImportsSeen; auto handleImport = [&](ImportedModule Import) { ModuleDecl *TheModule = Import.importedModule; ImportPath::Access Path = Import.accessPath; if (TheModule->getFiles().empty()) return; // Clang submodules are ignored and there's no lookup cost involved, // so just ignore them and don't put the empty results in the cache // because putting a lot of objects in the cache will push out // other lookups. if (isClangSubModule(TheModule)) return; std::vector AccessPath; for (auto Piece : Path) { AccessPath.push_back(std::string(Piece.Item)); } StringRef ModuleFilename = TheModule->getModuleFilename(); // ModuleFilename can be empty if something strange happened during // module loading, for example, the module file is corrupted. if (!ModuleFilename.empty()) { CodeCompletionCache::Key K{ ModuleFilename.str(), std::string(TheModule->getName()), AccessPath, Request.NeedLeadingDot, SF.hasTestableOrPrivateImport( AccessLevel::Internal, TheModule, SourceFile::ImportQueryKind::TestableOnly), SF.hasTestableOrPrivateImport( AccessLevel::Internal, TheModule, SourceFile::ImportQueryKind::PrivateOnly), CompletionContext.getAddInitsToTopLevel(), CompletionContext.addCallWithNoDefaultArgs(), CompletionContext.getAnnotateResult()}; using PairType = llvm::DenseSet>::iterator; std::pair Result = ImportsSeen.insert(K); if (!Result.second) return; // already handled. RequestedModules.push_back({std::move(K), TheModule, Request.OnlyTypes, Request.OnlyPrecedenceGroups}); auto TheModuleName = TheModule->getName(); if (Request.IncludeModuleQualifier && (!Lookup.isHiddenModuleName(TheModuleName) || explictlyImportedModules.contains(TheModule)) && seenModuleNames.insert(TheModuleName).second) Lookup.addModuleName(TheModule); } }; if (Request.TheModule) { // FIXME: actually check imports. for (auto Import : namelookup::getAllImports(Request.TheModule)) { handleImport(Import); } } else { // Add results from current module. Lookup.getToplevelCompletions(Request.OnlyTypes); // Add the qualifying module name auto curModule = SF.getParentModule(); if (Request.IncludeModuleQualifier && seenModuleNames.insert(curModule->getName()).second) Lookup.addModuleName(curModule); // Add results for all imported modules. SmallVector Imports; SF.getImportedModules( Imports, {ModuleDecl::ImportFilterKind::Exported, ModuleDecl::ImportFilterKind::Default, ModuleDecl::ImportFilterKind::ImplementationOnly}); for (auto Imported : Imports) { for (auto Import : namelookup::getAllImports(Imported.importedModule)) handleImport(Import); } } } Lookup.RequestedCachedResults.clear(); CompletionContext.typeContextKind = Lookup.typeContextKind(); postProcessCompletionResults(CompletionContext.getResultSink().Results, CompletionContext.CodeCompletionKind, DC, /*Sink=*/nullptr); Consumer.handleResultsAndModules(CompletionContext, RequestedModules, Lookup.getExpectedTypeContext(), DC); } bool CodeCompletionCallbacksImpl::trySolverCompletion(bool MaybeFuncBody) { assert(ParsedExpr || CurDeclContext); SourceLoc CompletionLoc = ParsedExpr ? ParsedExpr->getLoc() : CurDeclContext->getASTContext().SourceMgr.getCodeCompletionLoc(); switch (Kind) { case CompletionKind::DotExpr: { assert(CodeCompleteTokenExpr); assert(CurDeclContext); DotExprTypeCheckCompletionCallback Lookup(CodeCompleteTokenExpr); llvm::SaveAndRestore CompletionCollector(Context.CompletionCallback, &Lookup); typeCheckContextAt(CurDeclContext, CompletionLoc); // This (hopefully) only happens in cases where the expression isn't // typechecked during normal compilation either (e.g. member completion in a // switch case where there control expression is invalid). Having normal // typechecking still resolve even these cases would be beneficial for // tooling in general though. if (!Lookup.gotCallback()) Lookup.fallbackTypeCheck(CurDeclContext); addKeywords(CompletionContext.getResultSink(), MaybeFuncBody); Expr *CheckedBase = CodeCompleteTokenExpr->getBase(); Lookup.deliverResults(CheckedBase, CurDeclContext, DotLoc, isInsideObjCSelector(), CompletionContext, Consumer); return true; } case CompletionKind::UnresolvedMember: { assert(CodeCompleteTokenExpr); assert(CurDeclContext); UnresolvedMemberTypeCheckCompletionCallback Lookup(CodeCompleteTokenExpr); llvm::SaveAndRestore CompletionCollector(Context.CompletionCallback, &Lookup); typeCheckContextAt(CurDeclContext, CompletionLoc); if (!Lookup.gotCallback()) Lookup.fallbackTypeCheck(CurDeclContext); addKeywords(CompletionContext.getResultSink(), MaybeFuncBody); Lookup.deliverResults(CurDeclContext, DotLoc, CompletionContext, Consumer); return true; } case CompletionKind::KeyPathExprSwift: { assert(CurDeclContext); // CodeCompletionCallbacks::completeExprKeyPath takes a \\c KeyPathExpr, // so we can safely cast the \\c ParsedExpr back to a \\c KeyPathExpr. auto KeyPath = cast(ParsedExpr); KeyPathTypeCheckCompletionCallback Lookup(KeyPath); llvm::SaveAndRestore CompletionCollector( Context.CompletionCallback, &Lookup); typeCheckContextAt(CurDeclContext, CompletionLoc); Lookup.deliverResults(CurDeclContext, DotLoc, CompletionContext, Consumer); return true; } default: return false; } } // Undoes the single-expression closure/function body transformation on the // given DeclContext and its parent contexts if they have a single expression // body that contains the code completion location. // // FIXME: Remove this once all expression position completions are migrated // to work via TypeCheckCompletionCallback. static void undoSingleExpressionReturn(DeclContext *DC) { auto updateBody = [](BraceStmt *BS, ASTContext &Ctx) -> bool { ASTNode LastElem = BS->getLastElement(); auto *RS = dyn_cast_or_null(LastElem.dyn_cast()); if (!RS || !RS->isImplicit()) return false; BS->setLastElement(RS->getResult()); return true; }; while (ClosureExpr *CE = dyn_cast_or_null(DC)) { if (CE->hasSingleExpressionBody()) { if (updateBody(CE->getBody(), CE->getASTContext())) CE->setBody(CE->getBody(), false); } DC = DC->getParent(); } if (FuncDecl *FD = dyn_cast_or_null(DC)) { if (FD->hasSingleExpressionBody()) { if (updateBody(FD->getBody(), FD->getASTContext())) FD->setHasSingleExpressionBody(false); } } } void CodeCompletionCallbacksImpl::doneParsing() { CompletionContext.CodeCompletionKind = Kind; if (Kind == CompletionKind::None) { return; } bool MaybeFuncBody = true; if (CurDeclContext) { auto *CD = CurDeclContext->getLocalContext(); if (!CD || CD->getContextKind() == DeclContextKind::Initializer || CD->getContextKind() == DeclContextKind::TopLevelCodeDecl) MaybeFuncBody = false; } if (auto *DC = dyn_cast_or_null(ParsedDecl)) { if (DC->isChildContextOf(CurDeclContext)) CurDeclContext = DC; } if (trySolverCompletion(MaybeFuncBody)) return; undoSingleExpressionReturn(CurDeclContext); typeCheckContextAt( CurDeclContext, ParsedExpr ? ParsedExpr->getLoc() : CurDeclContext->getASTContext().SourceMgr.getCodeCompletionLoc()); // Add keywords even if type checking fails completely. addKeywords(CompletionContext.getResultSink(), MaybeFuncBody); Optional ExprType; ConcreteDeclRef ReferencedDecl = nullptr; if (ParsedExpr) { if (auto *checkedExpr = findParsedExpr(CurDeclContext, ParsedExpr->getSourceRange())) { ParsedExpr = checkedExpr; } if (auto typechecked = typeCheckParsedExpr()) { ExprType = typechecked->first; ReferencedDecl = typechecked->second; ParsedExpr->setType(*ExprType); } if (!ExprType && Kind != CompletionKind::PostfixExprParen && Kind != CompletionKind::CallArg && Kind != CompletionKind::KeyPathExprObjC) return; } if (!ParsedTypeLoc.isNull() && !typecheckParsedType()) return; CompletionLookup Lookup(CompletionContext.getResultSink(), P.Context, CurDeclContext, &CompletionContext); if (ExprType) { Lookup.setIsStaticMetatype(ParsedExpr->isStaticallyDerivedMetatype()); } if (auto *DRE = dyn_cast_or_null(ParsedExpr)) { Lookup.setIsSelfRefExpr(DRE->getDecl()->getName() == Context.Id_self); } else if (isa_and_nonnull(ParsedExpr)) { Lookup.setIsSuperRefExpr(); } if (isInsideObjCSelector()) Lookup.includeInstanceMembers(); if (PreferFunctionReferencesToCalls) Lookup.setPreferFunctionReferencesToCalls(); auto DoPostfixExprBeginning = [&] (){ SourceLoc Loc = P.Context.SourceMgr.getCodeCompletionLoc(); Lookup.getValueCompletionsInDeclContext(Loc); Lookup.getSelfTypeCompletionInDeclContext(Loc, /*isForDeclResult=*/false); }; switch (Kind) { case CompletionKind::None: case CompletionKind::DotExpr: case CompletionKind::UnresolvedMember: case CompletionKind::KeyPathExprSwift: llvm_unreachable(""should be already handled""); return; case CompletionKind::StmtOrExpr: case CompletionKind::ForEachSequence: case CompletionKind::PostfixExprBeginning: { ExprContextInfo ContextInfo(CurDeclContext, CodeCompleteTokenExpr); Lookup.setExpectedTypes(ContextInfo.getPossibleTypes(), ContextInfo.isImplicitSingleExpressionReturn()); DoPostfixExprBeginning(); break; } case CompletionKind::PostfixExpr: { Lookup.setHaveLeadingSpace(HasSpace); if (isDynamicLookup(*ExprType)) Lookup.setIsDynamicLookup(); Lookup.getValueExprCompletions(*ExprType, ReferencedDecl.getDecl()); /// We set the type of ParsedExpr explicitly above. But we don't want an /// unresolved type in our AST when we type check again for operator /// completions. Remove the type of the ParsedExpr and see if we can come up /// with something more useful based on the the full sequence expression. if (ParsedExpr->getType()->is()) { ParsedExpr->setType(nullptr); } Lookup.getOperatorCompletions(ParsedExpr, leadingSequenceExprs); Lookup.getPostfixKeywordCompletions(*ExprType, ParsedExpr); break; } case CompletionKind::PostfixExprParen: { Lookup.setHaveLParen(true); ExprContextInfo ContextInfo(CurDeclContext, CodeCompleteTokenExpr); if (ShouldCompleteCallPatternAfterParen) { ExprContextInfo ParentContextInfo(CurDeclContext, ParsedExpr); Lookup.setExpectedTypes( ParentContextInfo.getPossibleTypes(), ParentContextInfo.isImplicitSingleExpressionReturn()); if (!ContextInfo.getPossibleCallees().empty()) { for (auto &typeAndDecl : ContextInfo.getPossibleCallees()) Lookup.tryFunctionCallCompletions(typeAndDecl.Type, typeAndDecl.Decl, typeAndDecl.SemanticContext); } else if (ExprType && ((*ExprType)->is() || (*ExprType)->is())) { Lookup.getValueExprCompletions(*ExprType, ReferencedDecl.getDecl()); } } else { // Add argument labels, then fallthrough to get values. Lookup.addCallArgumentCompletionResults(ContextInfo.getPossibleParams()); } if (!Lookup.FoundFunctionCalls || (Lookup.FoundFunctionCalls && Lookup.FoundFunctionsWithoutFirstKeyword)) { Lookup.setExpectedTypes(ContextInfo.getPossibleTypes(), ContextInfo.isImplicitSingleExpressionReturn()); Lookup.setHaveLParen(false); // Add any keywords that can be used in an argument expr position. addSuperKeyword(CompletionContext.getResultSink(), CurDeclContext); addExprKeywords(CompletionContext.getResultSink(), CurDeclContext); DoPostfixExprBeginning(); } break; } case CompletionKind::KeyPathExprObjC: { if (DotLoc.isValid()) Lookup.setHaveDot(DotLoc); Lookup.setIsKeyPathExpr(); Lookup.includeInstanceMembers(); if (ExprType) { if (isDynamicLookup(*ExprType)) Lookup.setIsDynamicLookup(); Lookup.getValueExprCompletions(*ExprType, ReferencedDecl.getDecl()); } else { SourceLoc Loc = P.Context.SourceMgr.getCodeCompletionLoc(); Lookup.getValueCompletionsInDeclContext(Loc, KeyPathFilter, /*LiteralCompletions=*/false); } break; } case CompletionKind::TypeDeclResultBeginning: case CompletionKind::TypeSimpleBeginning: { auto Loc = Context.SourceMgr.getCodeCompletionLoc(); Lookup.getTypeCompletionsInDeclContext(Loc); Lookup.getSelfTypeCompletionInDeclContext( Loc, Kind == CompletionKind::TypeDeclResultBeginning); break; } case CompletionKind::TypeIdentifierWithDot: { Lookup.setHaveDot(SourceLoc()); Lookup.getTypeCompletions(ParsedTypeLoc.getType()); break; } case CompletionKind::TypeIdentifierWithoutDot: { Lookup.getTypeCompletions(ParsedTypeLoc.getType()); break; } case CompletionKind::CaseStmtBeginning: { ExprContextInfo ContextInfo(CurDeclContext, CodeCompleteTokenExpr); Lookup.setExpectedTypes(ContextInfo.getPossibleTypes(), ContextInfo.isImplicitSingleExpressionReturn()); Lookup.setIdealExpectedType(CodeCompleteTokenExpr->getType()); Lookup.getUnresolvedMemberCompletions(ContextInfo.getPossibleTypes()); DoPostfixExprBeginning(); break; } case CompletionKind::NominalMemberBeginning: { CompletionOverrideLookup OverrideLookup(CompletionContext.getResultSink(), P.Context, CurDeclContext, ParsedKeywords, introducerLoc); OverrideLookup.getOverrideCompletions(SourceLoc()); break; } case CompletionKind::AccessorBeginning: { if (isa(ParsedDecl)) { ExprContextInfo ContextInfo(CurDeclContext, CodeCompleteTokenExpr); Lookup.setExpectedTypes(ContextInfo.getPossibleTypes(), ContextInfo.isImplicitSingleExpressionReturn()); DoPostfixExprBeginning(); } break; } case CompletionKind::AttributeBegin: { Lookup.getAttributeDeclCompletions(IsInSil, AttTargetDK); // TypeName at attribute position after '@'. // - VarDecl: Property Wrappers. // - ParamDecl/VarDecl/FuncDecl: Function Builders. if (!AttTargetDK || *AttTargetDK == DeclKind::Var || *AttTargetDK == DeclKind::Param || *AttTargetDK == DeclKind::Func) Lookup.getTypeCompletionsInDeclContext( P.Context.SourceMgr.getCodeCompletionLoc()); break; } case CompletionKind::AttributeDeclParen: { Lookup.getAttributeDeclParamCompletions(AttrKind, AttrParamIndex); break; } case CompletionKind::PoundAvailablePlatform: { Lookup.getPoundAvailablePlatformCompletions(); break; } case CompletionKind::Import: { if (DotLoc.isValid()) Lookup.addSubModuleNames(SubModuleNameVisibilityPairs); else Lookup.addImportModuleNames(); break; } case CompletionKind::CallArg: { ExprContextInfo ContextInfo(CurDeclContext, CodeCompleteTokenExpr); bool shouldPerformGlobalCompletion = true; if (ShouldCompleteCallPatternAfterParen && !ContextInfo.getPossibleCallees().empty()) { Lookup.setHaveLParen(true); for (auto &typeAndDecl : ContextInfo.getPossibleCallees()) { auto apply = ContextInfo.getAnalyzedExpr(); if (isa_and_nonnull(apply)) { Lookup.addSubscriptCallPattern( typeAndDecl.Type, dyn_cast_or_null(typeAndDecl.Decl), typeAndDecl.SemanticContext); } else { Lookup.addFunctionCallPattern( typeAndDecl.Type, dyn_cast_or_null(typeAndDecl.Decl), typeAndDecl.SemanticContext); } } Lookup.setHaveLParen(false); shouldPerformGlobalCompletion = !Lookup.FoundFunctionCalls || (Lookup.FoundFunctionCalls && Lookup.FoundFunctionsWithoutFirstKeyword); } else if (!ContextInfo.getPossibleParams().empty()) { auto params = ContextInfo.getPossibleParams(); Lookup.addCallArgumentCompletionResults(params); shouldPerformGlobalCompletion = !ContextInfo.getPossibleTypes().empty(); // Fallback to global completion if the position is out of number. It's // better than suggest nothing. shouldPerformGlobalCompletion |= llvm::all_of( params, [](const PossibleParamInfo &P) { return !P.Param; }); } if (shouldPerformGlobalCompletion) { Lookup.setExpectedTypes(ContextInfo.getPossibleTypes(), ContextInfo.isImplicitSingleExpressionReturn()); // Add any keywords that can be used in an argument expr position. addSuperKeyword(CompletionContext.getResultSink(), CurDeclContext); addExprKeywords(CompletionContext.getResultSink(), CurDeclContext); DoPostfixExprBeginning(); } break; } case CompletionKind::LabeledTrailingClosure: { ExprContextInfo ContextInfo(CurDeclContext, CodeCompleteTokenExpr); SmallVector params; // Only complete function type parameters llvm::copy_if(ContextInfo.getPossibleParams(), std::back_inserter(params), [](const PossibleParamInfo &P) { // nullptr indicates out of bounds. if (!P.Param) return true; return P.Param->getPlainType() ->lookThroughAllOptionalTypes() ->is(); }); bool allRequired = false; if (!params.empty()) { Lookup.addCallArgumentCompletionResults( params, /*isLabeledTrailingClosure=*/true); allRequired = llvm::all_of( params, [](const PossibleParamInfo &P) { return P.IsRequired; }); } // If there're optional parameters, do global completion or member // completion depending on the completion is happening at the start of line. if (!allRequired) { if (IsAtStartOfLine) { // foo() {} // auto &Sink = CompletionContext.getResultSink(); if (isa(CurDeclContext)) CurDeclContext = CurDeclContext->getParent(); if (CurDeclContext->isTypeContext()) { // Override completion (CompletionKind::NominalMemberBeginning). addDeclKeywords(Sink, CurDeclContext, Context.LangOpts.EnableExperimentalConcurrency); addLetVarKeywords(Sink); SmallVector ParsedKeywords; CompletionOverrideLookup OverrideLookup(Sink, Context, CurDeclContext, ParsedKeywords, SourceLoc()); OverrideLookup.getOverrideCompletions(SourceLoc()); } else { // Global completion (CompletionKind::PostfixExprBeginning). addDeclKeywords(Sink, CurDeclContext, Context.LangOpts.EnableExperimentalConcurrency); addStmtKeywords(Sink, CurDeclContext, MaybeFuncBody); addSuperKeyword(Sink, CurDeclContext); addLetVarKeywords(Sink); addExprKeywords(Sink, CurDeclContext); addAnyTypeKeyword(Sink, Context.TheAnyType); DoPostfixExprBeginning(); } } else { // foo() {} // Member completion. Expr *analyzedExpr = ContextInfo.getAnalyzedExpr(); if (!analyzedExpr) break; // Only if the completion token is the last token in the call. if (analyzedExpr->getEndLoc() != CodeCompleteTokenExpr->getLoc()) break; Type resultTy = analyzedExpr->getType(); // If the call expression doesn't have a type, fallback to: if (!resultTy || resultTy->is()) { // 1) Try to type check removing CodeCompletionExpr from the call. Expr *removedExpr = analyzedExpr; removeCodeCompletionExpr(CurDeclContext->getASTContext(), removedExpr); ConcreteDeclRef referencedDecl; auto optT = getTypeOfCompletionContextExpr( CurDeclContext->getASTContext(), CurDeclContext, CompletionTypeCheckKind::Normal, removedExpr, referencedDecl); if (optT) { resultTy = *optT; analyzedExpr->setType(resultTy); } } if (!resultTy || resultTy->is()) { // 2) Infer it from the possible callee info. if (!ContextInfo.getPossibleCallees().empty()) { auto calleeInfo = ContextInfo.getPossibleCallees()[0]; resultTy = calleeInfo.Type->getResult(); analyzedExpr->setType(resultTy); } } if (!resultTy || resultTy->is()) { // 3) Give up providing postfix completions. break; } auto &SM = CurDeclContext->getASTContext().SourceMgr; auto leadingChar = SM.extractText({SM.getCodeCompletionLoc().getAdvancedLoc(-1), 1}); Lookup.setHaveLeadingSpace(leadingChar.find_first_of("" \\t\\f\\v"") != StringRef::npos); if (isDynamicLookup(resultTy)) Lookup.setIsDynamicLookup(); Lookup.getValueExprCompletions(resultTy, /*VD=*/nullptr); Lookup.getOperatorCompletions(analyzedExpr, leadingSequenceExprs); Lookup.getPostfixKeywordCompletions(resultTy, analyzedExpr); } } break; } case CompletionKind::ReturnStmtExpr : { SourceLoc Loc = P.Context.SourceMgr.getCodeCompletionLoc(); SmallVector possibleReturnTypes; collectPossibleReturnTypesFromContext(CurDeclContext, possibleReturnTypes); Lookup.setExpectedTypes(possibleReturnTypes, /*isImplicitSingleExpressionReturn*/ false); Lookup.getValueCompletionsInDeclContext(Loc); break; } case CompletionKind::YieldStmtExpr: { SourceLoc Loc = P.Context.SourceMgr.getCodeCompletionLoc(); if (auto FD = dyn_cast(CurDeclContext)) { if (FD->isCoroutine()) { // TODO: handle multi-value yields. Lookup.setExpectedTypes(FD->getStorage()->getValueInterfaceType(), /*isImplicitSingleExpressionReturn*/ false); } } Lookup.getValueCompletionsInDeclContext(Loc); break; } case CompletionKind::AfterPoundExpr: { ExprContextInfo ContextInfo(CurDeclContext, CodeCompleteTokenExpr); Lookup.setExpectedTypes(ContextInfo.getPossibleTypes(), ContextInfo.isImplicitSingleExpressionReturn()); Lookup.addPoundAvailable(ParentStmtKind); Lookup.addPoundLiteralCompletions(/*needPound=*/false); Lookup.addObjCPoundKeywordCompletions(/*needPound=*/false); break; } case CompletionKind::AfterPoundDirective: { addPoundDirectives(CompletionContext.getResultSink()); // FIXME: Add pound expressions (e.g. '#selector()') if it's at statements // position. break; } case CompletionKind::PlatformConditon: { addPlatformConditions(CompletionContext.getResultSink()); addConditionalCompilationFlags(CurDeclContext->getASTContext(), CompletionContext.getResultSink()); break; } case CompletionKind::GenericRequirement: { auto Loc = Context.SourceMgr.getCodeCompletionLoc(); Lookup.getGenericRequirementCompletions(CurDeclContext, Loc); break; } case CompletionKind::PrecedenceGroup: Lookup.getPrecedenceGroupCompletions(SyntxKind); break; case CompletionKind::StmtLabel: { SourceLoc Loc = P.Context.SourceMgr.getCodeCompletionLoc(); Lookup.getStmtLabelCompletions(Loc, ParentStmtKind == StmtKind::Continue); break; } case CompletionKind::TypeAttrBeginning: { Lookup.getTypeAttributeKeywordCompletions(); // Type names at attribute position after '@'. Lookup.getTypeCompletionsInDeclContext( P.Context.SourceMgr.getCodeCompletionLoc()); break; } case CompletionKind::AfterIfStmtElse: case CompletionKind::CaseStmtKeyword: case CompletionKind::EffectsSpecifier: case CompletionKind::ForEachPatternBeginning: // Handled earlier by keyword completions. break; } deliverCompletionResults(CompletionContext, Lookup, CurDeclContext, Consumer); } namespace { class CodeCompletionCallbacksFactoryImpl : public CodeCompletionCallbacksFactory { CodeCompletionContext &CompletionContext; CodeCompletionConsumer &Consumer; public: CodeCompletionCallbacksFactoryImpl(CodeCompletionContext &CompletionContext, CodeCompletionConsumer &Consumer) : CompletionContext(CompletionContext), Consumer(Consumer) {} CodeCompletionCallbacks *createCodeCompletionCallbacks(Parser &P) override { return new CodeCompletionCallbacksImpl(P, CompletionContext, Consumer); } }; } // end anonymous namespace CodeCompletionCallbacksFactory * swift::ide::makeCodeCompletionCallbacksFactory( CodeCompletionContext &CompletionContext, CodeCompletionConsumer &Consumer) { return new CodeCompletionCallbacksFactoryImpl(CompletionContext, Consumer); } void swift::ide::lookupCodeCompletionResultsFromModule( CodeCompletionResultSink &targetSink, const ModuleDecl *module, ArrayRef accessPath, bool needLeadingDot, const SourceFile *SF) { // Use the SourceFile as the decl context, to avoid decl context specific // behaviors. CompletionLookup Lookup(targetSink, module->getASTContext(), SF); Lookup.lookupExternalModuleDecls(module, accessPath, needLeadingDot); } ",16312,True,3003.089882979377,median " //// This file is generated! See _meta/fields.yml and scripts/generate_field_docs.py //// [[exported-fields]] = Exported fields [partintro] -- This document describes the fields that are exported by Journalbeat. They are grouped in the following categories: * <> * <> * <> * <> * <> * <> * <> -- [[exported-fields-beat]] == Beat fields Contains common beat fields available in all event types. *`beat.timezone`*:: + -- type: alias alias to: event.timezone -- *`fields`*:: + -- type: object Contains user configurable fields. -- [float] == error fields Error fields containing additional info in case of errors. *`error.type`*:: + -- type: keyword Error type. -- [[exported-fields-cloud]] == Cloud provider metadata fields Metadata from cloud providers added by the add_cloud_metadata processor. *`cloud.project.id`*:: + -- example: project-x Name of the project in Google Cloud. -- *`meta.cloud.provider`*:: + -- type: alias alias to: cloud.provider -- *`meta.cloud.instance_id`*:: + -- type: alias alias to: cloud.instance.id -- *`meta.cloud.instance_name`*:: + -- type: alias alias to: cloud.instance.name -- *`meta.cloud.machine_type`*:: + -- type: alias alias to: cloud.machine.type -- *`meta.cloud.availability_zone`*:: + -- type: alias alias to: cloud.availability_zone -- *`meta.cloud.project_id`*:: + -- type: alias alias to: cloud.project.id -- *`meta.cloud.region`*:: + -- type: alias alias to: cloud.region -- [[exported-fields-common]] == Common Journalbeat fields Contains common fields available in all event types. *`read_timestamp`*:: + -- The time when Journalbeat read the journal entry. -- [float] == coredump fields Fields used by systemd-coredump kernel helper. *`coredump.unit`*:: + -- type: keyword Annotations of messages containing coredumps from system units. -- *`coredump.user_unit`*:: + -- type: keyword Annotations of messages containing coredumps from user units. -- [float] == journald fields Fields to log on behalf of a different program. [float] == audit fields Audit fields of event. *`journald.audit.loginuid`*:: + -- type: long example: 1000 required: False The login UID of the source process. -- *`journald.audit.session`*:: + -- type: long example: 3 required: False The audit session of the source process. -- *`journald.cmd`*:: + -- type: keyword example: /lib/systemd/systemd --user required: False The command line of the process. -- *`journald.name`*:: + -- type: keyword example: /lib/systemd/systemd required: False Name of the executable. -- *`journald.executable`*:: + -- type: keyword example: /lib/systemd/systemd required: False Path to the the executable. -- *`journald.pid`*:: + -- type: long example: 1 required: False The ID of the process which logged the message. -- *`journald.gid`*:: + -- type: long example: 1 required: False The ID of the group which runs the process. -- *`journald.uid`*:: + -- type: long example: 1 required: False The ID of the user which runs the process. -- *`journald.capabilites`*:: + -- required: False The effective capabilites of the process. -- [float] == systemd fields Fields of systemd. *`systemd.invocation_id`*:: + -- type: keyword example: 8450f1672de646c88cd133aadd4f2d70 required: False The invocation ID for the runtime cycle of the unit the message was generated in. -- *`systemd.cgroup`*:: + -- type: keyword example: /user.slice/user-1234.slice/session-2.scope required: False The control group path in the systemd hierarchy. -- *`systemd.owner_uid`*:: + -- type: long required: False The owner UID of the systemd user unit or systemd session. -- *`systemd.session`*:: + -- type: keyword required: False The ID of the systemd session. -- *`systemd.slice`*:: + -- type: keyword example: user-1234.slice required: False The systemd slice unit. -- *`systemd.user_slice`*:: + -- type: keyword required: False The systemd user slice unit. -- *`systemd.unit`*:: + -- type: keyword example: nginx.service required: False The name of the systemd unit. -- *`systemd.user_unit`*:: + -- type: keyword example: user-1234.slice required: False The name of the systemd user unit. -- *`systemd.transport`*:: + -- type: keyword example: syslog required: True How the log message was received by journald. -- [float] == host fields Fields of the host. *`host.boot_id`*:: + -- type: text example: dd8c974asdf01dbe2ef26d7fasdf264c9 required: False The boot ID for the boot the log was generated in. -- [float] == syslog fields Fields of the code generating the event. *`syslog.priority`*:: + -- type: long example: 1 required: False The priority of the message. A syslog compatibility field. -- *`syslog.facility`*:: + -- type: long example: 1 required: False The facility of the message. A syslog compatibility field. -- *`syslog.identifier`*:: + -- type: text example: su required: False The identifier of the message. A syslog compatibility field. -- *`custom`*:: + -- type: nested required: False Arbitrary fields coming from processes. -- [[exported-fields-docker-processor]] == Docker fields Docker stats collected from Docker. *`docker.container.id`*:: + -- type: keyword Unique container id. -- *`docker.container.image`*:: + -- type: keyword Name of the image the container was built on. -- *`docker.container.name`*:: + -- type: keyword Container name. -- *`docker.container.labels`*:: + -- type: object Image labels. -- [[exported-fields-ecs]] == ECS fields ECS fields. *`@timestamp`*:: + -- type: date example: 2016-05-23T08:05:34.853Z required: True Date/time when the event originated. For log events this is the date/time when the event was generated, and not when it was read. Required field for all events. -- *`tags`*:: + -- type: keyword example: [""production"", ""env2""] List of keywords used to tag each event. -- *`labels`*:: + -- type: object example: {'application': 'foo-bar', 'env': 'production'} Key/value pairs. Can be used to add meta information to events. Should not contain nested objects. All values are stored as keyword. Example: `docker` and `k8s` labels. -- *`message`*:: + -- type: text example: Hello World For log events the message field contains the log message. In other use cases the message field can be used to concatenate different values which are then freely searchable. If multiple messages exist, they can be combined into one message. -- [float] == agent fields The agent fields contain the data about the software entity, if any, that collects, detects, or observes events on a host, or takes measurements on a host. Examples include Beats. Agents may also run on observers. ECS agent.* fields shall be populated with details of the agent running on the host or observer where the event happened or the measurement was taken. *`agent.version`*:: + -- type: keyword example: 6.0.0-rc2 Version of the agent. -- *`agent.name`*:: + -- type: keyword example: foo Name of the agent. This is a name that can be given to an agent. This can be helpful if for example two Filebeat instances are running on the same host but a human readable separation is needed on which Filebeat instance data is coming from. If no name is given, the name is often left empty. -- *`agent.type`*:: + -- type: keyword example: filebeat Type of the agent. The agent type stays always the same and should be given by the agent used. In case of Filebeat the agent would always be Filebeat also if two Filebeat instances are run on the same machine. -- *`agent.id`*:: + -- type: keyword example: 8a4f500d Unique identifier of this agent (if one exists). Example: For Beats this would be beat.id. -- *`agent.ephemeral_id`*:: + -- type: keyword example: 8a4f500f Ephemeral identifier of this agent (if one exists). This id normally changes across restarts, but `agent.id` does not. -- [float] == client fields A client is defined as the initiator of a network connection for events regarding sessions, connections, or bidirectional flow records. For TCP events, the client is the initiator of the TCP connection that sends the SYN packet(s). For other protocols, the client is generally the initiator or requestor in the network transaction. Some systems use the term ""originator"" to refer the client in TCP connections. The client fields describe details about the system acting as the client in the network event. Client fields are usually populated in conjuction with server fields. Client fields are generally not populated for packet-level events. *`client.ip`*:: + -- type: ip IP address of the client. Can be one or multiple IPv4 or IPv6 addresses. -- *`client.port`*:: + -- type: long Port of the client. -- *`client.mac`*:: + -- type: keyword MAC address of the client. -- *`client.domain`*:: + -- type: keyword Client domain. -- *`client.bytes`*:: + -- type: long example: 184 Bytes sent from the client to the server. -- *`client.packets`*:: + -- type: long example: 12 Packets sent from the client to the server. -- [float] == geo fields Geo fields can carry data about a specific location related to an event or geo information derived from an IP field. *`client.geo.location`*:: + -- type: geo_point example: { ""lon"": -73.614830, ""lat"": 45.505918 } Longitude and latitude. -- *`client.geo.continent_name`*:: + -- type: keyword example: North America Name of the continent. -- *`client.geo.country_name`*:: + -- type: keyword example: Canada Country name. -- *`client.geo.region_name`*:: + -- type: keyword example: Quebec Region name. -- *`client.geo.city_name`*:: + -- type: keyword example: Montreal City name. -- *`client.geo.country_iso_code`*:: + -- type: keyword example: CA Country ISO code. -- *`client.geo.region_iso_code`*:: + -- type: keyword example: CA-QC Region ISO code. -- *`client.geo.name`*:: + -- type: keyword example: boston-dc User-defined description of a location, at the level of granularity they care about. Could be the name of their data centers, the floor number, if this describes a local physical entity, city names. Not typically used in automated geolocation. -- [float] == cloud fields Fields related to the cloud or infrastructure the events are coming from. *`cloud.provider`*:: + -- type: keyword example: ec2 Name of the cloud provider. Example values are ec2, gce, or digitalocean. -- *`cloud.availability_zone`*:: + -- type: keyword example: us-east-1c Availability zone in which this host is running. -- *`cloud.region`*:: + -- type: keyword example: us-east-1 Region in which this host is running. -- *`cloud.instance.id`*:: + -- type: keyword example: i-1234567890abcdef0 Instance ID of the host machine. -- *`cloud.instance.name`*:: + -- type: keyword Instance name of the host machine. -- *`cloud.machine.type`*:: + -- type: keyword example: t2.medium Machine type of the host machine. -- *`cloud.account.id`*:: + -- type: keyword example: 666777888999 The cloud account or organization id used to identify different entities in a multi-tenant environment. Examples: AWS account id, Google Cloud ORG Id, or other unique identifier. -- [float] == container fields Container fields are used for meta information about the specific container that is the source of information. These fields help correlate data based containers from any runtime. *`container.runtime`*:: + -- type: keyword example: docker Runtime managing this container. -- *`container.id`*:: + -- type: keyword Unique container id. -- *`container.image.name`*:: + -- type: keyword Name of the image the container was built on. -- *`container.image.tag`*:: + -- type: keyword Container image tag. -- *`container.name`*:: + -- type: keyword Container name. -- *`container.labels`*:: + -- type: object Image labels. -- [float] == destination fields Destination fields describe details about the destination of a packet/event. Destination fields are usually populated in conjunction with source fields. *`destination.ip`*:: + -- type: ip IP address of the destination. Can be one or multiple IPv4 or IPv6 addresses. -- *`destination.port`*:: + -- type: long Port of the destination. -- *`destination.mac`*:: + -- type: keyword MAC address of the destination. -- *`destination.domain`*:: + -- type: keyword Destination domain. -- *`destination.bytes`*:: + -- type: long example: 184 Bytes sent from the destination to the source. -- *`destination.packets`*:: + -- type: long example: 12 Packets sent from the destination to the source. -- [float] == geo fields Geo fields can carry data about a specific location related to an event or geo information derived from an IP field. *`destination.geo.location`*:: + -- type: geo_point example: { ""lon"": -73.614830, ""lat"": 45.505918 } Longitude and latitude. -- *`destination.geo.continent_name`*:: + -- type: keyword example: North America Name of the continent. -- *`destination.geo.country_name`*:: + -- type: keyword example: Canada Country name. -- *`destination.geo.region_name`*:: + -- type: keyword example: Quebec Region name. -- *`destination.geo.city_name`*:: + -- type: keyword example: Montreal City name. -- *`destination.geo.country_iso_code`*:: + -- type: keyword example: CA Country ISO code. -- *`destination.geo.region_iso_code`*:: + -- type: keyword example: CA-QC Region ISO code. -- *`destination.geo.name`*:: + -- type: keyword example: boston-dc User-defined description of a location, at the level of granularity they care about. Could be the name of their data centers, the floor number, if this describes a local physical entity, city names. Not typically used in automated geolocation. -- [float] == ecs fields Meta-information specific to ECS. *`ecs.version`*:: + -- type: keyword example: 1.0.0-beta1 required: True ECS version this event conforms to. `ecs.version` is a required field and must exist in all events. When querying across multiple indices -- which may conform to slightly different ECS versions -- this field lets integrations adjust to the schema version of the events. The current version is 1.0.0-beta1 . -- [float] == error fields These fields can represent errors of any kind. Use them for errors that happen while fetching events or in cases where the event itself contains an error. *`error.id`*:: + -- type: keyword Unique identifier for the error. -- *`error.message`*:: + -- type: text Error message. -- *`error.code`*:: + -- type: keyword Error code describing the error. -- [float] == event fields The event fields are used for context information about the log or metric event itself. A log is defined as an event containing details of something that happened. Log events must include the time at which the thing happened. Examples of log events include a process starting on a host, a network packet being sent from a source to a destination, or a network connection between a client and a server being initiated or closed. A metric is defined as an event containing one or more numerical or categorical measurements and the time at which the measurement was taken. Examples of metric events include memory pressure measured on a host, or vulnerabilities measured on a scanned host. *`event.id`*:: + -- type: keyword example: 8a4f500d Unique ID to describe the event. -- *`event.kind`*:: + -- type: keyword example: state The kind of the event. This gives information about what type of information the event contains, without being specific to the contents of the event. Examples are `event`, `state`, `alarm`. Warning: In future versions of ECS, we plan to provide a list of acceptable values for this field, please use with caution. -- *`event.category`*:: + -- type: keyword example: user-management Event category. This contains high-level information about the contents of the event. It is more generic than `event.action`, in the sense that typically a category contains multiple actions. Warning: In future versions of ECS, we plan to provide a list of acceptable values for this field, please use with caution. -- *`event.action`*:: + -- type: keyword example: user-password-change The action captured by the event. This describes the information in the event. It is more specific than `event.category`. Examples are `group-add`, `process-started`, `file-created`. The value is normally defined by the implementer. -- *`event.outcome`*:: + -- type: keyword example: success The outcome of the event. If the event describes an action, this fields contains the outcome of that action. Examples outcomes are `success` and `failure`. Warning: In future versions of ECS, we plan to provide a list of acceptable values for this field, please use with caution. -- *`event.type`*:: + -- type: keyword Reserved for future usage. Please avoid using this field for user data. -- *`event.module`*:: + -- type: keyword example: mysql Name of the module this data is coming from. This information is coming from the modules used in Beats or Logstash. -- *`event.dataset`*:: + -- type: keyword example: stats Name of the dataset. The concept of a `dataset` (fileset / metricset) is used in Beats as a subset of modules. It contains the information which is currently stored in metricset.name and metricset.module or fileset.name. -- *`event.severity`*:: + -- type: long example: 7 Severity describes the severity of the event. What the different severity values mean can very different between use cases. It's up to the implementer to make sure severities are consistent across events. -- *`event.original`*:: + -- type: keyword example: Sep 19 08:26:10 host CEF:0|Security| threatmanager|1.0|100| worm successfully stopped|10|src=10.0.0.1 dst=2.1.2.2spt=1232 Raw text message of entire event. Used to demonstrate log integrity. This field is not indexed and doc_values are disabled. It cannot be searched, but it can be retrieved from `_source`. Field is not indexed. -- *`event.hash`*:: + -- type: keyword example: 123456789012345678901234567890ABCD Hash (perhaps logstash fingerprint) of raw field to be able to demonstrate log integrity. -- *`event.duration`*:: + -- type: long Duration of the event in nanoseconds. If event.start and event.end are known this value should be the difference between the end and start time. -- *`event.timezone`*:: + -- type: keyword This field should be populated when the event's timestamp does not include timezone information already (e.g. default Syslog timestamps). It's optional otherwise. Acceptable timezone formats are: a canonical ID (e.g. ""Europe/Amsterdam""), abbreviated (e.g. ""EST"") or an HH:mm differential (e.g. ""-05:00""). -- *`event.created`*:: + -- type: date event.created contains the date when the event was created. This timestamp is distinct from @timestamp in that @timestamp contains the processed timestamp. For logs these two timestamps can be different as the timestamp in the log line and when the event is read for example by Filebeat are not identical. `@timestamp` must contain the timestamp extracted from the log line, event.created when the log line is read. The same could apply to package capturing where @timestamp contains the timestamp extracted from the network package and event.created when the event was created. In case the two timestamps are identical, @timestamp should be used. -- *`event.start`*:: + -- type: date event.start contains the date when the event started or when the activity was first observed. -- *`event.end`*:: + -- type: date event.end contains the date when the event ended or when the activity was last observed. -- *`event.risk_score`*:: + -- type: float Risk score or priority of the event (e.g. security solutions). Use your system's original value here. -- *`event.risk_score_norm`*:: + -- type: float Normalized risk score or priority of the event, on a scale of 0 to 100. This is mainly useful if you use more than one system that assigns risk scores, and you want to see a normalized value across all systems. -- [float] == file fields A file is defined as a set of information that has been created on, or has existed on a filesystem. File objects can be associated with host events, network events, and/or file events (e.g., those produced by File Integrity Monitoring [FIM] products or services). File fields provide details about the affected file associated with the event or metric. *`file.path`*:: + -- type: keyword Path to the file. -- *`file.target_path`*:: + -- type: keyword Target path for symlinks. -- *`file.extension`*:: + -- type: keyword example: png File extension. This should allow easy filtering by file extensions. -- *`file.type`*:: + -- type: keyword File type (file, dir, or symlink). -- *`file.device`*:: + -- type: keyword Device that is the source of the file. -- *`file.inode`*:: + -- type: keyword Inode representing the file in the filesystem. -- *`file.uid`*:: + -- type: keyword The user ID (UID) or security identifier (SID) of the file owner. -- *`file.owner`*:: + -- type: keyword File owner's username. -- *`file.gid`*:: + -- type: keyword Primary group ID (GID) of the file. -- *`file.group`*:: + -- type: keyword Primary group name of the file. -- *`file.mode`*:: + -- type: keyword example: 416 Mode of the file in octal representation. -- *`file.size`*:: + -- type: long File size in bytes (field is only added when `type` is `file`). -- *`file.mtime`*:: + -- type: date Last time file content was modified. -- *`file.ctime`*:: + -- type: date Last time file metadata changed. -- [float] == group fields The group fields are meant to represent groups that are relevant to the event. *`group.id`*:: + -- type: keyword Unique identifier for the group on the system/platform. -- *`group.name`*:: + -- type: keyword Name of the group. -- [float] == host fields A host is defined as a general computing instance. ECS host.* fields should be populated with details about the host on which the event happened, or on which the measurement was taken. Host types include hardware, virtual machines, Docker containers, and Kubernetes nodes. *`host.hostname`*:: + -- type: keyword Hostname of the host. It normally contains what the `hostname` command returns on the host machine. -- *`host.name`*:: + -- type: keyword Name of the host. It can contain what `hostname` returns on Unix systems, the fully qualified domain name, or a name specified by the user. The sender decides which value to use. -- *`host.id`*:: + -- type: keyword Unique host id. As hostname is not always unique, use values that are meaningful in your environment. Example: The current usage of `beat.name`. -- *`host.ip`*:: + -- type: ip Host ip address. -- *`host.mac`*:: + -- type: keyword Host mac address. -- *`host.type`*:: + -- type: keyword Type of host. For Cloud providers this can be the machine type like `t2.medium`. If vm, this could be the container, for example, or other information meaningful in your environment. -- *`host.architecture`*:: + -- type: keyword example: x86_64 Operating system architecture. -- [float] == os fields The OS fields contain information about the operating system. *`host.os.platform`*:: + -- type: keyword example: darwin Operating system platform (such centos, ubuntu, windows). -- *`host.os.name`*:: + -- type: keyword example: Mac OS X Operating system name. -- *`host.os.family`*:: + -- type: keyword example: debian OS family (such as redhat, debian, freebsd, windows). -- *`host.os.version`*:: + -- type: keyword example: 10.12.6-rc2 Operating system version as a raw string. -- *`host.os.kernel`*:: + -- type: keyword example: 4.4.0-112-generic Operating system kernel version as a raw string. -- [float] == geo fields Geo fields can carry data about a specific location related to an event or geo information derived from an IP field. *`host.geo.location`*:: + -- type: geo_point example: { ""lon"": -73.614830, ""lat"": 45.505918 } Longitude and latitude. -- *`host.geo.continent_name`*:: + -- type: keyword example: North America Name of the continent. -- *`host.geo.country_name`*:: + -- type: keyword example: Canada Country name. -- *`host.geo.region_name`*:: + -- type: keyword example: Quebec Region name. -- *`host.geo.city_name`*:: + -- type: keyword example: Montreal City name. -- *`host.geo.country_iso_code`*:: + -- type: keyword example: CA Country ISO code. -- *`host.geo.region_iso_code`*:: + -- type: keyword example: CA-QC Region ISO code. -- *`host.geo.name`*:: + -- type: keyword example: boston-dc User-defined description of a location, at the level of granularity they care about. Could be the name of their data centers, the floor number, if this describes a local physical entity, city names. Not typically used in automated geolocation. -- [float] == http fields Fields related to HTTP activity. *`http.request.method`*:: + -- type: keyword example: GET, POST, PUT Http request method. -- *`http.request.referrer`*:: + -- type: keyword example: https://blog.example.com/ Referrer for this HTTP request. -- *`http.response.status_code`*:: + -- type: long example: 404 Http response status code. -- *`http.response.body`*:: + -- type: keyword example: Hello world The full http response body. -- *`http.version`*:: + -- type: keyword example: 1.1 Http version. -- [float] == log fields Fields which are specific to log events. *`log.level`*:: + -- type: keyword example: ERR Log level of the log event. Some examples are `WARN`, `ERR`, `INFO`. -- *`log.original`*:: + -- type: keyword example: Sep 19 08:26:10 localhost My log This is the original log message and contains the full log message before splitting it up in multiple parts. In contrast to the `message` field which can contain an extracted part of the log message, this field contains the original, full log message. It can have already some modifications applied like encoding or new lines removed to clean up the log message. This field is not indexed and doc_values are disabled so it can't be queried but the value can be retrieved from `_source`. Field is not indexed. -- [float] == network fields The network is defined as the communication path over which a host or network event happens. The network.* fields should be populated with details about the network activity associated with an event. *`network.name`*:: + -- type: keyword example: Guest Wifi Name given by operators to sections of their network. -- *`network.type`*:: + -- type: keyword example: IPv4 In the OSI Model this would be the Network Layer. IPv4, IPv6, IPSec, PIM, etc -- *`network.iana_number`*:: + -- type: keyword example: 6 IANA Protocol Number (https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml). Standardized list of protocols. This aligns well with NetFlow and sFlow related logs which use the IANA Protocol Number. -- *`network.transport`*:: + -- type: keyword example: TCP Same as network.iana_number, but instead using the Keyword name of the transport layer (UDP, TCP, IPv6-ICMP, etc.) -- *`network.application`*:: + -- type: keyword example: AIM A name given to an application. This can be arbitrarily assigned for things like microservices, but also apply to things like skype, icq, facebook, twitter. This would be used in situations where the vendor or service can be decoded such as from the source/dest IP owners, ports, or wire format. -- *`network.protocol`*:: + -- type: keyword example: http L7 Network protocol name. ex. http, lumberjack, transport protocol -- *`network.direction`*:: + -- type: keyword example: inbound Direction of the network traffic. Recommended values are: * inbound * outbound * internal * external * unknown When mapping events from a host-based monitoring context, populate this field from the host's point of view. When mapping events from a network or perimeter-based monitoring context, populate this field from the point of view of your network perimeter. -- *`network.forwarded_ip`*:: + -- type: ip example: 192.1.1.2 Host IP address when the source IP address is the proxy. -- *`network.community_id`*:: + -- type: keyword example: 1:hO+sN4H+MG5MY/8hIrXPqc4ZQz0= A hash of source and destination IPs and ports, as well as the protocol used in a communication. This is a tool-agnostic standard to identify flows. Learn more at https://github.com/corelight/community-id-spec. -- *`network.bytes`*:: + -- type: long example: 368 Total bytes transferred in both directions. If `source.bytes` and `destination.bytes` are known, `network.bytes` is their sum. -- *`network.packets`*:: + -- type: long example: 24 Total packets transferred in both directions. If `source.packets` and `destination.packets` are known, `network.packets` is their sum. -- [float] == observer fields An observer is defined as a special network, security, or application device used to detect, observe, or create network, security, or application-related events and metrics. This could be a custom hardware appliance or a server that has been configured to run special network, security, or application software. Examples include firewalls, intrusion detection/prevention systems, network monitoring sensors, web application firewalls, data loss prevention systems, and APM servers. The observer.* fields shall be populated with details of the system, if any, that detects, observes and/or creates a network, security, or application event or metric. Message queues and ETL components used in processing events or metrics are not considered observers in ECS. *`observer.mac`*:: + -- type: keyword MAC address of the observer -- *`observer.ip`*:: + -- type: ip IP address of the observer. -- *`observer.hostname`*:: + -- type: keyword Hostname of the observer. -- *`observer.vendor`*:: + -- type: keyword observer vendor information. -- *`observer.version`*:: + -- type: keyword Observer version. -- *`observer.serial_number`*:: + -- type: keyword Observer serial number. -- *`observer.type`*:: + -- type: keyword example: firewall The type of the observer the data is coming from. There is no predefined list of observer types. Some examples are `forwarder`, `firewall`, `ids`, `ips`, `proxy`, `poller`, `sensor`, `APM server`. -- [float] == os fields The OS fields contain information about the operating system. *`observer.os.platform`*:: + -- type: keyword example: darwin Operating system platform (such centos, ubuntu, windows). -- *`observer.os.name`*:: + -- type: keyword example: Mac OS X Operating system name. -- *`observer.os.family`*:: + -- type: keyword example: debian OS family (such as redhat, debian, freebsd, windows). -- *`observer.os.version`*:: + -- type: keyword example: 10.12.6-rc2 Operating system version as a raw string. -- *`observer.os.kernel`*:: + -- type: keyword example: 4.4.0-112-generic Operating system kernel version as a raw string. -- [float] == geo fields Geo fields can carry data about a specific location related to an event or geo information derived from an IP field. *`observer.geo.location`*:: + -- type: geo_point example: { ""lon"": -73.614830, ""lat"": 45.505918 } Longitude and latitude. -- *`observer.geo.continent_name`*:: + -- type: keyword example: North America Name of the continent. -- *`observer.geo.country_name`*:: + -- type: keyword example: Canada Country name. -- *`observer.geo.region_name`*:: + -- type: keyword example: Quebec Region name. -- *`observer.geo.city_name`*:: + -- type: keyword example: Montreal City name. -- *`observer.geo.country_iso_code`*:: + -- type: keyword example: CA Country ISO code. -- *`observer.geo.region_iso_code`*:: + -- type: keyword example: CA-QC Region ISO code. -- *`observer.geo.name`*:: + -- type: keyword example: boston-dc User-defined description of a location, at the level of granularity they care about. Could be the name of their data centers, the floor number, if this describes a local physical entity, city names. Not typically used in automated geolocation. -- [float] == organization fields The organization fields enrich data with information about the company or entity the data is associated with. These fields help you arrange or filter data stored in an index by one or multiple organizations. *`organization.name`*:: + -- type: keyword Organization name. -- *`organization.id`*:: + -- type: keyword Unique identifier for the organization. -- [float] == os fields The OS fields contain information about the operating system. *`os.platform`*:: + -- type: keyword example: darwin Operating system platform (such centos, ubuntu, windows). -- *`os.name`*:: + -- type: keyword example: Mac OS X Operating system name. -- *`os.family`*:: + -- type: keyword example: debian OS family (such as redhat, debian, freebsd, windows). -- *`os.version`*:: + -- type: keyword example: 10.12.6-rc2 Operating system version as a raw string. -- *`os.kernel`*:: + -- type: keyword example: 4.4.0-112-generic Operating system kernel version as a raw string. -- [float] == process fields These fields contain information about a process. These fields can help you correlate metrics information with a process id/name from a log message. The `process.pid` often stays in the metric itself and is copied to the global field for correlation. *`process.pid`*:: + -- type: long Process id. -- *`process.name`*:: + -- type: keyword example: ssh Process name. Sometimes called program name or similar. -- *`process.ppid`*:: + -- type: long Process parent id. -- *`process.args`*:: + -- type: keyword example: ['ssh', '-l', 'user', '10.0.0.16'] Process arguments. May be filtered to protect sensitive information. -- *`process.executable`*:: + -- type: keyword example: /usr/bin/ssh Absolute path to the process executable. -- *`process.title`*:: + -- type: keyword Process title. The proctitle, some times the same as process name. Can also be different: for example a browser setting its title to the web page currently opened. -- *`process.thread.id`*:: + -- type: long example: 4242 Thread ID. -- *`process.start`*:: + -- type: date example: 2016-05-23T08:05:34.853Z The time the process started. -- *`process.working_directory`*:: + -- type: keyword example: /home/alice The working directory of the process. -- [float] == related fields This field set is meant to facilitate pivoting around a piece of data. Some pieces of information can be seen in many places in ECS. To facilitate searching for them, append values to their corresponding field in `related.`. A concrete example is IP addresses, which can be under host, observer, source, destination, client, server, and network.forwarded_ip. If you append all IPs to `related.ip`, you can then search for a given IP trivially, no matter where it appeared, by querying `related.ip:a.b.c.d`. *`related.ip`*:: + -- type: ip All of the IPs seen on your event. -- [float] == server fields A Server is defined as the responder in a network connection for events regarding sessions, connections, or bidirectional flow records. For TCP events, the server is the receiver of the initial SYN packet(s) of the TCP connection. For other protocols, the server is generally the responder in the network transaction. Some systems actually use the term ""responder"" to refer the server in TCP connections. The server fields describe details about the system acting as the server in the network event. Server fields are usually populated in conjunction with client fields. Server fields are generally not populated for packet-level events. *`server.ip`*:: + -- type: ip IP address of the server. Can be one or multiple IPv4 or IPv6 addresses. -- *`server.port`*:: + -- type: long Port of the server. -- *`server.mac`*:: + -- type: keyword MAC address of the server. -- *`server.domain`*:: + -- type: keyword Server domain. -- *`server.bytes`*:: + -- type: long example: 184 Bytes sent from the server to the client. -- *`server.packets`*:: + -- type: long example: 12 Packets sent from the server to the client. -- [float] == geo fields Geo fields can carry data about a specific location related to an event or geo information derived from an IP field. *`server.geo.location`*:: + -- type: geo_point example: { ""lon"": -73.614830, ""lat"": 45.505918 } Longitude and latitude. -- *`server.geo.continent_name`*:: + -- type: keyword example: North America Name of the continent. -- *`server.geo.country_name`*:: + -- type: keyword example: Canada Country name. -- *`server.geo.region_name`*:: + -- type: keyword example: Quebec Region name. -- *`server.geo.city_name`*:: + -- type: keyword example: Montreal City name. -- *`server.geo.country_iso_code`*:: + -- type: keyword example: CA Country ISO code. -- *`server.geo.region_iso_code`*:: + -- type: keyword example: CA-QC Region ISO code. -- *`server.geo.name`*:: + -- type: keyword example: boston-dc User-defined description of a location, at the level of granularity they care about. Could be the name of their data centers, the floor number, if this describes a local physical entity, city names. Not typically used in automated geolocation. -- [float] == service fields The service fields describe the service for or from which the data was collected. These fields help you find and correlate logs for a specific service and version. *`service.id`*:: + -- type: keyword example: d37e5ebfe0ae6c4972dbe9f0174a1637bb8247f6 Unique identifier of the running service. This id should uniquely identify this service. This makes it possible to correlate logs and metrics for one specific service. Example: If you are experiencing issues with one redis instance, you can filter on that id to see metrics and logs for that single instance. -- *`service.name`*:: + -- type: keyword example: elasticsearch-metrics Name of the service data is collected from. The name of the service is normally user given. This allows if two instances of the same service are running on the same machine they can be differentiated by the `service.name`. Also it allows for distributed services that run on multiple hosts to correlate the related instances based on the name. In the case of Elasticsearch the service.name could contain the cluster name. For Beats the service.name is by default a copy of the `service.type` field if no name is specified. -- *`service.type`*:: + -- type: keyword example: elasticsearch The type of the service data is collected from. The type can be used to group and correlate logs and metrics from one service type. Example: If logs or metrics are collected from Elasticsearch, `service.type` would be `elasticsearch`. -- *`service.state`*:: + -- type: keyword Current state of the service. -- *`service.version`*:: + -- type: keyword example: 3.2.4 Version of the service the data was collected from. This allows to look at a data set only for a specific version of a service. -- *`service.ephemeral_id`*:: + -- type: keyword example: 8a4f500f Ephemeral identifier of this service (if one exists). This id normally changes across restarts, but `service.id` does not. -- [float] == source fields Source fields describe details about the source of a packet/event. Source fields are usually populated in conjunction with destination fields. *`source.address`*:: + -- type: keyword Some event source addresses are defined ambiguously. The event will sometimes list an IP, a domain or a unix socket. You should always store the raw address in the `.address` field. Then it should be duplicated to `.ip` or `.domain`, depending on which one it is. -- *`source.ip`*:: + -- type: ip IP address of the source. Can be one or multiple IPv4 or IPv6 addresses. -- *`source.port`*:: + -- type: long Port of the source. -- *`source.mac`*:: + -- type: keyword MAC address of the source. -- *`source.domain`*:: + -- type: keyword Source domain. -- *`source.bytes`*:: + -- type: long example: 184 Bytes sent from the source to the destination. -- *`source.packets`*:: + -- type: long example: 12 Packets sent from the source to the destination. -- [float] == geo fields Geo fields can carry data about a specific location related to an event or geo information derived from an IP field. *`source.geo.location`*:: + -- type: geo_point example: { ""lon"": -73.614830, ""lat"": 45.505918 } Longitude and latitude. -- *`source.geo.continent_name`*:: + -- type: keyword example: North America Name of the continent. -- *`source.geo.country_name`*:: + -- type: keyword example: Canada Country name. -- *`source.geo.region_name`*:: + -- type: keyword example: Quebec Region name. -- *`source.geo.city_name`*:: + -- type: keyword example: Montreal City name. -- *`source.geo.country_iso_code`*:: + -- type: keyword example: CA Country ISO code. -- *`source.geo.region_iso_code`*:: + -- type: keyword example: CA-QC Region ISO code. -- *`source.geo.name`*:: + -- type: keyword example: boston-dc User-defined description of a location, at the level of granularity they care about. Could be the name of their data centers, the floor number, if this describes a local physical entity, city names. Not typically used in automated geolocation. -- [float] == url fields URL fields provide a complete URL, with scheme, host, and path. *`url.original`*:: + -- type: keyword example: https://www.elastic.co:443/search?q=elasticsearch#top or /search?q=elasticsearch Unmodified original url as seen in the event source. Note that in network monitoring, the observed URL may be a full URL, whereas in access logs, the URL is often just represented as a path. This field is meant to represent the URL as it was observed, complete or not. -- *`url.full`*:: + -- type: keyword example: https://www.elastic.co:443/search?q=elasticsearch#top If full URLs are important to your use case, they should be stored in `url.full`, whether this field is reconstructed or present in the event source. -- *`url.scheme`*:: + -- type: keyword example: https Scheme of the request, such as ""https"". Note: The `:` is not part of the scheme. -- *`url.domain`*:: + -- type: keyword example: www.elastic.co Domain of the request, such as ""www.elastic.co"". In some cases a URL may refer to an IP and/or port directly, without a domain name. In this case, the IP address would go to the `domain` field. -- *`url.port`*:: + -- type: integer example: 443 Port of the request, such as 443. -- *`url.path`*:: + -- type: keyword Path of the request, such as ""/search"". -- *`url.query`*:: + -- type: keyword The query field describes the query string of the request, such as ""q=elasticsearch"". The `?` is excluded from the query string. If a URL contains no `?`, there is no query field. If there is a `?` but no query, the query field exists with an empty string. The `exists` query can be used to differentiate between the two cases. -- *`url.fragment`*:: + -- type: keyword Portion of the url after the `#`, such as ""top"". The `#` is not part of the fragment. -- *`url.username`*:: + -- type: keyword Username of the request. -- *`url.password`*:: + -- type: keyword Password of the request. -- [float] == user fields The user fields describe information about the user that is relevant to the event. Fields can have one entry or multiple entries. If a user has more than one id, provide an array that includes all of them. *`user.id`*:: + -- type: keyword One or multiple unique identifiers of the user. -- *`user.name`*:: + -- type: keyword example: albert Short name or login of the user. -- *`user.full_name`*:: + -- type: keyword example: Albert Einstein User's full name, if available. -- *`user.email`*:: + -- type: keyword User email address. -- *`user.hash`*:: + -- type: keyword Unique user hash to correlate information for a user in anonymized form. Useful if `user.id` or `user.name` contain confidential information and cannot be used. -- *`user.group`*:: + -- type: keyword Group the user is a part of. This field can contain a list of groups, if necessary. -- [float] == user_agent fields The user_agent fields normally come from a browser request. They often show up in web service logs coming from the parsed user agent string. *`user_agent.original`*:: + -- type: keyword example: Mozilla/5.0 (iPhone; CPU iPhone OS 12_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1 Unparsed version of the user_agent. Field is not indexed. -- *`user_agent.name`*:: + -- type: keyword example: Safari Name of the user agent. -- *`user_agent.version`*:: + -- type: keyword example: 12.0 Version of the user agent. -- *`user_agent.device.name`*:: + -- type: keyword example: iPhone Name of the device. -- [float] == os fields The OS fields contain information about the operating system. *`user_agent.os.platform`*:: + -- type: keyword example: darwin Operating system platform (such centos, ubuntu, windows). -- *`user_agent.os.name`*:: + -- type: keyword example: Mac OS X Operating system name. -- *`user_agent.os.family`*:: + -- type: keyword example: debian OS family (such as redhat, debian, freebsd, windows). -- *`user_agent.os.version`*:: + -- type: keyword example: 10.12.6-rc2 Operating system version as a raw string. -- *`user_agent.os.kernel`*:: + -- type: keyword example: 4.4.0-112-generic Operating system kernel version as a raw string. -- *`beat.name`*:: + -- type: alias alias to: agent.type -- *`beat.hostname`*:: + -- type: alias alias to: agent.hostname -- *`agent.hostname`*:: + -- type: keyword Hostname of the agent. -- *`user_agent.patch`*:: + -- type: keyword Patch version of the user agent. -- *`user_agent.minor`*:: + -- type: keyword Minor version of the user agent. -- *`user_agent.major`*:: + -- type: keyword Major version of the user agent. -- *`user_agent.device`*:: + -- type: keyword Name of the physical device. -- *`user_agent.os.major`*:: + -- type: long Major version of the operating system. -- *`user_agent.os.minor`*:: + -- type: long Minor version of the operating system. -- *`url.hostname`*:: + -- type: keyword Hostname of the request, such as ""elastic.co"". -- [[exported-fields-host-processor]] == Host fields Info collected for the host machine. [[exported-fields-kubernetes-processor]] == Kubernetes fields Kubernetes metadata added by the kubernetes processor *`kubernetes.pod.name`*:: + -- type: keyword Kubernetes pod name -- *`kubernetes.pod.uid`*:: + -- type: keyword Kubernetes Pod UID -- *`kubernetes.namespace`*:: + -- type: keyword Kubernetes namespace -- *`kubernetes.node.name`*:: + -- type: keyword Kubernetes node name -- *`kubernetes.labels`*:: + -- type: object Kubernetes labels map -- *`kubernetes.annotations`*:: + -- type: object Kubernetes annotations map -- *`kubernetes.container.name`*:: + -- type: keyword Kubernetes container name -- *`kubernetes.container.image`*:: + -- type: keyword Kubernetes container image -- ",12127,True,2934.476555957716,median "// Copyright 2008-present Contributors to the OpenImageIO project. // SPDX-License-Identifier: BSD-3-Clause // https://github.com/OpenImageIO/oiio #include #include #ifndef _WIN32 # include #endif #include #include ""imageviewer.h"" #include ""ivgl.h"" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include ""ivutils.h"" namespace { inline bool IsSpecSrgb(const ImageSpec& spec) { return Strutil::iequals(spec.get_string_attribute(""oiio:ColorSpace""), ""sRGB""); } } // namespace // clang-format off static const char *s_file_filters = """" ""Image Files (*.bmp *.cin *.dcm *.dds *.dpx *.fits *.gif *.hdr *.ico *.iff "" ""*.jpg *.jpe *.jpeg *.jif *.jfif *.jfi *.jp2 *.j2k *.exr *.png *.pbm *.pgm "" ""*.ppm *.psd *.ptex *.rla *.sgi *.rgb *.rgba *.bw *.int *.inta *.pic *.tga "" ""*.tpic *.tif *.tiff *.tx *.env *.sm *.vsm *.vdb *.webp *.zfile);;"" ""BMP (*.bmp);;"" ""Cineon (*.cin);;"" ""Direct Draw Surface (*.dds);;"" ""DICOM (*.dcm);;"" ""DPX (*.dpx);;"" ""FITS (*.fits);;"" ""GIF (*.gif);;"" ""HDR/RGBE (*.hdr);;"" ""Icon (*.ico);;"" ""IFF (*.iff);;"" ""JPEG (*.jpg *.jpe *.jpeg *.jif *.jfif *.jfi);;"" ""JPEG-2000 (*.jp2 *.j2k);;"" ""OpenEXR (*.exr);;"" ""OpenVDB (*.vdb);;"" ""PhotoShop (*.psd);;"" ""Portable Network Graphics (*.png);;"" ""PNM / Netpbm (*.pbm *.pgm *.ppm);;"" ""Ptex (*.ptex);;"" ""RLA (*.rla);;"" ""SGI (*.sgi *.rgb *.rgba *.bw *.int *.inta);;"" ""Softimage PIC (*.pic);;"" ""Targa (*.tga *.tpic);;"" ""TIFF (*.tif *.tiff *.tx *.env *.sm *.vsm);;"" ""Webp (*.webp);;"" ""Zfile (*.zfile);;"" ""All Files (*)""; // clang-format on ImageViewer::ImageViewer() : infoWindow(NULL) , preferenceWindow(NULL) , darkPaletteBox(NULL) , m_current_image(-1) , m_current_channel(0) , m_color_mode(RGBA) , m_last_image(-1) , m_zoom(1) , m_fullscreen(false) , m_default_gamma(1) , m_darkPalette(false) { readSettings(false); float gam = Strutil::stof(Sysutil::getenv(""GAMMA"")); if (gam >= 0.1 && gam <= 5) m_default_gamma = gam; // FIXME -- would be nice to have a more nuanced approach to display // color space, in particular knowing whether the display is sRGB. // Also, some time in the future we may want a real 3D LUT for // ""film look"", etc. if (darkPalette()) m_palette = QPalette(Qt::darkGray); // darkGray? else m_palette = QPalette(); QApplication::setPalette(m_palette); // FIXME -- why not work? this->setPalette(m_palette); slideTimer = new QTimer(); slideDuration_ms = 5000; slide_loop = true; glwin = new IvGL(this, *this); glwin->setPalette(m_palette); glwin->resize(m_default_width, m_default_height); setCentralWidget(glwin); createActions(); createMenus(); createToolBars(); createStatusBar(); readSettings(); setWindowTitle(tr(""Image Viewer"")); resize(m_default_width, m_default_height); // setSizePolicy (QSizePolicy::Ignored, QSizePolicy::Ignored); } ImageViewer::~ImageViewer() { for (auto i : m_images) delete i; } void ImageViewer::closeEvent(QCloseEvent*) { writeSettings(); } void ImageViewer::createActions() { openAct = new QAction(tr(""&Open...""), this); openAct->setShortcut(tr(""Ctrl+O"")); connect(openAct, SIGNAL(triggered()), this, SLOT(open())); for (auto& i : openRecentAct) { i = new QAction(this); i->setVisible(false); connect(i, SIGNAL(triggered()), this, SLOT(openRecentFile())); } reloadAct = new QAction(tr(""&Reload image""), this); reloadAct->setShortcut(tr(""Ctrl+R"")); connect(reloadAct, SIGNAL(triggered()), this, SLOT(reload())); closeImgAct = new QAction(tr(""&Close Image""), this); closeImgAct->setShortcut(tr(""Ctrl+W"")); connect(closeImgAct, SIGNAL(triggered()), this, SLOT(closeImg())); saveAsAct = new QAction(tr(""&Save As...""), this); saveAsAct->setShortcut(tr(""Ctrl+S"")); connect(saveAsAct, SIGNAL(triggered()), this, SLOT(saveAs())); saveWindowAsAct = new QAction(tr(""Save Window As...""), this); connect(saveWindowAsAct, SIGNAL(triggered()), this, SLOT(saveWindowAs())); saveSelectionAsAct = new QAction(tr(""Save Selection As...""), this); connect(saveSelectionAsAct, SIGNAL(triggered()), this, SLOT(saveSelectionAs())); printAct = new QAction(tr(""&Print...""), this); printAct->setShortcut(tr(""Ctrl+P"")); printAct->setEnabled(false); connect(printAct, SIGNAL(triggered()), this, SLOT(print())); deleteCurrentImageAct = new QAction(tr(""&Delete from disk""), this); deleteCurrentImageAct->setShortcut(tr(""Delete"")); connect(deleteCurrentImageAct, SIGNAL(triggered()), this, SLOT(deleteCurrentImage())); editPreferencesAct = new QAction(tr(""&Preferences...""), this); editPreferencesAct->setShortcut(tr(""Ctrl+,"")); editPreferencesAct->setEnabled(true); connect(editPreferencesAct, SIGNAL(triggered()), this, SLOT(editPreferences())); exitAct = new QAction(tr(""E&xit""), this); exitAct->setShortcut(tr(""Ctrl+Q"")); connect(exitAct, SIGNAL(triggered()), this, SLOT(close())); exposurePlusOneTenthStopAct = new QAction(tr(""Exposure +1/10 stop""), this); exposurePlusOneTenthStopAct->setShortcut(tr(""]"")); connect(exposurePlusOneTenthStopAct, SIGNAL(triggered()), this, SLOT(exposurePlusOneTenthStop())); exposurePlusOneHalfStopAct = new QAction(tr(""Exposure +1/2 stop""), this); exposurePlusOneHalfStopAct->setShortcut(tr(""}"")); connect(exposurePlusOneHalfStopAct, SIGNAL(triggered()), this, SLOT(exposurePlusOneHalfStop())); exposureMinusOneTenthStopAct = new QAction(tr(""Exposure -1/10 stop""), this); exposureMinusOneTenthStopAct->setShortcut(tr(""["")); connect(exposureMinusOneTenthStopAct, SIGNAL(triggered()), this, SLOT(exposureMinusOneTenthStop())); exposureMinusOneHalfStopAct = new QAction(tr(""Exposure -1/2 stop""), this); exposureMinusOneHalfStopAct->setShortcut(tr(""{"")); connect(exposureMinusOneHalfStopAct, SIGNAL(triggered()), this, SLOT(exposureMinusOneHalfStop())); gammaPlusAct = new QAction(tr(""Gamma +0.1""), this); gammaPlusAct->setShortcut(tr("")"")); connect(gammaPlusAct, SIGNAL(triggered()), this, SLOT(gammaPlus())); gammaMinusAct = new QAction(tr(""Gamma -0.1""), this); gammaMinusAct->setShortcut(tr(""("")); connect(gammaMinusAct, SIGNAL(triggered()), this, SLOT(gammaMinus())); viewChannelFullAct = new QAction(tr(""Full Color""), this); viewChannelFullAct->setShortcut(tr(""c"")); viewChannelFullAct->setCheckable(true); viewChannelFullAct->setChecked(true); connect(viewChannelFullAct, SIGNAL(triggered()), this, SLOT(viewChannelFull())); viewChannelRedAct = new QAction(tr(""Red""), this); viewChannelRedAct->setShortcut(tr(""r"")); viewChannelRedAct->setCheckable(true); connect(viewChannelRedAct, SIGNAL(triggered()), this, SLOT(viewChannelRed())); viewChannelGreenAct = new QAction(tr(""Green""), this); viewChannelGreenAct->setShortcut(tr(""g"")); viewChannelGreenAct->setCheckable(true); connect(viewChannelGreenAct, SIGNAL(triggered()), this, SLOT(viewChannelGreen())); viewChannelBlueAct = new QAction(tr(""Blue""), this); viewChannelBlueAct->setShortcut(tr(""b"")); viewChannelBlueAct->setCheckable(true); connect(viewChannelBlueAct, SIGNAL(triggered()), this, SLOT(viewChannelBlue())); viewChannelAlphaAct = new QAction(tr(""Alpha""), this); viewChannelAlphaAct->setShortcut(tr(""a"")); viewChannelAlphaAct->setCheckable(true); connect(viewChannelAlphaAct, SIGNAL(triggered()), this, SLOT(viewChannelAlpha())); viewColorLumAct = new QAction(tr(""Luminance""), this); viewColorLumAct->setShortcut(tr(""l"")); viewColorLumAct->setCheckable(true); connect(viewColorLumAct, SIGNAL(triggered()), this, SLOT(viewChannelLuminance())); viewColorRGBAAct = new QAction(tr(""RGBA""), this); //viewColorRGBAAct->setShortcut (tr(""Ctrl+c"")); viewColorRGBAAct->setCheckable(true); viewColorRGBAAct->setChecked(true); connect(viewColorRGBAAct, SIGNAL(triggered()), this, SLOT(viewColorRGBA())); viewColorRGBAct = new QAction(tr(""RGB""), this); //viewColorRGBAct->setShortcut (tr(""Ctrl+a"")); viewColorRGBAct->setCheckable(true); connect(viewColorRGBAct, SIGNAL(triggered()), this, SLOT(viewColorRGB())); viewColor1ChAct = new QAction(tr(""Single channel""), this); viewColor1ChAct->setShortcut(tr(""1"")); viewColor1ChAct->setCheckable(true); connect(viewColor1ChAct, SIGNAL(triggered()), this, SLOT(viewColor1Ch())); viewColorHeatmapAct = new QAction(tr(""Single channel (Heatmap)""), this); viewColorHeatmapAct->setShortcut(tr(""h"")); viewColorHeatmapAct->setCheckable(true); connect(viewColorHeatmapAct, SIGNAL(triggered()), this, SLOT(viewColorHeatmap())); viewChannelPrevAct = new QAction(tr(""Prev Channel""), this); viewChannelPrevAct->setShortcut(tr("","")); connect(viewChannelPrevAct, SIGNAL(triggered()), this, SLOT(viewChannelPrev())); viewChannelNextAct = new QAction(tr(""Next Channel""), this); viewChannelNextAct->setShortcut(tr(""."")); connect(viewChannelNextAct, SIGNAL(triggered()), this, SLOT(viewChannelNext())); viewSubimagePrevAct = new QAction(tr(""Prev Subimage""), this); viewSubimagePrevAct->setShortcut(tr(""<"")); connect(viewSubimagePrevAct, SIGNAL(triggered()), this, SLOT(viewSubimagePrev())); viewSubimageNextAct = new QAction(tr(""Next Subimage""), this); viewSubimageNextAct->setShortcut(tr("">"")); connect(viewSubimageNextAct, SIGNAL(triggered()), this, SLOT(viewSubimageNext())); zoomInAct = new QAction(tr(""Zoom &In""), this); zoomInAct->setShortcut(tr(""Ctrl++"")); connect(zoomInAct, SIGNAL(triggered()), this, SLOT(zoomIn())); zoomOutAct = new QAction(tr(""Zoom &Out""), this); zoomOutAct->setShortcut(tr(""Ctrl+-"")); connect(zoomOutAct, SIGNAL(triggered()), this, SLOT(zoomOut())); normalSizeAct = new QAction(tr(""&Normal Size (1:1)""), this); normalSizeAct->setShortcut(tr(""Ctrl+0"")); connect(normalSizeAct, SIGNAL(triggered()), this, SLOT(normalSize())); fitWindowToImageAct = new QAction(tr(""&Fit Window to Image""), this); fitWindowToImageAct->setShortcut(tr(""f"")); connect(fitWindowToImageAct, SIGNAL(triggered()), this, SLOT(fitWindowToImage())); fitImageToWindowAct = new QAction(tr(""Fit Image to Window""), this); // fitImageToWindowAct->setEnabled(false); fitImageToWindowAct->setCheckable(true); fitImageToWindowAct->setShortcut(tr(""Alt+f"")); connect(fitImageToWindowAct, SIGNAL(triggered()), this, SLOT(fitImageToWindow())); fullScreenAct = new QAction(tr(""Full screen""), this); // fullScreenAct->setEnabled(false); // fullScreenAct->setCheckable(true); fullScreenAct->setShortcut(tr(""Ctrl+f"")); connect(fullScreenAct, SIGNAL(triggered()), this, SLOT(fullScreenToggle())); aboutAct = new QAction(tr(""&About""), this); connect(aboutAct, SIGNAL(triggered()), this, SLOT(about())); prevImageAct = new QAction(tr(""Previous Image""), this); prevImageAct->setShortcut(tr(""PgUp"")); // prevImageAct->setEnabled(true); connect(prevImageAct, SIGNAL(triggered()), this, SLOT(prevImage())); nextImageAct = new QAction(tr(""Next Image""), this); nextImageAct->setShortcut(tr(""PgDown"")); // nextImageAct->setEnabled(true); connect(nextImageAct, SIGNAL(triggered()), this, SLOT(nextImage())); toggleImageAct = new QAction(tr(""Toggle image""), this); toggleImageAct->setShortcut(tr(""T"")); // toggleImageAct->setEnabled(true); connect(toggleImageAct, SIGNAL(triggered()), this, SLOT(toggleImage())); slideShowAct = new QAction(tr(""Start Slide Show""), this); connect(slideShowAct, SIGNAL(triggered()), this, SLOT(slideShow())); slideLoopAct = new QAction(tr(""Loop slide show""), this); slideLoopAct->setCheckable(true); slideLoopAct->setChecked(true); connect(slideLoopAct, SIGNAL(triggered()), this, SLOT(slideLoop())); slideNoLoopAct = new QAction(tr(""Stop at end""), this); slideNoLoopAct->setCheckable(true); connect(slideNoLoopAct, SIGNAL(triggered()), this, SLOT(slideNoLoop())); sortByNameAct = new QAction(tr(""By Name""), this); connect(sortByNameAct, SIGNAL(triggered()), this, SLOT(sortByName())); sortByPathAct = new QAction(tr(""By File Path""), this); connect(sortByPathAct, SIGNAL(triggered()), this, SLOT(sortByPath())); sortByImageDateAct = new QAction(tr(""By Image Date""), this); connect(sortByImageDateAct, SIGNAL(triggered()), this, SLOT(sortByImageDate())); sortByFileDateAct = new QAction(tr(""By File Date""), this); connect(sortByFileDateAct, SIGNAL(triggered()), this, SLOT(sortByFileDate())); sortReverseAct = new QAction(tr(""Reverse current order""), this); connect(sortReverseAct, SIGNAL(triggered()), this, SLOT(sortReverse())); showInfoWindowAct = new QAction(tr(""&Image info...""), this); showInfoWindowAct->setShortcut(tr(""Ctrl+I"")); // showInfoWindowAct->setEnabled(true); connect(showInfoWindowAct, SIGNAL(triggered()), this, SLOT(showInfoWindow())); showPixelviewWindowAct = new QAction(tr(""&Pixel closeup view...""), this); showPixelviewWindowAct->setCheckable(true); showPixelviewWindowAct->setShortcut(tr(""P"")); connect(showPixelviewWindowAct, SIGNAL(triggered()), this, SLOT(showPixelviewWindow())); pixelviewFollowsMouseBox = new QCheckBox(tr(""Pixel view follows mouse"")); pixelviewFollowsMouseBox->setChecked(false); linearInterpolationBox = new QCheckBox(tr(""Linear interpolation"")); linearInterpolationBox->setChecked(true); darkPaletteBox = new QCheckBox(tr(""Dark palette"")); darkPaletteBox->setChecked(true); autoMipmap = new QCheckBox(tr(""Generate mipmaps (requires restart)"")); autoMipmap->setChecked(false); maxMemoryICLabel = new QLabel( tr(""Image Cache max memory (requires restart)"")); maxMemoryIC = new QSpinBox(); if (sizeof(void*) == 4) maxMemoryIC->setRange(128, 2048); //2GB is enough for 32 bit machines else maxMemoryIC->setRange(128, 8192); //8GB probably ok for 64 bit maxMemoryIC->setSingleStep(64); maxMemoryIC->setSuffix("" MB""); slideShowDurationLabel = new QLabel(tr(""Slide Show delay"")); slideShowDuration = new QSpinBox(); slideShowDuration->setRange(1, 3600); slideShowDuration->setSingleStep(1); slideShowDuration->setSuffix("" s""); slideShowDuration->setAccelerated(true); connect(slideShowDuration, SIGNAL(valueChanged(int)), this, SLOT(setSlideShowDuration(int))); } void ImageViewer::createMenus() { openRecentMenu = new QMenu(tr(""Open recent...""), this); for (auto& i : openRecentAct) openRecentMenu->addAction(i); fileMenu = new QMenu(tr(""&File""), this); fileMenu->addAction(openAct); fileMenu->addMenu(openRecentMenu); fileMenu->addAction(reloadAct); fileMenu->addAction(closeImgAct); fileMenu->addSeparator(); fileMenu->addAction(saveAsAct); fileMenu->addAction(saveWindowAsAct); fileMenu->addAction(saveSelectionAsAct); fileMenu->addSeparator(); fileMenu->addAction(printAct); fileMenu->addAction(deleteCurrentImageAct); fileMenu->addSeparator(); fileMenu->addAction(editPreferencesAct); fileMenu->addAction(exitAct); menuBar()->addMenu(fileMenu); // Copy // Paste // Clear selection // radio: prioritize selection, crop selection expgamMenu = new QMenu(tr(""Exposure/gamma"")); // submenu expgamMenu->addAction(exposureMinusOneHalfStopAct); expgamMenu->addAction(exposureMinusOneTenthStopAct); expgamMenu->addAction(exposurePlusOneHalfStopAct); expgamMenu->addAction(exposurePlusOneTenthStopAct); expgamMenu->addAction(gammaMinusAct); expgamMenu->addAction(gammaPlusAct); // imageMenu = new QMenu(tr(""&Image""), this); // menuBar()->addMenu (imageMenu); slideMenu = new QMenu(tr(""Slide Show"")); slideMenu->addAction(slideShowAct); slideMenu->addAction(slideLoopAct); slideMenu->addAction(slideNoLoopAct); sortMenu = new QMenu(tr(""Sort"")); sortMenu->addAction(sortByNameAct); sortMenu->addAction(sortByPathAct); sortMenu->addAction(sortByImageDateAct); sortMenu->addAction(sortByFileDateAct); sortMenu->addAction(sortReverseAct); channelMenu = new QMenu(tr(""Channels"")); // Color mode: true, random, falsegrgbacCrgR channelMenu->addAction(viewChannelFullAct); channelMenu->addAction(viewChannelRedAct); channelMenu->addAction(viewChannelGreenAct); channelMenu->addAction(viewChannelBlueAct); channelMenu->addAction(viewChannelAlphaAct); channelMenu->addAction(viewChannelPrevAct); channelMenu->addAction(viewChannelNextAct); colormodeMenu = new QMenu(tr(""Color mode"")); colormodeMenu->addAction(viewColorRGBAAct); colormodeMenu->addAction(viewColorRGBAct); colormodeMenu->addAction(viewColor1ChAct); colormodeMenu->addAction(viewColorLumAct); colormodeMenu->addAction(viewColorHeatmapAct); viewMenu = new QMenu(tr(""&View""), this); viewMenu->addAction(prevImageAct); viewMenu->addAction(nextImageAct); viewMenu->addAction(toggleImageAct); viewMenu->addSeparator(); viewMenu->addAction(zoomInAct); viewMenu->addAction(zoomOutAct); viewMenu->addAction(normalSizeAct); viewMenu->addAction(fitWindowToImageAct); viewMenu->addAction(fitImageToWindowAct); viewMenu->addAction(fullScreenAct); viewMenu->addSeparator(); viewMenu->addAction(viewSubimagePrevAct); viewMenu->addAction(viewSubimageNextAct); viewMenu->addMenu(channelMenu); viewMenu->addMenu(colormodeMenu); viewMenu->addMenu(expgamMenu); menuBar()->addMenu(viewMenu); // Full screen mode // prev subimage <, next subimage > // fg/bg image... toolsMenu = new QMenu(tr(""&Tools""), this); // Mode: select, zoom, pan, wipe toolsMenu->addAction(showInfoWindowAct); toolsMenu->addAction(showPixelviewWindowAct); toolsMenu->addMenu(slideMenu); toolsMenu->addMenu(sortMenu); // Menus, toolbars, & status // Annotate // [check] overwrite render // connect renderer // kill renderer // store render // Playback: forward, reverse, faster, slower, loop/pingpong menuBar()->addMenu(toolsMenu); helpMenu = new QMenu(tr(""&Help""), this); helpMenu->addAction(aboutAct); menuBar()->addMenu(helpMenu); // Bring up user's guide } void ImageViewer::createToolBars() { #if 0 fileToolBar = addToolBar(tr(""File"")); fileToolBar->addAction(newAct); fileToolBar->addAction(openAct); fileToolBar->addAction(saveAct); editToolBar = addToolBar(tr(""Edit"")); editToolBar->addAction(cutAct); editToolBar->addAction(copyAct); editToolBar->addAction(pasteAct); #endif } void ImageViewer::createStatusBar() { statusImgInfo = new QLabel; statusBar()->addWidget(statusImgInfo); statusViewInfo = new QLabel; statusBar()->addWidget(statusViewInfo); statusProgress = new QProgressBar; statusProgress->setRange(0, 100); statusProgress->reset(); statusBar()->addWidget(statusProgress); mouseModeComboBox = new QComboBox; mouseModeComboBox->addItem(tr(""Zoom"")); mouseModeComboBox->addItem(tr(""Pan"")); mouseModeComboBox->addItem(tr(""Wipe"")); mouseModeComboBox->addItem(tr(""Select"")); mouseModeComboBox->addItem(tr(""Annotate"")); // Note: the order of the above MUST match the order of enum MouseMode statusBar()->addWidget(mouseModeComboBox); mouseModeComboBox->hide(); } void ImageViewer::readSettings(bool ui_is_set_up) { QSettings settings(""OpenImageIO"", ""iv""); m_darkPalette = settings.value(""darkPalette"").toBool(); if (!ui_is_set_up) return; pixelviewFollowsMouseBox->setChecked( settings.value(""pixelviewFollowsMouse"").toBool()); linearInterpolationBox->setChecked( settings.value(""linearInterpolation"").toBool()); darkPaletteBox->setChecked(settings.value(""darkPalette"").toBool()); QStringList recent = settings.value(""RecentFiles"").toStringList(); for (auto&& s : recent) addRecentFile(s.toStdString()); updateRecentFilesMenu(); // only safe because it's called after menu setup autoMipmap->setChecked(settings.value(""autoMipmap"", false).toBool()); if (sizeof(void*) == 4) // 32 bit or 64? maxMemoryIC->setValue(settings.value(""maxMemoryIC"", 512).toInt()); else maxMemoryIC->setValue(settings.value(""maxMemoryIC"", 2048).toInt()); slideShowDuration->setValue( settings.value(""slideShowDuration"", 10).toInt()); ImageCache* imagecache = ImageCache::create(true); imagecache->attribute(""automip"", autoMipmap->isChecked()); imagecache->attribute(""max_memory_MB"", (float)maxMemoryIC->value()); } void ImageViewer::writeSettings() { QSettings settings(""OpenImageIO"", ""iv""); settings.setValue(""pixelviewFollowsMouse"", pixelviewFollowsMouseBox->isChecked()); settings.setValue(""linearInterpolation"", linearInterpolationBox->isChecked()); settings.setValue(""darkPalette"", darkPaletteBox->isChecked()); settings.setValue(""autoMipmap"", autoMipmap->isChecked()); settings.setValue(""maxMemoryIC"", maxMemoryIC->value()); settings.setValue(""slideShowDuration"", slideShowDuration->value()); QStringList recent; for (auto&& s : m_recent_files) recent.push_front(QString(s.c_str())); settings.setValue(""RecentFiles"", recent); } bool image_progress_callback(void* opaque, float done) { ImageViewer* viewer = (ImageViewer*)opaque; viewer->statusProgress->setValue((int)(done * 100)); QApplication::processEvents(); return false; } void ImageViewer::open() { static QString openPath = QDir::currentPath(); QFileDialog dialog(NULL, tr(""Open File(s)""), openPath, tr(s_file_filters)); dialog.setAcceptMode(QFileDialog::AcceptOpen); dialog.setFileMode(QFileDialog::ExistingFiles); if (!dialog.exec()) return; openPath = dialog.directory().path(); QStringList names = dialog.selectedFiles(); int old_lastimage = m_images.size() - 1; for (auto& name : names) { std::string filename = name.toUtf8().data(); if (filename.empty()) continue; add_image(filename); // int n = m_images.size()-1; // IvImage *newimage = m_images[n]; // newimage->read_iv (0, false, image_progress_callback, this); } if (old_lastimage >= 0) { // Otherwise, add_image already did this for us. current_image(old_lastimage + 1); fitWindowToImage(true, true); } } void ImageViewer::openRecentFile() { QAction* action = qobject_cast(sender()); if (action) { std::string filename = action->data().toString().toStdString(); // If it's an image we already have loaded, just switch to it // (and reload) rather than loading a second copy. for (size_t i = 0; i < m_images.size(); ++i) { if (m_images[i]->name() == filename) { current_image(i); reload(); return; } } // It's not an image we already have loaded add_image(filename); if (m_images.size() > 1) { // Otherwise, add_image already did this for us. current_image(m_images.size() - 1); fitWindowToImage(true, true); } } } void ImageViewer::addRecentFile(const std::string& name) { removeRecentFile(name); m_recent_files.insert(m_recent_files.begin(), name); if (m_recent_files.size() > MaxRecentFiles) m_recent_files.resize(MaxRecentFiles); } void ImageViewer::removeRecentFile(const std::string& name) { for (size_t i = 0; i < m_recent_files.size(); ++i) { if (m_recent_files[i] == name) { m_recent_files.erase(m_recent_files.begin() + i); --i; } } } void ImageViewer::updateRecentFilesMenu() { for (size_t i = 0; i < MaxRecentFiles; ++i) { if (i < m_recent_files.size()) { std::string name = Filesystem::filename(m_recent_files[i]); openRecentAct[i]->setText(QString::fromStdString(name)); openRecentAct[i]->setData(m_recent_files[i].c_str()); openRecentAct[i]->setVisible(true); } else { openRecentAct[i]->setVisible(false); } } } void ImageViewer::reload() { if (m_images.empty()) return; IvImage* newimage = m_images[m_current_image]; newimage->invalidate(); //glwin->trigger_redraw (); displayCurrentImage(); } void ImageViewer::add_image(const std::string& filename) { if (filename.empty()) return; IvImage* newimage = nullptr; if (rawcolor()) { ImageSpec config; config.attribute(""oiio:RawColor"", 1); newimage = new IvImage(filename, &config); } else { newimage = new IvImage(filename); } newimage->gamma(m_default_gamma); m_images.push_back(newimage); addRecentFile(filename); updateRecentFilesMenu(); #if 0 if (getspec) { if (! newimage->init_spec (filename)) { QMessageBox::information (this, tr(""iv Image Viewer""), tr(""%1"").arg(newimage->geterror().c_str())); } else { std::cerr << ""Added image "" << filename << "": "" << newimage->spec().width << "" x "" << newimage->spec().height << ""\\n""; } return; } #endif if (m_images.size() == 1) { // If this is the first image, resize to fit it displayCurrentImage(); fitWindowToImage(true, true); } } void ImageViewer::saveAs() { IvImage* img = cur(); if (!img) return; QString name; name = QFileDialog::getSaveFileName(this, tr(""Save Image""), QString(img->name().c_str()), tr(s_file_filters)); if (name.isEmpty()) return; bool ok = img->write(name.toStdString(), TypeUnknown, """", image_progress_callback, this); if (!ok) { std::cerr << ""Save failed: "" << img->geterror() << ""\\n""; } } void ImageViewer::saveWindowAs() { IvImage* img = cur(); if (!img) return; QString name; name = QFileDialog::getSaveFileName(this, tr(""Save Window""), QString(img->name().c_str())); if (name.isEmpty()) return; img->write(name.toStdString(), TypeUnknown, """", image_progress_callback, this); } void ImageViewer::saveSelectionAs() { IvImage* img = cur(); if (!img) return; QString name; name = QFileDialog::getSaveFileName(this, tr(""Save Selection""), QString(img->name().c_str())); if (name.isEmpty()) return; img->write(name.toStdString(), TypeUnknown, """", image_progress_callback, this); } void ImageViewer::updateTitle() { IvImage* img = cur(); if (!img) { setWindowTitle(tr(""iv Image Viewer (no image loaded)"")); return; } std::string message; message = Strutil::sprintf(""%s - iv Image Viewer"", img->name().c_str()); setWindowTitle(QString::fromLocal8Bit(message.c_str())); } void ImageViewer::updateStatusBar() { const ImageSpec* spec = curspec(); if (!spec) { statusImgInfo->setText(tr(""No image loaded"")); statusViewInfo->setText(tr("""")); return; } std::string message; message = Strutil::sprintf(""(%d/%d) : "", m_current_image + 1, (int)m_images.size()); message += cur()->shortinfo(); statusImgInfo->setText(message.c_str()); message.clear(); switch (m_color_mode) { case RGBA: message = Strutil::sprintf(""RGBA (%d-%d)"", m_current_channel, m_current_channel + 3); break; case RGB: message = Strutil::sprintf(""RGB (%d-%d)"", m_current_channel, m_current_channel + 2); break; case LUMINANCE: message = Strutil::sprintf(""Lum (%d-%d)"", m_current_channel, m_current_channel + 2); break; case HEATMAP: message = ""Heat ""; case SINGLE_CHANNEL: if ((int)spec->channelnames.size() > m_current_channel && spec->channelnames[m_current_channel].size()) message += spec->channelnames[m_current_channel]; else if (m_color_mode == HEATMAP) { message += Strutil::sprintf(""%d"", m_current_channel); } else { message = Strutil::sprintf(""chan %d"", m_current_channel); } break; } message += Strutil::sprintf("" %g:%g exp %+.1f gam %.2f"", zoom() >= 1 ? zoom() : 1.0f, zoom() >= 1 ? 1.0f : 1.0f / zoom(), cur()->exposure(), cur()->gamma()); if (cur()->nsubimages() > 1) { if (cur()->auto_subimage()) { message += Strutil::sprintf("" subimg AUTO (%d/%d)"", cur()->subimage() + 1, cur()->nsubimages()); } else { message += Strutil::sprintf("" subimg %d/%d"", cur()->subimage() + 1, cur()->nsubimages()); } } if (cur()->nmiplevels() > 1) { message += Strutil::sprintf("" MIP %d/%d"", cur()->miplevel() + 1, cur()->nmiplevels()); } statusViewInfo->setText(message.c_str()); // tr(""iv status"")); } bool ImageViewer::loadCurrentImage(int subimage, int miplevel) { if (m_current_image < 0 || m_current_image >= (int)m_images.size()) { m_current_image = 0; } IvImage* img = cur(); if (img) { // We need the spec available to compare the image format with // opengl's capabilities. if (!img->init_spec(img->name(), subimage, miplevel)) { statusImgInfo->setText( tr(""Could not display image: %1."").arg(img->name().c_str())); statusViewInfo->setText(tr("""")); return false; } // Used to check whether we'll need to do adjustments in the // CPU. If true, images should be loaded as UINT8. bool allow_transforms = false; bool srgb_transform = false; // By default, we try to load into OpenGL with the same format, TypeDesc read_format = TypeDesc::UNKNOWN; const ImageSpec& image_spec = img->spec(); if (image_spec.format.basetype == TypeDesc::DOUBLE) { // AFAIK, OpenGL doesn't support 64-bit floats as pixel size. read_format = TypeDesc::FLOAT; } if (glwin->is_glsl_capable()) { if (image_spec.format.basetype == TypeDesc::HALF && !glwin->is_half_capable()) { //std::cerr << ""Loading HALF-FLOAT as FLOAT\\n""; read_format = TypeDesc::FLOAT; } if (IsSpecSrgb(image_spec) && !glwin->is_srgb_capable()) { // If the image is in sRGB, but OpenGL can't load sRGB textures then // we'll need to do the transformation on the CPU after loading the // image. We (so far) can only do this with UINT8 images, so make // sure that it gets loaded in this format. //std::cerr << ""Loading as UINT8 to do sRGB\\n""; read_format = TypeDesc::UINT8; srgb_transform = true; allow_transforms = true; } } else { //std::cerr << ""Loading as UINT8\\n""; read_format = TypeDesc::UINT8; allow_transforms = true; if (IsSpecSrgb(image_spec) && !glwin->is_srgb_capable()) srgb_transform = true; } // FIXME: This actually won't work since the ImageCacheFile has already // been created when we did the init_spec. // Check whether IvGL recommends generating mipmaps for this image. //ImageCache *imagecache = ImageCache::create (true); //if (glwin->is_too_big (img) && autoMipmap->isChecked ()) { // imagecache->attribute (""automip"", 1); //} else { // imagecache->attribute (""automip"", 0); //} // Read the image from disk or from the ImageCache if available. if (img->read_iv(subimage, miplevel, false, read_format, image_progress_callback, this, allow_transforms)) { // The image was read successfully. // Check if we've got to do sRGB to linear (ie, when not supported // by OpenGL). // Do the first pixel transform to fill-in the secondary image // buffer. if (allow_transforms) { img->pixel_transform(srgb_transform, (int)current_color_mode(), current_channel()); } return true; } else { statusImgInfo->setText( tr(""Could not display image: %1."").arg(img->name().c_str())); statusViewInfo->setText(tr("""")); return false; } } return false; } void ImageViewer::displayCurrentImage(bool update) { if (m_current_image < 0 || m_current_image >= (int)m_images.size()) m_current_image = 0; IvImage* img = cur(); if (img) { if (!img->image_valid()) { bool load_result = false; statusViewInfo->hide(); statusProgress->show(); load_result = loadCurrentImage(std::max(0, img->subimage()), std::max(0, img->miplevel())); statusProgress->hide(); statusViewInfo->show(); if (load_result) { update = true; } else { return; } } } else { m_current_image = m_last_image = -1; ((QOpenGLWidget*)(glwin))->update(); } if (update) { glwin->update(); } float z = zoom(); if (fitImageToWindowAct->isChecked()) z = zoom_needed_to_fit(glwin->width(), glwin->height()); zoom(z); // glwin->trigger_redraw (); updateTitle(); updateStatusBar(); if (infoWindow) infoWindow->update(img); // printAct->setEnabled(true); // fitImageToWindowAct->setEnabled(true); // fullScreenAct->setEnabled(true); updateActions(); } void ImageViewer::deleteCurrentImage() { IvImage* img = cur(); if (img) { const char* filename = img->name().c_str(); QString message(""Are you sure you want to remove ""); message = message + QString(filename) + QString("" file from disk?""); QMessageBox::StandardButton button; button = QMessageBox::question(this, """", message, QMessageBox::Yes | QMessageBox::No); if (button == QMessageBox::Yes) { closeImg(); int r = remove(filename); if (r) QMessageBox::information(this, """", ""Unable to delete file""); } } } void ImageViewer::current_image(int newimage) { #ifndef NDEBUG Timer swap_image_time; swap_image_time.start(); #endif if (m_images.empty() || newimage < 0 || newimage >= (int)m_images.size()) m_current_image = 0; if (m_current_image != newimage) { m_last_image = (m_current_image >= 0) ? m_current_image : newimage; m_current_image = newimage; displayCurrentImage(); } else { displayCurrentImage(false); } #ifndef NDEBUG swap_image_time.stop(); std::cerr << ""Current Image change elapsed time: "" << swap_image_time() << "" seconds \\n""; #endif } void ImageViewer::prevImage() { if (m_images.empty()) return; if (m_current_image == 0) current_image((int)m_images.size() - 1); else current_image(current_image() - 1); } void ImageViewer::nextImage() { if (m_images.empty()) return; if (m_current_image >= (int)m_images.size() - 1) current_image(0); else current_image(current_image() + 1); } void ImageViewer::toggleImage() { current_image(m_last_image); } void ImageViewer::exposureMinusOneTenthStop() { if (m_images.empty()) return; IvImage* img = m_images[m_current_image]; img->exposure(img->exposure() - 0.1); if (!glwin->is_glsl_capable()) { bool srgb_transform = (!glwin->is_srgb_capable() && IsSpecSrgb(img->spec())); img->pixel_transform(srgb_transform, (int)current_color_mode(), current_channel()); displayCurrentImage(); } else { displayCurrentImage(false); } } void ImageViewer::exposureMinusOneHalfStop() { if (m_images.empty()) return; IvImage* img = m_images[m_current_image]; img->exposure(img->exposure() - 0.5); if (!glwin->is_glsl_capable()) { bool srgb_transform = (!glwin->is_srgb_capable() && IsSpecSrgb(img->spec())); img->pixel_transform(srgb_transform, (int)current_color_mode(), current_channel()); displayCurrentImage(); } else { displayCurrentImage(false); } } void ImageViewer::exposurePlusOneTenthStop() { if (m_images.empty()) return; IvImage* img = m_images[m_current_image]; img->exposure(img->exposure() + 0.1); if (!glwin->is_glsl_capable()) { bool srgb_transform = (!glwin->is_srgb_capable() && IsSpecSrgb(img->spec())); img->pixel_transform(srgb_transform, (int)current_color_mode(), current_channel()); displayCurrentImage(); } else { displayCurrentImage(false); } } void ImageViewer::exposurePlusOneHalfStop() { if (m_images.empty()) return; IvImage* img = m_images[m_current_image]; img->exposure(img->exposure() + 0.5); if (!glwin->is_glsl_capable()) { bool srgb_transform = (!glwin->is_srgb_capable() && IsSpecSrgb(img->spec())); img->pixel_transform(srgb_transform, (int)current_color_mode(), current_channel()); displayCurrentImage(); } else { displayCurrentImage(false); } } void ImageViewer::gammaMinus() { if (m_images.empty()) return; IvImage* img = m_images[m_current_image]; img->gamma(img->gamma() - 0.05); if (!glwin->is_glsl_capable()) { bool srgb_transform = (!glwin->is_srgb_capable() && IsSpecSrgb(img->spec())); img->pixel_transform(srgb_transform, (int)current_color_mode(), current_channel()); displayCurrentImage(); } else { displayCurrentImage(false); } } void ImageViewer::gammaPlus() { if (m_images.empty()) return; IvImage* img = m_images[m_current_image]; img->gamma(img->gamma() + 0.05); if (!glwin->is_glsl_capable()) { bool srgb_transform = (!glwin->is_srgb_capable() && IsSpecSrgb(img->spec())); img->pixel_transform(srgb_transform, (int)current_color_mode(), current_channel()); displayCurrentImage(); } else { displayCurrentImage(false); } } void ImageViewer::slide(long /*t*/, bool b) { slideLoopAct->setChecked(b == true); slideNoLoopAct->setChecked(b == false); } void ImageViewer::viewChannel(int c, COLOR_MODE colormode) { #ifndef NDEBUG Timer change_channel_time; change_channel_time.start(); #endif if (m_current_channel != c || colormode != m_color_mode) { bool update = true; if (!glwin->is_glsl_capable()) { IvImage* img = cur(); if (img) { bool srgb_transform = (!glwin->is_srgb_capable() && IsSpecSrgb(img->spec())); img->pixel_transform(srgb_transform, (int)colormode, c); } } else { // FIXME: There are even more chances to avoid updating the textures // if we can keep trac of which channels are in the texture. if (m_current_channel == c) { if (m_color_mode == SINGLE_CHANNEL || m_color_mode == HEATMAP) { if (colormode == HEATMAP || colormode == SINGLE_CHANNEL) update = false; } else if (m_color_mode == RGB || m_color_mode == LUMINANCE) { if (colormode == RGB || colormode == LUMINANCE) update = false; } } } m_current_channel = c; m_color_mode = colormode; displayCurrentImage(update); viewChannelFullAct->setChecked(c == 0 && m_color_mode == RGBA); viewChannelRedAct->setChecked(c == 0 && m_color_mode == SINGLE_CHANNEL); viewChannelGreenAct->setChecked(c == 1 && m_color_mode == SINGLE_CHANNEL); viewChannelBlueAct->setChecked(c == 2 && m_color_mode == SINGLE_CHANNEL); viewChannelAlphaAct->setChecked(c == 3 && m_color_mode == SINGLE_CHANNEL); viewColorLumAct->setChecked(m_color_mode == LUMINANCE); viewColorRGBAAct->setChecked(m_color_mode == RGBA); viewColorRGBAct->setChecked(m_color_mode == RGB); viewColor1ChAct->setChecked(m_color_mode == SINGLE_CHANNEL); viewColorHeatmapAct->setChecked(m_color_mode == HEATMAP); } #ifndef NDEBUG change_channel_time.stop(); std::cerr << ""Change channel elapsed time: "" << change_channel_time() << "" seconds \\n""; #endif } void ImageViewer::slideImages() { if (m_images.empty()) return; if (m_current_image >= (int)m_images.size() - 1) { if (slide_loop == true) current_image(0); else { slideTimer->stop(); disconnect(slideTimer, 0, 0, 0); } } else current_image(current_image() + 1); } void ImageViewer::slideShow() { fullScreenToggle(); connect(slideTimer, SIGNAL(timeout()), this, SLOT(slideImages())); slideTimer->start(slideDuration_ms); updateActions(); } void ImageViewer::slideLoop() { slide_loop = true; slide(slideDuration_ms, slide_loop); } void ImageViewer::slideNoLoop() { slide_loop = false; slide(slideDuration_ms, slide_loop); } void ImageViewer::setSlideShowDuration(int seconds) { slideDuration_ms = seconds * 1000; } static bool compName(IvImage* first, IvImage* second) { std::string firstFile = Filesystem::filename(first->name()); std::string secondFile = Filesystem::filename(second->name()); return (firstFile.compare(secondFile) < 0); } void ImageViewer::sortByName() { int numImg = m_images.size(); if (numImg < 2) return; std::sort(m_images.begin(), m_images.end(), &compName); current_image(0); displayCurrentImage(); // updateActions(); } static bool compPath(IvImage* first, IvImage* second) { std::string firstFile = first->name(); std::string secondFile = second->name(); return (firstFile.compare(secondFile) < 0); } void ImageViewer::sortByPath() { int numImg = m_images.size(); if (numImg < 2) return; std::sort(m_images.begin(), m_images.end(), &compPath); current_image(0); displayCurrentImage(); // updateActions(); } static bool DateTime_to_time_t(const char* datetime, time_t& timet) { int year, month, day, hour, min, sec; int r = sscanf(datetime, ""%d:%d:%d %d:%d:%d"", &year, &month, &day, &hour, &min, &sec); // printf (""%d %d:%d:%d %d:%d:%d\\n"", r, year, month, day, hour, min, sec); if (r != 6) return false; struct tm tmtime; time_t now; Sysutil::get_local_time(&now, &tmtime); // fill in defaults tmtime.tm_sec = sec; tmtime.tm_min = min; tmtime.tm_hour = hour; tmtime.tm_mday = day; tmtime.tm_mon = month - 1; tmtime.tm_year = year - 1900; timet = mktime(&tmtime); return true; } static bool compImageDate(IvImage* first, IvImage* second) { std::time_t firstFile = time(NULL); std::time_t secondFile = time(NULL); double diff; std::string metadatatime = first->spec().get_string_attribute(""DateTime""); if (metadatatime.empty()) { if (first->init_spec(first->name(), 0, 0)) { metadatatime = first->spec().get_string_attribute(""DateTime""); if (metadatatime.empty()) { if (!Filesystem::exists(first->name())) return false; firstFile = Filesystem::last_write_time(first->name()); } } else return false; } DateTime_to_time_t(metadatatime.c_str(), firstFile); metadatatime = second->spec().get_string_attribute(""DateTime""); if (metadatatime.empty()) { if (second->init_spec(second->name(), 0, 0)) { metadatatime = second->spec().get_string_attribute(""DateTime""); if (metadatatime.empty()) { if (!Filesystem::exists(second->name())) return true; secondFile = Filesystem::last_write_time(second->name()); } } else return true; } DateTime_to_time_t(metadatatime.c_str(), secondFile); diff = difftime(firstFile, secondFile); if (diff == 0) return compName(first, second); return (diff < 0); } void ImageViewer::sortByImageDate() { int numImg = m_images.size(); if (numImg < 2) return; std::sort(m_images.begin(), m_images.end(), &compImageDate); current_image(0); displayCurrentImage(); // updateActions(); } static bool compFileDate(IvImage* first, IvImage* second) { std::time_t firstFile, secondFile; double diff; if (!Filesystem::exists(first->name())) return false; firstFile = Filesystem::last_write_time(first->name()); if (!Filesystem::exists(second->name())) return true; secondFile = Filesystem::last_write_time(second->name()); diff = difftime(firstFile, secondFile); if (diff == 0) return compName(first, second); return (diff < 0); } void ImageViewer::sortByFileDate() { int numImg = m_images.size(); if (numImg < 2) return; std::sort(m_images.begin(), m_images.end(), &compFileDate); current_image(0); displayCurrentImage(); // updateActions(); } void ImageViewer::sortReverse() { int numImg = m_images.size(); if (numImg < 2) return; std::reverse(m_images.begin(), m_images.end()); current_image(0); displayCurrentImage(); // updateActions(); } void ImageViewer::viewChannelFull() { viewChannel(0, RGBA); } void ImageViewer::viewChannelRed() { viewChannel(0, SINGLE_CHANNEL); } void ImageViewer::viewChannelGreen() { viewChannel(1, SINGLE_CHANNEL); } void ImageViewer::viewChannelBlue() { viewChannel(2, SINGLE_CHANNEL); } void ImageViewer::viewChannelAlpha() { viewChannel(3, SINGLE_CHANNEL); } void ImageViewer::viewChannelLuminance() { viewChannel(m_current_channel, LUMINANCE); } void ImageViewer::viewColorRGBA() { viewChannel(m_current_channel, RGBA); } void ImageViewer::viewColorRGB() { viewChannel(m_current_channel, RGB); } void ImageViewer::viewColor1Ch() { viewChannel(m_current_channel, SINGLE_CHANNEL); } void ImageViewer::viewColorHeatmap() { viewChannel(m_current_channel, HEATMAP); } void ImageViewer::viewChannelPrev() { if (glwin->is_glsl_capable()) { if (m_current_channel > 0) viewChannel(m_current_channel - 1, m_color_mode); } else { // Simulate old behavior. if (m_color_mode == RGBA || m_color_mode == RGB) { viewChannel(m_current_channel, LUMINANCE); } else if (m_color_mode == SINGLE_CHANNEL) { if (m_current_channel == 0) viewChannelFull(); else viewChannel(m_current_channel - 1, SINGLE_CHANNEL); } } } void ImageViewer::viewChannelNext() { if (glwin->is_glsl_capable()) { viewChannel(m_current_channel + 1, m_color_mode); } else { // Simulate old behavior. if (m_color_mode == LUMINANCE) { viewChannelFull(); } else if (m_color_mode == RGBA || m_color_mode == RGB) { viewChannelRed(); } else if (m_color_mode == SINGLE_CHANNEL) { viewChannel(m_current_channel + 1, SINGLE_CHANNEL); } } } void ImageViewer::viewSubimagePrev() { IvImage* img = cur(); if (!img) return; bool ok = false; if (img->miplevel() > 0) { ok = loadCurrentImage(img->subimage(), img->miplevel() - 1); } else if (img->subimage() > 0) { ok = loadCurrentImage(img->subimage() - 1); } else if (img->nsubimages() > 0) { img->auto_subimage(true); ok = loadCurrentImage(0); } if (ok) { if (fitImageToWindowAct->isChecked()) fitImageToWindow(); displayCurrentImage(); } } void ImageViewer::viewSubimageNext() { IvImage* img = cur(); if (!img) return; bool ok = false; if (img->auto_subimage()) { img->auto_subimage(false); ok = loadCurrentImage(0); } else if (img->miplevel() < img->nmiplevels() - 1) { ok = loadCurrentImage(img->subimage(), img->miplevel() + 1); } else if (img->subimage() < img->nsubimages() - 1) { ok = loadCurrentImage(img->subimage() + 1); } if (ok) { if (fitImageToWindowAct->isChecked()) fitImageToWindow(); displayCurrentImage(); } } void ImageViewer::keyPressEvent(QKeyEvent* event) { switch (event->key()) { case Qt::Key_Left: case Qt::Key_Up: case Qt::Key_PageUp: prevImage(); return; //break; case Qt::Key_Right: // std::cerr << ""Modifier is "" << (int)event->modifiers() << '\\n'; // fprintf (stderr, ""%x\\n"", (int)event->modifiers()); // if (event->modifiers() & Qt::ShiftModifier) // std::cerr << ""hey, ctrl right\\n""; case Qt::Key_Down: case Qt::Key_PageDown: nextImage(); return; //break; case Qt::Key_Escape: if (m_fullscreen) fullScreenToggle(); return; case Qt::Key_Minus: case Qt::Key_Underscore: zoomOut(); break; case Qt::Key_Plus: case Qt::Key_Equal: zoomIn(); break; default: // std::cerr << ""ImageViewer key "" << (int)event->key() << '\\n'; QMainWindow::keyPressEvent(event); } } void ImageViewer::resizeEvent(QResizeEvent* event) { if (fitImageToWindowAct->isChecked()) fitImageToWindow(); QMainWindow::resizeEvent(event); } void ImageViewer::closeImg() { if (m_images.empty()) return; delete m_images[m_current_image]; m_images[m_current_image] = NULL; m_images.erase(m_images.begin() + m_current_image); // Update image indices // This should be done for all image indices we may be storing if (m_last_image == m_current_image) { if (!m_images.empty() && m_last_image > 0) m_last_image = 0; else m_last_image = -1; } if (m_last_image > m_current_image) m_last_image--; m_current_image = m_current_image < (int)m_images.size() ? m_current_image : 0; displayCurrentImage(); } void ImageViewer::print() { #if 0 Q_ASSERT(imageLabel->pixmap()); QPrintDialog dialog(&printer, this); if (dialog.exec()) { QPainter painter(&printer); QRect rect = painter.viewport(); QSize size = imageLabel->pixmap()->size(); size.scale(rect.size(), Qt::KeepAspectRatio); painter.setViewport(rect.x(), rect.y(), size.width(), size.height()); painter.setWindow(imageLabel->pixmap()->rect()); painter.drawPixmap(0, 0, *imageLabel->pixmap()); } #endif } void ImageViewer::zoomIn() { IvImage* img = cur(); if (!img) return; if (zoom() >= 64) return; float oldzoom = zoom(); float newzoom = ceil2f(oldzoom); float xc, yc; // Center view position glwin->get_center(xc, yc); int xm, ym; // Mouse position glwin->get_focus_image_pixel(xm, ym); float xoffset = xc - xm; float yoffset = yc - ym; float maxzoomratio = std::max(oldzoom / newzoom, newzoom / oldzoom); int nsteps = (int)OIIO::clamp(20 * (maxzoomratio - 1), 2.0f, 10.0f); for (int i = 1; i <= nsteps; ++i) { float a = (float)i / (float)nsteps; // Interpolation amount float z = OIIO::lerp(oldzoom, newzoom, a); float zoomratio = z / oldzoom; view(xm + xoffset / zoomratio, ym + yoffset / zoomratio, z, false); if (i != nsteps) { QApplication::processEvents(); Sysutil::usleep(1000000 / 4 / nsteps); } } fitImageToWindowAct->setChecked(false); } void ImageViewer::zoomOut() { IvImage* img = cur(); if (!img) return; if (zoom() <= 1.0f / 64) return; float oldzoom = zoom(); float newzoom = floor2f(oldzoom); float xcpel, ycpel; // Center view position glwin->get_center(xcpel, ycpel); int xmpel, ympel; // Mouse position glwin->get_focus_image_pixel(xmpel, ympel); float xoffset = xcpel - xmpel; float yoffset = ycpel - ympel; float maxzoomratio = std::max(oldzoom / newzoom, newzoom / oldzoom); int nsteps = (int)OIIO::clamp(20 * (maxzoomratio - 1), 2.0f, 10.0f); for (int i = 1; i <= nsteps; ++i) { float a = (float)i / (float)nsteps; // Interpolation amount float z = OIIO::lerp(oldzoom, newzoom, a); float zoomratio = z / oldzoom; view(xmpel + xoffset / zoomratio, ympel + yoffset / zoomratio, z, false); if (i != nsteps) { QApplication::processEvents(); Sysutil::usleep(1000000 / 4 / nsteps); } } fitImageToWindowAct->setChecked(false); } void ImageViewer::normalSize() { IvImage* img = cur(); if (!img) return; fitImageToWindowAct->setChecked(false); float xcenter = img->oriented_full_x() + 0.5 * img->oriented_full_width(); float ycenter = img->oriented_full_y() + 0.5 * img->oriented_full_height(); view(xcenter, ycenter, 1.0, true); fitWindowToImage(false); } float ImageViewer::zoom_needed_to_fit(int w, int h) { IvImage* img = cur(); if (!img) return 1; float zw = (float)w / img->oriented_width(); float zh = (float)h / img->oriented_height(); return std::min(zw, zh); } void ImageViewer::fitImageToWindow() { IvImage* img = cur(); if (!img) return; fitImageToWindowAct->setChecked(true); zoom(zoom_needed_to_fit(glwin->width(), glwin->height())); } void ImageViewer::fitWindowToImage(bool zoomok, bool minsize) { IvImage* img = cur(); // Don't resize when there's no image or the image hasn't been opened yet // (or we failed to open it). if (!img || !img->image_valid()) return; // FIXME -- figure out a way to make it exactly right, even for the // main window border, etc. #ifdef __APPLE__ int extraw = 0; //12; // width() - minimumWidth(); int extrah = statusBar()->height() + 0; //40; // height() - minimumHeight(); #else int extraw = 4; //12; // width() - minimumWidth(); int extrah = statusBar()->height() + 4; //40; // height() - minimumHeight(); #endif // std::cerr << ""extra wh = "" << extraw << ' ' << extrah << '\\n'; float z = zoom(); int w = (int)(img->oriented_full_width() * z) + extraw; int h = (int)(img->oriented_full_height() * z) + extrah; if (minsize) { if (w < m_default_width) { w = m_default_width; } if (h < m_default_height) { h = m_default_height; } } if (!m_fullscreen) { QDesktopWidget* desktop = QApplication::desktop(); QRect availgeom = desktop->availableGeometry(this); int availwidth = availgeom.width() - extraw - 20; int availheight = availgeom.height() - extrah - menuBar()->height() - 20; #if 0 QRect screengeom = desktop->screenGeometry (this); std::cerr << ""available desktop geom "" << availgeom.x() << ' ' << availgeom.y() << ' ' << availgeom.width() << ""x"" << availgeom.height() << ""\\n""; std::cerr << ""screen desktop geom "" << screengeom.x() << ' ' << screengeom.y() << ' ' << screengeom.width() << ""x"" << screengeom.height() << ""\\n""; #endif if (w > availwidth || h > availheight) { w = std::min(w, availwidth); h = std::min(h, availheight); if (zoomok) { z = zoom_needed_to_fit(w, h); w = (int)(img->oriented_full_width() * z) + extraw; h = (int)(img->oriented_full_height() * z) + extrah; // std::cerr << ""must rezoom to "" << z << "" to fit\\n""; } // std::cerr << ""New window geom "" << w << ""x"" << h << ""\\n""; int posx = x(), posy = y(); if (posx + w > availwidth || posy + h > availheight) { if (posx + w > availwidth) posx = std::max(0, availwidth - w) + availgeom.x(); if (posy + h > availheight) posy = std::max(0, availheight - h) + availgeom.y(); // std::cerr << ""New position "" << posx << ' ' << posy << ""\\n""; move(QPoint(posx, posy)); } } } float midx = img->oriented_full_x() + 0.5 * img->oriented_full_width(); float midy = img->oriented_full_y() + 0.5 * img->oriented_full_height(); view(midx, midy, z, false, false); resize(w, h); // Resize will trigger a repaint. #if 0 QRect g = geometry(); std::cerr << ""geom "" << g.x() << ' ' << g.y() << ' ' << g.width() << ""x"" << g.height() << ""\\n""; g = frameGeometry(); std::cerr << ""frame geom "" << g.x() << ' ' << g.y() << ' ' << g.width() << ""x"" << g.height() << ""\\n""; g = glwin->geometry(); std::cerr << ""ogl geom "" << g.x() << ' ' << g.y() << ' ' << g.width() << ""x"" << g.height() << ""\\n""; std::cerr << ""Status bar height = "" << statusBar()->height() << ""\\n""; #endif #if 0 bool fit = fitWindowToImageAct->isChecked(); if (!fit) { normalSize(); } #endif updateActions(); } void ImageViewer::fullScreenToggle() { if (m_fullscreen) { menuBar()->show(); statusBar()->show(); showNormal(); m_fullscreen = false; slideTimer->stop(); disconnect(slideTimer, 0, 0, 0); } else { menuBar()->hide(); statusBar()->hide(); showFullScreen(); m_fullscreen = true; fitImageToWindow(); } } void ImageViewer::about() { QMessageBox::about( this, tr(""About iv""), tr(""

iv is the image viewer for OpenImageIO.

"" ""

(c) Copyright Contributors to the OpenImageIO project.

"" ""

See http://openimageio.org for details.

"")); } void ImageViewer::updateActions() { // zoomInAct->setEnabled(!fitImageToWindowAct->isChecked()); // zoomOutAct->setEnabled(!fitImageToWindowAct->isChecked()); // normalSizeAct->setEnabled(!fitImageToWindowAct->isChecked()); } static inline void calc_subimage_from_zoom(const IvImage* img, int& subimage, float& zoom, float& xcenter, float& ycenter) { int rel_subimage = std::trunc(std::log2(1.0f / zoom)); subimage = clamp(img->subimage() + rel_subimage, 0, img->nsubimages() - 1); if (!(img->subimage() == 0 && zoom > 1) && !(img->subimage() == img->nsubimages() - 1 && zoom < 1)) { float pow_zoom = powf(2.0f, (float)rel_subimage); zoom *= pow_zoom; xcenter /= pow_zoom; ycenter /= pow_zoom; } } void ImageViewer::view(float xcenter, float ycenter, float newzoom, bool smooth, bool redraw) { IvImage* img = cur(); if (!img) return; float oldzoom = m_zoom; float oldxcenter, oldycenter; glwin->get_center(oldxcenter, oldycenter); float zoomratio = std::max(oldzoom / newzoom, newzoom / oldzoom); int nsteps = (int)OIIO::clamp(20 * (zoomratio - 1), 2.0f, 10.0f); if (!smooth || !redraw) nsteps = 1; for (int i = 1; i <= nsteps; ++i) { float a = (float)i / (float)nsteps; // Interpolation amount float xc = OIIO::lerp(oldxcenter, xcenter, a); float yc = OIIO::lerp(oldycenter, ycenter, a); m_zoom = OIIO::lerp(oldzoom, newzoom, a); glwin->view(xc, yc, m_zoom, redraw); // Triggers redraw automatically if (i != nsteps) { QApplication::processEvents(); Sysutil::usleep(1000000 / 4 / nsteps); } } if (img->auto_subimage()) { int subimage = 0; calc_subimage_from_zoom(img, subimage, m_zoom, xcenter, ycenter); if (subimage != img->subimage()) { //std::cerr << ""Changing to subimage "" << subimage; //std::cerr << "" With zoom: "" << m_zoom << '\\n'; loadCurrentImage(subimage); glwin->update(); glwin->view(xcenter, ycenter, m_zoom, redraw); } } // zoomInAct->setEnabled (zoom() < 64.0); // zoomOutAct->setEnabled (zoom() > 1.0/64); updateStatusBar(); } void ImageViewer::zoom(float newzoom, bool smooth) { float xcenter, ycenter; glwin->get_center(xcenter, ycenter); view(xcenter, ycenter, newzoom, smooth); } void ImageViewer::showInfoWindow() { if (!infoWindow) { infoWindow = new IvInfoWindow(*this, true); infoWindow->setPalette(m_palette); } infoWindow->update(cur()); if (infoWindow->isHidden()) infoWindow->show(); else infoWindow->hide(); } void ImageViewer::showPixelviewWindow() { ((QOpenGLWidget*)(glwin))->update(); } void ImageViewer::editPreferences() { if (!preferenceWindow) { preferenceWindow = new IvPreferenceWindow(*this); preferenceWindow->setPalette(m_palette); } preferenceWindow->show(); } ",16238,True,2632.7580868701084,median "#include #include #include #include #include #include ""imgui/imgui.h"" #include ""imgui/imgui_impl_win32.h"" #include ""imgui/imgui_stdlib.h"" #include ""imguiCustom.h"" #include ""GUI.h"" #include ""Config.h"" #include ""Hacks/Misc.h"" #include ""Hacks/Reportbot.h"" #include ""Hacks/SkinChanger.h"" #include ""Hooks.h"" #include ""SDK/InputSystem.h"" constexpr auto windowFlags = ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse; GUI::GUI() noexcept { ImGui::StyleColorsDark(); ImGuiStyle& style = ImGui::GetStyle(); style.ScrollbarSize = 9.0f; ImGuiIO& io = ImGui::GetIO(); io.IniFilename = nullptr; io.LogFilename = nullptr; io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange; if (PWSTR pathToFonts; SUCCEEDED(SHGetKnownFolderPath(FOLDERID_Fonts, 0, nullptr, &pathToFonts))) { const std::filesystem::path path{ pathToFonts }; CoTaskMemFree(pathToFonts); static constexpr ImWchar ranges[]{ 0x0020, 0xFFFF, 0 }; ImFontConfig cfg; cfg.OversampleV = 3; fonts.tahoma = io.Fonts->AddFontFromFileTTF((path / ""tahoma.ttf"").string().c_str(), 15.0f, &cfg, ranges); fonts.segoeui = io.Fonts->AddFontFromFileTTF((path / ""segoeui.ttf"").string().c_str(), 15.0f, &cfg, ranges); } } void GUI::render() noexcept { if (!config->style.menuStyle) { renderMenuBar(); renderAimbotWindow(); renderAntiAimWindow(); renderTriggerbotWindow(); renderBacktrackWindow(); renderGlowWindow(); renderChamsWindow(); renderEspWindow(); renderVisualsWindow(); renderSkinChangerWindow(); renderSoundWindow(); renderStyleWindow(); renderMiscWindow(); renderReportbotWindow(); renderConfigWindow(); } else { renderGuiStyle2(); } } void GUI::updateColors() const noexcept { switch (config->style.menuColors) { case 0: ImGui::StyleColorsDark(); break; case 1: ImGui::StyleColorsLight(); break; case 2: ImGui::StyleColorsClassic(); break; } } void GUI::hotkey(int& key) noexcept { key ? ImGui::Text(""[ %s ]"", interfaces->inputSystem->virtualKeyToString(key)) : ImGui::TextUnformatted(""[ key ]""); if (!ImGui::IsItemHovered()) return; ImGui::SetTooltip(""Press any key to change keybind""); ImGuiIO& io = ImGui::GetIO(); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (ImGui::IsKeyPressed(i) && i != config->misc.menuKey) key = i != VK_ESCAPE ? i : 0; for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseDown(i) && i + (i > 1 ? 2 : 1) != config->misc.menuKey) key = i + (i > 1 ? 2 : 1); } void GUI::renderMenuBar() noexcept { if (ImGui::BeginMainMenuBar()) { ImGui::MenuItem(""Aimbot"", nullptr, &window.aimbot); ImGui::MenuItem(""Anti aim"", nullptr, &window.antiAim); ImGui::MenuItem(""Triggerbot"", nullptr, &window.triggerbot); ImGui::MenuItem(""Backtrack"", nullptr, &window.backtrack); ImGui::MenuItem(""Glow"", nullptr, &window.glow); ImGui::MenuItem(""Chams"", nullptr, &window.chams); ImGui::MenuItem(""Esp"", nullptr, &window.esp); ImGui::MenuItem(""Visuals"", nullptr, &window.visuals); ImGui::MenuItem(""Skin changer"", nullptr, &window.skinChanger); ImGui::MenuItem(""Sound"", nullptr, &window.sound); ImGui::MenuItem(""Style"", nullptr, &window.style); ImGui::MenuItem(""Misc"", nullptr, &window.misc); ImGui::MenuItem(""Reportbot"", nullptr, &window.reportbot); ImGui::MenuItem(""Config"", nullptr, &window.config); ImGui::EndMainMenuBar(); } } void GUI::renderAimbotWindow(bool contentOnly) noexcept { if (!contentOnly) { if (!window.aimbot) return; ImGui::SetNextWindowSize({ 600.0f, 0.0f }); ImGui::Begin(""Aimbot"", &window.aimbot, windowFlags); } static int currentCategory{ 0 }; ImGui::PushItemWidth(110.0f); ImGui::PushID(0); ImGui::Combo("""", ¤tCategory, ""All\\0Pistols\\0Heavy\\0SMG\\0Rifles\\0""); ImGui::PopID(); ImGui::SameLine(); static int currentWeapon{ 0 }; ImGui::PushID(1); switch (currentCategory) { case 0: currentWeapon = 0; ImGui::NewLine(); break; case 1: { static int currentPistol{ 0 }; static constexpr const char* pistols[]{ ""All"", ""Glock-18"", ""P2000"", ""USP-S"", ""Dual Berettas"", ""P250"", ""Tec-9"", ""Five-Seven"", ""CZ-75"", ""Desert Eagle"", ""Revolver"" }; ImGui::Combo("""", ¤tPistol, [](void* data, int idx, const char** out_text) { if (config->aimbot[idx ? idx : 35].enabled) { static std::string name; name = pistols[idx]; *out_text = name.append("" *"").c_str(); } else { *out_text = pistols[idx]; } return true; }, nullptr, IM_ARRAYSIZE(pistols)); currentWeapon = currentPistol ? currentPistol : 35; break; } case 2: { static int currentHeavy{ 0 }; static constexpr const char* heavies[]{ ""All"", ""Nova"", ""XM1014"", ""Sawed-off"", ""MAG-7"", ""M249"", ""Negev"" }; ImGui::Combo("""", ¤tHeavy, [](void* data, int idx, const char** out_text) { if (config->aimbot[idx ? idx + 10 : 36].enabled) { static std::string name; name = heavies[idx]; *out_text = name.append("" *"").c_str(); } else { *out_text = heavies[idx]; } return true; }, nullptr, IM_ARRAYSIZE(heavies)); currentWeapon = currentHeavy ? currentHeavy + 10 : 36; break; } case 3: { static int currentSmg{ 0 }; static constexpr const char* smgs[]{ ""All"", ""Mac-10"", ""MP9"", ""MP7"", ""MP5-SD"", ""UMP-45"", ""P90"", ""PP-Bizon"" }; ImGui::Combo("""", ¤tSmg, [](void* data, int idx, const char** out_text) { if (config->aimbot[idx ? idx + 16 : 37].enabled) { static std::string name; name = smgs[idx]; *out_text = name.append("" *"").c_str(); } else { *out_text = smgs[idx]; } return true; }, nullptr, IM_ARRAYSIZE(smgs)); currentWeapon = currentSmg ? currentSmg + 16 : 37; break; } case 4: { static int currentRifle{ 0 }; static constexpr const char* rifles[]{ ""All"", ""Galil AR"", ""Famas"", ""AK-47"", ""M4A4"", ""M4A1-S"", ""SSG-08"", ""SG-553"", ""AUG"", ""AWP"", ""G3SG1"", ""SCAR-20"" }; ImGui::Combo("""", ¤tRifle, [](void* data, int idx, const char** out_text) { if (config->aimbot[idx ? idx + 23 : 38].enabled) { static std::string name; name = rifles[idx]; *out_text = name.append("" *"").c_str(); } else { *out_text = rifles[idx]; } return true; }, nullptr, IM_ARRAYSIZE(rifles)); currentWeapon = currentRifle ? currentRifle + 23 : 38; break; } } ImGui::PopID(); ImGui::SameLine(); ImGui::Checkbox(""Enabled"", &config->aimbot[currentWeapon].enabled); ImGui::Separator(); ImGui::Columns(2, nullptr, false); ImGui::SetColumnOffset(1, 220.0f); ImGui::Checkbox(""On key"", &config->aimbot[currentWeapon].onKey); ImGui::SameLine(); hotkey(config->aimbot[currentWeapon].key); ImGui::SameLine(); ImGui::PushID(2); ImGui::PushItemWidth(70.0f); ImGui::Combo("""", &config->aimbot[currentWeapon].keyMode, ""Hold\\0Toggle\\0""); ImGui::PopItemWidth(); ImGui::PopID(); ImGui::Checkbox(""Aimlock"", &config->aimbot[currentWeapon].aimlock); ImGui::Checkbox(""Silent"", &config->aimbot[currentWeapon].silent); ImGui::Checkbox(""Friendly fire"", &config->aimbot[currentWeapon].friendlyFire); ImGui::Checkbox(""Visible only"", &config->aimbot[currentWeapon].visibleOnly); ImGui::Checkbox(""Scoped only"", &config->aimbot[currentWeapon].scopedOnly); ImGui::Checkbox(""Ignore flash"", &config->aimbot[currentWeapon].ignoreFlash); ImGui::Checkbox(""Ignore smoke"", &config->aimbot[currentWeapon].ignoreSmoke); ImGui::Checkbox(""Auto shot"", &config->aimbot[currentWeapon].autoShot); ImGui::Checkbox(""Auto scope"", &config->aimbot[currentWeapon].autoScope); ImGui::Combo(""Bone"", &config->aimbot[currentWeapon].bone, ""Nearest\\0Best damage\\0Head\\0Neck\\0Sternum\\0Chest\\0Stomach\\0Pelvis\\0""); ImGui::NextColumn(); ImGui::PushItemWidth(240.0f); ImGui::SliderFloat(""Fov"", &config->aimbot[currentWeapon].fov, 0.0f, 255.0f, ""%.2f"", 2.5f); ImGui::SliderFloat(""Smooth"", &config->aimbot[currentWeapon].smooth, 1.0f, 100.0f, ""%.2f""); ImGui::SliderFloat(""Max aim inaccuracy"", &config->aimbot[currentWeapon].maxAimInaccuracy, 0.0f, 1.0f, ""%.5f"", 2.0f); ImGui::SliderFloat(""Max shot inaccuracy"", &config->aimbot[currentWeapon].maxShotInaccuracy, 0.0f, 1.0f, ""%.5f"", 2.0f); ImGui::InputInt(""Min damage"", &config->aimbot[currentWeapon].minDamage); config->aimbot[currentWeapon].minDamage = std::clamp(config->aimbot[currentWeapon].minDamage, 0, 250); ImGui::Checkbox(""Killshot"", &config->aimbot[currentWeapon].killshot); ImGui::Checkbox(""Between shots"", &config->aimbot[currentWeapon].betweenShots); ImGui::Columns(1); if (!contentOnly) ImGui::End(); } void GUI::renderAntiAimWindow(bool contentOnly) noexcept { if (!contentOnly) { if (!window.antiAim) return; ImGui::SetNextWindowSize({ 0.0f, 0.0f }); ImGui::Begin(""Anti aim"", &window.antiAim, windowFlags); } ImGui::Checkbox(""Enabled"", &config->antiAim.enabled); if (config->antiAim.enabled) { ImGui::Checkbox(""Pitch"", &config->antiAim.pitch); if (config->antiAim.pitch) { ImGui::SameLine(); ImGui::SetNextItemWidth(240.0f); ImGui::SliderFloat(""Pitch Angle"", &config->antiAim.pitchAngle, -89.0f, 89.0f, ""%.2f"", 1); } ImGui::Checkbox(""Yaw"", &config->antiAim.yaw); if (config->antiAim.yaw) { ImGui::SameLine(); ImGui::SetNextItemWidth(240.0f); ImGui::SliderFloat(""Yaw Angle"", &config->antiAim.yawAngle, -179.0f, 179.0f, ""%.2f"", 1); ImGui::Text(""Invert Key""); ImGui::SameLine(); hotkey(config->antiAim.yawInverseAngleKey); ImGui::SameLine(); ImGui::PushID(1); ImGui::SetNextItemWidth(75.0f); ImGui::Combo("""", &config->antiAim.yawInverseKeyMode, ""Hold\\0Toggle\\0""); ImGui::PopID(); } else { ImGui::Text(""Invert Key""); ImGui::SameLine(); hotkey(config->antiAim.yawInverseAngleKey); } ImGui::Checkbox(""Yaw Desync"", &config->antiAim.yawReal); if (config->antiAim.yawReal == true) { ImGui::SetNextItemWidth(240.0f); ImGui::SliderFloat(""Body Lean"", &config->antiAim.bodyLean, 0.0f, 100.0f, ""%.2f"", 1); ImGui::Checkbox(""LBY Breaker"", &config->antiAim.LBYBreaker); if (config->antiAim.LBYBreaker) { ImGui::SliderFloat(""LBY Angle"", &config->antiAim.LBYAngle, 0.0f, 180.0f, ""%.2f"", 1); } } ImGui::SetNextItemWidth(85.0f); ImGui::Combo(""Anti-Aim Mode"", &config->antiAim.mode, ""Static\\0Jitter\\0""); if (config->antiAim.mode == 1) { ImGui::SetNextItemWidth(240.0f); ImGui::SliderFloat(""Jitter Max"", &config->antiAim.jitterMax, -179.0f, 179.0f, ""%.2f"", 1); ImGui::SetNextItemWidth(240.0f); ImGui::SliderFloat(""Jitter Min"", &config->antiAim.jitterMin, -179.0f, 179.0f, ""%.2f"", 1); } } if (!contentOnly) ImGui::End(); } void GUI::renderTriggerbotWindow(bool contentOnly) noexcept { if (!contentOnly) { if (!window.triggerbot) return; ImGui::SetNextWindowSize({ 0.0f, 0.0f }); ImGui::Begin(""Triggerbot"", &window.triggerbot, windowFlags); } static int currentCategory{ 0 }; ImGui::PushItemWidth(110.0f); ImGui::PushID(0); ImGui::Combo("""", ¤tCategory, ""All\\0Pistols\\0Heavy\\0SMG\\0Rifles\\0Zeus x27\\0""); ImGui::PopID(); ImGui::SameLine(); static int currentWeapon{ 0 }; ImGui::PushID(1); switch (currentCategory) { case 0: currentWeapon = 0; ImGui::NewLine(); break; case 5: currentWeapon = 39; ImGui::NewLine(); break; case 1: { static int currentPistol{ 0 }; static constexpr const char* pistols[]{ ""All"", ""Glock-18"", ""P2000"", ""USP-S"", ""Dual Berettas"", ""P250"", ""Tec-9"", ""Five-Seven"", ""CZ-75"", ""Desert Eagle"", ""Revolver"" }; ImGui::Combo("""", ¤tPistol, [](void* data, int idx, const char** out_text) { if (config->triggerbot[idx ? idx : 35].enabled) { static std::string name; name = pistols[idx]; *out_text = name.append("" *"").c_str(); } else { *out_text = pistols[idx]; } return true; }, nullptr, IM_ARRAYSIZE(pistols)); currentWeapon = currentPistol ? currentPistol : 35; break; } case 2: { static int currentHeavy{ 0 }; static constexpr const char* heavies[]{ ""All"", ""Nova"", ""XM1014"", ""Sawed-off"", ""MAG-7"", ""M249"", ""Negev"" }; ImGui::Combo("""", ¤tHeavy, [](void* data, int idx, const char** out_text) { if (config->triggerbot[idx ? idx + 10 : 36].enabled) { static std::string name; name = heavies[idx]; *out_text = name.append("" *"").c_str(); } else { *out_text = heavies[idx]; } return true; }, nullptr, IM_ARRAYSIZE(heavies)); currentWeapon = currentHeavy ? currentHeavy + 10 : 36; break; } case 3: { static int currentSmg{ 0 }; static constexpr const char* smgs[]{ ""All"", ""Mac-10"", ""MP9"", ""MP7"", ""MP5-SD"", ""UMP-45"", ""P90"", ""PP-Bizon"" }; ImGui::Combo("""", ¤tSmg, [](void* data, int idx, const char** out_text) { if (config->triggerbot[idx ? idx + 16 : 37].enabled) { static std::string name; name = smgs[idx]; *out_text = name.append("" *"").c_str(); } else { *out_text = smgs[idx]; } return true; }, nullptr, IM_ARRAYSIZE(smgs)); currentWeapon = currentSmg ? currentSmg + 16 : 37; break; } case 4: { static int currentRifle{ 0 }; static constexpr const char* rifles[]{ ""All"", ""Galil AR"", ""Famas"", ""AK-47"", ""M4A4"", ""M4A1-S"", ""SSG-08"", ""SG-553"", ""AUG"", ""AWP"", ""G3SG1"", ""SCAR-20"" }; ImGui::Combo("""", ¤tRifle, [](void* data, int idx, const char** out_text) { if (config->triggerbot[idx ? idx + 23 : 38].enabled) { static std::string name; name = rifles[idx]; *out_text = name.append("" *"").c_str(); } else { *out_text = rifles[idx]; } return true; }, nullptr, IM_ARRAYSIZE(rifles)); currentWeapon = currentRifle ? currentRifle + 23 : 38; break; } } ImGui::PopID(); ImGui::SameLine(); ImGui::Checkbox(""Enabled"", &config->triggerbot[currentWeapon].enabled); ImGui::Separator(); ImGui::Checkbox(""On key"", &config->triggerbot[currentWeapon].onKey); ImGui::SameLine(); hotkey(config->triggerbot[currentWeapon].key); ImGui::Checkbox(""Friendly fire"", &config->triggerbot[currentWeapon].friendlyFire); ImGui::Checkbox(""Scoped only"", &config->triggerbot[currentWeapon].scopedOnly); ImGui::Checkbox(""Ignore flash"", &config->triggerbot[currentWeapon].ignoreFlash); ImGui::Checkbox(""Ignore smoke"", &config->triggerbot[currentWeapon].ignoreSmoke); ImGui::SetNextItemWidth(85.0f); ImGui::Combo(""Hitgroup"", &config->triggerbot[currentWeapon].hitgroup, ""All\\0Head\\0Chest\\0Stomach\\0Left arm\\0Right arm\\0Left leg\\0Right leg\\0""); ImGui::PushItemWidth(220.0f); ImGui::SliderInt(""Shot delay"", &config->triggerbot[currentWeapon].shotDelay, 0, 250, ""%d ms""); ImGui::InputInt(""Min damage"", &config->triggerbot[currentWeapon].minDamage); config->triggerbot[currentWeapon].minDamage = std::clamp(config->triggerbot[currentWeapon].minDamage, 0, 250); ImGui::Checkbox(""Killshot"", &config->triggerbot[currentWeapon].killshot); ImGui::SliderFloat(""Burst Time"", &config->triggerbot[currentWeapon].burstTime, 0.0f, 0.5f, ""%.3f s""); if (!contentOnly) ImGui::End(); } void GUI::renderBacktrackWindow(bool contentOnly) noexcept { if (!contentOnly) { if (!window.backtrack) return; ImGui::SetNextWindowSize({ 0.0f, 0.0f }); ImGui::Begin(""Backtrack"", &window.backtrack, windowFlags); } ImGui::Checkbox(""Enabled"", &config->backtrack.enabled); ImGui::Checkbox(""Ignore smoke"", &config->backtrack.ignoreSmoke); ImGui::Checkbox(""Recoil based fov"", &config->backtrack.recoilBasedFov); ImGui::PushItemWidth(220.0f); ImGui::SliderInt(""Time limit"", &config->backtrack.timeLimit, 1, 200, ""%d ms""); ImGui::PopItemWidth(); if (!contentOnly) ImGui::End(); } void GUI::renderGlowWindow(bool contentOnly) noexcept { if (!contentOnly) { if (!window.glow) return; ImGui::SetNextWindowSize({ 450.0f, 0.0f }); ImGui::Begin(""Glow"", &window.glow, windowFlags); } static int currentCategory{ 0 }; ImGui::PushItemWidth(110.0f); ImGui::PushID(0); ImGui::Combo("""", ¤tCategory, ""Allies\\0Enemies\\0Planting\\0Defusing\\0Local player\\0Weapons\\0C4\\0Planted C4\\0Chickens\\0Defuse kits\\0Projectiles\\0Hostages\\0Ragdolls\\0""); ImGui::PopID(); static int currentItem{ 0 }; if (currentCategory <= 3) { ImGui::SameLine(); static int currentType{ 0 }; ImGui::PushID(1); ImGui::Combo("""", ¤tType, ""All\\0Visible\\0Occluded\\0""); ImGui::PopID(); currentItem = currentCategory * 3 + currentType; } else { currentItem = currentCategory + 8; } ImGui::SameLine(); ImGui::Checkbox(""Enabled"", &config->glow[currentItem].enabled); ImGui::Separator(); ImGui::Columns(2, nullptr, false); ImGui::SetColumnOffset(1, 150.0f); ImGui::Checkbox(""Health based"", &config->glow[currentItem].healthBased); ImGuiCustom::colorPicker(""Color"", config->glow[currentItem].color.color, nullptr, &config->glow[currentItem].color.rainbow, &config->glow[currentItem].color.rainbowSpeed); ImGui::NextColumn(); ImGui::PushItemWidth(220.0f); ImGui::SliderFloat(""Thickness"", &config->glow[currentItem].thickness, 0.0f, 1.0f, ""%.2f""); ImGui::SliderFloat(""Alpha"", &config->glow[currentItem].alpha, 0.0f, 1.0f, ""%.2f""); ImGui::SliderInt(""Style"", &config->glow[currentItem].style, 0, 3); ImGui::Columns(1); if (!contentOnly) ImGui::End(); } void GUI::renderChamsWindow(bool contentOnly) noexcept { if (!contentOnly) { if (!window.chams) return; ImGui::SetNextWindowSize({ 0.0f, 0.0f }); ImGui::Begin(""Chams"", &window.chams, windowFlags); } static int currentCategory{ 0 }; ImGui::PushItemWidth(110.0f); ImGui::PushID(0); ImGui::Combo("""", ¤tCategory, ""Allies\\0Enemies\\0Planting\\0Defusing\\0Local player\\0Weapons\\0Hands\\0Backtrack\\0Sleeves\\0""); //Server Position\\0Real Angles\\0""); ImGui::PopID(); static int currentItem{ 0 }; if (currentCategory <= 3) { ImGui::SameLine(); static int currentType{ 0 }; ImGui::PushID(1); ImGui::Combo("""", ¤tType, ""All\\0Visible\\0Occluded\\0""); ImGui::PopID(); currentItem = currentCategory * 3 + currentType; } else { currentItem = currentCategory + 8; } ImGui::SameLine(); static int material = 1; if (ImGui::ArrowButton(""##left"", ImGuiDir_Left) && material > 1) --material; ImGui::SameLine(); ImGui::Text(""%d"", material); ImGui::SameLine(); if (ImGui::ArrowButton(""##right"", ImGuiDir_Right) && material < int(config->chams[0].materials.size())) ++material; ImGui::SameLine(); auto& chams{ config->chams[currentItem].materials[material - 1] }; ImGui::Checkbox(""Enabled"", &chams.enabled); ImGui::Separator(); ImGui::Checkbox(""Health based"", &chams.healthBased); ImGui::Checkbox(""Blinking"", &chams.blinking); ImGui::Combo(""Material"", &chams.material, ""Normal\\0Flat\\0Animated\\0Platinum\\0Glass\\0Chrome\\0Crystal\\0Silver\\0Gold\\0Plastic\\0Glow\\0""); ImGui::Checkbox(""Wireframe"", &chams.wireframe); ImGuiCustom::colorPicker(""Color"", chams.color.color, nullptr, &chams.color.rainbow, &chams.color.rainbowSpeed); ImGui::SetNextItemWidth(220.0f); ImGui::SliderFloat(""Alpha"", &chams.alpha, 0.0f, 1.0f, ""%.2f""); if (!contentOnly) { ImGui::End(); } } void GUI::renderEspWindow(bool contentOnly) noexcept { if (!contentOnly) { if (!window.esp) return; ImGui::SetNextWindowSize({ 0.0f, 0.0f }); ImGui::Begin(""Esp"", &window.esp, windowFlags); } static int currentCategory = 0; static int currentItem = 0; if (ImGui::ListBoxHeader(""##"", { 125.0f, 300.0f })) { static constexpr const char* players[]{ ""All"", ""Visible"", ""Occluded"" }; ImGui::Text(""Allies""); ImGui::Indent(); ImGui::PushID(""Allies""); ImGui::PushFont(fonts.segoeui); for (int i = 0; i < IM_ARRAYSIZE(players); i++) { bool isSelected = currentCategory == 0 && currentItem == i; if ((i == 0 || !config->esp.players[0].enabled) && ImGui::Selectable(players[i], isSelected)) { currentItem = i; currentCategory = 0; } } ImGui::PopFont(); ImGui::PopID(); ImGui::Unindent(); ImGui::Text(""Enemies""); ImGui::Indent(); ImGui::PushID(""Enemies""); ImGui::PushFont(fonts.segoeui); for (int i = 0; i < IM_ARRAYSIZE(players); i++) { bool isSelected = currentCategory == 1 && currentItem == i; if ((i == 0 || !config->esp.players[3].enabled) && ImGui::Selectable(players[i], isSelected)) { currentItem = i; currentCategory = 1; } } ImGui::PopFont(); ImGui::PopID(); ImGui::Unindent(); if (bool isSelected = currentCategory == 2; ImGui::Selectable(""Weapons"", isSelected)) currentCategory = 2; ImGui::Text(""Projectiles""); ImGui::Indent(); ImGui::PushID(""Projectiles""); ImGui::PushFont(fonts.segoeui); static constexpr const char* projectiles[]{ ""Flashbang"", ""HE Grenade"", ""Breach Charge"", ""Bump Mine"", ""Decoy Grenade"", ""Molotov"", ""TA Grenade"", ""Smoke Grenade"", ""Snowball"" }; for (int i = 0; i < IM_ARRAYSIZE(projectiles); i++) { bool isSelected = currentCategory == 3 && currentItem == i; if (ImGui::Selectable(projectiles[i], isSelected)) { currentItem = i; currentCategory = 3; } } ImGui::PopFont(); ImGui::PopID(); ImGui::Unindent(); ImGui::Text(""Danger Zone""); ImGui::Indent(); ImGui::PushID(""Danger Zone""); ImGui::PushFont(fonts.segoeui); static constexpr const char* dangerZone[]{ ""Sentries"", ""Drones"", ""Cash"", ""Cash Dufflebag"", ""Pistol Case"", ""Light Case"", ""Heavy Case"", ""Explosive Case"", ""Tools Case"", ""Full Armor"", ""Armor"", ""Helmet"", ""Parachute"", ""Briefcase"", ""Tablet Upgrade"", ""ExoJump"", ""Ammobox"", ""Radar Jammer"" }; for (int i = 0; i < IM_ARRAYSIZE(dangerZone); i++) { bool isSelected = currentCategory == 4 && currentItem == i; if (ImGui::Selectable(dangerZone[i], isSelected)) { currentItem = i; currentCategory = 4; } } ImGui::PopFont(); ImGui::PopID(); ImGui::ListBoxFooter(); } ImGui::SameLine(); if (ImGui::BeginChild(""##child"", { 400.0f, 0.0f })) { switch (currentCategory) { case 0: case 1: { int selected = currentCategory * 3 + currentItem; ImGui::Checkbox(""Enabled"", &config->esp.players[selected].enabled); ImGui::SameLine(0.0f, 50.0f); ImGui::SetNextItemWidth(85.0f); ImGui::InputInt(""Font"", &config->esp.players[selected].font, 1, 294); config->esp.players[selected].font = std::clamp(config->esp.players[selected].font, 1, 294); ImGui::Separator(); constexpr auto spacing{ 185.0f }; ImGuiCustom::colorPicker(""Snaplines"", config->esp.players[selected].snaplines); ImGui::SameLine(spacing); ImGuiCustom::colorPicker(""Box"", config->esp.players[selected].box); ImGui::SameLine(); ImGui::SetNextItemWidth(95.0f); ImGui::Combo("""", &config->esp.players[selected].boxType, ""2D\\0""""2D corners\\0""""3D\\0""""3D corners\\0""); ImGuiCustom::colorPicker(""Eye traces"", config->esp.players[selected].eyeTraces); ImGui::SameLine(spacing); ImGuiCustom::colorPicker(""Health"", config->esp.players[selected].health); ImGuiCustom::colorPicker(""Head dot"", config->esp.players[selected].headDot); ImGui::SameLine(spacing); ImGuiCustom::colorPicker(""Health bar"", config->esp.players[selected].healthBar); ImGui::SameLine(); ImGui::SetNextItemWidth(70.f); ImGui::Combo(""##HP side"", &config->esp.players[selected].hpside, ""Left\\0Bottom\\0Right\\0""); ImGui::PushID(""hotfix""); ImGuiCustom::colorPicker(""Name"", config->esp.players[selected].name); ImGui::SameLine(spacing); ImGuiCustom::colorPicker(""Armor"", config->esp.players[selected].armor); ImGuiCustom::colorPicker(""Money"", config->esp.players[selected].money); ImGui::SameLine(spacing); ImGuiCustom::colorPicker(""Armor bar"", config->esp.players[selected].armorBar); ImGui::SameLine(); ImGui::SetNextItemWidth(70.f); ImGui::PopID(); ImGui::Combo(""##AR side"", &config->esp.players[selected].armorside, ""Left\\0Bottom\\0Right\\0""); ImGuiCustom::colorPicker(""Outline"", config->esp.players[selected].outline); ImGui::SameLine(spacing); ImGuiCustom::colorPicker(""Distance"", config->esp.players[selected].distance); ImGuiCustom::colorPicker(""Active Weapon"", config->esp.players[selected].activeWeapon); ImGui::SameLine(spacing); ImGui::Checkbox(""Dead ESP"", &config->esp.players[selected].deadesp); ImGui::SliderFloat(""Max distance"", &config->esp.players[selected].maxDistance, 0.0f, 200.0f, ""%.2fm""); break; } case 2: { ImGui::Checkbox(""Enabled"", &config->esp.weapon.enabled); ImGui::SameLine(0.0f, 50.0f); ImGui::SetNextItemWidth(85.0f); ImGui::InputInt(""Font"", &config->esp.weapon.font, 1, 294); config->esp.weapon.font = std::clamp(config->esp.weapon.font, 1, 294); ImGui::Separator(); constexpr auto spacing{ 200.0f }; ImGuiCustom::colorPicker(""Snaplines"", config->esp.weapon.snaplines); ImGui::SameLine(spacing); ImGuiCustom::colorPicker(""Box"", config->esp.weapon.box); ImGui::SameLine(); ImGui::SetNextItemWidth(95.0f); ImGui::Combo("""", &config->esp.weapon.boxType, ""2D\\0""""2D corners\\0""""3D\\0""""3D corners\\0""); ImGuiCustom::colorPicker(""Name"", config->esp.weapon.name); ImGui::SameLine(spacing); ImGuiCustom::colorPicker(""Ammo"", config->esp.weapon.ammo); ImGuiCustom::colorPicker(""Outline"", config->esp.weapon.outline); ImGuiCustom::colorPicker(""Distance"", config->esp.weapon.distance); ImGui::SliderFloat(""Max distance"", &config->esp.weapon.maxDistance, 0.0f, 200.0f, ""%.2fm""); break; } case 3: { ImGui::Checkbox(""Enabled"", &config->esp.projectiles[currentItem].enabled); ImGui::SameLine(0.0f, 50.0f); ImGui::SetNextItemWidth(85.0f); ImGui::InputInt(""Font"", &config->esp.projectiles[currentItem].font, 1, 294); config->esp.projectiles[currentItem].font = std::clamp(config->esp.projectiles[currentItem].font, 1, 294); ImGui::Separator(); constexpr auto spacing{ 200.0f }; ImGuiCustom::colorPicker(""Snaplines"", config->esp.projectiles[currentItem].snaplines); ImGui::SameLine(spacing); ImGuiCustom::colorPicker(""Box"", config->esp.projectiles[currentItem].box); ImGui::SameLine(); ImGui::SetNextItemWidth(95.0f); ImGui::Combo("""", &config->esp.projectiles[currentItem].boxType, ""2D\\0""""2D corners\\0""""3D\\0""""3D corners\\0""); ImGuiCustom::colorPicker(""Name"", config->esp.projectiles[currentItem].name); ImGui::SameLine(spacing); ImGuiCustom::colorPicker(""Outline"", config->esp.projectiles[currentItem].outline); ImGuiCustom::colorPicker(""Distance"", config->esp.projectiles[currentItem].distance); ImGui::SliderFloat(""Max distance"", &config->esp.projectiles[currentItem].maxDistance, 0.0f, 200.0f, ""%.2fm""); break; } case 4: { int selected = currentItem; ImGui::Checkbox(""Enabled"", &config->esp.dangerZone[selected].enabled); ImGui::SameLine(0.0f, 50.0f); ImGui::SetNextItemWidth(85.0f); ImGui::InputInt(""Font"", &config->esp.dangerZone[selected].font, 1, 294); config->esp.dangerZone[selected].font = std::clamp(config->esp.dangerZone[selected].font, 1, 294); ImGui::Separator(); constexpr auto spacing{ 200.0f }; ImGuiCustom::colorPicker(""Snaplines"", config->esp.dangerZone[selected].snaplines); ImGui::SameLine(spacing); ImGuiCustom::colorPicker(""Box"", config->esp.dangerZone[selected].box); ImGui::SameLine(); ImGui::SetNextItemWidth(95.0f); ImGui::Combo("""", &config->esp.dangerZone[selected].boxType, ""2D\\0""""2D corners\\0""""3D\\0""""3D corners\\0""); ImGuiCustom::colorPicker(""Name"", config->esp.dangerZone[selected].name); ImGui::SameLine(spacing); ImGuiCustom::colorPicker(""Outline"", config->esp.dangerZone[selected].outline); ImGuiCustom::colorPicker(""Distance"", config->esp.dangerZone[selected].distance); ImGui::SliderFloat(""Max distance"", &config->esp.dangerZone[selected].maxDistance, 0.0f, 200.0f, ""%.2fm""); break; } } ImGui::EndChild(); } if (!contentOnly) ImGui::End(); } void GUI::renderVisualsWindow(bool contentOnly) noexcept { if (!contentOnly) { if (!window.visuals) return; ImGui::SetNextWindowSize({ 680.0f, 0.0f }); ImGui::Begin(""Visuals"", &window.visuals, windowFlags); } ImGui::Columns(2, nullptr, false); ImGui::SetColumnOffset(1, 280.0f); ImGui::Combo(""T Player Model"", &config->visuals.playerModelT, ""Default\\0Special Agent Ava | FBI\\0Operator | FBI SWAT\\0Markus Delrow | FBI HRT\\0Michael Syfers | FBI Sniper\\0B Squadron Officer | SAS\\0Seal Team 6 Soldier | NSWC SEAL\\0Buckshot | NSWC SEAL\\0Lt. Commander Ricksaw | NSWC SEAL\\0Third Commando Company | KSK\\0'Two Times' McCoy | USAF TACP\\0Dragomir | Sabre\\0Rezan The Ready | Sabre\\0'The Doctor' Romanov | Sabre\\0Maximus | Sabre\\0Blackwolf | Sabre\\0The Elite Mr. Muhlik | Elite Crew\\0Ground Rebel | Elite Crew\\0Osiris | Elite Crew\\0Prof. Shahmat | Elite Crew\\0Enforcer | Phoenix\\0Slingshot | Phoenix\\0Soldier | Phoenix\\0""); ImGui::Combo(""CT Player Model"", &config->visuals.playerModelCT, ""Default\\0Special Agent Ava | FBI\\0Operator | FBI SWAT\\0Markus Delrow | FBI HRT\\0Michael Syfers | FBI Sniper\\0B Squadron Officer | SAS\\0Seal Team 6 Soldier | NSWC SEAL\\0Buckshot | NSWC SEAL\\0Lt. Commander Ricksaw | NSWC SEAL\\0Third Commando Company | KSK\\0'Two Times' McCoy | USAF TACP\\0Dragomir | Sabre\\0Rezan The Ready | Sabre\\0'The Doctor' Romanov | Sabre\\0Maximus | Sabre\\0Blackwolf | Sabre\\0The Elite Mr. Muhlik | Elite Crew\\0Ground Rebel | Elite Crew\\0Osiris | Elite Crew\\0Prof. Shahmat | Elite Crew\\0Enforcer | Phoenix\\0Slingshot | Phoenix\\0Soldier | Phoenix\\0""); ImGui::Checkbox(""Disable post-processing"", &config->visuals.disablePostProcessing); ImGui::Checkbox(""Inverse ragdoll gravity"", &config->visuals.inverseRagdollGravity); ImGui::Checkbox(""No fog"", &config->visuals.noFog); ImGui::Checkbox(""No 3d sky"", &config->visuals.no3dSky); ImGui::Checkbox(""No aim punch"", &config->visuals.noAimPunch); ImGui::Checkbox(""No view punch"", &config->visuals.noViewPunch); ImGui::Checkbox(""No hands"", &config->visuals.noHands); ImGui::Checkbox(""No sleeves"", &config->visuals.noSleeves); ImGui::Checkbox(""No weapons"", &config->visuals.noWeapons); ImGui::Checkbox(""No smoke"", &config->visuals.noSmoke); ImGui::Checkbox(""No blur"", &config->visuals.noBlur); ImGui::Checkbox(""No scope overlay"", &config->visuals.noScopeOverlay); ImGui::Checkbox(""No grass"", &config->visuals.noGrass); ImGui::Checkbox(""No shadows"", &config->visuals.noShadows); ImGui::Checkbox(""Wireframe smoke"", &config->visuals.wireframeSmoke); ImGui::NextColumn(); ImGui::Checkbox(""Zoom"", &config->visuals.zoom); ImGui::SameLine(); hotkey(config->visuals.zoomKey); ImGui::Checkbox(""Thirdperson"", &config->visuals.thirdperson); ImGui::SameLine(); hotkey(config->visuals.thirdpersonKey); ImGui::SetNextItemWidth(140.0f); ImGui::Combo(""Thirdperson Angles"", &config->antiAim.thirdpersonMode, ""Fake\\0Real\\0Current Tick\\0""); ImGui::PushItemWidth(290.0f); ImGui::PushID(0); ImGui::SliderInt("""", &config->visuals.thirdpersonDistance, 0, 1000, ""Thirdperson distance: %d""); ImGui::PopID(); ImGui::PushID(1); ImGui::SliderInt("""", &config->visuals.viewmodelFov, -60, 60, ""Viewmodel FOV: %d""); ImGui::PopID(); ImGui::PushID(2); ImGui::SliderInt("""", &config->visuals.fov, -60, 60, ""FOV: %d""); ImGui::PopID(); ImGui::PushID(3); ImGui::SliderInt("""", &config->visuals.farZ, 0, 2000, ""Far Z: %d""); ImGui::PopID(); ImGui::PushID(4); ImGui::SliderInt("""", &config->visuals.flashReduction, 0, 100, ""Flash reduction: %d%%""); ImGui::PopID(); ImGui::PushID(5); ImGui::SliderFloat("""", &config->visuals.brightness, 0.0f, 1.0f, ""Brightness: %.2f""); ImGui::PopID(); ImGui::PopItemWidth(); ImGui::Combo(""Skybox"", &config->visuals.skybox, ""Default\\0cs_baggage_skybox_\\0cs_tibet\\0embassy\\0italy\\0jungle\\0nukeblank\\0office\\0sky_cs15_daylight01_hdr\\0sky_cs15_daylight02_hdr\\0sky_cs15_daylight03_hdr\\0sky_cs15_daylight04_hdr\\0sky_csgo_cloudy01\\0sky_csgo_night_flat\\0sky_csgo_night02\\0sky_day02_05_hdr\\0sky_day02_05\\0sky_dust\\0sky_l4d_rural02_ldr\\0sky_venice\\0vertigo_hdr\\0vertigo\\0vertigoblue_hdr\\0vietnam\\0""); ImGuiCustom::colorPicker(""World color"", config->visuals.world); ImGuiCustom::colorPicker(""Sky color"", config->visuals.sky); ImGui::Checkbox(""Deagle spinner"", &config->visuals.deagleSpinner); ImGui::Combo(""Screen effect"", &config->visuals.screenEffect, ""None\\0Drone cam\\0Drone cam with noise\\0Underwater\\0Healthboost\\0Dangerzone\\0""); ImGui::Combo(""Hit effect"", &config->visuals.hitEffect, ""None\\0Drone cam\\0Drone cam with noise\\0Underwater\\0Healthboost\\0Dangerzone\\0""); ImGui::SliderFloat(""Hit effect time"", &config->visuals.hitEffectTime, 0.1f, 1.5f, ""%.2fs""); ImGui::Combo(""Hit marker"", &config->visuals.hitMarker, ""None\\0Default (Cross)\\0""); ImGui::SliderFloat(""Hit marker time"", &config->visuals.hitMarkerTime, 0.1f, 1.5f, ""%.2fs""); ImGui::Checkbox(""Indicators"", &config->visuals.indicatorsEnabled); ImGui::SameLine(); ImGui::PushID(6); ImGuiCustom::MultiCombo("""", config->visuals.indicators, config->visuals.selectedIndicators, 4); ImGui::PopID(); ImGuiCustom::colorPicker(""Bullet Tracers"", config->visuals.bulletTracers); ImGui::Checkbox(""Color correction"", &config->visuals.colorCorrection.enabled); ImGui::SameLine(); bool ccPopup = ImGui::Button(""Edit""); if (ccPopup) ImGui::OpenPopup(""##popup""); if (ImGui::BeginPopup(""##popup"")) { ImGui::VSliderFloat(""##1"", { 40.0f, 160.0f }, &config->visuals.colorCorrection.blue, 0.0f, 1.0f, ""Blue\\n%.3f""); ImGui::SameLine(); ImGui::VSliderFloat(""##2"", { 40.0f, 160.0f }, &config->visuals.colorCorrection.red, 0.0f, 1.0f, ""Red\\n%.3f""); ImGui::SameLine(); ImGui::VSliderFloat(""##3"", { 40.0f, 160.0f }, &config->visuals.colorCorrection.mono, 0.0f, 1.0f, ""Mono\\n%.3f""); ImGui::SameLine(); ImGui::VSliderFloat(""##4"", { 40.0f, 160.0f }, &config->visuals.colorCorrection.saturation, 0.0f, 1.0f, ""Sat\\n%.3f""); ImGui::SameLine(); ImGui::VSliderFloat(""##5"", { 40.0f, 160.0f }, &config->visuals.colorCorrection.ghost, 0.0f, 1.0f, ""Ghost\\n%.3f""); ImGui::SameLine(); ImGui::VSliderFloat(""##6"", { 40.0f, 160.0f }, &config->visuals.colorCorrection.green, 0.0f, 1.0f, ""Green\\n%.3f""); ImGui::SameLine(); ImGui::VSliderFloat(""##7"", { 40.0f, 160.0f }, &config->visuals.colorCorrection.yellow, 0.0f, 1.0f, ""Yellow\\n%.3f""); ImGui::SameLine(); ImGui::EndPopup(); } ImGui::Columns(1); if (!contentOnly) ImGui::End(); } void GUI::renderSkinChangerWindow(bool contentOnly) noexcept { if (!contentOnly) { if (!window.skinChanger) return; ImGui::SetNextWindowSize({ 700.0f, 0.0f }); ImGui::Begin(""nSkinz"", &window.skinChanger, windowFlags); } static auto itemIndex = 0; ImGui::PushItemWidth(110.0f); ImGui::Combo(""##1"", &itemIndex, [](void* data, int idx, const char** out_text) { *out_text = game_data::weapon_names[idx].name; return true; }, nullptr, IM_ARRAYSIZE(game_data::weapon_names), 5); ImGui::PopItemWidth(); auto& selected_entry = config->skinChanger[itemIndex]; selected_entry.itemIdIndex = itemIndex; { ImGui::SameLine(); ImGui::Checkbox(""Enabled"", &selected_entry.enabled); ImGui::Separator(); ImGui::Columns(2, nullptr, false); ImGui::InputInt(""Seed"", &selected_entry.seed); ImGui::InputInt(""StatTrak"", &selected_entry.stat_trak); ImGui::SliderFloat(""Wear"", &selected_entry.wear, FLT_MIN, 1.f, ""%.10f"", 5); ImGui::Combo(""Paint Kit"", &selected_entry.paint_kit_vector_index, [](void* data, int idx, const char** out_text) { *out_text = (itemIndex == 1 ? SkinChanger::gloveKits : SkinChanger::skinKits)[idx].name.c_str(); return true; }, nullptr, (itemIndex == 1 ? SkinChanger::gloveKits : SkinChanger::skinKits).size(), 10); ImGui::Combo(""Quality"", &selected_entry.entity_quality_vector_index, [](void* data, int idx, const char** out_text) { *out_text = game_data::quality_names[idx].name; return true; }, nullptr, IM_ARRAYSIZE(game_data::quality_names), 5); if (itemIndex == 0) { ImGui::Combo(""Knife"", &selected_entry.definition_override_vector_index, [](void* data, int idx, const char** out_text) { *out_text = game_data::knife_names[idx].name; return true; }, nullptr, IM_ARRAYSIZE(game_data::knife_names), 5); } else if (itemIndex == 1) { ImGui::Combo(""Glove"", &selected_entry.definition_override_vector_index, [](void* data, int idx, const char** out_text) { *out_text = game_data::glove_names[idx].name; return true; }, nullptr, IM_ARRAYSIZE(game_data::glove_names), 5); } else { static auto unused_value = 0; selected_entry.definition_override_vector_index = 0; ImGui::Combo(""Unavailable"", &unused_value, ""For knives or gloves\\0""); } ImGui::InputText(""Name Tag"", selected_entry.custom_name, 32); } ImGui::NextColumn(); { ImGui::PushID(""sticker""); static auto selectedStickerSlot = 0; ImGui::PushItemWidth(-1); if (ImGui::ListBoxHeader("""", 5)) { for (int i = 0; i < 5; ++i) { ImGui::PushID(i); const auto kit_vector_index = config->skinChanger[itemIndex].stickers[i].kit_vector_index; const std::string text = '#' + std::to_string(i + 1) + "" "" + SkinChanger::stickerKits[kit_vector_index].name; if (ImGui::Selectable(text.c_str(), i == selectedStickerSlot)) selectedStickerSlot = i; ImGui::PopID(); } ImGui::ListBoxFooter(); } ImGui::PopItemWidth(); auto& selected_sticker = selected_entry.stickers[selectedStickerSlot]; ImGui::Combo(""Sticker Kit"", &selected_sticker.kit_vector_index, [](void* data, int idx, const char** out_text) { *out_text = SkinChanger::stickerKits[idx].name.c_str(); return true; }, nullptr, SkinChanger::stickerKits.size(), 10); ImGui::SliderFloat(""Wear"", &selected_sticker.wear, FLT_MIN, 1.0f, ""%.10f"", 5.0f); ImGui::SliderFloat(""Scale"", &selected_sticker.scale, 0.1f, 5.0f); ImGui::SliderFloat(""Rotation"", &selected_sticker.rotation, 0.0f, 360.0f); ImGui::PopID(); } selected_entry.update(); ImGui::Columns(1); ImGui::Separator(); if (ImGui::Button(""Update"", { 130.0f, 30.0f })) SkinChanger::scheduleHudUpdate(); ImGui::TextUnformatted(""nSkinz by namazso""); if (!contentOnly) ImGui::End(); } void GUI::renderSoundWindow(bool contentOnly) noexcept { if (!contentOnly) { if (!window.sound) return; ImGui::SetNextWindowSize({ 0.0f, 0.0f }); ImGui::Begin(""Sound"", &window.sound, windowFlags); } ImGui::SliderInt(""Chicken volume"", &config->sound.chickenVolume, 0, 200, ""%d%%""); static int currentCategory{ 0 }; ImGui::PushItemWidth(110.0f); ImGui::Combo("""", ¤tCategory, ""Local player\\0Allies\\0Enemies\\0""); ImGui::PopItemWidth(); ImGui::SliderInt(""Master volume"", &config->sound.players[currentCategory].masterVolume, 0, 200, ""%d%%""); ImGui::SliderInt(""Headshot volume"", &config->sound.players[currentCategory].headshotVolume, 0, 200, ""%d%%""); ImGui::SliderInt(""Weapon volume"", &config->sound.players[currentCategory].weaponVolume, 0, 200, ""%d%%""); ImGui::SliderInt(""Footstep volume"", &config->sound.players[currentCategory].footstepVolume, 0, 200, ""%d%%""); if (!contentOnly) ImGui::End(); } void GUI::renderStyleWindow(bool contentOnly) noexcept { if (!contentOnly) { if (!window.style) return; ImGui::SetNextWindowSize({ 0.0f, 0.0f }); ImGui::Begin(""Style"", &window.style, windowFlags); } ImGui::PushItemWidth(150.0f); if (ImGui::Combo(""Menu style"", &config->style.menuStyle, ""Classic\\0One window\\0"")) window = { }; if (ImGui::Combo(""Menu colors"", &config->style.menuColors, ""Dark\\0Light\\0Classic\\0Custom\\0"")) updateColors(); ImGui::PopItemWidth(); if (config->style.menuColors == 3) { ImGuiStyle& style = ImGui::GetStyle(); for (int i = 0; i < ImGuiCol_COUNT; i++) { if (i && i & 3) ImGui::SameLine(220.0f * (i & 3)); ImGuiCustom::colorPicker(ImGui::GetStyleColorName(i), (float*)&style.Colors[i]); } } if (!contentOnly) ImGui::End(); } void GUI::renderMiscWindow(bool contentOnly) noexcept { if (!contentOnly) { if (!window.misc) return; ImGui::SetNextWindowSize({ 580.0f, 0.0f }); ImGui::Begin(""Misc"", &window.misc, windowFlags); } ImGui::Columns(2, nullptr, false); ImGui::SetColumnOffset(1, 230.0f); ImGui::TextUnformatted(""Menu key""); ImGui::SameLine(); hotkey(config->misc.menuKey); ImGui::Checkbox(""Anti AFK kick"", &config->misc.antiAfkKick); ImGui::Checkbox(""Auto strafe"", &config->misc.autoStrafe); ImGui::Checkbox(""Bunny hop"", &config->misc.bunnyHop); ImGui::Checkbox(""Fast duck"", &config->misc.fastDuck); ImGui::Checkbox(""Moonwalk"", &config->misc.moonwalk); ImGui::Checkbox(""Edge Jump"", &config->misc.edgejump); ImGui::SameLine(); hotkey(config->misc.edgejumpkey); ImGui::Checkbox(""Slowwalk"", &config->misc.slowwalk); ImGui::SameLine(); hotkey(config->misc.slowwalkKey); ImGui::Checkbox(""Sniper crosshair"", &config->misc.sniperCrosshair); ImGui::Checkbox(""Recoil crosshair"", &config->misc.recoilCrosshair); ImGui::Checkbox(""Auto pistol"", &config->misc.autoPistol); ImGui::Checkbox(""Auto reload"", &config->misc.autoReload); ImGui::Checkbox(""Auto accept"", &config->misc.autoAccept); ImGui::Checkbox(""Radar hack"", &config->misc.radarHack); ImGui::Checkbox(""Reveal ranks"", &config->misc.revealRanks); ImGui::Checkbox(""Reveal money"", &config->misc.revealMoney); ImGui::Checkbox(""Reveal suspect"", &config->misc.revealSuspect); ImGuiCustom::colorPicker(""Spectator list"", config->misc.spectatorList); ImGuiCustom::colorPicker(""Watermark"", config->misc.watermark); ImGui::Checkbox(""Fix animation LOD"", &config->misc.fixAnimationLOD); ImGui::Checkbox(""Fix bone matrix"", &config->misc.fixBoneMatrix); ImGui::Checkbox(""Fix movement"", &config->misc.fixMovement); ImGui::Checkbox(""Disable model occlusion"", &config->misc.disableModelOcclusion); ImGui::SliderFloat(""Aspect Ratio"", &config->misc.aspectratio, 0.0f, 5.0f, ""%.2f""); ImGui::NextColumn(); ImGui::Checkbox(""Disable HUD blur"", &config->misc.disablePanoramablur); ImGui::Checkbox(""Animated clan tag"", &config->misc.animatedClanTag); ImGui::Checkbox(""Clock tag"", &config->misc.clocktag); ImGui::Checkbox(""Custom clantag"", &config->misc.customClanTag); ImGui::SameLine(); ImGui::PushItemWidth(120.0f); ImGui::PushID(0); if (ImGui::InputText("""", &config->misc.clanTag)) Misc::updateClanTag(true); ImGui::PopID(); ImGui::Checkbox(""Kill message"", &config->misc.killMessage); ImGui::SameLine(); ImGui::PushItemWidth(120.0f); ImGui::PushID(1); ImGui::InputText("""", &config->misc.killMessageString); ImGui::PopID(); ImGui::Checkbox(""Name stealer"", &config->misc.nameStealer); ImGui::PushID(3); ImGui::SetNextItemWidth(100.0f); ImGui::Combo("""", &config->misc.banColor, ""White\\0Red\\0Purple\\0Green\\0Light green\\0Turquoise\\0Light red\\0Gray\\0Yellow\\0Gray 2\\0Light blue\\0Gray/Purple\\0Blue\\0Pink\\0Dark orange\\0Orange\\0""); ImGui::PopID(); ImGui::SameLine(); ImGui::PushID(4); ImGui::InputText("""", &config->misc.banText); ImGui::PopID(); ImGui::SameLine(); if (ImGui::Button(""Setup fake ban"")) Misc::fakeBan(true); ImGui::Checkbox(""Fast plant"", &config->misc.fastPlant); ImGuiCustom::colorPicker(""Bomb timer"", config->misc.bombTimer); ImGui::Checkbox(""Quick reload"", &config->misc.quickReload); ImGui::Checkbox(""Prepare revolver"", &config->misc.prepareRevolver); ImGui::SameLine(); hotkey(config->misc.prepareRevolverKey); ImGui::Combo(""Hit Sound"", &config->misc.hitSound, ""None\\0Metal\\0Gamesense\\0Bell\\0Glass\\0Custom\\0""); if (config->misc.hitSound == 5) { ImGui::InputText(""Hit Sound filename"", &config->misc.customHitSound); if (ImGui::IsItemHovered()) ImGui::SetTooltip(""audio file must be put in csgo/sound/ directory""); } ImGui::PushID(5); ImGui::Combo(""Kill Sound"", &config->misc.killSound, ""None\\0Metal\\0Gamesense\\0Bell\\0Glass\\0Custom\\0""); if (config->misc.killSound == 5) { ImGui::InputText(""Kill Sound filename"", &config->misc.customKillSound); if (ImGui::IsItemHovered()) ImGui::SetTooltip(""audio file must be put in csgo/sound/ directory""); } ImGui::PopID(); ImGui::Combo(""Fake Lag"", &config->misc.fakeLagMode, ""Off\\0Normal\\0Adaptive\\0Random\\0Switch""); ImGui::SameLine(); hotkey(config->misc.fakeLagKey); if (!(config->misc.fakeLagMode == 0)) { ImGuiCustom::MultiCombo(""Flags"", config->misc.fakeLagFlags, config->misc.fakeLagSelectedFlags, 4); if (config->misc.fakeLagMode == 3) { ImGui::SetNextItemWidth(120.0f); ImGui::SliderInt(""Min Fakelag Amount"", &config->misc.fakeLagTicks, 1, 16); config->misc.fakeLagTicks = std::clamp(config->misc.fakeLagTicks, 1, 64); } else if (!(config->misc.fakeLagMode == 4)) { ImGui::SetNextItemWidth(120.0f); ImGui::SliderInt(""Fakelag Amount"", &config->misc.fakeLagTicks, 1, 16); config->misc.fakeLagTicks = std::clamp(config->misc.fakeLagTicks, 1, 64); } } ImGui::Text(""Quick healthshot""); ImGui::SameLine(); hotkey(config->misc.quickHealthshotKey); ImGui::Checkbox(""Grenade Prediction"", &config->misc.nadePredict); ImGui::Checkbox(""Fix tablet signal"", &config->misc.fixTabletSignal); ImGui::SetNextItemWidth(120.0f); ImGui::SliderFloat(""Max angle delta"", &config->misc.maxAngleDelta, 0.0f, 255.0f, ""%.2f""); ImGui::Checkbox(""Fake prime"", &config->misc.fakePrime); ImGui::Checkbox(""Zeusbot"", &config->misc.autoZeus); if (config->misc.autoZeus) { ImGui::SetNextItemWidth(120.0f); ImGui::SliderInt(""Zeus Max Wall Penetration Distance"", &config->misc.autoZeusMaxPenDist, 0, 50); config->misc.autoZeusMaxPenDist = std::clamp(config->misc.autoZeusMaxPenDist, 0, 50); ImGui::Checkbox(""Zeusbot BAIM Only"", &config->misc.autoZeusBaimOnly); } ImGui::Checkbox(""Fakeduck"", &config->misc.fakeDuck); ImGui::SameLine(); hotkey(config->misc.fakeDuckKey); ImGui::Checkbox(""Purchase List"", &config->misc.purchaseList.enabled); ImGui::SameLine(); ImGui::PushID(""Purchase List""); if (ImGui::Button(""..."")) ImGui::OpenPopup(""""); if (ImGui::BeginPopup("""")) { ImGui::SetNextItemWidth(75.0f); ImGui::Combo(""Mode"", &config->misc.purchaseList.mode, ""Details\\0Summary\\0""); ImGui::Checkbox(""Only During Freeze Time"", &config->misc.purchaseList.onlyDuringFreezeTime); ImGui::Checkbox(""Show Prices"", &config->misc.purchaseList.showPrices); ImGui::Checkbox(""No Title Bar"", &config->misc.purchaseList.noTitleBar); ImGui::EndPopup(); } ImGui::PopID(); if (ImGui::Button(""Unhook"")) hooks->uninstall(); ImGui::Columns(1); if (!contentOnly) ImGui::End(); } void GUI::renderReportbotWindow(bool contentOnly) noexcept { if (!contentOnly) { if (!window.reportbot) return; ImGui::SetNextWindowSize({ 0.0f, 0.0f }); ImGui::Begin(""Reportbot"", &window.reportbot, windowFlags); } ImGui::Checkbox(""Enabled"", &config->reportbot.enabled); ImGui::SameLine(0.0f, 50.0f); if (ImGui::Button(""Reset"")) Reportbot::reset(); ImGui::Separator(); ImGui::PushItemWidth(80.0f); ImGui::Combo(""Target"", &config->reportbot.target, ""Enemies\\0Allies\\0All\\0""); ImGui::InputInt(""Delay (s)"", &config->reportbot.delay); config->reportbot.delay = (std::max)(config->reportbot.delay, 1); ImGui::InputInt(""Rounds"", &config->reportbot.rounds); config->reportbot.rounds = (std::max)(config->reportbot.rounds, 1); ImGui::PopItemWidth(); ImGui::Checkbox(""Abusive Communications"", &config->reportbot.textAbuse); ImGui::Checkbox(""Griefing"", &config->reportbot.griefing); ImGui::Checkbox(""Wall Hacking"", &config->reportbot.wallhack); ImGui::Checkbox(""Aim Hacking"", &config->reportbot.aimbot); ImGui::Checkbox(""Other Hacking"", &config->reportbot.other); if (!contentOnly) ImGui::End(); } void GUI::renderConfigWindow(bool contentOnly) noexcept { if (!contentOnly) { if (!window.config) return; ImGui::SetNextWindowSize({ 290.0f, 200.0f }); ImGui::Begin(""Config"", &window.config, windowFlags); } ImGui::Columns(2, nullptr, false); ImGui::SetColumnOffset(1, 170.0f); ImGui::PushItemWidth(160.0f); if (ImGui::Button(""Reload configs"", { 160.0f, 25.0f })) config->listConfigs(); auto& configItems = config->getConfigs(); static int currentConfig = -1; if (static_cast(currentConfig) >= configItems.size()) currentConfig = -1; static std::string buffer; if (ImGui::ListBox("""", ¤tConfig, [](void* data, int idx, const char** out_text) { auto& vector = *static_cast*>(data); *out_text = vector[idx].c_str(); return true; }, &configItems, configItems.size(), 5) && currentConfig != -1) buffer = configItems[currentConfig]; ImGui::PushID(0); if (ImGui::InputText("""", &buffer, ImGuiInputTextFlags_EnterReturnsTrue)) { if (currentConfig != -1) config->rename(currentConfig, buffer.c_str()); } ImGui::PopID(); ImGui::NextColumn(); ImGui::PushItemWidth(100.0f); if (ImGui::Button(""Create config"", { 100.0f, 25.0f })) config->add(buffer.c_str()); if (ImGui::Button(""Reset config"", { 100.0f, 25.0f })) ImGui::OpenPopup(""Config to reset""); if (ImGui::BeginPopup(""Config to reset"")) { static constexpr const char* names[]{ ""Whole"", ""Aimbot"", ""Triggerbot"", ""Backtrack"", ""Anti aim"", ""Glow"", ""Chams"", ""Esp"", ""Visuals"", ""Skin changer"", ""Sound"", ""Style"", ""Misc"", ""Reportbot"" }; for (int i = 0; i < IM_ARRAYSIZE(names); i++) { if (i == 1) ImGui::Separator(); if (ImGui::Selectable(names[i])) { switch (i) { case 0: config->reset(); updateColors(); Misc::updateClanTag(true); SkinChanger::scheduleHudUpdate(); break; case 1: config->aimbot = { }; break; case 2: config->triggerbot = { }; break; case 3: config->backtrack = { }; break; case 4: config->antiAim = { }; break; case 5: config->glow = { }; break; case 6: config->chams = { }; break; case 7: config->esp = { }; break; case 8: config->visuals = { }; break; case 9: config->skinChanger = { }; SkinChanger::scheduleHudUpdate(); break; case 10: config->sound = { }; break; case 11: config->style = { }; updateColors(); break; case 12: config->misc = { }; Misc::updateClanTag(true); break; case 13: config->reportbot = { }; break; } } } ImGui::EndPopup(); } if (currentConfig != -1) { if (ImGui::Button(""Load selected"", { 100.0f, 25.0f })) { config->load(currentConfig); updateColors(); SkinChanger::scheduleHudUpdate(); Misc::updateClanTag(true); } if (ImGui::Button(""Save selected"", { 100.0f, 25.0f })) config->save(currentConfig); if (ImGui::Button(""Delete selected"", { 100.0f, 25.0f })) config->remove(currentConfig); } ImGui::Columns(1); if (!contentOnly) ImGui::End(); } void GUI::renderGuiStyle2() noexcept { ImGui::SetNextWindowSize({ 600.0f, 0.0f }); ImGui::Begin(""Osiris"", nullptr, windowFlags | ImGuiWindowFlags_NoTitleBar); if (ImGui::BeginTabBar(""TabBar"", ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_FittingPolicyScroll | ImGuiTabBarFlags_NoTooltip)) { if (ImGui::BeginTabItem(""Aimbot"")) { renderAimbotWindow(true); ImGui::EndTabItem(); } if (ImGui::BeginTabItem(""Anti aim"")) { renderAntiAimWindow(true); ImGui::EndTabItem(); } if (ImGui::BeginTabItem(""Triggerbot"")) { renderTriggerbotWindow(true); ImGui::EndTabItem(); } if (ImGui::BeginTabItem(""Backtrack"")) { renderBacktrackWindow(true); ImGui::EndTabItem(); } if (ImGui::BeginTabItem(""Glow"")) { renderGlowWindow(true); ImGui::EndTabItem(); } if (ImGui::BeginTabItem(""Chams"")) { renderChamsWindow(true); ImGui::EndTabItem(); } if (ImGui::BeginTabItem(""Esp"")) { renderEspWindow(true); ImGui::EndTabItem(); } if (ImGui::BeginTabItem(""Visuals"")) { renderVisualsWindow(true); ImGui::EndTabItem(); } if (ImGui::BeginTabItem(""Skin changer"")) { renderSkinChangerWindow(true); ImGui::EndTabItem(); } if (ImGui::BeginTabItem(""Sound"")) { renderSoundWindow(true); ImGui::EndTabItem(); } if (ImGui::BeginTabItem(""Style"")) { renderStyleWindow(true); ImGui::EndTabItem(); } if (ImGui::BeginTabItem(""Misc"")) { renderMiscWindow(true); ImGui::EndTabItem(); } if (ImGui::BeginTabItem(""Reportbot"")) { renderReportbotWindow(true); ImGui::EndTabItem(); } if (ImGui::BeginTabItem(""Config"")) { renderConfigWindow(true); ImGui::EndTabItem(); } ImGui::EndTabBar(); } ImGui::End(); } ",16377,True,3416.1175583956738,median "/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | | Copyright (c) 1997-2010 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include ""hphp/runtime/ext/std/ext_std_file.h"" #include ""hphp/util/hphp-config.h"" #include ""hphp/runtime/base/array-init.h"" #include ""hphp/runtime/base/array-util.h"" #include ""hphp/runtime/base/comparisons.h"" #include ""hphp/runtime/base/directory.h"" #include ""hphp/runtime/base/file-stream-wrapper.h"" #include ""hphp/runtime/base/file-util.h"" #include ""hphp/runtime/base/http-client.h"" #include ""hphp/runtime/base/http-stream-wrapper.h"" #include ""hphp/runtime/base/ini-setting.h"" #include ""hphp/runtime/base/pipe.h"" #include ""hphp/runtime/base/plain-file.h"" #include ""hphp/runtime/base/temp-file.h"" #include ""hphp/runtime/base/runtime-error.h"" #include ""hphp/runtime/base/runtime-option.h"" #include ""hphp/runtime/base/stat-cache.h"" #include ""hphp/runtime/base/stream-wrapper-registry.h"" #include ""hphp/runtime/base/string-util.h"" #include ""hphp/runtime/base/request-info.h"" #include ""hphp/runtime/base/zend-scanf.h"" #include ""hphp/runtime/ext/hash/ext_hash.h"" #if ENABLE_EXTENSION_POSIX #include ""hphp/runtime/ext/posix/ext_posix.h"" #endif #include ""hphp/runtime/ext/std/ext_std_options.h"" #include ""hphp/runtime/ext/string/ext_string.h"" #include ""hphp/runtime/server/cli-server.h"" #include ""hphp/runtime/server/static-content-cache.h"" #include ""hphp/system/systemlib.h"" #include ""hphp/util/logger.h"" #include ""hphp/util/process.h"" #include ""hphp/util/rds-local.h"" #include ""hphp/util/user-info.h"" #include #include #include #include #ifndef _MSC_VER #include #if defined(__FreeBSD__) || defined(__APPLE__) # include #else # include #endif #include #include #include #include #endif #include #include #include namespace fs = boost::filesystem; #define CHECK_HANDLE_BASE(handle, f, ret) \\ auto f = dyn_cast_or_null(handle); \\ if (f == nullptr || f->isClosed()) { \\ raise_warning(""Not a valid stream resource""); \\ return (ret); \\ } \\ #define CHECK_HANDLE(handle, f) \\ CHECK_HANDLE_BASE(handle, f, false) #define CHECK_HANDLE_RET_NULL(handle, f) \\ CHECK_HANDLE_BASE(handle, f, uninit_variant) #define CHECK_PATH_BASE(p, i, ret) \\ if (p.size() != strlen(p.data())) { \\ raise_warning( \\ ""%s() expects parameter %d to be a valid path, string given"", \\ __FUNCTION__ + 2, i \\ ); \\ return (ret); \\ } #define CHECK_PATH(p, i) \\ CHECK_PATH_BASE(p, i, uninit_variant) #define CHECK_PATH_FALSE(p, i) \\ CHECK_PATH_BASE(p, i, false) #define CHECK_SYSTEM(exp) \\ if ((exp) != 0) { \\ raise_warning( \\ ""%s(): %s"", \\ __FUNCTION__ + 2, \\ folly::errnoStr(errno).c_str() \\ ); \\ return false; \\ } \\ #define CHECK_SYSTEM_SILENT(exp) \\ if ((exp) != 0) { \\ Logger::Verbose(""%s/%d: %s"", __FUNCTION__, __LINE__, \\ folly::errnoStr(errno).c_str()); \\ return false; \\ } \\ #define CHECK_BOOST(dest, func, path) \\ boost::system::error_code ec; \\ dest = func(path.toCppString(), ec); \\ if (ec) { \\ raise_warning( \\ ""%s(): %s"", \\ __FUNCTION__ + 2, \\ ec.message().c_str() \\ ); \\ return false; \\ } \\ #define CHECK_BOOST_SILENT(dest, func, path) \\ boost::system::error_code ec; \\ dest = func(path.toCppString(), ec); \\ if (ec) { \\ Logger::Verbose(""%s/%d: %s"", __FUNCTION__, __LINE__, \\ ec.message().c_str() \\ ); \\ return false; \\ } \\ #define CHECK_BOOST_ASSIGN(func, path, arg) \\ boost::system::error_code ec; \\ func(path.toCppString(), arg, ec); \\ if (ec) { \\ raise_warning( \\ ""%s(): %s"", \\ __FUNCTION__ + 2, \\ ec.message().c_str() \\ ); \\ return false; \\ } \\ // libxml/xpathInternals.h defines CHECK_ERROR, // we need to undef it first #ifdef CHECK_ERROR #undef CHECK_ERROR #endif #define CHECK_ERROR(ret) \\ check_error(__FUNCTION__, __LINE__, (ret)) namespace HPHP { static const StaticString s_STREAM_URL_STAT_LINK(""STREAM_URL_STAT_LINK""); static const StaticString s_STREAM_URL_STAT_QUIET(""STREAM_URL_STAT_QUIET""); /////////////////////////////////////////////////////////////////////////////// // helpers static bool check_error(const char *function, int line, bool ret) { if (!ret) { Logger::Verbose(""%s/%d: %s"", function, line, folly::errnoStr(errno).c_str()); } return ret; } static int accessSyscall( const String& uri_or_path, int mode, bool useFileCache = false) { Stream::Wrapper* w = Stream::getWrapperFromURI(uri_or_path); if (!w) return -1; if (useFileCache && dynamic_cast(w)) { String path(uri_or_path); if (UNLIKELY(StringUtil::IsFileUrl(uri_or_path.data()))) { path = StringUtil::DecodeFileUrl(uri_or_path); if (path.empty()) { return -1; } } return ::access(File::TranslatePathWithFileCache(path).data(), mode); } return w->access(uri_or_path, mode); } static int statSyscall( const String& path, struct stat* buf, bool useFileCache = false) { bool isRelative = !FileUtil::isAbsolutePath(path.slice()); int pathIndex = 0; Stream::Wrapper* w = Stream::getWrapperFromURI(path, &pathIndex); if (!w) return -1; bool isFileStream = dynamic_cast(w); auto canUseFileCache = useFileCache && isFileStream; if (isRelative && !pathIndex) { auto fullpath = g_context->getCwd() + String::FromChar('/') + path; if (!RID().hasSafeFileAccess() && !canUseFileCache) { if (strlen(fullpath.data()) != fullpath.size()) return ENOENT; if (!isFileStream && w->isNormalFileStream()) { return w->stat(fullpath.data(), buf); } return ::stat(fullpath.data(), buf); } std::string realpath = StatCache::realpath(fullpath.data()); // realpath will return an empty string for nonexistent files if (realpath.empty()) { return ENOENT; } auto translatedPath = canUseFileCache ? File::TranslatePathWithFileCache(realpath) : File::TranslatePath(realpath); if (!isFileStream && w->isNormalFileStream()) { return w->stat(translatedPath.data(), buf); } return ::stat(translatedPath.data(), buf); } auto properPath = w->isNormalFileStream() ? path.substr(pathIndex) : path; if (canUseFileCache) { return ::stat(File::TranslatePathWithFileCache(properPath).data(), buf); } return w->stat(properPath, buf); } static int lstatSyscall( const String& path, struct stat* buf, bool useFileCache = false) { Stream::Wrapper* w = Stream::getWrapperFromURI(path); if (!w) return -1; if (useFileCache && dynamic_cast(w)) { return ::lstat(File::TranslatePathWithFileCache(path).data(), buf); } return w->lstat(path, buf); } const StaticString s_dev(""dev""), s_ino(""ino""), s_mode(""mode""), s_nlink(""nlink""), s_uid(""uid""), s_gid(""gid""), s_rdev(""rdev""), s_size(""size""), s_atime(""atime""), s_mtime(""mtime""), s_ctime(""ctime""), s_blksize(""blksize""), s_blocks(""blocks""); Array stat_impl(struct stat *stat_sb) { DictInit ret(26); ret.append((int64_t)stat_sb->st_dev); ret.append((int64_t)stat_sb->st_ino); ret.append((int64_t)stat_sb->st_mode); ret.append((int64_t)stat_sb->st_nlink); ret.append((int64_t)stat_sb->st_uid); ret.append((int64_t)stat_sb->st_gid); ret.append((int64_t)stat_sb->st_rdev); ret.append((int64_t)stat_sb->st_size); ret.append((int64_t)stat_sb->st_atime); ret.append((int64_t)stat_sb->st_mtime); ret.append((int64_t)stat_sb->st_ctime); #ifndef _MSC_VER ret.append((int64_t)stat_sb->st_blksize); ret.append((int64_t)stat_sb->st_blocks); #endif ret.set(s_dev, (int64_t)stat_sb->st_dev); ret.set(s_ino, (int64_t)stat_sb->st_ino); ret.set(s_mode, (int64_t)stat_sb->st_mode); ret.set(s_nlink, (int64_t)stat_sb->st_nlink); ret.set(s_uid, (int64_t)stat_sb->st_uid); ret.set(s_gid, (int64_t)stat_sb->st_gid); ret.set(s_rdev, (int64_t)stat_sb->st_rdev); ret.set(s_size, (int64_t)stat_sb->st_size); ret.set(s_atime, (int64_t)stat_sb->st_atime); ret.set(s_mtime, (int64_t)stat_sb->st_mtime); ret.set(s_ctime, (int64_t)stat_sb->st_ctime); #ifndef _MSC_VER ret.set(s_blksize, (int64_t)stat_sb->st_blksize); ret.set(s_blocks, (int64_t)stat_sb->st_blocks); #endif return ret.toArray(); } /////////////////////////////////////////////////////////////////////////////// Variant HHVM_FUNCTION(fopen, const String& filename, const String& mode, bool use_include_path /* = false */, const Variant& context /* = null */) { CHECK_PATH_FALSE(filename, 1); if (!context.isNull() && dyn_cast(context) == nullptr) { raise_warning(""$context must be a valid Stream Context or NULL""); return false; } if (filename.empty()) { raise_warning(""Filename cannot be empty""); return false; } auto file = File::Open(filename, mode, use_include_path ? File::USE_INCLUDE_PATH : 0, cast_or_null(context)); if (!file) { return false; } return Variant(file); } Variant HHVM_FUNCTION(popen, const String& command, const String& mode) { CHECK_PATH_FALSE(command, 1); auto file = req::make(); bool ret = CHECK_ERROR(file->open(File::TranslateCommand(command), mode)); if (!ret) { raise_warning(""popen(%s,%s): Invalid argument"", command.data(), mode.data()); return false; } return Variant(std::move(file)); } bool HHVM_FUNCTION(fclose, const Resource& handle) { CHECK_HANDLE(handle, f); return CHECK_ERROR(f->close()); } Variant HHVM_FUNCTION(pclose, const Variant& handle) { CHECK_HANDLE(handle.toResource(), f); CHECK_ERROR(f->close()); return *s_pcloseRet; } Variant HHVM_FUNCTION(fseek, const Resource& handle, int64_t offset, int64_t whence /* = SEEK_SET */) { CHECK_HANDLE(handle, f); return CHECK_ERROR(f->seek(offset, whence)) ? 0 : -1; } bool HHVM_FUNCTION(rewind, const Resource& handle) { CHECK_HANDLE(handle, f); return CHECK_ERROR(f->rewind()); } Variant HHVM_FUNCTION(ftell, const Resource& handle) { CHECK_HANDLE(handle, f); int64_t ret = f->tell(); if (!CHECK_ERROR(ret != -1)) { return false; } return ret; } bool HHVM_FUNCTION(feof, const Resource& handle) { CHECK_HANDLE(handle, f); return f->eof(); } Variant HHVM_FUNCTION(fstat, const Resource& handle) { CHECK_HANDLE(handle, f); struct stat sb; if (!CHECK_ERROR(f->stat(&sb))) return false; return stat_impl(&sb); } Variant HHVM_FUNCTION(fread, const Resource& handle, int64_t length) { CHECK_HANDLE(handle, f); if (length < 1) { raise_warning( ""fread(): Length parameter must be greater than 0"" ); return false; } return f->read(length); } Variant HHVM_FUNCTION(fgetc, const Resource& handle) { CHECK_HANDLE(handle, f); int result = f->getc(); if (result == EOF) { return false; } return String::FromChar(result); } Variant HHVM_FUNCTION(fgets, const Resource& handle, int64_t length /* = 0 */) { if (length < 0) { raise_invalid_argument_warning(""length (negative): %"" PRId64, length); return false; } CHECK_HANDLE(handle, f); String line = f->readLine(length - 1); if (!line.isNull()) { return line; } return false; } Variant HHVM_FUNCTION(fgetss, const Resource& handle, int64_t length /* = 0 */, const String& allowable_tags /* = null_string */) { Variant ret = HHVM_FN(fgets)(handle, length); if (!same(ret, false)) { return StringUtil::StripHTMLTags(ret.toString(), allowable_tags); } return ret; } Variant HHVM_FUNCTION(fscanf, const Resource& handle, const String& format) { CHECK_HANDLE(handle, f); String line = f->readLine(); if (line.length() == 0) { return false; } return HHVM_FN(sscanf)(line, format); } Variant HHVM_FUNCTION(fpassthru, const Resource& handle) { CHECK_HANDLE(handle, f); return f->print(); } Variant HHVM_FUNCTION(fwrite, const Resource& handle, const String& data, int64_t length /* = 0 */) { CHECK_HANDLE(handle, f); int64_t ret = f->write(data, length); if (ret < 0) { raise_notice(""fwrite(): send of %ld bytes failed with errno=%d %s"", data.size(), errno, folly::errnoStr(errno).c_str()); ret = 0; } return ret; } Variant HHVM_FUNCTION(fputs, const Resource& handle, const String& data, int64_t length /* = 0 */) { CHECK_HANDLE(handle, f); int64_t ret = f->write(data, length); if (ret < 0) ret = 0; return ret; } Variant HHVM_FUNCTION(fprintf, const Variant& handle, const String& format, const Array& args /* = null_array */) { if (!handle.isResource()) { raise_param_type_warning(""fprintf"", 1, ""resource"", *handle.asTypedValue()); return false; } const Resource res = handle.toResource(); CHECK_HANDLE(res, f); return f->printf(format, args); } Variant HHVM_FUNCTION(vfprintf, const Variant& handle, const Variant& format, const Variant& args) { CHECK_HANDLE(handle.toResource(), f); return f->printf(format.toString(), args.toArray()); } bool HHVM_FUNCTION(fflush, const Resource& handle) { CHECK_HANDLE(handle, f); return CHECK_ERROR(f->flush()); } bool HHVM_FUNCTION(ftruncate, const Resource& handle, int64_t size) { CHECK_HANDLE(handle, f); return CHECK_ERROR(f->truncate(size)); } static int flock_values[] = { LOCK_SH, LOCK_EX, LOCK_UN }; bool HHVM_FUNCTION(flock, const Resource& handle, int64_t operation, bool& wouldblock) { CHECK_HANDLE(handle, f); int act; wouldblock = false; act = operation & 3; if (act < 1 || act > 3) { raise_invalid_argument_warning(""operation: %ld"", operation); return false; } act = flock_values[act - 1] | (operation & 4 ? LOCK_NB : 0); bool ret = f->lock(act, wouldblock); return ret; } // match the behavior of PHP5 #define FCSV_CHECK_ARG(NAME) \\ if (NAME.size() == 0) { \\ raise_invalid_argument_warning(#NAME "": %s"", NAME.data()); \\ return false; \\ } else if (NAME.size() > 1) { \\ raise_notice(#NAME "" must be a single character""); \\ } \\ char NAME ## _char = NAME.charAt(0); \\ Variant HHVM_FUNCTION(fputcsv, const Resource& handle, const Array& fields, const String& delimiter /* = "","" */, const String& enclosure /* = ""\\"""" */, const String& escape /* = ""\\\\"" */) { FCSV_CHECK_ARG(delimiter); FCSV_CHECK_ARG(enclosure); FCSV_CHECK_ARG(escape); CHECK_HANDLE_RET_NULL(handle, f); return f->writeCSV(fields, delimiter_char, enclosure_char, escape_char); } Variant HHVM_FUNCTION(fgetcsv, const Resource& handle, int64_t length /* = 0 */, const String& delimiter /* = "","" */, const String& enclosure /* = ""\\"""" */, const String& escape /* = ""\\\\"" */) { if (length < 0) { raise_invalid_argument_warning(""Length parameter may not be negative""); return false; } FCSV_CHECK_ARG(delimiter); FCSV_CHECK_ARG(enclosure); FCSV_CHECK_ARG(escape); CHECK_HANDLE_RET_NULL(handle, f); Array ret = f->readCSV(length, delimiter_char, enclosure_char, escape_char); if (!ret.isNull()) { return ret; } return false; } /////////////////////////////////////////////////////////////////////////////// Variant HHVM_FUNCTION(file_get_contents, const String& filename, bool use_include_path /* = false */, const Variant& context /* = null */, int64_t offset /* = -1 */, int64_t maxlen /* = -1 */) { CHECK_PATH(filename, 1); Variant stream = HHVM_FN(fopen)(filename, ""rb"", use_include_path, context); if (same(stream, false)) return false; return HHVM_FN(stream_get_contents)(stream.toResource(), maxlen, offset); } Variant HHVM_FUNCTION(file_put_contents, const String& filename, const Variant& data, int64_t flags /* = 0 */, const Variant& context /* = null */) { CHECK_PATH(filename, 1); char mode[3] = ""wb""; if (flags & PHP_FILE_APPEND) { mode[0] = 'a'; } else if (flags & LOCK_EX) { // Open in ""create"" mode (writing only, create if needed, no truncate) // so that the file is not modified before we attempt to aquire the // requested lock. mode[0] = 'c'; } mode[2] = '\\0'; auto file = File::Open( filename, mode, flags, dyn_cast_or_null(context) ); if (!file) { return false; } if (flags & LOCK_EX) { // Check to make sure we are dealing with a regular file if (!isa(file)) { raise_warning( ""%s(): Exclusive locks may only be set for regular files"", __FUNCTION__ + 2); return false; } if (!file->lock(LOCK_EX)) { return false; } } if (mode[0] == 'c') { file->truncate(0); } int numbytes = 0; switch (data.getType()) { case KindOfResource: { auto fsrc = dyn_cast_or_null(data); if (!fsrc) { raise_warning(""Not a valid stream resource""); return false; } while (true) { char buffer[1024]; int len = fsrc->readImpl(buffer, sizeof(buffer)); if (len == 0) break; numbytes += len; int written = file->writeImpl(buffer, len); if (written != len) { numbytes = -1; break; } } break; } case KindOfPersistentVec: case KindOfVec: case KindOfPersistentDict: case KindOfDict: case KindOfPersistentKeyset: case KindOfKeyset: case KindOfClsMeth: { Array arr = data.toArray(); for (ArrayIter iter(arr); iter; ++iter) { auto const value = iter.second().toString(); if (!value.empty()) { numbytes += value.size(); int written = file->writeImpl(value.data(), value.size()); if (written != value.size()) { numbytes = -1; break; } } } break; } case KindOfObject: if (!data.getObjectData()->hasToString()) { raise_warning(""Not a valid stream resource""); return false; } // fallthrough case KindOfUninit: case KindOfNull: case KindOfBoolean: case KindOfInt64: case KindOfDouble: case KindOfPersistentString: case KindOfString: case KindOfFunc: case KindOfClass: case KindOfLazyClass: { String value = data.toString(); if (!value.empty()) { numbytes += value.size(); int written = file->writeImpl(value.data(), value.size()); if (written != value.size()) { numbytes = -1; } } break; } case KindOfRFunc: case KindOfRClsMeth: raise_warning(""Not a valid stream resource""); return false; } // like fwrite(), fclose() can error when fflush()ing if (numbytes < 0 || !file->close()) { return false; } return numbytes; } Variant HHVM_FUNCTION(file, const String& filename, int64_t flags /* = 0 */, const Variant& context /* = null */) { CHECK_PATH(filename, 1); Variant contents = HHVM_FN(file_get_contents)(filename, flags & PHP_FILE_USE_INCLUDE_PATH, context); if (same(contents, false)) { return false; } String content = contents.toString(); if (content.empty()) { return empty_vec_array(); } auto ret = Array::CreateVec(); char eol_marker = '\\n'; bool include_new_line = !(flags & PHP_FILE_IGNORE_NEW_LINES); bool skip_blank_lines = flags & PHP_FILE_SKIP_EMPTY_LINES; const char *s = content.data(); const char *e = s + content.size(); const char *p = (const char *)memchr(s, '\\n', content.size()); if (!p) { p = e; goto parse_eol; } if (include_new_line) { do { p++; parse_eol: ret.append(String(s, p-s, CopyString)); s = p; } while ((p = (const char *)memchr(p, eol_marker, (e-p)))); } else { do { int windows_eol = 0; if (p != content.data() && eol_marker == '\\n' && *(p - 1) == '\\r') { windows_eol++; } if (skip_blank_lines && !(p-s-windows_eol)) { s = ++p; continue; } ret.append(String(s, p-s-windows_eol, CopyString)); s = ++p; } while ((p = (const char *)memchr(p, eol_marker, (e-p)))); } /* handle any left overs of files without new lines */ if (s != e) { p = e; goto parse_eol; } return ret; } Variant HHVM_FUNCTION(readfile, const String& filename, bool use_include_path /* = false */, const Variant& context /* = null */) { CHECK_PATH_FALSE(filename, 1); Variant f = HHVM_FN(fopen)(filename, ""rb"", use_include_path, context); if (same(f, false)) { Logger::Verbose(""%s/%d: %s"", __FUNCTION__, __LINE__, folly::errnoStr(errno).c_str()); return false; } Variant ret = HHVM_FN(fpassthru)(f.toResource()); return ret; } bool HHVM_FUNCTION(move_uploaded_file, const String& filename, const String& destination) { Transport *transport = g_context->getTransport(); if (!transport || !transport->isUploadedFile(filename)) { return false; } CHECK_PATH_FALSE(destination, 2); if (HHVM_FN(rename)(filename, destination)) { return true; } // If rename didn't work, fall back to copy followed by unlink if (!HHVM_FN(copy)(filename, destination)) { return false; } HHVM_FN(unlink)(filename); return true; } namespace { String resolve_parse_ini_filename(const String& filename) { // Try cleaning up the path. Use file_exists to avoid a warning // that get_contents generates String resolved = File::TranslatePath(filename); if (!resolved.empty() && HHVM_FN(file_exists)(resolved)) { return resolved; } if (FileUtil::isAbsolutePath(filename.data())) { return null_string; } // Still no go, and not an absolute path, try to resolve based // on containing file name. auto const cfd = String::attach(g_context->getContainingFileName()); if (!cfd.empty()) { int npos = cfd.rfind('/'); if (npos >= 0) { resolved = cfd.substr(0, npos + 1) + filename; if (!resolved.empty() && HHVM_FN(file_exists)(resolved)) { return resolved; } } } // Next, see if include path was set in the ini settings. auto const& includePaths = RID().getIncludePaths(); for (auto const& path : includePaths) { resolved = path + FileUtil::getDirSeparator() + filename; if (HHVM_FN(file_exists)(resolved)) { return resolved; } } return null_string; } } Variant HHVM_FUNCTION(parse_ini_file, const String& filename, bool process_sections /* = false */, int64_t scanner_mode /* = k_INI_SCANNER_NORMAL */) { CHECK_PATH_FALSE(filename, 1); if (filename.empty()) { raise_invalid_argument_warning(""Filename cannot be empty!""); return false; } // Block ability to load ini files via http (eg., remotely) int oFilename = 0; Stream::Wrapper* w = Stream::getWrapperFromURI(filename, &oFilename); if (nullptr != dynamic_cast(w)) { raise_warning(""remote access to ini files is not allowed""); return false; } // Extract the (local) filename String wrapperPrefix = filename.substr(0, oFilename); String path = resolve_parse_ini_filename(filename.substr(oFilename)); if (path.empty()) { // At this point, we were unable to find the file. raise_warning(""No such file or directory""); return false; } Variant content = HHVM_FN(file_get_contents)(wrapperPrefix + path); if (same(content, false)) { // Don't generate a warning, as they have already been generated. return false; } return IniSetting::FromString(content.toString(), filename, process_sections, scanner_mode); } Variant HHVM_FUNCTION(parse_ini_string, const String& ini, bool process_sections /* = false */, int64_t scanner_mode /* = k_INI_SCANNER_NORMAL */) { return IniSetting::FromString(ini, """", process_sections, scanner_mode); } Variant HHVM_FUNCTION(md5_file, const String& filename, bool raw_output /* = false */) { CHECK_PATH(filename, 1); return HHVM_FN(hash_file)(""md5"", filename, raw_output); } Variant HHVM_FUNCTION(sha1_file, const String& filename, bool raw_output /* = false */) { CHECK_PATH(filename, 1); return HHVM_FN(hash_file)(""sha1"", filename, raw_output); } /////////////////////////////////////////////////////////////////////////////// // stats functions Variant HHVM_FUNCTION(fileperms, const String& filename) { CHECK_PATH(filename, 1); struct stat sb; CHECK_SYSTEM(statSyscall(filename, &sb, true)); return (int64_t)sb.st_mode; } Variant HHVM_FUNCTION(fileinode, const String& filename) { CHECK_PATH(filename, 1); struct stat sb; CHECK_SYSTEM(statSyscall(filename, &sb)); return (int64_t)sb.st_ino; } Variant HHVM_FUNCTION(filesize, const String& filename) { CHECK_PATH(filename, 1); if (filename.empty()) { return false; } if (StaticContentCache::TheFileCache) { int64_t size = StaticContentCache::TheFileCache->fileSize(filename.data(), filename.data()[0] != '/'); if (size >= 0) return size; } struct stat sb; CHECK_SYSTEM(statSyscall(filename, &sb, true)); return (int64_t)sb.st_size; } Variant HHVM_FUNCTION(fileowner, const String& filename) { CHECK_PATH(filename, 1); struct stat sb; CHECK_SYSTEM(statSyscall(filename, &sb, true)); return (int64_t)sb.st_uid; } Variant HHVM_FUNCTION(filegroup, const String& filename) { CHECK_PATH(filename, 1); struct stat sb; CHECK_SYSTEM(statSyscall(filename, &sb, true)); return (int64_t)sb.st_gid; } Variant HHVM_FUNCTION(fileatime, const String& filename) { CHECK_PATH(filename, 1); struct stat sb; CHECK_SYSTEM(statSyscall(filename, &sb, true)); return (int64_t)sb.st_atime; } Variant HHVM_FUNCTION(filemtime, const String& filename) { CHECK_PATH(filename, 1); struct stat sb; CHECK_SYSTEM(statSyscall(filename, &sb, true)); return (int64_t)sb.st_mtime; } Variant HHVM_FUNCTION(filectime, const String& filename) { CHECK_PATH(filename, 1); struct stat sb; CHECK_SYSTEM(statSyscall(filename, &sb, true)); return (int64_t)sb.st_ctime; } Variant HHVM_FUNCTION(filetype, const String& filename) { CHECK_PATH(filename, 1); struct stat sb; CHECK_SYSTEM(lstatSyscall(filename, &sb)); switch (sb.st_mode & S_IFMT) { case S_IFLNK: return ""link""; case S_IFIFO: return ""fifo""; case S_IFCHR: return ""char""; case S_IFDIR: return ""dir""; case S_IFBLK: return ""block""; case S_IFREG: return ""file""; case S_IFSOCK: return ""socket""; } return ""unknown""; } Variant HHVM_FUNCTION(linkinfo, const String& filename) { CHECK_PATH(filename, 1); struct stat sb; CHECK_SYSTEM(statSyscall(filename, &sb)); return (int64_t)sb.st_dev; } bool HHVM_FUNCTION(is_writable, const String& filename) { CHECK_PATH_FALSE(filename, 1); if (filename.empty()) { return false; } CHECK_SYSTEM_SILENT(accessSyscall(filename, W_OK)); return true; /* int mask = S_IWOTH; if (sb.st_uid == getuid()) { mask = S_IWUSR; } else if (sb.st_gid == getgid()) { mask = S_IWGRP; } else { int groups = getgroups(0, NULL); if (groups > 0) { gid_t *gids = (gid_t *)malloc(groups * sizeof(gid_t)); int n = getgroups(groups, gids); for (int i = 0; i < n; i++) { if (sb.st_gid == gids[i]) { mask = S_IWGRP; break; } } free(gids); } } return sb.st_mode & mask; */ } bool HHVM_FUNCTION(is_writeable, const String& filename) { CHECK_PATH_FALSE(filename, 1); return HHVM_FN(is_writable)(filename); } bool HHVM_FUNCTION(is_readable, const String& filename) { CHECK_PATH_FALSE(filename, 1); if (filename.empty()) { return false; } CHECK_SYSTEM_SILENT(accessSyscall(filename, R_OK, true)); return true; /* int mask = S_IROTH; if (sb.st_uid == getuid()) { mask = S_IRUSR; } else if (sb.st_gid == getgid()) { mask = S_IRGRP; } else { int groups = getgroups(0, NULL); if (groups > 0) { gid_t *gids = (gid_t *)malloc(groups * sizeof(gid_t)); int n = getgroups(groups, gids); for (int i = 0; i < n; i++) { if (sb.st_gid == gids[i]) { mask = S_IRGRP; break; } } free(gids); } } return sb.st_mode & mask; */ } bool HHVM_FUNCTION(is_executable, const String& filename) { CHECK_PATH_FALSE(filename, 1); if (filename.empty()) { return false; } CHECK_SYSTEM_SILENT(accessSyscall(filename, X_OK)); return true; /* int mask = S_IXOTH; if (sb.st_uid == getuid()) { mask = S_IXUSR; } else if (sb.st_gid == getgid()) { mask = S_IXGRP; } else { int groups = getgroups(0, NULL); if (groups > 0) { gid_t *gids = (gid_t *)malloc(groups * sizeof(gid_t)); int n = getgroups(groups, gids); for (int i = 0; i < n; i++) { if (sb.st_gid == gids[i]) { mask = S_IXGRP; break; } } free(gids); } } return (sb.st_mode & mask) && (sb.st_mode & S_IFMT) != S_IFDIR; */ } static VFileType lookupVirtualFile(const String& filename) { if (filename.empty() || !StaticContentCache::TheFileCache) { return VFileType::NotFound; } String cwd; std::string root; bool isRelative = !FileUtil::isAbsolutePath(filename.slice()); if (isRelative) { cwd = g_context->getCwd(); root = RuntimeOption::SourceRoot; if (cwd.empty() || FileUtil::isDirSeparator(cwd[cwd.size() - 1])) { root.pop_back(); } } if (!isRelative || !root.compare(cwd.data())) { return StaticContentCache::TheFileCache->getFileType(filename.data()); } return VFileType::NotFound; } bool HHVM_FUNCTION(is_file, const String& filename) { CHECK_PATH_FALSE(filename, 1); if (filename.empty()) { return false; } auto vtype = lookupVirtualFile(filename); if (vtype != VFileType::NotFound) { return vtype == VFileType::PlainFile; } struct stat sb; CHECK_SYSTEM_SILENT(statSyscall(filename, &sb, true)); return (sb.st_mode & S_IFMT) == S_IFREG; } bool HHVM_FUNCTION(is_dir, const String& filename) { CHECK_PATH_FALSE(filename, 1); if (filename.empty()) { return false; } auto vtype = lookupVirtualFile(filename); if (vtype != VFileType::NotFound) { return vtype == VFileType::Directory; } struct stat sb; CHECK_SYSTEM_SILENT(statSyscall(filename, &sb, false)); return (sb.st_mode & S_IFMT) == S_IFDIR; } bool HHVM_FUNCTION(is_link, const String& filename) { CHECK_PATH_FALSE(filename, 1); struct stat sb; CHECK_SYSTEM_SILENT(lstatSyscall(filename, &sb)); return (sb.st_mode & S_IFMT) == S_IFLNK; } bool HHVM_FUNCTION(is_uploaded_file, const String& filename) { Transport *transport = g_context->getTransport(); if (transport) { return transport->isUploadedFile(filename); } return false; } bool HHVM_FUNCTION(file_exists, const String& filename) { CHECK_PATH_FALSE(filename, 1); auto vtype = lookupVirtualFile(filename); if (vtype != VFileType::NotFound) { return true; } if (filename.empty() || (accessSyscall(filename, F_OK, true)) < 0) { return false; } return true; } Variant HHVM_FUNCTION(stat, const String& filename) { CHECK_PATH(filename, 1); if (filename.empty()) { return false; } struct stat sb; if (statSyscall(filename, &sb, true) != 0) { raise_warning( ""stat(): stat failed for %s"", filename.c_str() ); return false; } return stat_impl(&sb); } Variant HHVM_FUNCTION(lstat, const String& filename) { CHECK_PATH(filename, 1); if (filename.empty()) { return false; } struct stat sb; CHECK_SYSTEM(lstatSyscall(filename, &sb, true)); return stat_impl(&sb); } void HHVM_FUNCTION(clearstatcache, bool /*clear_realpath_cache*/ /* = false */, const Variant& /*filename*/ /* = uninit_variant */) { // we are not having a cache for file stats, so do nothing here } Variant HHVM_FUNCTION(readlink_internal, const String& path, bool warning_compliance) { char buff[PATH_MAX]; int ret = readlink(File::TranslatePath(path).data(), buff, PATH_MAX-1); if (ret < 0) { Logger::Verbose(""%s/%d: %s"", __FUNCTION__, __LINE__, folly::errnoStr(errno).c_str()); if (warning_compliance) { raise_warning(""readlink(): No such file or directory %s"",path.c_str()); } return false; } buff[ret] = '\\0'; return String(buff, ret, CopyString); } Variant HHVM_FUNCTION(readlink, const String& path) { CHECK_PATH(path, 1); return HHVM_FN(readlink_internal)(path, true); } Variant HHVM_FUNCTION(realpath, const String& path) { CHECK_PATH(path, 1); String translated; if (path.empty()) { translated = File::TranslatePath(g_context->getCwd()); } else { translated = File::TranslatePath(path); } if (translated.empty()) { return false; } if (StaticContentCache::TheFileCache && StaticContentCache::TheFileCache->exists(translated.data(), false)) { return translated; } // Zend doesn't support streams in realpath Stream::Wrapper* w = Stream::getWrapperFromURI(path); if (!w || !w->isNormalFileStream()) { return false; } if (!dynamic_cast(w)) { auto str = w->realpath(translated); if (str.isNull()) return false; return str; } char resolved_path[PATH_MAX]; if (!realpath(translated.c_str(), resolved_path)) { return false; } return String(resolved_path, CopyString); } #define PHP_PATHINFO_DIRNAME 1 #define PHP_PATHINFO_BASENAME 2 #define PHP_PATHINFO_EXTENSION 4 #define PHP_PATHINFO_FILENAME 8 const StaticString s_dirname(""dirname""), s_basename(""basename""), s_extension(""extension""), s_filename(""filename""); Variant HHVM_FUNCTION(pathinfo, const String& path, int64_t opt /* = 15 */) { DictInit ret{4}; if (opt == 0) { return empty_string_variant(); } if ((opt & PHP_PATHINFO_DIRNAME) == PHP_PATHINFO_DIRNAME) { String dirname = HHVM_FN(dirname)(path); if (opt == PHP_PATHINFO_DIRNAME) { return dirname; } if (!dirname.equal(staticEmptyString())) { ret.set(s_dirname, dirname); } } String basename = HHVM_FN(basename)(path); if ((opt & PHP_PATHINFO_BASENAME) == PHP_PATHINFO_BASENAME) { if (opt == PHP_PATHINFO_BASENAME) { return basename; } ret.set(s_basename, basename); } if ((opt & PHP_PATHINFO_EXTENSION) == PHP_PATHINFO_EXTENSION) { int pos = basename.rfind('.'); String extension(empty_string()); if (pos >= 0) { extension = basename.substr(pos + 1); ret.set(s_extension, extension); } if (opt == PHP_PATHINFO_EXTENSION) { return extension; } } if ((opt & PHP_PATHINFO_FILENAME) == PHP_PATHINFO_FILENAME) { int pos = basename.rfind('.'); String filename(empty_string()); if (pos >= 0) { filename = basename.substr(0, pos); } else { filename = basename; } if (opt == PHP_PATHINFO_FILENAME) { return filename; } ret.set(s_filename, filename); } return ret.toVariant(); } Variant HHVM_FUNCTION(disk_free_space, const String& directory) { CHECK_PATH(directory, 1); fs::space_info sb; String translated = File::TranslatePath(directory); CHECK_BOOST(sb, fs::space, translated); return (double)sb.free; } Variant HHVM_FUNCTION(diskfreespace, const String& directory) { CHECK_PATH(directory, 1); return HHVM_FN(disk_free_space)(directory); } Variant HHVM_FUNCTION(disk_total_space, const String& directory) { CHECK_PATH(directory, 1); fs::space_info sb; String translated = File::TranslatePath(directory); CHECK_BOOST(sb, fs::space, translated); return (double)sb.capacity; } /////////////////////////////////////////////////////////////////////////////// // system wrappers bool HHVM_FUNCTION(chmod, const String& filename, int64_t mode) { CHECK_PATH_FALSE(filename, 1); String translated = File::TranslatePath(filename); // If filename points to a user file, invoke ExtendedWrapper::chmod(..) Stream::Wrapper* w = Stream::getWrapperFromURI(filename); auto usw = dynamic_cast(w); if (usw != nullptr) { return usw->chmod(filename, mode); } CHECK_SYSTEM(chmod(translated.c_str(), mode)); return true; } static bool do_chown(const String& filename, const Variant& user, bool islChown, const char* funcName) { // If filename points to a user file, invoke ExtendedWrapper::chown(..) Stream::Wrapper* w = Stream::getWrapperFromURI(filename); auto usw = dynamic_cast(w); if (usw != nullptr) { if (user.isInteger()) { return usw->chown(filename, user.toInt64()); } else if (user.isString()) { return usw->chown(filename, user.toString()); } raise_warning(""%s(): parameter 2 should be string or integer, %s given"", funcName, getDataTypeString(user.getType()).c_str()); return false; } #ifdef WIN32 return false; #else int uid; if (user.isString()) { String suser = user.toString(); auto buf = PasswdBuffer{}; struct passwd *pw; if (getpwnam_r(suser.data(), &buf.ent, buf.data.get(), buf.size, &pw)) { // failed to read user info return false; } if (!pw) { Logger::Verbose(""%s/%d: Unable to find uid for %s"", __FUNCTION__, __LINE__, suser.data()); raise_warning(""%s(): Unable to find uid for %s"", funcName, user.toString().c_str()); return false; } uid = pw->pw_uid; } else { uid = user.toInt32(); } if (islChown) { CHECK_SYSTEM(lchown(File::TranslatePath(filename).data(), uid, (gid_t)-1)); } else { CHECK_SYSTEM(chown(File::TranslatePath(filename).data(), uid, (gid_t)-1)); } return true; #endif } bool HHVM_FUNCTION(chown, const String& filename, const Variant& user) { CHECK_PATH_FALSE(filename, 1); return do_chown(filename, user, false, ""chown""); } bool HHVM_FUNCTION(lchown, const String& filename, const Variant& user) { #ifdef WIN32 return false; #else CHECK_PATH_FALSE(filename, 1); return do_chown(filename, user, true, ""lchown""); #endif } static bool do_chgrp(const String& filename, const Variant& group, bool islChgrp, const char* funcName) { // If filename points to a user file, invoke ExtendedWrapper::chgrp(..) Stream::Wrapper* w = Stream::getWrapperFromURI(filename); auto usw = dynamic_cast(w); if (usw != nullptr) { if (group.isInteger()) { return usw->chgrp(filename, group.toInt64()); } else if (group.isString()) { return usw->chgrp(filename, group.toString()); } raise_warning(""%s(): parameter 2 should be string or integer, %s given"", funcName, getDataTypeString(group.getType()).c_str()); return false; } #ifdef WIN32 return false; #else int gid; if (group.isString()) { String sgroup = group.toString(); auto buf = GroupBuffer{}; struct group *gr; while (true) { if (getgrnam_r(sgroup.data(), &buf.ent, buf.data.get(), buf.size, &gr)) { if (errno == ERANGE) { buf.resize(); continue; } else if (errno == ENOENT || errno == ESRCH) { gr = nullptr; break; } // failed to read group info return false; } break; } if (!gr) { Logger::Verbose(""%s/%d: Unable to find gid for %s"", __FUNCTION__, __LINE__, sgroup.data()); raise_warning(""%s(): Unable to find gid for %s"", funcName, group.toString().c_str()); return false; } gid = gr->gr_gid; } else { gid = group.toInt32(); } if (islChgrp) { CHECK_SYSTEM(lchown(File::TranslatePath(filename).data(), (uid_t)-1, gid)); } else { CHECK_SYSTEM(chown(File::TranslatePath(filename).data(), (uid_t)-1, gid)); } return true; #endif } bool HHVM_FUNCTION(chgrp, const String& filename, const Variant& group) { CHECK_PATH_FALSE(filename, 1); return do_chgrp(filename, group, false, ""chgrp""); } bool HHVM_FUNCTION(lchgrp, const String& filename, const Variant& group) { #ifdef WIN32 return false; #else CHECK_PATH_FALSE(filename, 1); return do_chgrp(filename, group, true, ""lchgrp""); #endif } bool HHVM_FUNCTION(touch, const String& filename, int64_t mtime /* = 0 */, int64_t atime /* = 0 */) { CHECK_PATH_FALSE(filename, 1); if (filename.empty()) { return false; } // If filename points to a user file, invoke ExtendedWrapper::touch(..) Stream::Wrapper* w = Stream::getWrapperFromURI(filename); auto usw = dynamic_cast(w); if (usw != nullptr) { return usw->touch(filename, mtime, atime); } String translated = File::TranslatePath(filename); /* create the file if it doesn't exist already */ if (accessSyscall(translated, F_OK)) { FILE *f = fopen(translated.data(), ""w""); if (!f) { raise_warning( ""touch(): Unable to create file %s because %s"", translated.data(), folly::errnoStr(errno).c_str() ); return false; } fclose(f); } #ifdef _MSC_VER CHECK_BOOST_ASSIGN(fs::last_write_time, translated, mtime); // Windows doesn't have an access time to set. #else if (mtime == 0 && atime == 0) { // It is important to pass nullptr so that the OS sets mtime and atime // to the current time with maximum precision (more precise then seconds) CHECK_SYSTEM(utime(translated.data(), nullptr)); } else { struct utimbuf newtime; newtime.actime = atime ? atime : mtime; newtime.modtime = mtime; CHECK_SYSTEM(utime(translated.data(), &newtime)); } #endif return true; } bool HHVM_FUNCTION(copy, const String& source, const String& dest, const Variant& context /* = null */) { CHECK_PATH_FALSE(source, 1); CHECK_PATH_FALSE(dest, 2); if (!context.isNull() || !File::IsPlainFilePath(source) || !File::IsPlainFilePath(dest) || is_cli_server_mode()) { Variant sfile = HHVM_FN(fopen)(source, ""r"", false, context); if (same(sfile, false)) { return false; } Variant dfile = HHVM_FN(fopen)(dest, ""w"", false, context); if (same(dfile, false)) { return false; } if (!HHVM_FN(stream_copy_to_stream)(sfile.toResource(), dfile.toResource()).toBoolean() && HHVM_FN(filesize)(source).toBoolean()) { return false; } return HHVM_FN(fclose)(dfile.toResource()); } else { int ret = RuntimeOption::UseDirectCopy ? FileUtil::directCopy(File::TranslatePath(source).data(), File::TranslatePath(dest).data()) : FileUtil::copy(File::TranslatePath(source).data(), File::TranslatePath(dest).data()); return (ret == 0); } } bool HHVM_FUNCTION(rename, const String& oldname, const String& newname, const Variant& /*context*/ /* = null */) { CHECK_PATH_FALSE(oldname, 1); CHECK_PATH_FALSE(newname, 2); Stream::Wrapper* w = Stream::getWrapperFromURI(oldname); if (!w) return false; if (w != Stream::getWrapperFromURI(newname)) { raise_warning(""Can't rename a file on different streams""); return false; } CHECK_SYSTEM(w->rename(oldname, newname)); return true; } int64_t HHVM_FUNCTION(umask, const Variant& mask /* = uninit_variant */) { int oldumask = umask(077); if (mask.isNull()) { umask(oldumask); } else { umask(mask.toInt32()); } return oldumask; } bool HHVM_FUNCTION(unlink, const String& filename, const Variant& /*context*/ /* = null */) { CHECK_PATH_FALSE(filename, 1); Stream::Wrapper* w = Stream::getWrapperFromURI(filename); if (!w) return false; CHECK_SYSTEM_SILENT(w->unlink(filename)); return true; } bool HHVM_FUNCTION(link, const String& target, const String& link) { CHECK_PATH_FALSE(target, 1); CHECK_PATH_FALSE(link, 2); CHECK_BOOST_ASSIGN(fs::create_hard_link, File::TranslatePath(target), File::TranslatePath(link).toCppString()); return true; } bool HHVM_FUNCTION(symlink, const String& target, const String& link) { CHECK_PATH_FALSE(target, 1); CHECK_PATH_FALSE(link, 2); if (HHVM_FN(is_dir)(target)) { CHECK_BOOST_ASSIGN(fs::create_directory_symlink, File::TranslatePathKeepRelative(target), File::TranslatePath(link).toCppString()); } else { CHECK_BOOST_ASSIGN(fs::create_symlink, File::TranslatePathKeepRelative(target), File::TranslatePath(link).toCppString()); } return true; } String HHVM_FUNCTION(basename, const String& path, const String& suffix /* = null_string */) { int state = 0; const char *c = path.data(); const char *comp, *cend; comp = cend = c; for (int cnt = path.size(); cnt > 0; --cnt, ++c) { if (FileUtil::isDirSeparator(*c)) { if (state == 1) { state = 0; cend = c; } } else if (state == 0) { comp = c; state = 1; } } if (state == 1) { cend = c; } int sufflen = suffix.size(); if (!suffix.empty() && sufflen < (int)(cend - comp) && memcmp(cend - sufflen, suffix.data(), sufflen) == 0) { cend -= sufflen; } return String(comp, cend - comp, CopyString); } bool HHVM_FUNCTION(fnmatch, const String& pattern, const String& filename, int64_t flags /* = 0 */) { CHECK_PATH_FALSE(pattern, 1); CHECK_PATH_FALSE(filename, 2); if (filename.size() >= PATH_MAX) { raise_warning( ""Filename exceeds the maximum allowed length of %d characters"", PATH_MAX); return false; } if (pattern.size() >= PATH_MAX) { raise_warning(""Path exceeds the maximum allowed length of %d characters"", PATH_MAX); return false; } return fnmatch(pattern.data(), filename.data(), flags) == 0; } Variant HHVM_FUNCTION(glob, const String& pattern, int64_t flags /* = 0 */) { CHECK_PATH(pattern, 1); glob_t globbuf; int cwd_skip = 0; memset(&globbuf, 0, sizeof(glob_t)); globbuf.gl_offs = 0; String work_pattern; if (pattern.size() >= PATH_MAX) { raise_warning(""Pattern exceeds the maximum allowed length of %d characters"", PATH_MAX); return false; } if (pattern.charAt(0) == '/') { work_pattern = pattern; } else { String cwd = g_context->getCwd(); if (!cwd.empty() && cwd[cwd.length() - 1] == '/') { work_pattern = cwd + pattern; cwd_skip = cwd.length(); } else { work_pattern = cwd + ""/"" + pattern; cwd_skip = cwd.length() + 1; } } int nret = glob(work_pattern.data(), flags & PHP_GLOB_FLAGMASK, nullptr, &globbuf); if (nret == GLOB_NOMATCH) { globfree(&globbuf); return empty_vec_array(); } if (!globbuf.gl_pathc || !globbuf.gl_pathv) { if (RID().hasSafeFileAccess()) { if (!HHVM_FN(is_dir)(work_pattern)) { globfree(&globbuf); return false; } } globfree(&globbuf); return empty_vec_array(); } if (nret) { globfree(&globbuf); return false; } auto ret = Array::CreateVec(); bool basedir_limit = false; for (int n = 0; n < (int)globbuf.gl_pathc; n++) { String translated = File::TranslatePath(globbuf.gl_pathv[n]); if (translated.empty()) { basedir_limit = true; continue; } /* we need to do this every time since GLOB_ONLYDIR does not guarantee that * all directories will be filtered. GNU libc documentation states the * following: * If the information about the type of the file is easily available * non-directories will be rejected but no extra work will be done to * determine the information for each file. I.e., the caller must still be * able to filter directories out. */ if ((flags & GLOB_ONLYDIR) && !HHVM_FN(is_dir)(globbuf.gl_pathv[n])) { continue; } ret.append(String(globbuf.gl_pathv[n] + cwd_skip, CopyString)); } globfree(&globbuf); if (basedir_limit && ret.empty()) { return false; } // php's glob always produces an array, but Variant::Variant(CArrRef) // will produce KindOfNull if given a req::ptr wrapped around null. if (ret.isNull()) { return empty_vec_array(); } return ret; } Variant HHVM_FUNCTION(tempnam, const String& dir, const String& prefix) { CHECK_PATH(dir, 1); CHECK_PATH(prefix, 2); String tmpdir = dir, trailing_slash = ""/""; if (tmpdir.empty() || !HHVM_FN(is_dir)(tmpdir) || !HHVM_FN(is_writable)(tmpdir)) { tmpdir = HHVM_FN(sys_get_temp_dir)(); } tmpdir = File::TranslatePath(tmpdir); String pbase = HHVM_FN(basename)(prefix); if (pbase.size() > 64) pbase = pbase.substr(0, 63); if ((tmpdir.length() > 0) && (tmpdir[tmpdir.length() - 1] == '/')) { trailing_slash = """"; } String templ = tmpdir + trailing_slash + pbase + ""XXXXXX""; auto buf = templ.get()->mutableData(); if (UNLIKELY(is_cli_server_mode())) { if (!cli_mkstemp(buf)) return false; } else { int fd = mkstemp(buf); if (fd < 0) { Logger::Verbose(""%s/%d: %s"", __FUNCTION__, __LINE__, folly::errnoStr(errno).c_str()); return false; } close(fd); } return templ.setSize(strlen(buf)); } Variant HHVM_FUNCTION(tmpfile) { auto file = req::make(true); if (!file->valid()) { return false; } return Variant(file); } /////////////////////////////////////////////////////////////////////////////// // directory functions bool HHVM_FUNCTION(mkdir, const String& pathname, int64_t mode /* = 0777 */, bool recursive /* = false */, const Variant& /*context*/ /* = null */) { CHECK_PATH_FALSE(pathname, 1); Stream::Wrapper* w = Stream::getWrapperFromURI(pathname); if (!w) return false; int options = recursive ? k_STREAM_MKDIR_RECURSIVE : 0; CHECK_SYSTEM_SILENT(w->mkdir(pathname, mode, options)); return true; } bool HHVM_FUNCTION(rmdir, const String& dirname, const Variant& /*context*/ /* = null */) { CHECK_PATH_FALSE(dirname, 1); Stream::Wrapper* w = Stream::getWrapperFromURI(dirname); if (!w) return false; int options = 0; CHECK_SYSTEM_SILENT(w->rmdir(dirname, options)); return true; } String HHVM_FUNCTION(dirname, const String& path) { return FileUtil::dirname(path); } Variant HHVM_FUNCTION(getcwd) { return g_context->getCwd(); } bool HHVM_FUNCTION(chdir, const String& directory) { CHECK_PATH_FALSE(directory, 1); if (!HHVM_FN(is_dir)(directory)) { raise_warning(""chdir(): No such file or directory (errno 2)""); return false; } #if ENABLE_EXTENSION_POSIX if (!HHVM_FN(posix_access)(directory, X_OK)) { raise_warning(""chdir(): Permission denied (errno 13)""); return false; } #endif g_context->setCwd(HHVM_FN(realpath)(directory).toString()); return true; } #ifndef WIN32 bool HHVM_FUNCTION(chroot, const String& directory) { CHECK_PATH_FALSE(directory, 1); CHECK_SYSTEM(chroot(File::TranslatePath(directory).data())); CHECK_SYSTEM(chdir(""/"")); return true; } #endif /////////////////////////////////////////////////////////////////////////////// /** * A stack maintains the states of nested structures. */ struct DirectoryData final : RequestEventHandler { void requestInit() override { assertx(!defaultDirectory); } void requestShutdown() override { defaultDirectory = nullptr; } req::ptr defaultDirectory; }; namespace { IMPLEMENT_STATIC_REQUEST_LOCAL(DirectoryData, s_directory_data); const StaticString s_handle(""handle""), s_path(""path""); req::ptr get_dir(const Resource& dir_handle) { if (dir_handle.isNull()) { auto defaultDir = s_directory_data->defaultDirectory; if (!defaultDir) { raise_warning(""no Directory resource supplied""); return nullptr; } return defaultDir; } auto d = dyn_cast_or_null(dir_handle); if (!d) { raise_warning(""Not a valid directory resource""); return nullptr; } return d; } bool StringDescending(const String& s1, const String& s2) { return s1.more(s2); } bool StringAscending(const String& s1, const String& s2) { return s1.less(s2); } } Variant HHVM_FUNCTION(dir, const String& directory) { CHECK_PATH(directory, 1); Variant dir = HHVM_FN(opendir)(directory); if (same(dir, false)) { return false; } auto d = SystemLib::AllocDirectoryObject(); d->setProp(nullptr, s_path.get(), directory.asTypedValue()); d->setProp(nullptr, s_handle.get(), *dir.asTypedValue()); return d; } Variant HHVM_FUNCTION(opendir, const String& path, const Variant& /*context*/ /* = null */) { CHECK_PATH(path, 1); Stream::Wrapper* w = Stream::getWrapperFromURI(path); if (!w) return false; auto p = w->opendir(path); if (!p) { return false; } s_directory_data->defaultDirectory = p; return Variant(p); } Variant HHVM_FUNCTION(readdir, const Variant& dir_handle /* = null */) { const Resource& res_dir_handle = dir_handle.isNull() ? null_resource : dir_handle.toResource(); auto dir = get_dir(res_dir_handle); if (!dir) { return false; } return dir->read(); } void HHVM_FUNCTION(rewinddir, const Variant& dir_handle /* = null */) { const Resource& res_dir_handle = dir_handle.isNull() ? null_resource : dir_handle.toResource(); auto dir = get_dir(res_dir_handle); if (!dir) { return; } dir->rewind(); } Variant HHVM_FUNCTION(scandir, const String& directory, bool descending /* = false */, const Variant& /*context*/ /* = null */) { if (directory.empty()) { raise_warning(""scandir(): Directory name cannot be empty""); return false; } CHECK_PATH(directory, 1); Stream::Wrapper* w = Stream::getWrapperFromURI(directory); if (!w) return false; auto dir = w->opendir(directory); if (!dir) { return false; } std::vector names; while (true) { auto name = dir->read(); if (same(name, false)) { break; } names.push_back(name.toString()); } dir->close(); sort( names.begin(), names.end(), descending ? StringDescending : StringAscending ); VecInit ret{names.size()}; for (auto& name : names) { ret.append(name); } return ret.toVariant(); } void HHVM_FUNCTION(closedir, const Variant& dir_handle /* = null */) { const Resource& res_dir_handle = dir_handle.isNull() ? null_resource : dir_handle.toResource(); auto d = get_dir(res_dir_handle); if (!d) { return; } if (s_directory_data->defaultDirectory == d) { s_directory_data->defaultDirectory = nullptr; } d->close(); } /////////////////////////////////////////////////////////////////////////////// const StaticString s_STDIN(""STDIN""), s_STDOUT(""STDOUT""), s_STDERR(""STDERR""); void StandardExtension::initFile() { HHVM_RC_STR(DIRECTORY_SEPARATOR, s_DIRECTORY_SEPARATOR); HHVM_RC_STR(PATH_SEPARATOR, s_PATH_SEPARATOR); HHVM_RC_INT(FILE_USE_INCLUDE_PATH, PHP_FILE_USE_INCLUDE_PATH); HHVM_RC_INT(FILE_IGNORE_NEW_LINES, PHP_FILE_IGNORE_NEW_LINES); HHVM_RC_INT(FILE_SKIP_EMPTY_LINES, PHP_FILE_SKIP_EMPTY_LINES); HHVM_RC_INT(FILE_APPEND, PHP_FILE_APPEND); HHVM_RC_INT(FILE_NO_DEFAULT_CONTEXT, PHP_FILE_NO_DEFAULT_CONTEXT); HHVM_RC_INT(FILE_TEXT, 0); HHVM_RC_INT(FILE_BINARY, 0); HHVM_RC_INT_SAME(FNM_NOESCAPE); HHVM_RC_INT_SAME(FNM_CASEFOLD); HHVM_RC_INT_SAME(FNM_PERIOD); HHVM_RC_INT_SAME(FNM_PATHNAME); HHVM_RC_INT(GLOB_AVAILABLE_FLAGS, PHP_GLOB_FLAGS); HHVM_RC_INT_SAME(GLOB_BRACE); HHVM_RC_INT_SAME(GLOB_ERR); HHVM_RC_INT_SAME(GLOB_MARK); HHVM_RC_INT_SAME(GLOB_NOCHECK); HHVM_RC_INT_SAME(GLOB_NOESCAPE); HHVM_RC_INT_SAME(GLOB_NOSORT); HHVM_RC_INT_SAME(GLOB_ONLYDIR); HHVM_RC_INT(LOCK_SH, k_LOCK_SH); HHVM_RC_INT(LOCK_EX, k_LOCK_EX); HHVM_RC_INT(LOCK_UN, k_LOCK_UN); HHVM_RC_INT(LOCK_NB, k_LOCK_NB); HHVM_RC_INT(SCANDIR_SORT_ASCENDING, k_SCANDIR_SORT_ASCENDING); HHVM_RC_INT(SCANDIR_SORT_DESCENDING, k_SCANDIR_SORT_DESCENDING); HHVM_RC_INT(SCANDIR_SORT_NONE, k_SCANDIR_SORT_NONE); HHVM_RC_INT_SAME(SEEK_SET); HHVM_RC_INT_SAME(SEEK_CUR); HHVM_RC_INT_SAME(SEEK_END); Native::registerConstant(s_STDIN.get(), BuiltinFiles::getSTDIN); Native::registerConstant(s_STDOUT.get(), BuiltinFiles::getSTDOUT); Native::registerConstant(s_STDERR.get(), BuiltinFiles::getSTDERR); HHVM_RC_INT(INI_SCANNER_NORMAL, k_INI_SCANNER_NORMAL); HHVM_RC_INT(INI_SCANNER_RAW, k_INI_SCANNER_RAW); HHVM_RC_INT(PATHINFO_BASENAME, PHP_PATHINFO_BASENAME); HHVM_RC_INT(PATHINFO_DIRNAME, PHP_PATHINFO_DIRNAME); HHVM_RC_INT(PATHINFO_EXTENSION, PHP_PATHINFO_EXTENSION); HHVM_RC_INT(PATHINFO_FILENAME, PHP_PATHINFO_FILENAME); HHVM_FE(fopen); HHVM_FE(popen); HHVM_FE(fclose); HHVM_FE(pclose); HHVM_FE(fseek); HHVM_FE(rewind); HHVM_FE(ftell); HHVM_FE(feof); HHVM_FE(fstat); HHVM_FE(fread); HHVM_FE(fgetc); HHVM_FE(fgets); HHVM_FE(fgetss); HHVM_FE(fscanf); HHVM_FE(fpassthru); HHVM_FE(fwrite); HHVM_FE(fputs); HHVM_FE(fprintf); HHVM_FE(vfprintf); HHVM_FE(fflush); HHVM_FE(ftruncate); HHVM_FE(flock); HHVM_FE(fputcsv); HHVM_FE(fgetcsv); HHVM_FE(file_get_contents); HHVM_FE(file_put_contents); HHVM_FE(file); HHVM_FE(readfile); HHVM_FE(move_uploaded_file); HHVM_FE(parse_ini_file); HHVM_FE(parse_ini_string); HHVM_FE(md5_file); HHVM_FE(sha1_file); HHVM_FE(chmod); HHVM_FE(chown); HHVM_FE(lchown); HHVM_FE(chgrp); HHVM_FE(lchgrp); HHVM_FE(touch); HHVM_FE(copy); HHVM_FE(rename); HHVM_FE(umask); HHVM_FE(unlink); HHVM_FE(link); HHVM_FE(symlink); HHVM_FE(basename); HHVM_FE(fnmatch); HHVM_FE(glob); HHVM_FE(tempnam); HHVM_FE(tmpfile); HHVM_FE(fileperms); HHVM_FE(fileinode); HHVM_FE(filesize); HHVM_FE(fileowner); HHVM_FE(filegroup); HHVM_FE(fileatime); HHVM_FE(filemtime); HHVM_FE(filectime); HHVM_FE(filetype); HHVM_FE(linkinfo); HHVM_FE(is_writable); HHVM_FE(is_writeable); HHVM_FE(is_readable); HHVM_FE(is_executable); HHVM_FE(is_file); HHVM_FE(is_dir); HHVM_FE(is_link); HHVM_FE(is_uploaded_file); HHVM_FE(file_exists); HHVM_FE(stat); HHVM_FE(lstat); HHVM_FE(clearstatcache); HHVM_FE(readlink_internal); HHVM_FE(readlink); HHVM_FE(realpath); HHVM_FE(pathinfo); HHVM_FE(disk_free_space); HHVM_FE(diskfreespace); HHVM_FE(disk_total_space); HHVM_FE(mkdir); HHVM_FE(rmdir); HHVM_FE(dirname); HHVM_FE(getcwd); HHVM_FE(chdir); #ifndef WIN32 HHVM_FE(chroot); #endif HHVM_FE(dir); HHVM_FE(opendir); HHVM_FE(readdir); HHVM_FE(rewinddir); HHVM_FE(scandir); HHVM_FE(closedir); loadSystemlib(""std_file""); } /////////////////////////////////////////////////////////////////////////////// } ",16280,True,2968.648964087952,median " //// This file is generated! See _meta/fields.yml and scripts/generate_field_docs.py //// [[exported-fields]] = Exported fields [partintro] -- This document describes the fields that are exported by Packetbeat. They are grouped in the following categories: * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> -- [[exported-fields-amqp]] == AMQP fields AMQP specific event fields. [float] === `amqp.reply-code` type: long example: 404 AMQP reply code to an error, similar to http reply-code [float] === `amqp.reply-text` type: keyword Text explaining the error. [float] === `amqp.class-id` type: long Failing method class. [float] === `amqp.method-id` type: long Failing method ID. [float] === `amqp.exchange` type: keyword Name of the exchange. [float] === `amqp.exchange-type` type: keyword example: fanout Exchange type. [float] === `amqp.passive` type: boolean If set, do not create exchange/queue. [float] === `amqp.durable` type: boolean If set, request a durable exchange/queue. [float] === `amqp.exclusive` type: boolean If set, request an exclusive queue. [float] === `amqp.auto-delete` type: boolean If set, auto-delete queue when unused. [float] === `amqp.no-wait` type: boolean If set, the server will not respond to the method. [float] === `amqp.consumer-tag` Identifier for the consumer, valid within the current channel. [float] === `amqp.delivery-tag` type: long The server-assigned and channel-specific delivery tag. [float] === `amqp.message-count` type: long The number of messages in the queue, which will be zero for newly-declared queues. [float] === `amqp.consumer-count` type: long The number of consumers of a queue. [float] === `amqp.routing-key` type: keyword Message routing key. [float] === `amqp.no-ack` type: boolean If set, the server does not expect acknowledgements for messages. [float] === `amqp.no-local` type: boolean If set, the server will not send messages to the connection that published them. [float] === `amqp.if-unused` type: boolean Delete only if unused. [float] === `amqp.if-empty` type: boolean Delete only if empty. [float] === `amqp.queue` type: keyword The queue name identifies the queue within the vhost. [float] === `amqp.redelivered` type: boolean Indicates that the message has been previously delivered to this or another client. [float] === `amqp.multiple` type: boolean Acknowledge multiple messages. [float] === `amqp.arguments` type: object Optional additional arguments passed to some methods. Can be of various types. [float] === `amqp.mandatory` type: boolean Indicates mandatory routing. [float] === `amqp.immediate` type: boolean Request immediate delivery. [float] === `amqp.content-type` type: keyword example: text/plain MIME content type. [float] === `amqp.content-encoding` type: keyword MIME content encoding. [float] === `amqp.headers` type: object Message header field table. [float] === `amqp.delivery-mode` type: keyword Non-persistent (1) or persistent (2). [float] === `amqp.priority` type: long Message priority, 0 to 9. [float] === `amqp.correlation-id` type: keyword Application correlation identifier. [float] === `amqp.reply-to` type: keyword Address to reply to. [float] === `amqp.expiration` type: keyword Message expiration specification. [float] === `amqp.message-id` type: keyword Application message identifier. [float] === `amqp.timestamp` type: keyword Message timestamp. [float] === `amqp.type` type: keyword Message type name. [float] === `amqp.user-id` type: keyword Creating user id. [float] === `amqp.app-id` type: keyword Creating application id. [[exported-fields-beat]] == Beat fields Contains common beat fields available in all event types. [float] === `beat.name` The name of the Beat sending the log messages. If the Beat name is set in the configuration file, then that value is used. If it is not set, the hostname is used. To set the Beat name, use the `name` option in the configuration file. [float] === `beat.hostname` The hostname as returned by the operating system on which the Beat is running. [float] === `beat.timezone` The timezone as returned by the operating system on which the Beat is running. [float] === `beat.version` The version of the beat that generated this event. [float] === `@timestamp` type: date example: August 26th 2016, 12:35:53.332 format: date required: True The timestamp when the event log record was generated. [float] === `tags` Arbitrary tags that can be set per Beat and per transaction type. [float] === `fields` type: object Contains user configurable fields. [float] == error fields Error fields containing additional info in case of errors. [float] === `error.message` type: text Error message. [float] === `error.code` type: long Error code. [float] === `error.type` type: keyword Error type. [[exported-fields-cassandra]] == Cassandra fields Cassandra v4/3 specific event fields. [float] == cassandra fields Information about the Cassandra request and response. [float] == request fields Cassandra request. [float] == headers fields Cassandra request headers. [float] === `cassandra.request.headers.version` type: long The version of the protocol. [float] === `cassandra.request.headers.flags` type: keyword Flags applying to this frame. [float] === `cassandra.request.headers.stream` type: keyword A frame has a stream id. If a client sends a request message with the stream id X, it is guaranteed that the stream id of the response to that message will be X. [float] === `cassandra.request.headers.op` type: keyword An operation type that distinguishes the actual message. [float] === `cassandra.request.headers.length` type: long A integer representing the length of the body of the frame (a frame is limited to 256MB in length). [float] === `cassandra.request.query` type: keyword The CQL query which client send to cassandra. [float] == response fields Cassandra response. [float] == headers fields Cassandra response headers, the structure is as same as request's header. [float] === `cassandra.response.headers.version` type: long The version of the protocol. [float] === `cassandra.response.headers.flags` type: keyword Flags applying to this frame. [float] === `cassandra.response.headers.stream` type: keyword A frame has a stream id. If a client sends a request message with the stream id X, it is guaranteed that the stream id of the response to that message will be X. [float] === `cassandra.response.headers.op` type: keyword An operation type that distinguishes the actual message. [float] === `cassandra.response.headers.length` type: long A integer representing the length of the body of the frame (a frame is limited to 256MB in length). [float] == result fields Details about the returned result. [float] === `cassandra.response.result.type` type: keyword Cassandra result type. [float] == rows fields Details about the rows. [float] === `cassandra.response.result.rows.num_rows` type: long Representing the number of rows present in this result. [float] == meta fields Composed of result metadata. [float] === `cassandra.response.result.rows.meta.keyspace` type: keyword Only present after set Global_tables_spec, the keyspace name. [float] === `cassandra.response.result.rows.meta.table` type: keyword Only present after set Global_tables_spec, the table name. [float] === `cassandra.response.result.rows.meta.flags` type: keyword Provides information on the formatting of the remaining information. [float] === `cassandra.response.result.rows.meta.col_count` type: long Representing the number of columns selected by the query that produced this result. [float] === `cassandra.response.result.rows.meta.pkey_columns` type: long Representing the PK columns index and counts. [float] === `cassandra.response.result.rows.meta.paging_state` type: keyword The paging_state is a bytes value that should be used in QUERY/EXECUTE to continue paging and retrieve the remainder of the result for this query. [float] === `cassandra.response.result.keyspace` type: keyword Indicating the name of the keyspace that has been set. [float] == schema_change fields The result to a schema_change message. [float] === `cassandra.response.result.schema_change.change` type: keyword Representing the type of changed involved. [float] === `cassandra.response.result.schema_change.keyspace` type: keyword This describes which keyspace has changed. [float] === `cassandra.response.result.schema_change.table` type: keyword This describes which table has changed. [float] === `cassandra.response.result.schema_change.object` type: keyword This describes the name of said affected object (either the table, user type, function, or aggregate name). [float] === `cassandra.response.result.schema_change.target` type: keyword Target could be ""FUNCTION"" or ""AGGREGATE"", multiple arguments. [float] === `cassandra.response.result.schema_change.name` type: keyword The function/aggregate name. [float] === `cassandra.response.result.schema_change.args` type: keyword One string for each argument type (as CQL type). [float] == prepared fields The result to a PREPARE message. [float] === `cassandra.response.result.prepared.prepared_id` type: keyword Representing the prepared query ID. [float] == req_meta fields This describes the request metadata. [float] === `cassandra.response.result.prepared.req_meta.keyspace` type: keyword Only present after set Global_tables_spec, the keyspace name. [float] === `cassandra.response.result.prepared.req_meta.table` type: keyword Only present after set Global_tables_spec, the table name. [float] === `cassandra.response.result.prepared.req_meta.flags` type: keyword Provides information on the formatting of the remaining information. [float] === `cassandra.response.result.prepared.req_meta.col_count` type: long Representing the number of columns selected by the query that produced this result. [float] === `cassandra.response.result.prepared.req_meta.pkey_columns` type: long Representing the PK columns index and counts. [float] === `cassandra.response.result.prepared.req_meta.paging_state` type: keyword The paging_state is a bytes value that should be used in QUERY/EXECUTE to continue paging and retrieve the remainder of the result for this query. [float] == resp_meta fields This describes the metadata for the result set. [float] === `cassandra.response.result.prepared.resp_meta.keyspace` type: keyword Only present after set Global_tables_spec, the keyspace name. [float] === `cassandra.response.result.prepared.resp_meta.table` type: keyword Only present after set Global_tables_spec, the table name. [float] === `cassandra.response.result.prepared.resp_meta.flags` type: keyword Provides information on the formatting of the remaining information. [float] === `cassandra.response.result.prepared.resp_meta.col_count` type: long Representing the number of columns selected by the query that produced this result. [float] === `cassandra.response.result.prepared.resp_meta.pkey_columns` type: long Representing the PK columns index and counts. [float] === `cassandra.response.result.prepared.resp_meta.paging_state` type: keyword The paging_state is a bytes value that should be used in QUERY/EXECUTE to continue paging and retrieve the remainder of the result for this query. [float] === `cassandra.response.supported` type: object Indicates which startup options are supported by the server. This message comes as a response to an OPTIONS message. [float] == authentication fields Indicates that the server requires authentication, and which authentication mechanism to use. [float] === `cassandra.response.authentication.class` type: keyword Indicates the full class name of the IAuthenticator in use [float] === `cassandra.response.warnings` type: keyword The text of the warnings, only occur when Warning flag was set. [float] == event fields Event pushed by the server. A client will only receive events for the types it has REGISTERed to. [float] === `cassandra.response.event.type` type: keyword Representing the event type. [float] === `cassandra.response.event.change` type: keyword The message corresponding respectively to the type of change followed by the address of the new/removed node. [float] === `cassandra.response.event.host` type: keyword Representing the node ip. [float] === `cassandra.response.event.port` type: long Representing the node port. [float] == schema_change fields The events details related to schema change. [float] === `cassandra.response.event.schema_change.change` type: keyword Representing the type of changed involved. [float] === `cassandra.response.event.schema_change.keyspace` type: keyword This describes which keyspace has changed. [float] === `cassandra.response.event.schema_change.table` type: keyword This describes which table has changed. [float] === `cassandra.response.event.schema_change.object` type: keyword This describes the name of said affected object (either the table, user type, function, or aggregate name). [float] === `cassandra.response.event.schema_change.target` type: keyword Target could be ""FUNCTION"" or ""AGGREGATE"", multiple arguments. [float] === `cassandra.response.event.schema_change.name` type: keyword The function/aggregate name. [float] === `cassandra.response.event.schema_change.args` type: keyword One string for each argument type (as CQL type). [float] == error fields Indicates an error processing a request. The body of the message will be an error code followed by a error message. Then, depending on the exception, more content may follow. [float] === `cassandra.response.error.code` type: long The error code of the Cassandra response. [float] === `cassandra.response.error.msg` type: keyword The error message of the Cassandra response. [float] === `cassandra.response.error.type` type: keyword The error type of the Cassandra response. [float] == details fields The details of the error. [float] === `cassandra.response.error.details.read_consistency` type: keyword Representing the consistency level of the query that triggered the exception. [float] === `cassandra.response.error.details.required` type: long Representing the number of nodes that should be alive to respect consistency level. [float] === `cassandra.response.error.details.alive` type: long Representing the number of replicas that were known to be alive when the request had been processed (since an unavailable exception has been triggered). [float] === `cassandra.response.error.details.received` type: long Representing the number of nodes having acknowledged the request. [float] === `cassandra.response.error.details.blockfor` type: long Representing the number of replicas whose acknowledgement is required to achieve consistency level. [float] === `cassandra.response.error.details.write_type` type: keyword Describe the type of the write that timed out. [float] === `cassandra.response.error.details.data_present` type: boolean It means the replica that was asked for data had responded. [float] === `cassandra.response.error.details.keyspace` type: keyword The keyspace of the failed function. [float] === `cassandra.response.error.details.table` type: keyword The keyspace of the failed function. [float] === `cassandra.response.error.details.stmt_id` type: keyword Representing the unknown ID. [float] === `cassandra.response.error.details.num_failures` type: keyword Representing the number of nodes that experience a failure while executing the request. [float] === `cassandra.response.error.details.function` type: keyword The name of the failed function. [float] === `cassandra.response.error.details.arg_types` type: keyword One string for each argument type (as CQL type) of the failed function. [[exported-fields-cloud]] == Cloud provider metadata fields Metadata from cloud providers added by the add_cloud_metadata processor. [float] === `meta.cloud.provider` example: ec2 Name of the cloud provider. Possible values are ec2, gce, or digitalocean. [float] === `meta.cloud.instance_id` Instance ID of the host machine. [float] === `meta.cloud.instance_name` Instance name of the host machine. [float] === `meta.cloud.machine_type` example: t2.medium Machine type of the host machine. [float] === `meta.cloud.availability_zone` example: us-east-1c Availability zone in which this host is running. [float] === `meta.cloud.project_id` example: project-x Name of the project in Google Cloud. [float] === `meta.cloud.region` Region in which this host is running. [[exported-fields-common]] == Common fields These fields contain data about the environment in which the transaction or flow was captured. [float] === `server` The name of the server that served the transaction. [float] === `client_server` The name of the server that initiated the transaction. [float] === `service` The name of the logical service that served the transaction. [float] === `client_service` The name of the logical service that initiated the transaction. [float] === `ip` format: dotted notation. The IP address of the server that served the transaction. [float] === `client_ip` format: dotted notation. The IP address of the server that initiated the transaction. [float] === `real_ip` format: Dotted notation. If the server initiating the transaction is a proxy, this field contains the original client IP address. For HTTP, for example, the IP address extracted from a configurable HTTP header, by default `X-Forwarded-For`. Unless this field is disabled, it always has a value, and it matches the `client_ip` for non proxy clients. [float] == client_geoip fields The GeoIP information of the client. [float] === `client_geoip.location` type: geo_point example: {'lat': 51, 'lon': 9} The GeoIP location of the `client_ip` address. This field is available only if you define a https://www.elastic.co/guide/en/elasticsearch/plugins/master/using-ingest-geoip.html[GeoIP Processor] as a pipeline in the https://www.elastic.co/guide/en/elasticsearch/plugins/master/ingest-geoip.html[Ingest GeoIP processor plugin] or using Logstash. [float] === `client_port` format: dotted notation. The layer 4 port of the process that initiated the transaction. [float] === `transport` example: udp The transport protocol used for the transaction. If not specified, then tcp is assumed. [float] === `type` required: True The type of the transaction (for example, HTTP, MySQL, Redis, or RUM) or ""flow"" in case of flows. [float] === `port` format: dotted notation. The layer 4 port of the process that served the transaction. [float] === `proc` The name of the process that served the transaction. [float] === `client_proc` The name of the process that initiated the transaction. [float] === `release` The software release of the service serving the transaction. This can be the commit id or a semantic version. [[exported-fields-dns]] == DNS fields DNS-specific event fields. [float] === `dns.id` type: long The DNS packet identifier assigned by the program that generated the query. The identifier is copied to the response. [float] === `dns.op_code` example: QUERY The DNS operation code that specifies the kind of query in the message. This value is set by the originator of a query and copied into the response. [float] === `dns.flags.authoritative` type: boolean A DNS flag specifying that the responding server is an authority for the domain name used in the question. [float] === `dns.flags.recursion_available` type: boolean A DNS flag specifying whether recursive query support is available in the name server. [float] === `dns.flags.recursion_desired` type: boolean A DNS flag specifying that the client directs the server to pursue a query recursively. Recursive query support is optional. [float] === `dns.flags.authentic_data` type: boolean A DNS flag specifying that the recursive server considers the response authentic. [float] === `dns.flags.checking_disabled` type: boolean A DNS flag specifying that the client disables the server signature validation of the query. [float] === `dns.flags.truncated_response` type: boolean A DNS flag specifying that only the first 512 bytes of the reply were returned. [float] === `dns.response_code` example: NOERROR The DNS status code. [float] === `dns.question.name` example: www.google.com. The domain name being queried. If the name field contains non-printable characters (below 32 or above 126), then those characters are represented as escaped base 10 integers (\\DDD). Back slashes and quotes are escaped. Tabs, carriage returns, and line feeds are converted to \\t, \\r, and \\n respectively. [float] === `dns.question.type` example: AAAA The type of records being queried. [float] === `dns.question.class` example: IN The class of of records being queried. [float] === `dns.question.etld_plus_one` example: amazon.co.uk. The effective top-level domain (eTLD) plus one more label. For example, the eTLD+1 for ""foo.bar.golang.org."" is ""golang.org."". The data for determining the eTLD comes from an embedded copy of the data from http://publicsuffix.org. [float] === `dns.answers` type: object An array containing a dictionary about each answer section returned by the server. [float] === `dns.answers_count` type: long The number of resource records contained in the `dns.answers` field. [float] === `dns.answers.name` example: example.com. The domain name to which this resource record pertains. [float] === `dns.answers.type` example: MX The type of data contained in this resource record. [float] === `dns.answers.class` example: IN The class of DNS data contained in this resource record. [float] === `dns.answers.ttl` type: long The time interval in seconds that this resource record may be cached before it should be discarded. Zero values mean that the data should not be cached. [float] === `dns.answers.data` The data describing the resource. The meaning of this data depends on the type and class of the resource record. [float] === `dns.authorities` type: object An array containing a dictionary for each authority section from the answer. [float] === `dns.authorities_count` type: long The number of resource records contained in the `dns.authorities` field. The `dns.authorities` field may or may not be included depending on the configuration of Packetbeat. [float] === `dns.authorities.name` example: example.com. The domain name to which this resource record pertains. [float] === `dns.authorities.type` example: NS The type of data contained in this resource record. [float] === `dns.authorities.class` example: IN The class of DNS data contained in this resource record. [float] === `dns.additionals` type: object An array containing a dictionary for each additional section from the answer. [float] === `dns.additionals_count` type: long The number of resource records contained in the `dns.additionals` field. The `dns.additionals` field may or may not be included depending on the configuration of Packetbeat. [float] === `dns.additionals.name` example: example.com. The domain name to which this resource record pertains. [float] === `dns.additionals.type` example: NS The type of data contained in this resource record. [float] === `dns.additionals.class` example: IN The class of DNS data contained in this resource record. [float] === `dns.additionals.ttl` type: long The time interval in seconds that this resource record may be cached before it should be discarded. Zero values mean that the data should not be cached. [float] === `dns.additionals.data` The data describing the resource. The meaning of this data depends on the type and class of the resource record. [float] === `dns.opt.version` example: 0 The EDNS version. [float] === `dns.opt.do` type: boolean If set, the transaction uses DNSSEC. [float] === `dns.opt.ext_rcode` example: BADVERS Extended response code field. [float] === `dns.opt.udp_size` type: long Requestor's UDP payload size (in bytes). [[exported-fields-docker-processor]] == Docker fields beta[] Docker stats collected from Docker. [float] === `docker.container.id` type: keyword Unique container id. [float] === `docker.container.image` type: keyword Name of the image the container was built on. [float] === `docker.container.name` type: keyword Container name. [float] === `docker.container.labels` type: object Image labels. [[exported-fields-flows_event]] == Flow Event fields These fields contain data about the flow itself. [float] === `start_time` type: date example: 2015-01-24 14:06:05.071000 format: YYYY-MM-DDTHH:MM:SS.milliZ required: True The time, the first packet for the flow has been seen. [float] === `last_time` type: date example: 2015-01-24 14:06:05.071000 format: YYYY-MM-DDTHH:MM:SS.milliZ required: True The time, the most recent processed packet for the flow has been seen. [float] === `final` Indicates if event is last event in flow. If final is false, the event reports an intermediate flow state only. [float] === `flow_id` Internal flow id based on connection meta data and address. [float] === `vlan` Innermost VLAN address used in network packets. [float] === `outer_vlan` Second innermost VLAN address used in network packets. [float] == source fields Properties of the source host [float] === `source.mac` Source MAC address as indicated by first packet seen for the current flow. [float] === `source.ip` Innermost IPv4 source address as indicated by first packet seen for the current flow. [float] === `source.ip_location` type: geo_point example: 40.715, -74.011 The GeoIP location of the `ip_source` IP address. The field is a string containing the latitude and longitude separated by a comma. [float] === `source.outer_ip` Second innermost IPv4 source address as indicated by first packet seen for the current flow. [float] === `source.outer_ip_location` type: geo_point example: 40.715, -74.011 The GeoIP location of the `outer_ip_source` IP address. The field is a string containing the latitude and longitude separated by a comma. [float] === `source.ipv6` Innermost IPv6 source address as indicated by first packet seen for the current flow. [float] === `source.ipv6_location` type: geo_point example: 60.715, -76.011 The GeoIP location of the `ipv6_source` IP address. The field is a string containing the latitude and longitude separated by a comma. [float] === `source.outer_ipv6` Second innermost IPv6 source address as indicated by first packet seen for the current flow. [float] === `source.outer_ipv6_location` type: geo_point example: 60.715, -76.011 The GeoIP location of the `outer_ipv6_source` IP address. The field is a string containing the latitude and longitude separated by a comma. [float] === `source.port` Source port number as indicated by first packet seen for the current flow. [float] == stats fields Object with source to destination flow measurements. [float] === `source.stats.net_packets_total` type: long Total number of packets [float] === `source.stats.net_bytes_total` type: long Total number of bytes [float] == dest fields Properties of the destination host [float] === `dest.mac` Destination MAC address as indicated by first packet seen for the current flow. [float] === `dest.ip` Innermost IPv4 destination address as indicated by first packet seen for the current flow. [float] === `dest.ip_location` type: geo_point example: 40.715, -74.011 The GeoIP location of the `ip_dest` IP address. The field is a string containing the latitude and longitude separated by a comma. [float] === `dest.outer_ip` Second innermost IPv4 destination address as indicated by first packet seen for the current flow. [float] === `dest.outer_ip_location` type: geo_point example: 40.715, -74.011 The GeoIP location of the `outer_ip_dest` IP address. The field is a string containing the latitude and longitude separated by a comma. [float] === `dest.ipv6` Innermost IPv6 destination address as indicated by first packet seen for the current flow. [float] === `dest.ipv6_location` type: geo_point example: 60.715, -76.011 The GeoIP location of the `ipv6_dest` IP address. The field is a string containing the latitude and longitude separated by a comma. [float] === `dest.outer_ipv6` Second innermost IPv6 destination address as indicated by first packet seen for the current flow. [float] === `dest.outer_ipv6_location` type: geo_point example: 60.715, -76.011 The GeoIP location of the `outer_ipv6_dest` IP address. The field is a string containing the latitude and longitude separated by a comma. [float] === `dest.port` Destination port number as indicated by first packet seen for the current flow. [float] == stats fields Object with destination to source flow measurements. [float] === `dest.stats.net_packets_total` type: long Total number of packets [float] === `dest.stats.net_bytes_total` type: long Total number of bytes [float] === `icmp_id` ICMP id used in ICMP based flow. [float] === `connection_id` optional TCP connection id [[exported-fields-http]] == HTTP fields HTTP-specific event fields. [float] == http fields Information about the HTTP request and response. [float] == request fields HTTP request [float] === `http.request.params` The query parameters or form values. The query parameters are available in the Request-URI and the form values are set in the HTTP body when the content-type is set to `x-www-form-urlencoded`. [float] === `http.request.headers` type: object A map containing the captured header fields from the request. Which headers to capture is configurable. If headers with the same header name are present in the message, they will be separated by commas. [float] === `http.request.body` type: text The body of the HTTP request. [float] == response fields HTTP response [float] === `http.response.code` example: 404 The HTTP status code. [float] === `http.response.phrase` example: Not found. The HTTP status phrase. [float] === `http.response.headers` type: object A map containing the captured header fields from the response. Which headers to capture is configurable. If headers with the same header name are present in the message, they will be separated by commas. [float] === `http.response.body` The body of the HTTP response. [[exported-fields-icmp]] == ICMP fields ICMP specific event fields. [float] === `icmp.version` The version of the ICMP protocol. [float] === `icmp.request.message` type: keyword A human readable form of the request. [float] === `icmp.request.type` type: long The request type. [float] === `icmp.request.code` type: long The request code. [float] === `icmp.response.message` type: keyword A human readable form of the response. [float] === `icmp.response.type` type: long The response type. [float] === `icmp.response.code` type: long The response code. [[exported-fields-kubernetes-processor]] == Kubernetes fields beta[] Kubernetes metadata added by the kubernetes processor [float] === `kubernetes.pod.name` type: keyword Kubernetes pod name [float] === `kubernetes.namespace` type: keyword Kubernetes namespace [float] === `kubernetes.labels` type: object Kubernetes labels map [float] === `kubernetes.annotations` type: object Kubernetes annotations map [float] === `kubernetes.container.name` type: keyword Kubernetes container name [float] === `kubernetes.container.image` type: keyword Kubernetes container image [[exported-fields-memcache]] == Memcache fields Memcached-specific event fields [float] === `memcache.protocol_type` type: keyword The memcache protocol implementation. The value can be ""binary"" for binary-based, ""text"" for text-based, or ""unknown"" for an unknown memcache protocol type. [float] === `memcache.request.line` type: keyword The raw command line for unknown commands ONLY. [float] === `memcache.request.command` type: keyword The memcache command being requested in the memcache text protocol. For example ""set"" or ""get"". The binary protocol opcodes are translated into memcache text protocol commands. [float] === `memcache.response.command` type: keyword Either the text based protocol response message type or the name of the originating request if binary protocol is used. [float] === `memcache.request.type` type: keyword The memcache command classification. This value can be ""UNKNOWN"", ""Load"", ""Store"", ""Delete"", ""Counter"", ""Info"", ""SlabCtrl"", ""LRUCrawler"", ""Stats"", ""Success"", ""Fail"", or ""Auth"". [float] === `memcache.response.type` type: keyword The memcache command classification. This value can be ""UNKNOWN"", ""Load"", ""Store"", ""Delete"", ""Counter"", ""Info"", ""SlabCtrl"", ""LRUCrawler"", ""Stats"", ""Success"", ""Fail"", or ""Auth"". The text based protocol will employ any of these, whereas the binary based protocol will mirror the request commands only (see `memcache.response.status` for binary protocol). [float] === `memcache.response.error_msg` type: keyword The optional error message in the memcache response (text based protocol only). [float] === `memcache.request.opcode` type: keyword The binary protocol message opcode name. [float] === `memcache.response.opcode` type: keyword The binary protocol message opcode name. [float] === `memcache.request.opcode_value` type: long The binary protocol message opcode value. [float] === `memcache.response.opcode_value` type: long The binary protocol message opcode value. [float] === `memcache.request.opaque` type: long The binary protocol opaque header value used for correlating request with response messages. [float] === `memcache.response.opaque` type: long The binary protocol opaque header value used for correlating request with response messages. [float] === `memcache.request.vbucket` type: long The vbucket index sent in the binary message. [float] === `memcache.response.status` type: keyword The textual representation of the response error code (binary protocol only). [float] === `memcache.response.status_code` type: long The status code value returned in the response (binary protocol only). [float] === `memcache.request.keys` type: array The list of keys sent in the store or load commands. [float] === `memcache.response.keys` type: array The list of keys returned for the load command (if present). [float] === `memcache.request.count_values` type: long The number of values found in the memcache request message. If the command does not send any data, this field is missing. [float] === `memcache.response.count_values` type: long The number of values found in the memcache response message. If the command does not send any data, this field is missing. [float] === `memcache.request.values` type: array The list of base64 encoded values sent with the request (if present). [float] === `memcache.response.values` type: array The list of base64 encoded values sent with the response (if present). [float] === `memcache.request.bytes` type: long format: bytes The byte count of the values being transferred. [float] === `memcache.response.bytes` type: long format: bytes The byte count of the values being transferred. [float] === `memcache.request.delta` type: long The counter increment/decrement delta value. [float] === `memcache.request.initial` type: long The counter increment/decrement initial value parameter (binary protocol only). [float] === `memcache.request.verbosity` type: long The value of the memcache ""verbosity"" command. [float] === `memcache.request.raw_args` type: keyword The text protocol raw arguments for the ""stats ..."" and ""lru crawl ..."" commands. [float] === `memcache.request.source_class` type: long The source class id in 'slab reassign' command. [float] === `memcache.request.dest_class` type: long The destination class id in 'slab reassign' command. [float] === `memcache.request.automove` type: keyword The automove mode in the 'slab automove' command expressed as a string. This value can be ""standby""(=0), ""slow""(=1), ""aggressive""(=2), or the raw value if the value is unknown. [float] === `memcache.request.flags` type: long The memcache command flags sent in the request (if present). [float] === `memcache.response.flags` type: long The memcache message flags sent in the response (if present). [float] === `memcache.request.exptime` type: long The data expiry time in seconds sent with the memcache command (if present). If the value is <30 days, the expiry time is relative to ""now"", or else it is an absolute Unix time in seconds (32-bit). [float] === `memcache.request.sleep_us` type: long The sleep setting in microseconds for the 'lru_crawler sleep' command. [float] === `memcache.response.value` type: long The counter value returned by a counter operation. [float] === `memcache.request.noreply` type: boolean Set to true if noreply was set in the request. The `memcache.response` field will be missing. [float] === `memcache.request.quiet` type: boolean Set to true if the binary protocol message is to be treated as a quiet message. [float] === `memcache.request.cas_unique` type: long The CAS (compare-and-swap) identifier if present. [float] === `memcache.response.cas_unique` type: long The CAS (compare-and-swap) identifier to be used with CAS-based updates (if present). [float] === `memcache.response.stats` type: array The list of statistic values returned. Each entry is a dictionary with the fields ""name"" and ""value"". [float] === `memcache.response.version` type: keyword The returned memcache version string. [[exported-fields-mongodb]] == MongoDb fields MongoDB-specific event fields. These fields mirror closely the fields for the MongoDB wire protocol. The higher level fields (for example, `query` and `resource`) apply to MongoDB events as well. [float] === `mongodb.error` If the MongoDB request has resulted in an error, this field contains the error message returned by the server. [float] === `mongodb.fullCollectionName` The full collection name. The full collection name is the concatenation of the database name with the collection name, using a dot (.) for the concatenation. For example, for the database foo and the collection bar, the full collection name is foo.bar. [float] === `mongodb.numberToSkip` type: long Sets the number of documents to omit - starting from the first document in the resulting dataset - when returning the result of the query. [float] === `mongodb.numberToReturn` type: long The requested maximum number of documents to be returned. [float] === `mongodb.numberReturned` type: long The number of documents in the reply. [float] === `mongodb.startingFrom` Where in the cursor this reply is starting. [float] === `mongodb.query` A JSON document that represents the query. The query will contain one or more elements, all of which must match for a document to be included in the result set. Possible elements include $query, $orderby, $hint, $explain, and $snapshot. [float] === `mongodb.returnFieldsSelector` A JSON document that limits the fields in the returned documents. The returnFieldsSelector contains one or more elements, each of which is the name of a field that should be returned, and the integer value 1. [float] === `mongodb.selector` A BSON document that specifies the query for selecting the document to update or delete. [float] === `mongodb.update` A BSON document that specifies the update to be performed. For information on specifying updates, see the Update Operations documentation from the MongoDB Manual. [float] === `mongodb.cursorId` The cursor identifier returned in the OP_REPLY. This must be the value that was returned from the database. [float] == rpc fields OncRPC specific event fields. [float] === `rpc.xid` RPC message transaction identifier. [float] === `rpc.call_size` type: long RPC call size with argument. [float] === `rpc.reply_size` type: long RPC reply size with argument. [float] === `rpc.status` RPC message reply status. [float] === `rpc.time` type: long RPC message processing time. [float] === `rpc.time_str` RPC message processing time in human readable form. [float] === `rpc.auth_flavor` RPC authentication flavor. [float] === `rpc.cred.uid` type: long RPC caller's user id, in case of auth-unix. [float] === `rpc.cred.gid` type: long RPC caller's group id, in case of auth-unix. [float] === `rpc.cred.gids` RPC caller's secondary group ids, in case of auth-unix. [float] === `rpc.cred.stamp` type: long Arbitrary ID which the caller machine may generate. [float] === `rpc.cred.machinename` The name of the caller's machine. [[exported-fields-mysql]] == MySQL fields MySQL-specific event fields. [float] === `mysql.iserror` type: boolean If the MySQL query returns an error, this field is set to true. [float] === `mysql.affected_rows` type: long If the MySQL command is successful, this field contains the affected number of rows of the last statement. [float] === `mysql.insert_id` If the INSERT query is successful, this field contains the id of the newly inserted row. [float] === `mysql.num_fields` If the SELECT query is successful, this field is set to the number of fields returned. [float] === `mysql.num_rows` If the SELECT query is successful, this field is set to the number of rows returned. [float] === `mysql.query` The row mysql query as read from the transaction's request. [float] === `mysql.error_code` type: long The error code returned by MySQL. [float] === `mysql.error_message` The error info message returned by MySQL. [[exported-fields-nfs]] == NFS fields NFS v4/3 specific event fields. [float] === `nfs.version` type: long NFS protocol version number. [float] === `nfs.minor_version` type: long NFS protocol minor version number. [float] === `nfs.tag` NFS v4 COMPOUND operation tag. [float] === `nfs.opcode` NFS operation name, or main operation name, in case of COMPOUND calls. [float] === `nfs.status` NFS operation reply status. [[exported-fields-pgsql]] == PostgreSQL fields PostgreSQL-specific event fields. [float] === `pgsql.query` The row pgsql query as read from the transaction's request. [float] === `pgsql.iserror` type: boolean If the PgSQL query returns an error, this field is set to true. [float] === `pgsql.error_code` type: long The PostgreSQL error code. [float] === `pgsql.error_message` The PostgreSQL error message. [float] === `pgsql.error_severity` The PostgreSQL error severity. [float] === `pgsql.num_fields` If the SELECT query if successful, this field is set to the number of fields returned. [float] === `pgsql.num_rows` If the SELECT query if successful, this field is set to the number of rows returned. [[exported-fields-raw]] == Raw fields These fields contain the raw transaction data. [float] === `request` type: text For text protocols, this is the request as seen on the wire (application layer only). For binary protocols this is our representation of the request. [float] === `response` type: text For text protocols, this is the response as seen on the wire (application layer only). For binary protocols this is our representation of the request. [[exported-fields-redis]] == Redis fields Redis-specific event fields. [float] === `redis.return_value` The return value of the Redis command in a human readable format. [float] === `redis.error` If the Redis command has resulted in an error, this field contains the error message returned by the Redis server. [[exported-fields-thrift]] == Thrift-RPC fields Thrift-RPC specific event fields. [float] === `thrift.params` The RPC method call parameters in a human readable format. If the IDL files are available, the parameters use names whenever possible. Otherwise, the IDs from the message are used. [float] === `thrift.service` The name of the Thrift-RPC service as defined in the IDL files. [float] === `thrift.return_value` The value returned by the Thrift-RPC call. This is encoded in a human readable format. [float] === `thrift.exceptions` If the call resulted in exceptions, this field contains the exceptions in a human readable format. [[exported-fields-tls]] == TLS fields TLS-specific event fields. [float] === `tls.handshake_completed` type: boolean Whether the TLS negotiation has been successful and the session has transitioned to encrypted mode. [float] === `tls.resumed` type: boolean If the TLS session has been resumed from a previous session. [float] === `tls.resumption_method` type: keyword If the session has been resumed, the underlying method used. One of ""id"" for TLS session ID or ""ticket"" for TLS ticket extension. [float] === `tls.client_certificate_requested` type: boolean Whether the server has requested the client to authenticate itself using a client certificate. [float] === `tls.client_hello.version` type: keyword The version of the TLS protocol by which the client wishes to communicate during this session. [float] === `tls.client_hello.supported_ciphers` type: array List of ciphers the client is willing to use for this session. See https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-4 [float] === `tls.client_hello.supported_compression_methods` type: array The list of compression methods the client supports. See https://www.iana.org/assignments/comp-meth-ids/comp-meth-ids.xhtml [float] == extensions fields The hello extensions provided by the client. [float] === `tls.client_hello.extensions.server_name_indication` type: keyword List of hostnames [float] === `tls.client_hello.extensions.application_layer_protocol_negotiation` type: keyword List of application-layer protocols the client is willing to use. [float] === `tls.client_hello.extensions.session_ticket` type: keyword Length of the session ticket, if provided, or an empty string to advertise support for tickets. [float] === `tls.server_hello.version` type: keyword The version of the TLS protocol that is used for this session. It is the highest version supported by the server not exceeding the version requested in the client hello. [float] === `tls.server_hello.selected_cipher` type: keyword The cipher suite selected by the server from the list provided by in the client hello. [float] === `tls.server_hello.selected_compression_method` type: keyword The compression method selected by the server from the list provided in the client hello. [float] == extensions fields The hello extensions provided by the server. [float] === `tls.server_hello.extensions.application_layer_protocol_negotiation` type: array Negotiated application layer protocol [float] === `tls.server_hello.extensions.session_ticket` type: keyword Used to announce that a session ticket will be provided by the server. Always an empty string. [float] == client_certificate fields Certificate provided by the client for authentication. [float] === `tls.client_certificate.version` type: long X509 format version. [float] === `tls.client_certificate.serial_number` type: keyword The certificate's serial number. [float] === `tls.client_certificate.not_before` type: date Date before which the certificate is not valid. [float] === `tls.client_certificate.not_after` type: date Date after which the certificate expires. [float] === `tls.client_certificate.public_key_algorithm` type: keyword The algorithm used for this certificate's public key. One of RSA, DSA or ECDSA. [float] === `tls.client_certificate.signature_algorithm` type: keyword The algorithm used for the certificate's signature. [float] === `tls.client_certificate.alternative_names` type: array Subject Alternative Names for this certificate. [float] === `tls.client_certificate.raw` type: keyword The raw certificate in PEM format. [float] == subject fields Subject represented by this certificate. [float] === `tls.client_certificate.subject.country` type: keyword Country code. [float] === `tls.client_certificate.subject.organization` type: keyword Organization name. [float] === `tls.client_certificate.subject.organizational_unit` type: keyword Unit within organization. [float] === `tls.client_certificate.subject.province` type: keyword Province or region within country. [float] === `tls.client_certificate.subject.common_name` type: keyword Name or host name identified by the certificate. [float] == issuer fields Entity that issued and signed this certificate. [float] === `tls.client_certificate.issuer.country` type: keyword Country code. [float] === `tls.client_certificate.issuer.organization` type: keyword Organization name. [float] === `tls.client_certificate.issuer.organizational_unit` type: keyword Unit within organization. [float] === `tls.client_certificate.issuer.province` type: keyword Province or region within country. [float] === `tls.client_certificate.issuer.common_name` type: keyword Name or host name identified by the certificate. [float] == server_certificate fields Certificate provided by the server for authentication. [float] === `tls.server_certificate.version` type: long X509 format version. [float] === `tls.server_certificate.serial_number` type: keyword The certificate's serial number. [float] === `tls.server_certificate.not_before` type: date Date before which the certificate is not valid. [float] === `tls.server_certificate.not_after` type: date Date after which the certificate expires. [float] === `tls.server_certificate.public_key_algorithm` type: keyword The algorithm used for this certificate's public key. One of RSA, DSA or ECDSA. [float] === `tls.server_certificate.signature_algorithm` type: keyword The algorithm used for the certificate's signature. [float] === `tls.server_certificate.alternative_names` type: array Subject Alternative Names for this certificate. [float] === `tls.server_certificate.raw` type: keyword The raw certificate in PEM format. [float] == subject fields Subject represented by this certificate. [float] === `tls.server_certificate.subject.country` type: keyword Country code. [float] === `tls.server_certificate.subject.organization` type: keyword Organization name. [float] === `tls.server_certificate.subject.organizational_unit` type: keyword Unit within organization. [float] === `tls.server_certificate.subject.province` type: keyword Province or region within country. [float] === `tls.server_certificate.subject.common_name` type: keyword Name or host name identified by the certificate. [float] == issuer fields Entity that issued and signed this certificate. [float] === `tls.server_certificate.issuer.country` type: keyword Country code. [float] === `tls.server_certificate.issuer.organization` type: keyword Organization name. [float] === `tls.server_certificate.issuer.organizational_unit` type: keyword Unit within organization. [float] === `tls.server_certificate.issuer.province` type: keyword Province or region within country. [float] === `tls.server_certificate.issuer.common_name` type: keyword Name or host name identified by the certificate. [float] === `tls.server_certificate_chain` type: array Chain of trust for the server certificate. [float] === `tls.client_certificate_chain` type: array Chain of trust for the client certificate. [float] === `tls.alert_types` type: keyword An array containing the TLS alert type for every alert received. [[exported-fields-trans_event]] == Transaction Event fields These fields contain data about the transaction itself. [float] === `direction` required: True Indicates whether the transaction is inbound (emitted by server) or outbound (emitted by the client). Values can be in or out. No defaults. [float] === `status` required: True The high level status of the transaction. The way to compute this value depends on the protocol, but the result has a meaning independent of the protocol. [float] === `method` The command/verb/method of the transaction. For HTTP, this is the method name (GET, POST, PUT, and so on), for SQL this is the verb (SELECT, UPDATE, DELETE, and so on). [float] === `resource` The logical resource that this transaction refers to. For HTTP, this is the URL path up to the last slash (/). For example, if the URL is `/users/1`, the resource is `/users`. For databases, the resource is typically the table name. The field is not filled for all transaction types. [float] === `path` required: True The path the transaction refers to. For HTTP, this is the URL. For SQL databases, this is the table name. For key-value stores, this is the key. [float] === `query` type: keyword The query in a human readable format. For HTTP, it will typically be something like `GET /users/_search?name=test`. For MySQL, it is something like `SELECT id from users where name=test`. [float] === `params` type: text The request parameters. For HTTP, these are the POST or GET parameters. For Thrift-RPC, these are the parameters from the request. [float] === `notes` Messages from Packetbeat itself. This field usually contains error messages for interpreting the raw data. This information can be helpful for troubleshooting. [[exported-fields-trans_measurements]] == Measurements (Transactions) fields These fields contain measurements related to the transaction. [float] === `responsetime` type: long The wall clock time it took to complete the transaction. The precision is in milliseconds. [float] === `cpu_time` type: long The CPU time it took to complete the transaction. [float] === `bytes_in` type: long format: bytes The number of bytes of the request. Note that this size is the application layer message length, without the length of the IP or TCP headers. [float] === `bytes_out` type: long format: bytes The number of bytes of the response. Note that this size is the application layer message length, without the length of the IP or TCP headers. [float] === `dnstime` type: long The time it takes to query the name server for a given request. This is typically used for RUM (real-user-monitoring) but can also have values for server-to-server communication when DNS is used for service discovery. The precision is in microseconds. [float] === `connecttime` type: long The time it takes for the TCP connection to be established for the given transaction. The precision is in microseconds. [float] === `loadtime` type: long The time it takes for the content to be loaded. This is typically used for RUM (real-user-monitoring) but it can make sense in other cases as well. The precision is in microseconds. [float] === `domloadtime` type: long In RUM (real-user-monitoring), the total time it takes for the DOM to be loaded. In terms of the W3 Navigation Timing API, this is the difference between `domContentLoadedEnd` and `domContentLoadedStart`. ",12490,False,2272.2204557788104,median "// Copyright (c) 2014-2019, The Monero Project // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers #include #include #include ""wipeable_string.h"" #include ""string_tools.h"" #include ""serialization/string.h"" #include ""cryptonote_format_utils.h"" #include ""cryptonote_config.h"" #include ""crypto/crypto.h"" #include ""crypto/hash.h"" #include ""ringct/rctSigs.h"" using namespace epee; #undef MONERO_DEFAULT_LOG_CATEGORY #define MONERO_DEFAULT_LOG_CATEGORY ""cn"" // #define ENABLE_HASH_CASH_INTEGRITY_CHECK using namespace crypto; static const uint64_t valid_decomposed_outputs[] = { (uint64_t)1, (uint64_t)2, (uint64_t)3, (uint64_t)4, (uint64_t)5, (uint64_t)6, (uint64_t)7, (uint64_t)8, (uint64_t)9, // 1 piconero (uint64_t)10, (uint64_t)20, (uint64_t)30, (uint64_t)40, (uint64_t)50, (uint64_t)60, (uint64_t)70, (uint64_t)80, (uint64_t)90, (uint64_t)100, (uint64_t)200, (uint64_t)300, (uint64_t)400, (uint64_t)500, (uint64_t)600, (uint64_t)700, (uint64_t)800, (uint64_t)900, (uint64_t)1000, (uint64_t)2000, (uint64_t)3000, (uint64_t)4000, (uint64_t)5000, (uint64_t)6000, (uint64_t)7000, (uint64_t)8000, (uint64_t)9000, (uint64_t)10000, (uint64_t)20000, (uint64_t)30000, (uint64_t)40000, (uint64_t)50000, (uint64_t)60000, (uint64_t)70000, (uint64_t)80000, (uint64_t)90000, (uint64_t)100000, (uint64_t)200000, (uint64_t)300000, (uint64_t)400000, (uint64_t)500000, (uint64_t)600000, (uint64_t)700000, (uint64_t)800000, (uint64_t)900000, (uint64_t)1000000, (uint64_t)2000000, (uint64_t)3000000, (uint64_t)4000000, (uint64_t)5000000, (uint64_t)6000000, (uint64_t)7000000, (uint64_t)8000000, (uint64_t)9000000, // 1 micronero (uint64_t)10000000, (uint64_t)20000000, (uint64_t)30000000, (uint64_t)40000000, (uint64_t)50000000, (uint64_t)60000000, (uint64_t)70000000, (uint64_t)80000000, (uint64_t)90000000, (uint64_t)100000000, (uint64_t)200000000, (uint64_t)300000000, (uint64_t)400000000, (uint64_t)500000000, (uint64_t)600000000, (uint64_t)700000000, (uint64_t)800000000, (uint64_t)900000000, (uint64_t)1000000000, (uint64_t)2000000000, (uint64_t)3000000000, (uint64_t)4000000000, (uint64_t)5000000000, (uint64_t)6000000000, (uint64_t)7000000000, (uint64_t)8000000000, (uint64_t)9000000000, (uint64_t)10000000000, (uint64_t)20000000000, (uint64_t)30000000000, (uint64_t)40000000000, (uint64_t)50000000000, (uint64_t)60000000000, (uint64_t)70000000000, (uint64_t)80000000000, (uint64_t)90000000000, (uint64_t)100000000000, (uint64_t)200000000000, (uint64_t)300000000000, (uint64_t)400000000000, (uint64_t)500000000000, (uint64_t)600000000000, (uint64_t)700000000000, (uint64_t)800000000000, (uint64_t)900000000000, (uint64_t)1000000000000, (uint64_t)2000000000000, (uint64_t)3000000000000, (uint64_t)4000000000000, (uint64_t)5000000000000, (uint64_t)6000000000000, (uint64_t)7000000000000, (uint64_t)8000000000000, (uint64_t)9000000000000, // 1 monero (uint64_t)10000000000000, (uint64_t)20000000000000, (uint64_t)30000000000000, (uint64_t)40000000000000, (uint64_t)50000000000000, (uint64_t)60000000000000, (uint64_t)70000000000000, (uint64_t)80000000000000, (uint64_t)90000000000000, (uint64_t)100000000000000, (uint64_t)200000000000000, (uint64_t)300000000000000, (uint64_t)400000000000000, (uint64_t)500000000000000, (uint64_t)600000000000000, (uint64_t)700000000000000, (uint64_t)800000000000000, (uint64_t)900000000000000, (uint64_t)1000000000000000, (uint64_t)2000000000000000, (uint64_t)3000000000000000, (uint64_t)4000000000000000, (uint64_t)5000000000000000, (uint64_t)6000000000000000, (uint64_t)7000000000000000, (uint64_t)8000000000000000, (uint64_t)9000000000000000, (uint64_t)10000000000000000, (uint64_t)20000000000000000, (uint64_t)30000000000000000, (uint64_t)40000000000000000, (uint64_t)50000000000000000, (uint64_t)60000000000000000, (uint64_t)70000000000000000, (uint64_t)80000000000000000, (uint64_t)90000000000000000, (uint64_t)100000000000000000, (uint64_t)200000000000000000, (uint64_t)300000000000000000, (uint64_t)400000000000000000, (uint64_t)500000000000000000, (uint64_t)600000000000000000, (uint64_t)700000000000000000, (uint64_t)800000000000000000, (uint64_t)900000000000000000, (uint64_t)1000000000000000000, (uint64_t)2000000000000000000, (uint64_t)3000000000000000000, (uint64_t)4000000000000000000, (uint64_t)5000000000000000000, (uint64_t)6000000000000000000, (uint64_t)7000000000000000000, (uint64_t)8000000000000000000, (uint64_t)9000000000000000000, // 1 meganero (uint64_t)10000000000000000000ull }; static std::atomic default_decimal_point(CRYPTONOTE_DISPLAY_DECIMAL_POINT); static std::atomic tx_hashes_calculated_count(0); static std::atomic tx_hashes_cached_count(0); static std::atomic block_hashes_calculated_count(0); static std::atomic block_hashes_cached_count(0); #define CHECK_AND_ASSERT_THROW_MES_L1(expr, message) {if(!(expr)) {MWARNING(message); throw std::runtime_error(message);}} namespace cryptonote { static inline unsigned char *operator &(ec_point &point) { return &reinterpret_cast(point); } static inline const unsigned char *operator &(const ec_point &point) { return &reinterpret_cast(point); } // a copy of rct::addKeys, since we can't link to libringct to avoid circular dependencies static void add_public_key(crypto::public_key &AB, const crypto::public_key &A, const crypto::public_key &B) { ge_p3 B2, A2; CHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&B2, &B) == 0, ""ge_frombytes_vartime failed at ""+boost::lexical_cast(__LINE__)); CHECK_AND_ASSERT_THROW_MES_L1(ge_frombytes_vartime(&A2, &A) == 0, ""ge_frombytes_vartime failed at ""+boost::lexical_cast(__LINE__)); ge_cached tmp2; ge_p3_to_cached(&tmp2, &B2); ge_p1p1 tmp3; ge_add(&tmp3, &A2, &tmp2); ge_p1p1_to_p3(&A2, &tmp3); ge_p3_tobytes(&AB, &A2); } uint64_t get_transaction_weight_clawback(const transaction &tx, size_t n_padded_outputs) { const rct::rctSig &rv = tx.rct_signatures; const uint64_t bp_base = 368; const size_t n_outputs = tx.vout.size(); if (n_padded_outputs <= 2) return 0; size_t nlr = 0; while ((1u << nlr) < n_padded_outputs) ++nlr; nlr += 6; const size_t bp_size = 32 * (9 + 2 * nlr); CHECK_AND_ASSERT_THROW_MES_L1(n_outputs <= BULLETPROOF_MAX_OUTPUTS, ""maximum number of outputs is "" + std::to_string(BULLETPROOF_MAX_OUTPUTS) + "" per transaction""); CHECK_AND_ASSERT_THROW_MES_L1(bp_base * n_padded_outputs >= bp_size, ""Invalid bulletproof clawback: bp_base "" + std::to_string(bp_base) + "", n_padded_outputs "" + std::to_string(n_padded_outputs) + "", bp_size "" + std::to_string(bp_size)); const uint64_t bp_clawback = (bp_base * n_padded_outputs - bp_size) * 4 / 5; return bp_clawback; } //--------------------------------------------------------------- } namespace cryptonote { //--------------------------------------------------------------- void get_transaction_prefix_hash(const transaction_prefix& tx, crypto::hash& h, hw::device &hwdev) { hwdev.get_transaction_prefix_hash(tx,h); } //--------------------------------------------------------------- crypto::hash get_transaction_prefix_hash(const transaction_prefix& tx, hw::device &hwdev) { crypto::hash h = null_hash; get_transaction_prefix_hash(tx, h, hwdev); return h; } //--------------------------------------------------------------- void get_transaction_prefix_hash(const transaction_prefix& tx, crypto::hash& h) { std::ostringstream s; binary_archive a(s); ::serialization::serialize(a, const_cast(tx)); crypto::cn_fast_hash(s.str().data(), s.str().size(), h); } //--------------------------------------------------------------- crypto::hash get_transaction_prefix_hash(const transaction_prefix& tx) { crypto::hash h = null_hash; get_transaction_prefix_hash(tx, h); return h; } //--------------------------------------------------------------- bool expand_transaction_1(transaction &tx, bool base_only) { if (tx.version >= 2 && !is_coinbase(tx)) { rct::rctSig &rv = tx.rct_signatures; if (rv.type == rct::RCTTypeNull) return true; if (rv.outPk.size() != tx.vout.size()) { LOG_PRINT_L1(""Failed to parse transaction from blob, bad outPk size in tx "" << get_transaction_hash(tx)); return false; } for (size_t n = 0; n < tx.rct_signatures.outPk.size(); ++n) { if (tx.vout[n].target.type() != typeid(txout_to_key)) { LOG_PRINT_L1(""Unsupported output type in tx "" << get_transaction_hash(tx)); return false; } rv.outPk[n].dest = rct::pk2rct(boost::get(tx.vout[n].target).key); } if (!base_only) { const bool bulletproof = rct::is_rct_bulletproof(rv.type); if (bulletproof) { if (rv.p.bulletproofs.size() != 1) { LOG_PRINT_L1(""Failed to parse transaction from blob, bad bulletproofs size in tx "" << get_transaction_hash(tx)); return false; } if (rv.p.bulletproofs[0].L.size() < 6) { LOG_PRINT_L1(""Failed to parse transaction from blob, bad bulletproofs L size in tx "" << get_transaction_hash(tx)); return false; } const size_t max_outputs = 1 << (rv.p.bulletproofs[0].L.size() - 6); if (max_outputs < tx.vout.size()) { LOG_PRINT_L1(""Failed to parse transaction from blob, bad bulletproofs max outputs in tx "" << get_transaction_hash(tx)); return false; } const size_t n_amounts = tx.vout.size(); CHECK_AND_ASSERT_MES(n_amounts == rv.outPk.size(), false, ""Internal error filling out V""); rv.p.bulletproofs[0].V.resize(n_amounts); for (size_t i = 0; i < n_amounts; ++i) rv.p.bulletproofs[0].V[i] = rct::scalarmultKey(rv.outPk[i].mask, rct::INV_EIGHT); } } } return true; } //--------------------------------------------------------------- bool parse_and_validate_tx_from_blob(const blobdata& tx_blob, transaction& tx) { std::stringstream ss; ss << tx_blob; binary_archive ba(ss); bool r = ::serialization::serialize(ba, tx); CHECK_AND_ASSERT_MES(r, false, ""Failed to parse transaction from blob""); CHECK_AND_ASSERT_MES(expand_transaction_1(tx, false), false, ""Failed to expand transaction data""); tx.invalidate_hashes(); tx.set_blob_size(tx_blob.size()); return true; } //--------------------------------------------------------------- bool parse_and_validate_tx_base_from_blob(const blobdata& tx_blob, transaction& tx) { std::stringstream ss; ss << tx_blob; binary_archive ba(ss); bool r = tx.serialize_base(ba); CHECK_AND_ASSERT_MES(r, false, ""Failed to parse transaction from blob""); CHECK_AND_ASSERT_MES(expand_transaction_1(tx, true), false, ""Failed to expand transaction data""); tx.invalidate_hashes(); return true; } //--------------------------------------------------------------- bool parse_and_validate_tx_prefix_from_blob(const blobdata& tx_blob, transaction_prefix& tx) { std::stringstream ss; ss << tx_blob; binary_archive ba(ss); bool r = ::serialization::serialize_noeof(ba, tx); CHECK_AND_ASSERT_MES(r, false, ""Failed to parse transaction prefix from blob""); return true; } //--------------------------------------------------------------- bool parse_and_validate_tx_from_blob(const blobdata& tx_blob, transaction& tx, crypto::hash& tx_hash) { std::stringstream ss; ss << tx_blob; binary_archive ba(ss); bool r = ::serialization::serialize(ba, tx); CHECK_AND_ASSERT_MES(r, false, ""Failed to parse transaction from blob""); CHECK_AND_ASSERT_MES(expand_transaction_1(tx, false), false, ""Failed to expand transaction data""); tx.invalidate_hashes(); //TODO: validate tx return get_transaction_hash(tx, tx_hash); } //--------------------------------------------------------------- bool parse_and_validate_tx_from_blob(const blobdata& tx_blob, transaction& tx, crypto::hash& tx_hash, crypto::hash& tx_prefix_hash) { if (!parse_and_validate_tx_from_blob(tx_blob, tx, tx_hash)) return false; get_transaction_prefix_hash(tx, tx_prefix_hash); return true; } //--------------------------------------------------------------- bool is_v1_tx(const blobdata_ref& tx_blob) { uint64_t version; const char* begin = static_cast(tx_blob.data()); const char* end = begin + tx_blob.size(); int read = tools::read_varint(begin, end, version); if (read <= 0) throw std::runtime_error(""Internal error getting transaction version""); return version <= 1; } //--------------------------------------------------------------- bool is_v1_tx(const blobdata& tx_blob) { return is_v1_tx(blobdata_ref{tx_blob.data(), tx_blob.size()}); } //--------------------------------------------------------------- bool generate_key_image_helper(const account_keys& ack, const std::unordered_map& subaddresses, const crypto::public_key& out_key, const crypto::public_key& tx_public_key, const std::vector& additional_tx_public_keys, size_t real_output_index, keypair& in_ephemeral, crypto::key_image& ki, hw::device &hwdev) { crypto::key_derivation recv_derivation = AUTO_VAL_INIT(recv_derivation); bool r = hwdev.generate_key_derivation(tx_public_key, ack.m_view_secret_key, recv_derivation); if (!r) { MWARNING(""key image helper: failed to generate_key_derivation("" << tx_public_key << "", "" << ack.m_view_secret_key << "")""); memcpy(&recv_derivation, rct::identity().bytes, sizeof(recv_derivation)); } std::vector additional_recv_derivations; for (size_t i = 0; i < additional_tx_public_keys.size(); ++i) { crypto::key_derivation additional_recv_derivation = AUTO_VAL_INIT(additional_recv_derivation); r = hwdev.generate_key_derivation(additional_tx_public_keys[i], ack.m_view_secret_key, additional_recv_derivation); if (!r) { MWARNING(""key image helper: failed to generate_key_derivation("" << additional_tx_public_keys[i] << "", "" << ack.m_view_secret_key << "")""); } else { additional_recv_derivations.push_back(additional_recv_derivation); } } boost::optional subaddr_recv_info = is_out_to_acc_precomp(subaddresses, out_key, recv_derivation, additional_recv_derivations, real_output_index,hwdev); CHECK_AND_ASSERT_MES(subaddr_recv_info, false, ""key image helper: given output pubkey doesn't seem to belong to this address""); return generate_key_image_helper_precomp(ack, out_key, subaddr_recv_info->derivation, real_output_index, subaddr_recv_info->index, in_ephemeral, ki, hwdev); } //--------------------------------------------------------------- bool generate_key_image_helper_precomp(const account_keys& ack, const crypto::public_key& out_key, const crypto::key_derivation& recv_derivation, size_t real_output_index, const subaddress_index& received_index, keypair& in_ephemeral, crypto::key_image& ki, hw::device &hwdev) { if (hwdev.compute_key_image(ack, out_key, recv_derivation, real_output_index, received_index, in_ephemeral, ki)) { return true; } if (ack.m_spend_secret_key == crypto::null_skey) { // for watch-only wallet, simply copy the known output pubkey in_ephemeral.pub = out_key; in_ephemeral.sec = crypto::null_skey; } else { // derive secret key with subaddress - step 1: original CN derivation crypto::secret_key scalar_step1; hwdev.derive_secret_key(recv_derivation, real_output_index, ack.m_spend_secret_key, scalar_step1); // computes Hs(a*R || idx) + b // step 2: add Hs(a || index_major || index_minor) crypto::secret_key subaddr_sk; crypto::secret_key scalar_step2; if (received_index.is_zero()) { scalar_step2 = scalar_step1; // treat index=(0,0) as a special case representing the main address } else { subaddr_sk = hwdev.get_subaddress_secret_key(ack.m_view_secret_key, received_index); hwdev.sc_secret_add(scalar_step2, scalar_step1,subaddr_sk); } in_ephemeral.sec = scalar_step2; if (ack.m_multisig_keys.empty()) { // when not in multisig, we know the full spend secret key, so the output pubkey can be obtained by scalarmultBase CHECK_AND_ASSERT_MES(hwdev.secret_key_to_public_key(in_ephemeral.sec, in_ephemeral.pub), false, ""Failed to derive public key""); } else { // when in multisig, we only know the partial spend secret key. but we do know the full spend public key, so the output pubkey can be obtained by using the standard CN key derivation CHECK_AND_ASSERT_MES(hwdev.derive_public_key(recv_derivation, real_output_index, ack.m_account_address.m_spend_public_key, in_ephemeral.pub), false, ""Failed to derive public key""); // and don't forget to add the contribution from the subaddress part if (!received_index.is_zero()) { crypto::public_key subaddr_pk; CHECK_AND_ASSERT_MES(hwdev.secret_key_to_public_key(subaddr_sk, subaddr_pk), false, ""Failed to derive public key""); add_public_key(in_ephemeral.pub, in_ephemeral.pub, subaddr_pk); } } CHECK_AND_ASSERT_MES(in_ephemeral.pub == out_key, false, ""key image helper precomp: given output pubkey doesn't match the derived one""); } hwdev.generate_key_image(in_ephemeral.pub, in_ephemeral.sec, ki); return true; } //--------------------------------------------------------------- uint64_t power_integral(uint64_t a, uint64_t b) { if(b == 0) return 1; uint64_t total = a; for(uint64_t i = 1; i != b; i++) total *= a; return total; } //--------------------------------------------------------------- bool parse_amount(uint64_t& amount, const std::string& str_amount_) { std::string str_amount = str_amount_; boost::algorithm::trim(str_amount); size_t point_index = str_amount.find_first_of('.'); size_t fraction_size; if (std::string::npos != point_index) { fraction_size = str_amount.size() - point_index - 1; while (default_decimal_point < fraction_size && '0' == str_amount.back()) { str_amount.erase(str_amount.size() - 1, 1); --fraction_size; } if (default_decimal_point < fraction_size) return false; str_amount.erase(point_index, 1); } else { fraction_size = 0; } if (str_amount.empty()) return false; if (fraction_size < default_decimal_point) { str_amount.append(default_decimal_point - fraction_size, '0'); } return string_tools::get_xtype_from_string(amount, str_amount); } //--------------------------------------------------------------- uint64_t get_transaction_weight(const transaction &tx, size_t blob_size) { CHECK_AND_ASSERT_MES(!tx.pruned, std::numeric_limits::max(), ""get_transaction_weight does not support pruned txes""); if (tx.version < 2) return blob_size; const rct::rctSig &rv = tx.rct_signatures; if (!rct::is_rct_bulletproof(rv.type)) return blob_size; const size_t n_padded_outputs = rct::n_bulletproof_max_amounts(rv.p.bulletproofs); uint64_t bp_clawback = get_transaction_weight_clawback(tx, n_padded_outputs); CHECK_AND_ASSERT_THROW_MES_L1(bp_clawback <= std::numeric_limits::max() - blob_size, ""Weight overflow""); return blob_size + bp_clawback; } //--------------------------------------------------------------- uint64_t get_pruned_transaction_weight(const transaction &tx) { CHECK_AND_ASSERT_MES(tx.pruned, std::numeric_limits::max(), ""get_pruned_transaction_weight does not support non pruned txes""); CHECK_AND_ASSERT_MES(tx.version >= 2, std::numeric_limits::max(), ""get_pruned_transaction_weight does not support v1 txes""); CHECK_AND_ASSERT_MES(tx.rct_signatures.type >= rct::RCTTypeBulletproof2, std::numeric_limits::max(), ""get_pruned_transaction_weight does not support older range proof types""); CHECK_AND_ASSERT_MES(!tx.vin.empty(), std::numeric_limits::max(), ""empty vin""); CHECK_AND_ASSERT_MES(tx.vin[0].type() == typeid(cryptonote::txin_to_key), std::numeric_limits::max(), ""empty vin""); // get pruned data size std::ostringstream s; binary_archive a(s); ::serialization::serialize(a, const_cast(tx)); uint64_t weight = s.str().size(), extra; // nbps (technically varint) weight += 1; // calculate deterministic bulletproofs size (assumes canonical BP format) size_t nrl = 0, n_padded_outputs; while ((n_padded_outputs = (1u << nrl)) < tx.vout.size()) ++nrl; nrl += 6; extra = 32 * (9 + 2 * nrl) + 2; weight += extra; // calculate deterministic MLSAG data size const size_t ring_size = boost::get(tx.vin[0]).key_offsets.size(); extra = tx.vin.size() * (ring_size * (1 + 1) * 32 + 32 /* cc */); weight += extra; // calculate deterministic pseudoOuts size extra = 32 * (tx.vin.size()); weight += extra; // clawback uint64_t bp_clawback = get_transaction_weight_clawback(tx, n_padded_outputs); CHECK_AND_ASSERT_THROW_MES_L1(bp_clawback <= std::numeric_limits::max() - weight, ""Weight overflow""); weight += bp_clawback; return weight; } //--------------------------------------------------------------- uint64_t get_transaction_weight(const transaction &tx) { size_t blob_size; if (tx.is_blob_size_valid()) { blob_size = tx.blob_size; } else { std::ostringstream s; binary_archive a(s); ::serialization::serialize(a, const_cast(tx)); blob_size = s.str().size(); } return get_transaction_weight(tx, blob_size); } //--------------------------------------------------------------- bool get_tx_fee(const transaction& tx, uint64_t & fee) { if (tx.version > 1) { fee = tx.rct_signatures.txnFee; return true; } uint64_t amount_in = 0; uint64_t amount_out = 0; for(auto& in: tx.vin) { CHECK_AND_ASSERT_MES(in.type() == typeid(txin_to_key), 0, ""unexpected type id in transaction""); amount_in += boost::get(in).amount; } for(auto& o: tx.vout) amount_out += o.amount; CHECK_AND_ASSERT_MES(amount_in >= amount_out, false, ""transaction spend ("" <& tx_extra, std::vector& tx_extra_fields) { tx_extra_fields.clear(); if(tx_extra.empty()) return true; std::string extra_str(reinterpret_cast(tx_extra.data()), tx_extra.size()); std::istringstream iss(extra_str); binary_archive ar(iss); bool eof = false; while (!eof) { tx_extra_field field; bool r = ::do_serialize(ar, field); CHECK_AND_NO_ASSERT_MES_L1(r, false, ""failed to deserialize extra field. extra = "" << string_tools::buff_to_hex_nodelimer(std::string(reinterpret_cast(tx_extra.data()), tx_extra.size()))); tx_extra_fields.push_back(field); std::ios_base::iostate state = iss.rdstate(); eof = (EOF == iss.peek()); iss.clear(state); } CHECK_AND_NO_ASSERT_MES_L1(::serialization::check_stream_state(ar), false, ""failed to deserialize extra field. extra = "" << string_tools::buff_to_hex_nodelimer(std::string(reinterpret_cast(tx_extra.data()), tx_extra.size()))); return true; } //--------------------------------------------------------------- template static bool pick(binary_archive &ar, std::vector &fields, uint8_t tag) { std::vector::iterator it; while ((it = std::find_if(fields.begin(), fields.end(), [](const tx_extra_field &f) { return f.type() == typeid(T); })) != fields.end()) { bool r = ::do_serialize(ar, tag); CHECK_AND_NO_ASSERT_MES_L1(r, false, ""failed to serialize tx extra field""); r = ::do_serialize(ar, boost::get(*it)); CHECK_AND_NO_ASSERT_MES_L1(r, false, ""failed to serialize tx extra field""); fields.erase(it); } return true; } //--------------------------------------------------------------- bool sort_tx_extra(const std::vector& tx_extra, std::vector &sorted_tx_extra, bool allow_partial) { std::vector tx_extra_fields; if(tx_extra.empty()) { sorted_tx_extra.clear(); return true; } std::string extra_str(reinterpret_cast(tx_extra.data()), tx_extra.size()); std::istringstream iss(extra_str); binary_archive ar(iss); bool eof = false; size_t processed = 0; while (!eof) { tx_extra_field field; bool r = ::do_serialize(ar, field); if (!r) { MWARNING(""failed to deserialize extra field. extra = "" << string_tools::buff_to_hex_nodelimer(std::string(reinterpret_cast(tx_extra.data()), tx_extra.size()))); if (!allow_partial) return false; break; } tx_extra_fields.push_back(field); processed = iss.tellg(); std::ios_base::iostate state = iss.rdstate(); eof = (EOF == iss.peek()); iss.clear(state); } if (!::serialization::check_stream_state(ar)) { MWARNING(""failed to deserialize extra field. extra = "" << string_tools::buff_to_hex_nodelimer(std::string(reinterpret_cast(tx_extra.data()), tx_extra.size()))); if (!allow_partial) return false; } MTRACE(""Sorted "" << processed << ""/"" << tx_extra.size()); std::ostringstream oss; binary_archive nar(oss); // sort by: if (!pick(nar, tx_extra_fields, TX_EXTRA_TAG_PUBKEY)) return false; if (!pick(nar, tx_extra_fields, TX_EXTRA_TAG_ADDITIONAL_PUBKEYS)) return false; if (!pick(nar, tx_extra_fields, TX_EXTRA_NONCE)) return false; if (!pick(nar, tx_extra_fields, TX_EXTRA_MERGE_MINING_TAG)) return false; if (!pick(nar, tx_extra_fields, TX_EXTRA_MYSTERIOUS_MINERGATE_TAG)) return false; if (!pick(nar, tx_extra_fields, TX_EXTRA_TAG_PADDING)) return false; // if not empty, someone added a new type and did not add a case above if (!tx_extra_fields.empty()) { MERROR(""tx_extra_fields not empty after sorting, someone forgot to add a case above""); return false; } std::string oss_str = oss.str(); if (allow_partial && processed < tx_extra.size()) { MDEBUG(""Appending unparsed data""); oss_str += std::string((const char*)tx_extra.data() + processed, tx_extra.size() - processed); } sorted_tx_extra = std::vector(oss_str.begin(), oss_str.end()); return true; } //--------------------------------------------------------------- crypto::public_key get_tx_pub_key_from_extra(const std::vector& tx_extra, size_t pk_index) { std::vector tx_extra_fields; parse_tx_extra(tx_extra, tx_extra_fields); tx_extra_pub_key pub_key_field; if(!find_tx_extra_field_by_type(tx_extra_fields, pub_key_field, pk_index)) return null_pkey; return pub_key_field.pub_key; } //--------------------------------------------------------------- crypto::public_key get_tx_pub_key_from_extra(const transaction_prefix& tx_prefix, size_t pk_index) { return get_tx_pub_key_from_extra(tx_prefix.extra, pk_index); } //--------------------------------------------------------------- crypto::public_key get_tx_pub_key_from_extra(const transaction& tx, size_t pk_index) { return get_tx_pub_key_from_extra(tx.extra, pk_index); } //--------------------------------------------------------------- bool add_tx_pub_key_to_extra(transaction& tx, const crypto::public_key& tx_pub_key) { return add_tx_pub_key_to_extra(tx.extra, tx_pub_key); } //--------------------------------------------------------------- bool add_tx_pub_key_to_extra(transaction_prefix& tx, const crypto::public_key& tx_pub_key) { return add_tx_pub_key_to_extra(tx.extra, tx_pub_key); } //--------------------------------------------------------------- bool add_tx_pub_key_to_extra(std::vector& tx_extra, const crypto::public_key& tx_pub_key) { tx_extra.resize(tx_extra.size() + 1 + sizeof(crypto::public_key)); tx_extra[tx_extra.size() - 1 - sizeof(crypto::public_key)] = TX_EXTRA_TAG_PUBKEY; *reinterpret_cast(&tx_extra[tx_extra.size() - sizeof(crypto::public_key)]) = tx_pub_key; return true; } //--------------------------------------------------------------- std::vector get_additional_tx_pub_keys_from_extra(const std::vector& tx_extra) { // parse std::vector tx_extra_fields; parse_tx_extra(tx_extra, tx_extra_fields); // find corresponding field tx_extra_additional_pub_keys additional_pub_keys; if(!find_tx_extra_field_by_type(tx_extra_fields, additional_pub_keys)) return {}; return additional_pub_keys.data; } //--------------------------------------------------------------- std::vector get_additional_tx_pub_keys_from_extra(const transaction_prefix& tx) { return get_additional_tx_pub_keys_from_extra(tx.extra); } //--------------------------------------------------------------- bool add_additional_tx_pub_keys_to_extra(std::vector& tx_extra, const std::vector& additional_pub_keys) { // convert to variant tx_extra_field field = tx_extra_additional_pub_keys{ additional_pub_keys }; // serialize std::ostringstream oss; binary_archive ar(oss); bool r = ::do_serialize(ar, field); CHECK_AND_NO_ASSERT_MES_L1(r, false, ""failed to serialize tx extra additional tx pub keys""); // append std::string tx_extra_str = oss.str(); size_t pos = tx_extra.size(); tx_extra.resize(tx_extra.size() + tx_extra_str.size()); memcpy(&tx_extra[pos], tx_extra_str.data(), tx_extra_str.size()); return true; } //--------------------------------------------------------------- bool add_extra_nonce_to_tx_extra(std::vector& tx_extra, const blobdata& extra_nonce) { CHECK_AND_ASSERT_MES(extra_nonce.size() <= TX_EXTRA_NONCE_MAX_COUNT, false, ""extra nonce could be 255 bytes max""); size_t start_pos = tx_extra.size(); tx_extra.resize(tx_extra.size() + 2 + extra_nonce.size()); //write tag tx_extra[start_pos] = TX_EXTRA_NONCE; //write len ++start_pos; tx_extra[start_pos] = static_cast(extra_nonce.size()); //write data ++start_pos; memcpy(&tx_extra[start_pos], extra_nonce.data(), extra_nonce.size()); return true; } //--------------------------------------------------------------- bool remove_field_from_tx_extra(std::vector& tx_extra, const std::type_info &type) { if (tx_extra.empty()) return true; std::string extra_str(reinterpret_cast(tx_extra.data()), tx_extra.size()); std::istringstream iss(extra_str); binary_archive ar(iss); std::ostringstream oss; binary_archive newar(oss); bool eof = false; while (!eof) { tx_extra_field field; bool r = ::do_serialize(ar, field); CHECK_AND_NO_ASSERT_MES_L1(r, false, ""failed to deserialize extra field. extra = "" << string_tools::buff_to_hex_nodelimer(std::string(reinterpret_cast(tx_extra.data()), tx_extra.size()))); if (field.type() != type) ::do_serialize(newar, field); std::ios_base::iostate state = iss.rdstate(); eof = (EOF == iss.peek()); iss.clear(state); } CHECK_AND_NO_ASSERT_MES_L1(::serialization::check_stream_state(ar), false, ""failed to deserialize extra field. extra = "" << string_tools::buff_to_hex_nodelimer(std::string(reinterpret_cast(tx_extra.data()), tx_extra.size()))); tx_extra.clear(); std::string s = oss.str(); tx_extra.reserve(s.size()); std::copy(s.begin(), s.end(), std::back_inserter(tx_extra)); return true; } //--------------------------------------------------------------- void set_payment_id_to_tx_extra_nonce(blobdata& extra_nonce, const crypto::hash& payment_id) { extra_nonce.clear(); extra_nonce.push_back(TX_EXTRA_NONCE_PAYMENT_ID); const uint8_t* payment_id_ptr = reinterpret_cast(&payment_id); std::copy(payment_id_ptr, payment_id_ptr + sizeof(payment_id), std::back_inserter(extra_nonce)); } //--------------------------------------------------------------- void set_encrypted_payment_id_to_tx_extra_nonce(blobdata& extra_nonce, const crypto::hash8& payment_id) { extra_nonce.clear(); extra_nonce.push_back(TX_EXTRA_NONCE_ENCRYPTED_PAYMENT_ID); const uint8_t* payment_id_ptr = reinterpret_cast(&payment_id); std::copy(payment_id_ptr, payment_id_ptr + sizeof(payment_id), std::back_inserter(extra_nonce)); } //--------------------------------------------------------------- bool get_payment_id_from_tx_extra_nonce(const blobdata& extra_nonce, crypto::hash& payment_id) { if(sizeof(crypto::hash) + 1 != extra_nonce.size()) return false; if(TX_EXTRA_NONCE_PAYMENT_ID != extra_nonce[0]) return false; payment_id = *reinterpret_cast(extra_nonce.data() + 1); return true; } //--------------------------------------------------------------- bool get_encrypted_payment_id_from_tx_extra_nonce(const blobdata& extra_nonce, crypto::hash8& payment_id) { if(sizeof(crypto::hash8) + 1 != extra_nonce.size()) return false; if (TX_EXTRA_NONCE_ENCRYPTED_PAYMENT_ID != extra_nonce[0]) return false; payment_id = *reinterpret_cast(extra_nonce.data() + 1); return true; } //--------------------------------------------------------------- bool get_inputs_money_amount(const transaction& tx, uint64_t& money) { money = 0; for(const auto& in: tx.vin) { CHECKED_GET_SPECIFIC_VARIANT(in, const txin_to_key, tokey_in, false); money += tokey_in.amount; } return true; } //--------------------------------------------------------------- uint64_t get_block_height(const block& b) { CHECK_AND_ASSERT_MES(b.miner_tx.vin.size() == 1, 0, ""wrong miner tx in block: "" << get_block_hash(b) << "", b.miner_tx.vin.size() != 1""); CHECKED_GET_SPECIFIC_VARIANT(b.miner_tx.vin[0], const txin_gen, coinbase_in, 0); return coinbase_in.height; } //--------------------------------------------------------------- bool check_inputs_types_supported(const transaction& tx) { for(const auto& in: tx.vin) { CHECK_AND_ASSERT_MES(in.type() == typeid(txin_to_key), false, ""wrong variant type: "" << in.type().name() << "", expected "" << typeid(txin_to_key).name() << "", in transaction id="" << get_transaction_hash(tx)); } return true; } //----------------------------------------------------------------------------------------------- bool check_outs_valid(const transaction& tx) { for(const tx_out& out: tx.vout) { CHECK_AND_ASSERT_MES(out.target.type() == typeid(txout_to_key), false, ""wrong variant type: "" << out.target.type().name() << "", expected "" << typeid(txout_to_key).name() << "", in transaction id="" << get_transaction_hash(tx)); if (tx.version == 1) { CHECK_AND_NO_ASSERT_MES(0 < out.amount, false, ""zero amount output in transaction id="" << get_transaction_hash(tx)); } if(!check_key(boost::get(out.target).key)) return false; } return true; } //----------------------------------------------------------------------------------------------- bool check_money_overflow(const transaction& tx) { return check_inputs_overflow(tx) && check_outs_overflow(tx); } //--------------------------------------------------------------- bool check_inputs_overflow(const transaction& tx) { uint64_t money = 0; for(const auto& in: tx.vin) { CHECKED_GET_SPECIFIC_VARIANT(in, const txin_to_key, tokey_in, false); if(money > tokey_in.amount + money) return false; money += tokey_in.amount; } return true; } //--------------------------------------------------------------- bool check_outs_overflow(const transaction& tx) { uint64_t money = 0; for(const auto& o: tx.vout) { if(money > o.amount + money) return false; money += o.amount; } return true; } //--------------------------------------------------------------- uint64_t get_outs_money_amount(const transaction& tx) { uint64_t outputs_amount = 0; for(const auto& o: tx.vout) outputs_amount += o.amount; return outputs_amount; } //--------------------------------------------------------------- std::string short_hash_str(const crypto::hash& h) { std::string res = string_tools::pod_to_hex(h); CHECK_AND_ASSERT_MES(res.size() == 64, res, ""wrong hash256 with string_tools::pod_to_hex conversion""); auto erased_pos = res.erase(8, 48); res.insert(8, ""....""); return res; } //--------------------------------------------------------------- bool is_out_to_acc(const account_keys& acc, const txout_to_key& out_key, const crypto::public_key& tx_pub_key, const std::vector& additional_tx_pub_keys, size_t output_index) { crypto::key_derivation derivation; bool r = acc.get_device().generate_key_derivation(tx_pub_key, acc.m_view_secret_key, derivation); CHECK_AND_ASSERT_MES(r, false, ""Failed to generate key derivation""); crypto::public_key pk; r = acc.get_device().derive_public_key(derivation, output_index, acc.m_account_address.m_spend_public_key, pk); CHECK_AND_ASSERT_MES(r, false, ""Failed to derive public key""); if (pk == out_key.key) return true; // try additional tx pubkeys if available if (!additional_tx_pub_keys.empty()) { CHECK_AND_ASSERT_MES(output_index < additional_tx_pub_keys.size(), false, ""wrong number of additional tx pubkeys""); r = acc.get_device().generate_key_derivation(additional_tx_pub_keys[output_index], acc.m_view_secret_key, derivation); CHECK_AND_ASSERT_MES(r, false, ""Failed to generate key derivation""); r = acc.get_device().derive_public_key(derivation, output_index, acc.m_account_address.m_spend_public_key, pk); CHECK_AND_ASSERT_MES(r, false, ""Failed to derive public key""); return pk == out_key.key; } return false; } //--------------------------------------------------------------- boost::optional is_out_to_acc_precomp(const std::unordered_map& subaddresses, const crypto::public_key& out_key, const crypto::key_derivation& derivation, const std::vector& additional_derivations, size_t output_index, hw::device &hwdev) { // try the shared tx pubkey crypto::public_key subaddress_spendkey; hwdev.derive_subaddress_public_key(out_key, derivation, output_index, subaddress_spendkey); auto found = subaddresses.find(subaddress_spendkey); if (found != subaddresses.end()) return subaddress_receive_info{ found->second, derivation }; // try additional tx pubkeys if available if (!additional_derivations.empty()) { CHECK_AND_ASSERT_MES(output_index < additional_derivations.size(), boost::none, ""wrong number of additional derivations""); hwdev.derive_subaddress_public_key(out_key, additional_derivations[output_index], output_index, subaddress_spendkey); found = subaddresses.find(subaddress_spendkey); if (found != subaddresses.end()) return subaddress_receive_info{ found->second, additional_derivations[output_index] }; } return boost::none; } //--------------------------------------------------------------- bool lookup_acc_outs(const account_keys& acc, const transaction& tx, std::vector& outs, uint64_t& money_transfered) { crypto::public_key tx_pub_key = get_tx_pub_key_from_extra(tx); if(null_pkey == tx_pub_key) return false; std::vector additional_tx_pub_keys = get_additional_tx_pub_keys_from_extra(tx); return lookup_acc_outs(acc, tx, tx_pub_key, additional_tx_pub_keys, outs, money_transfered); } //--------------------------------------------------------------- bool lookup_acc_outs(const account_keys& acc, const transaction& tx, const crypto::public_key& tx_pub_key, const std::vector& additional_tx_pub_keys, std::vector& outs, uint64_t& money_transfered) { CHECK_AND_ASSERT_MES(additional_tx_pub_keys.empty() || additional_tx_pub_keys.size() == tx.vout.size(), false, ""wrong number of additional pubkeys"" ); money_transfered = 0; size_t i = 0; for(const tx_out& o: tx.vout) { CHECK_AND_ASSERT_MES(o.target.type() == typeid(txout_to_key), false, ""wrong type id in transaction out"" ); if(is_out_to_acc(acc, boost::get(o.target), tx_pub_key, additional_tx_pub_keys, i)) { outs.push_back(i); money_transfered += o.amount; } i++; } return true; } //--------------------------------------------------------------- void get_blob_hash(const epee::span& blob, crypto::hash& res) { cn_fast_hash(blob.data(), blob.size(), res); } //--------------------------------------------------------------- void get_blob_hash(const blobdata& blob, crypto::hash& res) { cn_fast_hash(blob.data(), blob.size(), res); } //--------------------------------------------------------------- void set_default_decimal_point(unsigned int decimal_point) { switch (decimal_point) { case 12: case 9: case 6: case 3: case 0: default_decimal_point = decimal_point; break; default: ASSERT_MES_AND_THROW(""Invalid decimal point specification: "" << decimal_point); } } //--------------------------------------------------------------- unsigned int get_default_decimal_point() { return default_decimal_point; } //--------------------------------------------------------------- std::string get_unit(unsigned int decimal_point) { if (decimal_point == (unsigned int)-1) decimal_point = default_decimal_point; switch (decimal_point) { case 12: return ""crypto""; case 6: return ""cryptini""; case 0: return ""atoms""; default: ASSERT_MES_AND_THROW(""Invalid decimal point specification: "" << decimal_point); } } //--------------------------------------------------------------- static void insert_money_decimal_point(std::string &s, unsigned int decimal_point) { if (decimal_point == (unsigned int)-1) decimal_point = default_decimal_point; if(s.size() < decimal_point+1) { s.insert(0, decimal_point+1 - s.size(), '0'); } if (decimal_point > 0) s.insert(s.size() - decimal_point, "".""); } //--------------------------------------------------------------- std::string print_money(uint64_t amount, unsigned int decimal_point) { std::string s = std::to_string(amount); insert_money_decimal_point(s, decimal_point); return s; } //--------------------------------------------------------------- std::string print_money(const boost::multiprecision::uint128_t &amount, unsigned int decimal_point) { std::stringstream ss; ss << amount; std::string s = ss.str(); insert_money_decimal_point(s, decimal_point); return s; } //--------------------------------------------------------------- crypto::hash get_blob_hash(const blobdata& blob) { crypto::hash h = null_hash; get_blob_hash(blob, h); return h; } //--------------------------------------------------------------- crypto::hash get_blob_hash(const epee::span& blob) { crypto::hash h = null_hash; get_blob_hash(blob, h); return h; } //--------------------------------------------------------------- crypto::hash get_transaction_hash(const transaction& t) { crypto::hash h = null_hash; get_transaction_hash(t, h, NULL); CHECK_AND_ASSERT_THROW_MES(get_transaction_hash(t, h, NULL), ""Failed to calculate transaction hash""); return h; } //--------------------------------------------------------------- bool get_transaction_hash(const transaction& t, crypto::hash& res) { return get_transaction_hash(t, res, NULL); } //--------------------------------------------------------------- bool calculate_transaction_prunable_hash(const transaction& t, const cryptonote::blobdata *blob, crypto::hash& res) { if (t.version == 1) return false; const unsigned int unprunable_size = t.unprunable_size; if (blob && unprunable_size) { CHECK_AND_ASSERT_MES(unprunable_size <= blob->size(), false, ""Inconsistent transaction unprunable and blob sizes""); cryptonote::get_blob_hash(epee::span(blob->data() + unprunable_size, blob->size() - unprunable_size), res); } else { transaction &tt = const_cast(t); std::stringstream ss; binary_archive ba(ss); const size_t inputs = t.vin.size(); const size_t outputs = t.vout.size(); const size_t mixin = t.vin.empty() ? 0 : t.vin[0].type() == typeid(txin_to_key) ? boost::get(t.vin[0]).key_offsets.size() - 1 : 0; bool r = tt.rct_signatures.p.serialize_rctsig_prunable(ba, t.rct_signatures.type, inputs, outputs, mixin); CHECK_AND_ASSERT_MES(r, false, ""Failed to serialize rct signatures prunable""); cryptonote::get_blob_hash(ss.str(), res); } return true; } //--------------------------------------------------------------- crypto::hash get_transaction_prunable_hash(const transaction& t, const cryptonote::blobdata *blobdata) { crypto::hash res; if (t.is_prunable_hash_valid()) { #ifdef ENABLE_HASH_CASH_INTEGRITY_CHECK CHECK_AND_ASSERT_THROW_MES(!calculate_transaction_prunable_hash(t, blobdata, res) || t.hash == res, ""tx hash cash integrity failure""); #endif res = t.prunable_hash; ++tx_hashes_cached_count; return res; } ++tx_hashes_calculated_count; CHECK_AND_ASSERT_THROW_MES(calculate_transaction_prunable_hash(t, blobdata, res), ""Failed to calculate tx prunable hash""); t.set_prunable_hash(res); return res; } //--------------------------------------------------------------- crypto::hash get_pruned_transaction_hash(const transaction& t, const crypto::hash &pruned_data_hash) { // v1 transactions hash the entire blob CHECK_AND_ASSERT_THROW_MES(t.version > 1, ""Hash for pruned v1 tx cannot be calculated""); // v2 transactions hash different parts together, than hash the set of those hashes crypto::hash hashes[3]; // prefix get_transaction_prefix_hash(t, hashes[0]); transaction &tt = const_cast(t); // base rct { std::stringstream ss; binary_archive ba(ss); const size_t inputs = t.vin.size(); const size_t outputs = t.vout.size(); bool r = tt.rct_signatures.serialize_rctsig_base(ba, inputs, outputs); CHECK_AND_ASSERT_THROW_MES(r, ""Failed to serialize rct signatures base""); cryptonote::get_blob_hash(ss.str(), hashes[1]); } // prunable rct if (t.rct_signatures.type == rct::RCTTypeNull) hashes[2] = crypto::null_hash; else hashes[2] = pruned_data_hash; // the tx hash is the hash of the 3 hashes crypto::hash res = cn_fast_hash(hashes, sizeof(hashes)); t.set_hash(res); return res; } //--------------------------------------------------------------- bool calculate_transaction_hash(const transaction& t, crypto::hash& res, size_t* blob_size) { CHECK_AND_ASSERT_MES(!t.pruned, false, ""Cannot calculate the hash of a pruned transaction""); // v1 transactions hash the entire blob if (t.version == 1) { size_t ignored_blob_size, &blob_size_ref = blob_size ? *blob_size : ignored_blob_size; return get_object_hash(t, res, blob_size_ref); } // v2 transactions hash different parts together, than hash the set of those hashes crypto::hash hashes[3]; // prefix get_transaction_prefix_hash(t, hashes[0]); const blobdata blob = tx_to_blob(t); const unsigned int unprunable_size = t.unprunable_size; const unsigned int prefix_size = t.prefix_size; // base rct CHECK_AND_ASSERT_MES(prefix_size <= unprunable_size && unprunable_size <= blob.size(), false, ""Inconsistent transaction prefix, unprunable and blob sizes""); cryptonote::get_blob_hash(epee::span(blob.data() + prefix_size, unprunable_size - prefix_size), hashes[1]); // prunable rct if (t.rct_signatures.type == rct::RCTTypeNull) { hashes[2] = crypto::null_hash; } else { CHECK_AND_ASSERT_MES(calculate_transaction_prunable_hash(t, &blob, hashes[2]), false, ""Failed to get tx prunable hash""); } // the tx hash is the hash of the 3 hashes res = cn_fast_hash(hashes, sizeof(hashes)); // we still need the size if (blob_size) { if (!t.is_blob_size_valid()) { t.set_blob_size(blob.size()); } *blob_size = t.blob_size; } return true; } //--------------------------------------------------------------- bool get_transaction_hash(const transaction& t, crypto::hash& res, size_t* blob_size) { if (t.is_hash_valid()) { #ifdef ENABLE_HASH_CASH_INTEGRITY_CHECK CHECK_AND_ASSERT_THROW_MES(!calculate_transaction_hash(t, res, blob_size) || t.hash == res, ""tx hash cash integrity failure""); #endif res = t.hash; if (blob_size) { if (!t.is_blob_size_valid()) { t.set_blob_size(get_object_blobsize(t)); } *blob_size = t.blob_size; } ++tx_hashes_cached_count; return true; } ++tx_hashes_calculated_count; bool ret = calculate_transaction_hash(t, res, blob_size); if (!ret) return false; t.set_hash(res); if (blob_size) { t.set_blob_size(*blob_size); } return true; } //--------------------------------------------------------------- bool get_transaction_hash(const transaction& t, crypto::hash& res, size_t& blob_size) { return get_transaction_hash(t, res, &blob_size); } //--------------------------------------------------------------- blobdata get_block_hashing_blob(const block& b) { blobdata blob; if(b.major_version < HF_VERSION_CUCKOO) { blob = t_serializable_object_to_blob(static_cast(b)); } else { blob = t_serializable_object_to_blob(b.major_version); blob.append(reinterpret_cast(&b.minor_version), sizeof(b.minor_version)); blob.append(reinterpret_cast(&b.timestamp), sizeof(b.timestamp)); blob.append(reinterpret_cast(&b.prev_id), sizeof(b.prev_id)); } crypto::hash tree_root_hash = get_tx_tree_hash(b); blob.append(reinterpret_cast(&tree_root_hash), sizeof(tree_root_hash)); blob.append(tools::get_varint_data(b.tx_hashes.size()+1)); if (b.major_version >= HF_VERSION_NONCE8) { blob.append(reinterpret_cast(&b.nonce8), sizeof(b.nonce8)); } return blob; } //--------------------------------------------------------------- bool calculate_block_hash(const block& b, crypto::hash& res, const blobdata *blob) { bool hash_result = get_object_hash(get_block_hashing_blob(b), res); if (!hash_result) return false; return hash_result; } //--------------------------------------------------------------- bool get_block_hash(const block& b, crypto::hash& res) { if (b.is_hash_valid()) { #ifdef ENABLE_HASH_CASH_INTEGRITY_CHECK CHECK_AND_ASSERT_THROW_MES(!calculate_block_hash(b, res) || b.hash == res, ""block hash cash integrity failure""); #endif res = b.hash; ++block_hashes_cached_count; return true; } ++block_hashes_calculated_count; bool ret = calculate_block_hash(b, res); if (!ret) return false; b.set_hash(res); return true; } //--------------------------------------------------------------- crypto::hash get_block_hash(const block& b) { crypto::hash p = null_hash; get_block_hash(b, p); return p; } //--------------------------------------------------------------- std::vector relative_output_offsets_to_absolute(const std::vector& off) { std::vector res = off; for(size_t i = 1; i < res.size(); i++) res[i] += res[i-1]; return res; } //--------------------------------------------------------------- std::vector absolute_output_offsets_to_relative(const std::vector& off) { std::vector res = off; if(!off.size()) return res; std::sort(res.begin(), res.end());//just to be sure, actually it is already should be sorted for(size_t i = res.size()-1; i != 0; i--) res[i] -= res[i-1]; return res; } //--------------------------------------------------------------- bool parse_and_validate_block_from_blob(const blobdata& b_blob, block& b, crypto::hash *block_hash) { std::stringstream ss; ss << b_blob; binary_archive ba(ss); bool r = ::serialization::serialize(ba, b); CHECK_AND_ASSERT_MES(r, false, ""Failed to parse block from blob""); b.invalidate_hashes(); b.miner_tx.invalidate_hashes(); if (block_hash) { calculate_block_hash(b, *block_hash, &b_blob); ++block_hashes_calculated_count; b.set_hash(*block_hash); } return true; } //--------------------------------------------------------------- bool parse_and_validate_block_from_blob(const blobdata& b_blob, block& b) { return parse_and_validate_block_from_blob(b_blob, b, NULL); } //--------------------------------------------------------------- bool parse_and_validate_block_from_blob(const blobdata& b_blob, block& b, crypto::hash &block_hash) { return parse_and_validate_block_from_blob(b_blob, b, &block_hash); } //--------------------------------------------------------------- blobdata block_to_blob(const block& b) { return t_serializable_object_to_blob(b); } //--------------------------------------------------------------- bool block_to_blob(const block& b, blobdata& b_blob) { return t_serializable_object_to_blob(b, b_blob); } //--------------------------------------------------------------- blobdata tx_to_blob(const transaction& tx) { return t_serializable_object_to_blob(tx); } //--------------------------------------------------------------- bool tx_to_blob(const transaction& tx, blobdata& b_blob) { return t_serializable_object_to_blob(tx, b_blob); } //--------------------------------------------------------------- void get_tx_tree_hash(const std::vector& tx_hashes, crypto::hash& h) { tree_hash(tx_hashes.data(), tx_hashes.size(), h); } //--------------------------------------------------------------- crypto::hash get_tx_tree_hash(const std::vector& tx_hashes) { crypto::hash h = null_hash; get_tx_tree_hash(tx_hashes, h); return h; } //--------------------------------------------------------------- crypto::hash get_tx_tree_hash(const block& b) { std::vector txs_ids; txs_ids.reserve(1 + b.tx_hashes.size()); crypto::hash h = null_hash; size_t bl_sz = 0; CHECK_AND_ASSERT_THROW_MES(get_transaction_hash(b.miner_tx, h, bl_sz), ""Failed to calculate transaction hash""); txs_ids.push_back(h); for(auto& th: b.tx_hashes) txs_ids.push_back(th); return get_tx_tree_hash(txs_ids); } //--------------------------------------------------------------- bool is_valid_decomposed_amount(uint64_t amount) { const uint64_t *begin = valid_decomposed_outputs; const uint64_t *end = valid_decomposed_outputs + sizeof(valid_decomposed_outputs) / sizeof(valid_decomposed_outputs[0]); return std::binary_search(begin, end, amount); } //--------------------------------------------------------------- void get_hash_stats(uint64_t &tx_hashes_calculated, uint64_t &tx_hashes_cached, uint64_t &block_hashes_calculated, uint64_t & block_hashes_cached) { tx_hashes_calculated = tx_hashes_calculated_count; tx_hashes_cached = tx_hashes_cached_count; block_hashes_calculated = block_hashes_calculated_count; block_hashes_cached = block_hashes_cached_count; } //--------------------------------------------------------------- crypto::secret_key encrypt_key(crypto::secret_key key, const epee::wipeable_string &passphrase) { crypto::hash hash; crypto::cn_slow_hash(passphrase.data(), passphrase.size(), hash); sc_add((unsigned char*)key.data, (const unsigned char*)key.data, (const unsigned char*)hash.data); return key; } //--------------------------------------------------------------- crypto::secret_key decrypt_key(crypto::secret_key key, const epee::wipeable_string &passphrase) { crypto::hash hash; crypto::cn_slow_hash(passphrase.data(), passphrase.size(), hash); sc_sub((unsigned char*)key.data, (const unsigned char*)key.data, (const unsigned char*)hash.data); return key; } } ",16282,True,2710.4581367145156,median "// // Copyright (c) 2017-2018 Advanced Micro Devices, Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the ""Software""), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include ""misc/buffer_create_info.h"" #include ""misc/debug.h"" #include ""misc/formats.h"" #include ""misc/image_create_info.h"" #include ""misc/memory_block_create_info.h"" #include ""misc/object_tracker.h"" #include ""misc/struct_chainer.h"" #include ""misc/swapchain_create_info.h"" #include ""wrappers/buffer.h"" #include ""wrappers/command_buffer.h"" #include ""wrappers/command_pool.h"" #include ""wrappers/device.h"" #include ""wrappers/image.h"" #include ""wrappers/memory_block.h"" #include ""wrappers/physical_device.h"" #include ""wrappers/queue.h"" #include ""wrappers/swapchain.h"" #include #ifdef max #undef max #endif #ifdef min #undef min #endif /* Please see header for specification */ Anvil::Image::Image(Anvil::ImageCreateInfoUniquePtr in_create_info_ptr) :CallbacksSupportProvider (IMAGE_CALLBACK_ID_COUNT), DebugMarkerSupportProvider (in_create_info_ptr->get_device(), VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT), MTSafetySupportProvider (Anvil::Utils::convert_mt_safety_enum_to_boolean(in_create_info_ptr->get_mt_safety(), in_create_info_ptr->get_device () )), m_alignment (UINT64_MAX), m_has_transitioned_to_post_alloc_layout(false), m_image (VK_NULL_HANDLE), m_memory_types (0), m_n_mipmaps (0), m_storage_size (0), m_swapchain_memory_assigned (false) { m_create_info_ptr = std::move(in_create_info_ptr); /* Register this instance */ Anvil::ObjectTracker::get()->register_object(Anvil::OBJECT_TYPE_IMAGE, this); } /** Please see header for specification */ void Anvil::Image::change_image_layout(Anvil::Queue* in_queue_ptr, VkAccessFlags in_src_access_mask, VkImageLayout in_src_layout, VkAccessFlags in_dst_access_mask, VkImageLayout in_dst_layout, const VkImageSubresourceRange& in_subresource_range, const uint32_t in_opt_n_wait_semaphores, const VkPipelineStageFlags* in_opt_wait_dst_stage_mask_ptrs, Anvil::Semaphore* const* in_opt_wait_semaphore_ptrs, const uint32_t in_opt_n_set_semaphores, Anvil::Semaphore* const* in_opt_set_semaphore_ptrs) { const Anvil::DeviceType device_type (m_device_ptr->get_type() ); const uint32_t in_queue_family_index (in_queue_ptr->get_queue_family_index() ); auto mem_block_ptr (get_memory_block() ); Anvil::PrimaryCommandBufferUniquePtr transition_command_buffer_ptr; /* mem_block_ptr is only used here in order to trigger memory allocator bakes if there are any pending. Other than that, * we are not going to be accessing it in this func. */ ANVIL_REDUNDANT_VARIABLE(mem_block_ptr); transition_command_buffer_ptr = m_device_ptr->get_command_pool_for_queue_family_index(in_queue_ptr->get_queue_family_index())->alloc_primary_level_command_buffer(); transition_command_buffer_ptr->start_recording(true, /* one_time_submit */ false); /* simultaneous_use_allowed */ { const auto sharing_mode (m_create_info_ptr->get_sharing_mode() ); const auto queue_fam_index((sharing_mode == VK_SHARING_MODE_CONCURRENT) ? VK_QUEUE_FAMILY_IGNORED : in_queue_family_index); Anvil::ImageBarrier image_barrier (in_src_access_mask, in_dst_access_mask, true, /* in_by_region_barrier */ in_src_layout, in_dst_layout, queue_fam_index, queue_fam_index, this, in_subresource_range); transition_command_buffer_ptr->record_pipeline_barrier(VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_FALSE, /* in_by_region */ 0, /* in_memory_barrier_count */ nullptr, /* in_memory_barrier_ptrs */ 0, /* in_buffer_memory_barrier_count */ nullptr, /* in_buffer_memory_barrier_ptrs */ 1, /* in_image_memory_barrier_count */ &image_barrier); } transition_command_buffer_ptr->stop_recording(); if (device_type == Anvil::DEVICE_TYPE_SINGLE_GPU) { Anvil::CommandBufferBase* cmd_buffer_ptr = transition_command_buffer_ptr.get(); in_queue_ptr->submit( Anvil::SubmitInfo::create(1, /* in_n_cmd_bufers */ &cmd_buffer_ptr, in_opt_n_set_semaphores, in_opt_set_semaphore_ptrs, in_opt_n_wait_semaphores, in_opt_wait_semaphore_ptrs, in_opt_wait_dst_stage_mask_ptrs, true /* should_block */) ); } } /** Please see header for specification */ Anvil::ImageUniquePtr Anvil::Image::create(Anvil::ImageCreateInfoUniquePtr in_create_info_ptr) { ImageUniquePtr result_ptr(new Image(std::move(in_create_info_ptr) ), std::default_delete() ); if (result_ptr != nullptr) { const auto image_type = result_ptr->m_create_info_ptr->get_type(); switch (image_type) { case Anvil::ImageType::NONSPARSE_ALLOC: case Anvil::ImageType::NONSPARSE_NO_ALLOC: case Anvil::ImageType::SPARSE_NO_ALLOC: { if (!result_ptr->init() ) { result_ptr.reset(); } break; } case Anvil::ImageType::SWAPCHAIN_WRAPPER: { result_ptr->m_image = result_ptr->m_create_info_ptr->get_swapchain_image(); result_ptr->m_memory_types = 0; result_ptr->m_n_mipmaps = 1; result_ptr->m_storage_size = 0; anvil_assert(result_ptr->m_image != VK_NULL_HANDLE); result_ptr->init_mipmap_props(); break; } default: { anvil_assert_fail(); result_ptr.reset(); } } } return result_ptr; } /** Please see header for specification */ bool Anvil::Image::get_aspect_subresource_layout(VkImageAspectFlags in_aspect, uint32_t in_n_layer, uint32_t in_n_mip, VkSubresourceLayout* out_subresource_layout_ptr) const { auto aspect_iterator = m_aspects.find(static_cast(in_aspect) ); bool result = false; anvil_assert(m_create_info_ptr->get_tiling() == VK_IMAGE_TILING_LINEAR); if (aspect_iterator != m_aspects.end() ) { auto layer_mip_iterator = aspect_iterator->second.find(LayerMipKey(in_n_layer, in_n_mip) ); if (layer_mip_iterator != aspect_iterator->second.end() ) { *out_subresource_layout_ptr = layer_mip_iterator->second; result = true; } } return result; } /** Please see header for specification */ Anvil::MemoryBlock* Anvil::Image::get_memory_block() { bool is_callback_needed = false; const auto is_sparse = (m_create_info_ptr->get_type() == Anvil::ImageType::SPARSE_NO_ALLOC); if (is_sparse) { IsImageMemoryAllocPendingQueryCallbackArgument callback_arg(this); callback(IMAGE_CALLBACK_ID_IS_ALLOC_PENDING, &callback_arg); is_callback_needed = callback_arg.result; } else if (m_memory_blocks_owned.size() == 0) { is_callback_needed = true; } if (is_callback_needed) { OnMemoryBlockNeededForImageCallbackArgument callback_argument(this); callback_safe(IMAGE_CALLBACK_ID_MEMORY_BLOCK_NEEDED, &callback_argument); } if (is_sparse) { if (m_create_info_ptr->get_residency_scope() == Anvil::SPARSE_RESIDENCY_SCOPE_NONE) { anvil_assert(m_page_tracker_ptr != nullptr); return m_page_tracker_ptr->get_memory_block(0); } else { /* More than just one memory block may exist. You need to use page tracker manually. */ return nullptr; } } else { return (m_memory_blocks_owned.size() > 0) ? m_memory_blocks_owned.at(0).get() : nullptr; } } /** Private function which initializes the Image instance. * * For argument discussion, please see documentation of the constructors. **/ bool Anvil::Image::init() { std::vector aspects_used; VkImageCreateFlags image_flags = 0; Anvil::ImageFormatProperties image_format_props; const auto memory_features = m_create_info_ptr->get_memory_features(); uint32_t n_queue_family_indices = 0; uint32_t queue_family_indices[3]; VkResult result = VK_ERROR_INITIALIZATION_FAILED; bool result_bool = true; Anvil::StructChainer struct_chainer; if ((memory_features & MEMORY_FEATURE_FLAG_MAPPABLE) == 0) { anvil_assert((memory_features & MEMORY_FEATURE_FLAG_HOST_COHERENT) == 0); } if (m_create_info_ptr->get_mipmaps_to_upload().size() > 0) { m_create_info_ptr->set_usage_flags(m_create_info_ptr->get_usage_flags() | VK_IMAGE_USAGE_TRANSFER_DST_BIT); } if (m_create_info_ptr->get_type() == Anvil::ImageType::SWAPCHAIN_WRAPPER && m_create_info_ptr->get_swapchain()->get_create_info_ptr()->get_flags() & VK_SWAPCHAIN_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR) { anvil_assert(!m_create_info_ptr->uses_full_mipmap_chain() ); anvil_assert(m_create_info_ptr->get_n_layers () == 1); anvil_assert(m_create_info_ptr->get_type_vk () == VK_IMAGE_TYPE_2D); anvil_assert(m_create_info_ptr->get_tiling () == VK_IMAGE_TILING_OPTIMAL); } /* Form the queue family array */ Anvil::Utils::convert_queue_family_bits_to_family_indices(m_device_ptr, m_create_info_ptr->get_queue_families(), queue_family_indices, &n_queue_family_indices); /* Is the requested texture size valid? */ if (!m_device_ptr->get_physical_device_image_format_properties(Anvil::ImageFormatPropertiesQuery(m_create_info_ptr->get_format (), m_create_info_ptr->get_type_vk (), m_create_info_ptr->get_tiling (), m_create_info_ptr->get_usage_flags (), m_create_info_ptr->get_create_flags() ), &image_format_props) ) { anvil_assert_fail(); goto end; } anvil_assert(m_create_info_ptr->get_base_mip_width() <= image_format_props.max_extent.width); if (m_create_info_ptr->get_base_mip_height() > 1) { anvil_assert(m_create_info_ptr->get_base_mip_height() <= image_format_props.max_extent.height); } if (m_create_info_ptr->get_base_mip_depth() > 1) { anvil_assert(m_create_info_ptr->get_base_mip_depth() <= image_format_props.max_extent.depth); } anvil_assert(m_create_info_ptr->get_n_layers() >= 1); if (m_create_info_ptr->get_n_layers() > 1) { anvil_assert(m_create_info_ptr->get_n_layers() <= image_format_props.n_max_array_layers); } /* If multisample image is requested, make sure the number of samples is supported. */ anvil_assert(m_create_info_ptr->get_sample_count() >= 1); if (m_create_info_ptr->get_sample_count() > 1) { anvil_assert((image_format_props.sample_counts & m_create_info_ptr->get_sample_count() ) != 0); } /* Create the image object */ if ( (m_create_info_ptr->get_create_flags() & Anvil::IMAGE_CREATE_FLAG_CUBE_COMPATIBLE_BIT) != 0) { anvil_assert(m_create_info_ptr->get_type_vk() == VK_IMAGE_TYPE_2D); anvil_assert((m_create_info_ptr->get_n_layers() % 6) == 0); image_flags |= VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT; } if ( (m_create_info_ptr->get_create_flags() & Anvil::IMAGE_CREATE_FLAG_MUTABLE_FORMAT_BIT) != 0) { image_flags |= VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT; } if ( (m_create_info_ptr->get_create_flags() & Anvil::IMAGE_CREATE_FLAG_2D_ARRAY_COMPATIBLE_BIT) != 0) { anvil_assert(m_device_ptr->get_extension_info()->khr_maintenance1() ); anvil_assert(m_create_info_ptr->get_type_vk() == VK_IMAGE_TYPE_3D); image_flags |= VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT_KHR; } if (m_create_info_ptr->get_type() == Anvil::ImageType::SWAPCHAIN_WRAPPER) { if (m_create_info_ptr->get_swapchain()->get_create_info_ptr()->get_flags() & VK_SWAPCHAIN_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR) { image_flags |= VK_IMAGE_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR; } } if (m_create_info_ptr->get_type() == Anvil::ImageType::SPARSE_NO_ALLOC) { /* Convert residency scope to Vulkan image create flags */ switch (m_create_info_ptr->get_residency_scope() ) { case Anvil::SPARSE_RESIDENCY_SCOPE_ALIASED: image_flags |= VK_IMAGE_CREATE_SPARSE_ALIASED_BIT | VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT | VK_IMAGE_CREATE_SPARSE_BINDING_BIT; break; case Anvil::SPARSE_RESIDENCY_SCOPE_NONALIASED: image_flags |= VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT | VK_IMAGE_CREATE_SPARSE_BINDING_BIT; break; case Anvil::SPARSE_RESIDENCY_SCOPE_NONE: image_flags |= VK_IMAGE_CREATE_SPARSE_BINDING_BIT; break; default: { anvil_assert_fail(); } } } { const auto max_dimension = std::max(std::max(m_create_info_ptr->get_base_mip_depth(), m_create_info_ptr->get_base_mip_height() ), m_create_info_ptr->get_base_mip_width() ); m_n_mipmaps = static_cast((m_create_info_ptr->uses_full_mipmap_chain() ) ? (1 + log2(max_dimension)) : 1); } { VkImageCreateInfo image_create_info; image_create_info.arrayLayers = m_create_info_ptr->get_n_layers (); image_create_info.extent.depth = m_create_info_ptr->get_base_mip_depth (); image_create_info.extent.height = m_create_info_ptr->get_base_mip_height(); image_create_info.extent.width = m_create_info_ptr->get_base_mip_width (); image_create_info.flags = image_flags; image_create_info.format = m_create_info_ptr->get_format (); image_create_info.imageType = m_create_info_ptr->get_type_vk (); image_create_info.initialLayout = m_create_info_ptr->get_post_create_image_layout(); image_create_info.mipLevels = m_n_mipmaps; image_create_info.pNext = nullptr; image_create_info.pQueueFamilyIndices = queue_family_indices; image_create_info.queueFamilyIndexCount = n_queue_family_indices; image_create_info.samples = static_cast(m_create_info_ptr->get_sample_count() ); image_create_info.sharingMode = m_create_info_ptr->get_sharing_mode(); image_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; image_create_info.tiling = m_create_info_ptr->get_tiling (); image_create_info.usage = m_create_info_ptr->get_usage_flags(); if (m_create_info_ptr->get_external_memory_handle_types() != 0) { anvil_assert(image_create_info.initialLayout == VK_IMAGE_LAYOUT_UNDEFINED); } struct_chainer.append_struct(image_create_info); } if (m_create_info_ptr->get_external_memory_handle_types() != 0) { VkExternalMemoryImageCreateInfoKHR external_memory_image_create_info; const auto handle_types = m_create_info_ptr->get_external_memory_handle_types(); external_memory_image_create_info.handleTypes = Anvil::Utils::convert_external_memory_handle_type_bits_to_vk_external_memory_handle_type_flags(handle_types); external_memory_image_create_info.pNext = nullptr; external_memory_image_create_info.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO_KHR; struct_chainer.append_struct(external_memory_image_create_info); } { auto struct_chain_ptr = struct_chainer.create_chain(); result = vkCreateImage(m_device_ptr->get_device_vk(), struct_chain_ptr->get_root_struct(), nullptr, /* pAllocator */ &m_image); } if (!is_vk_call_successful(result) ) { anvil_assert_vk_call_succeeded(result); result_bool = false; goto end; } set_vk_handle(m_image); if (m_create_info_ptr->get_type() != Anvil::ImageType::SWAPCHAIN_WRAPPER) { /* Extract various image properties we're going to need later */ vkGetImageMemoryRequirements(m_device_ptr->get_device_vk(), m_image, &m_memory_reqs); m_alignment = m_memory_reqs.alignment; m_memory_types = m_memory_reqs.memoryTypeBits; m_storage_size = m_memory_reqs.size; } /* Cache aspect subresource properties if we're dealing with a linear image */ if (m_create_info_ptr->get_tiling() == VK_IMAGE_TILING_LINEAR) { const auto n_layers = m_create_info_ptr->get_n_layers(); Anvil::Formats::get_format_aspects(m_create_info_ptr->get_format(), &aspects_used); for (const auto& current_aspect : aspects_used) { VkImageSubresource subresource; subresource.aspectMask = current_aspect; for (uint32_t n_layer = 0; n_layer < n_layers; ++n_layer) { subresource.arrayLayer = n_layer; for (uint32_t n_mip = 0; n_mip < m_n_mipmaps; ++n_mip) { VkSubresourceLayout subresource_layout; subresource.mipLevel = n_mip; vkGetImageSubresourceLayout(m_device_ptr->get_device_vk(), m_image, &subresource, &subresource_layout); m_aspects[static_cast(current_aspect)][LayerMipKey(n_layer, n_mip)] = subresource_layout; } } } } /* Initialize mipmap props storage */ init_mipmap_props(); if (m_create_info_ptr->get_residency_scope() == SPARSE_RESIDENCY_SCOPE_ALIASED || m_create_info_ptr->get_residency_scope() == SPARSE_RESIDENCY_SCOPE_NONALIASED) { uint32_t n_reqs = 0; std::vector sparse_image_memory_reqs; anvil_assert(m_create_info_ptr->get_type() != Anvil::ImageType::SWAPCHAIN_WRAPPER); /* TODO: can images, to which swapchains can be bound, be sparse? */ /* Retrieve image aspect properties. Since Vulkan lets a single props structure to refer to more than * just a single aspect, we first cache the exposed info in a vec and then distribute the information to * a map, whose key is allowed to consist of a single bit ( = individual aspect) only */ vkGetImageSparseMemoryRequirements(m_device_ptr->get_device_vk(), m_image, &n_reqs, nullptr); anvil_assert(n_reqs >= 1); sparse_image_memory_reqs.resize(n_reqs); vkGetImageSparseMemoryRequirements(m_device_ptr->get_device_vk(), m_image, &n_reqs, &sparse_image_memory_reqs[0]); for (const auto& image_memory_req : sparse_image_memory_reqs) { for (uint32_t n_bit = 0; (1u << n_bit) <= image_memory_req.formatProperties.aspectMask; ++n_bit) { VkImageAspectFlagBits aspect = static_cast(1 << n_bit); if ((image_memory_req.formatProperties.aspectMask & aspect) == 0) { continue; } anvil_assert(m_sparse_aspect_props.find(aspect) == m_sparse_aspect_props.end() ); m_sparse_aspect_props[aspect] = Anvil::SparseImageAspectProperties(image_memory_req); } } /* Continue by setting up storage for page occupancy data */ init_page_occupancy(sparse_image_memory_reqs); } else if (m_create_info_ptr->get_residency_scope() == Anvil::SPARSE_RESIDENCY_SCOPE_NONE) { m_page_tracker_ptr.reset( new Anvil::PageTracker(m_storage_size, m_alignment) ); } if (m_create_info_ptr->get_type() == Anvil::ImageType::NONSPARSE_ALLOC) { /* Allocate memory for the image */ Anvil::MemoryBlockUniquePtr memory_block_ptr; { auto create_info_ptr = Anvil::MemoryBlockCreateInfo::create_regular(m_device_ptr, m_memory_reqs.memoryTypeBits, m_memory_reqs.size, m_create_info_ptr->get_memory_features() ); create_info_ptr->set_mt_safety(Anvil::Utils::convert_boolean_to_mt_safety_enum(is_mt_safe()) ); memory_block_ptr = Anvil::MemoryBlock::create(std::move(create_info_ptr) ); } if (memory_block_ptr == nullptr) { anvil_assert(memory_block_ptr != nullptr); result_bool = false; goto end; } if (!set_memory(std::move(memory_block_ptr) )) { anvil_assert_fail(); result_bool = false; goto end; } } end: return result_bool; } /** Initializes page occupancy data. Should only be used for sparse images. * * @param memory_reqs Image memory requirements. **/ void Anvil::Image::init_page_occupancy(const std::vector& in_memory_reqs) { anvil_assert(m_create_info_ptr->get_residency_scope() != Anvil::SPARSE_RESIDENCY_SCOPE_NONE && m_create_info_ptr->get_residency_scope() != Anvil::SPARSE_RESIDENCY_SCOPE_UNDEFINED); /* First, allocate space for an AspectPageOccupancyData instance for all aspects used by the image. * * Vulkan may interleave data of more than one aspect in one memory region, so we need to go the extra * mile to ensure the same AspectPageOccupancyData structure is assigned to such aspects. */ for (const auto& memory_req : in_memory_reqs) { AspectPageOccupancyData* occupancy_data_ptr = nullptr; for (uint32_t n_aspect_bit = 0; (1u << n_aspect_bit) <= memory_req.formatProperties.aspectMask; ++n_aspect_bit) { VkImageAspectFlagBits current_aspect = static_cast(1 << n_aspect_bit); if ((memory_req.formatProperties.aspectMask & current_aspect) == 0) { continue; } if (m_sparse_aspect_page_occupancy.find(current_aspect) != m_sparse_aspect_page_occupancy.end() ) { occupancy_data_ptr = m_sparse_aspect_page_occupancy.at(current_aspect); break; } } if (occupancy_data_ptr == nullptr) { m_sparse_aspect_page_occupancy_data_items_owned.push_back( std::unique_ptr(new AspectPageOccupancyData() ) ); } for (uint32_t n_aspect_bit = 0; (1u << n_aspect_bit) <= memory_req.formatProperties.aspectMask; ++n_aspect_bit) { VkImageAspectFlagBits current_aspect = static_cast(1 << n_aspect_bit); if ((memory_req.formatProperties.aspectMask & current_aspect) == 0) { continue; } m_sparse_aspect_page_occupancy[current_aspect] = m_sparse_aspect_page_occupancy_data_items_owned.back().get(); } } /* Next, iterate over each aspect and initialize storage for the mip chain */ anvil_assert(m_memory_reqs.alignment != 0); for (auto occupancy_iterator = m_sparse_aspect_page_occupancy.begin(); occupancy_iterator != m_sparse_aspect_page_occupancy.end(); ++occupancy_iterator) { const VkImageAspectFlagBits& current_aspect = occupancy_iterator->first; decltype(m_sparse_aspect_props)::const_iterator current_aspect_props_iterator; AspectPageOccupancyData* page_occupancy_ptr = occupancy_iterator->second; if (page_occupancy_ptr->layers.size() > 0) { /* Already initialized */ continue; } if (current_aspect == VK_IMAGE_ASPECT_METADATA_BIT) { /* Don't initialize per-layer occupancy data for metadata aspect */ continue; } current_aspect_props_iterator = m_sparse_aspect_props.find(current_aspect); anvil_assert(current_aspect_props_iterator != m_sparse_aspect_props.end() ); anvil_assert(current_aspect_props_iterator->second.granularity.width >= 1); anvil_assert(current_aspect_props_iterator->second.granularity.height >= 1); anvil_assert(current_aspect_props_iterator->second.granularity.depth >= 1); /* Initialize storage for layer data.. */ for (uint32_t n_layer = 0; n_layer < m_create_info_ptr->get_n_layers(); ++n_layer) { page_occupancy_ptr->layers.push_back(AspectPageOccupancyLayerData() ); auto& current_layer = page_occupancy_ptr->layers.back(); /* Tail can be, but does not necessarily have to be a part of non-zero layers. Take this into account, * when determining how many pages we need to alloc space for it. */ if (current_aspect_props_iterator->second.mip_tail_size > 0) { const bool is_single_miptail = (current_aspect_props_iterator->second.flags & VK_SPARSE_IMAGE_FORMAT_SINGLE_MIPTAIL_BIT) != 0; if ((is_single_miptail && n_layer == 0) || !is_single_miptail) { anvil_assert( (current_aspect_props_iterator->second.mip_tail_size % m_memory_reqs.alignment) == 0); current_layer.n_total_tail_pages = static_cast(current_aspect_props_iterator->second.mip_tail_size / m_memory_reqs.alignment); current_layer.tail_occupancy.resize(1 + current_layer.n_total_tail_pages / (sizeof(PageOccupancyStatus) * 8 /* bits in byte */) ); } else { current_layer.n_total_tail_pages = 0; } } else { current_layer.n_total_tail_pages = 0; } for (const auto& current_mip : m_mipmaps) { AspectPageOccupancyLayerMipData mip_data(current_mip.width, current_mip.height, current_mip.depth, current_aspect_props_iterator->second.granularity.width, current_aspect_props_iterator->second.granularity.height, current_aspect_props_iterator->second.granularity.depth); anvil_assert(current_mip.width >= 1); anvil_assert(current_mip.height >= 1); anvil_assert(current_mip.depth >= 1); current_layer.mips.push_back(mip_data); } } } } /** Releases the Vulkan image object, as well as the memory object associated with the Image instance. */ Anvil::Image::~Image() { if (m_image != VK_NULL_HANDLE && m_create_info_ptr->get_type() != Anvil::ImageType::SWAPCHAIN_WRAPPER) { lock(); { vkDestroyImage(m_device_ptr->get_device_vk(), m_image, nullptr /* pAllocator */); } unlock(); m_image = VK_NULL_HANDLE; } /* Unregister the object */ Anvil::ObjectTracker::get()->unregister_object(Anvil::OBJECT_TYPE_IMAGE, this); } /* Please see header for specification */ const VkImage& Anvil::Image::get_image() { if (m_create_info_ptr->get_type() != Anvil::ImageType::SPARSE_NO_ALLOC) { if (m_memory_blocks_owned.size() == 0) { get_memory_block(); } } return m_image; } /* Please see header for specification */ VkExtent2D Anvil::Image::get_image_extent_2D(uint32_t in_n_mipmap) const { VkExtent2D result; uint32_t size[2]; if (!get_image_mipmap_size(in_n_mipmap, size + 0, size + 1, nullptr) ) { anvil_assert_fail(); goto end; } result.height = size[1]; result.width = size[0]; end: return result; } /* Please see header for specification */ VkExtent3D Anvil::Image::get_image_extent_3D(uint32_t in_n_mipmap) const { VkExtent3D result; uint32_t size[3]; if (!get_image_mipmap_size(in_n_mipmap, size + 0, size + 1, size + 2) ) { anvil_assert_fail(); goto end; } result.depth = size[2]; result.height = size[1]; result.width = size[0]; end: return result; } /* Please see header for specification */ bool Anvil::Image::get_image_mipmap_size(uint32_t in_n_mipmap, uint32_t* out_opt_width_ptr, uint32_t* out_opt_height_ptr, uint32_t* out_opt_depth_ptr) const { bool result = false; /* Is this a sensible mipmap index? */ if (m_mipmaps.size() <= in_n_mipmap) { goto end; } /* Return the result data.. */ if (out_opt_width_ptr != nullptr) { *out_opt_width_ptr = m_mipmaps[in_n_mipmap].width; } if (out_opt_height_ptr != nullptr) { *out_opt_height_ptr = m_mipmaps[in_n_mipmap].height; } if (out_opt_depth_ptr != nullptr) { *out_opt_depth_ptr = m_mipmaps[in_n_mipmap].depth; } /* All done */ result = true; end: return result; } /** Please see header for specification */ bool Anvil::Image::get_sparse_image_aspect_properties(const VkImageAspectFlagBits in_aspect, const Anvil::SparseImageAspectProperties** out_result_ptr_ptr) const { decltype(m_sparse_aspect_props)::const_iterator prop_iterator; bool result = false; if (m_create_info_ptr->get_type() != Anvil::ImageType::SPARSE_NO_ALLOC) { anvil_assert(m_create_info_ptr->get_type() == Anvil::ImageType::SPARSE_NO_ALLOC); goto end; } if (m_create_info_ptr->get_residency_scope() == Anvil::SPARSE_RESIDENCY_SCOPE_NONE) { anvil_assert(m_create_info_ptr->get_residency_scope() != Anvil::SPARSE_RESIDENCY_SCOPE_NONE); goto end; } prop_iterator = m_sparse_aspect_props.find(in_aspect); if (prop_iterator == m_sparse_aspect_props.end() ) { anvil_assert(prop_iterator != m_sparse_aspect_props.end() ); goto end; } *out_result_ptr_ptr = &prop_iterator->second; result = true; end: return result; } /** TODO */ VkImageCreateInfo Anvil::Image::get_create_info_for_swapchain(const Anvil::Swapchain* in_swapchain_ptr) { VkImageCreateInfo result; in_swapchain_ptr->get_image(0)->get_image_mipmap_size(0, /* n_mipmap */ &result.extent.width, &result.extent.height, &result.arrayLayers); result.extent.depth = 1; result.flags = in_swapchain_ptr->get_create_info_ptr()->get_flags (); result.format = in_swapchain_ptr->get_create_info_ptr()->get_format(); result.imageType = VK_IMAGE_TYPE_2D; result.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; result.mipLevels = 1; result.pNext = nullptr; result.pQueueFamilyIndices = nullptr; result.queueFamilyIndexCount = UINT32_MAX; result.samples = VK_SAMPLE_COUNT_1_BIT; result.sharingMode = in_swapchain_ptr->get_image(0)->get_create_info_ptr()->get_sharing_mode(); result.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; result.tiling = VK_IMAGE_TILING_OPTIMAL; result.usage = in_swapchain_ptr->get_image(0)->get_create_info_ptr()->get_usage_flags(); return result; } /** Please see header for specification */ VkImageSubresourceRange Anvil::Image::get_subresource_range() const { VkImageSubresourceRange result; switch (m_create_info_ptr->get_format() ) { case VK_FORMAT_D16_UNORM: case VK_FORMAT_D32_SFLOAT: { result.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT; break; } case VK_FORMAT_D16_UNORM_S8_UINT: case VK_FORMAT_D24_UNORM_S8_UINT: case VK_FORMAT_D32_SFLOAT_S8_UINT: { result.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT; break; } case VK_FORMAT_S8_UINT: { result.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT; break; } default: { result.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; break; } } result.baseArrayLayer = 0; result.baseMipLevel = 0; result.layerCount = VK_REMAINING_ARRAY_LAYERS; result.levelCount = VK_REMAINING_MIP_LEVELS; return result; } /** Please see header for specification */ bool Anvil::Image::has_aspects(VkImageAspectFlags in_aspects) const { VkImageAspectFlags checked_aspects = 0; bool result = true; if (m_create_info_ptr->get_residency_scope() == SPARSE_RESIDENCY_SCOPE_ALIASED || m_create_info_ptr->get_residency_scope() == SPARSE_RESIDENCY_SCOPE_NONALIASED) { for (uint32_t n_bit = 0; n_bit < sizeof(uint32_t) * 8 /* bits in byte */ && result; ++n_bit) { VkImageAspectFlagBits current_aspect = static_cast(1 << n_bit); if ((in_aspects & current_aspect) != 0 && m_sparse_aspect_props.find(current_aspect) == m_sparse_aspect_props.end() ) { result = false; } } } else { const Anvil::ComponentLayout component_layout = Anvil::Formats::get_format_component_layout(m_create_info_ptr->get_format() ); bool has_color_components = false; bool has_depth_components = false; bool has_stencil_components = false; switch (component_layout) { case COMPONENT_LAYOUT_ABGR: case COMPONENT_LAYOUT_ARGB: case COMPONENT_LAYOUT_BGR: case COMPONENT_LAYOUT_BGRA: case COMPONENT_LAYOUT_EBGR: case COMPONENT_LAYOUT_R: case COMPONENT_LAYOUT_RG: case COMPONENT_LAYOUT_RGB: case COMPONENT_LAYOUT_RGBA: { has_color_components = true; break; } case COMPONENT_LAYOUT_D: case COMPONENT_LAYOUT_XD: { has_depth_components = true; break; } case COMPONENT_LAYOUT_DS: { has_depth_components = true; has_stencil_components = true; break; } case COMPONENT_LAYOUT_S: { has_stencil_components = true; break; } default: { anvil_assert_fail(); } } if (in_aspects & VK_IMAGE_ASPECT_COLOR_BIT) { result &= has_color_components; checked_aspects |= VK_IMAGE_ASPECT_COLOR_BIT; } if (result && (in_aspects & VK_IMAGE_ASPECT_DEPTH_BIT) != 0) { result &= has_depth_components; checked_aspects |= VK_IMAGE_ASPECT_DEPTH_BIT; } if (result && (in_aspects & VK_IMAGE_ASPECT_STENCIL_BIT) != 0) { result &= has_stencil_components; checked_aspects |= VK_IMAGE_ASPECT_STENCIL_BIT; } anvil_assert(!result || result && checked_aspects == in_aspects); } return result; } /** Fills the m_mipmaps vector with mipmap size data. */ void Anvil::Image::init_mipmap_props() { uint32_t current_mipmap_size[3] = { m_create_info_ptr->get_base_mip_width (), m_create_info_ptr->get_base_mip_height(), m_create_info_ptr->get_base_mip_depth () }; anvil_assert(m_n_mipmaps != 0); anvil_assert(m_mipmaps.size() == 0); for (uint32_t mipmap_level = 0; mipmap_level < m_n_mipmaps; ++mipmap_level) { m_mipmaps.push_back(Mipmap(current_mipmap_size[0], current_mipmap_size[1], current_mipmap_size[2]) ); current_mipmap_size[0] /= 2; current_mipmap_size[1] /= 2; if (m_create_info_ptr->get_type_vk() == VK_IMAGE_TYPE_3D) { current_mipmap_size[2] /= 2; } if (current_mipmap_size[0] < 1) { current_mipmap_size[0] = 1; } if (current_mipmap_size[1] < 1) { current_mipmap_size[1] = 1; } if (current_mipmap_size[2] < 1) { current_mipmap_size[2] = 1; } } } /* Please see header for specification */ bool Anvil::Image::is_memory_bound_for_texel(VkImageAspectFlagBits in_aspect, uint32_t in_n_layer, uint32_t in_n_mip, uint32_t in_x, uint32_t in_y, uint32_t in_z) const { bool result = false; /* Sanity checks */ anvil_assert(m_create_info_ptr->get_residency_scope() == SPARSE_RESIDENCY_SCOPE_ALIASED || m_create_info_ptr->get_residency_scope() == SPARSE_RESIDENCY_SCOPE_NONALIASED); anvil_assert(m_create_info_ptr->get_n_layers () > in_n_layer); anvil_assert(m_n_mipmaps > in_n_mip); anvil_assert(m_sparse_aspect_page_occupancy.find(in_aspect) != m_sparse_aspect_page_occupancy.end() ); /* Retrieve the tile status */ const auto& aspect_data = m_sparse_aspect_props.at(in_aspect); const auto& layer_data = m_sparse_aspect_page_occupancy.at(in_aspect)->layers.at(in_n_layer); if (in_n_mip >= aspect_data.mip_tail_first_lod) { /* For tails, we only have enough info to work at layer granularity */ const VkDeviceSize layer_start_offset = aspect_data.mip_tail_offset + aspect_data.mip_tail_stride * in_n_layer; ANVIL_REDUNDANT_VARIABLE_CONST(layer_start_offset); /* TODO */ result = true; } else { const auto& mip_data = layer_data.mips.at(in_n_mip); const uint32_t tile_index = mip_data.get_texture_space_xyz_to_block_mapping_index(in_x, in_y, in_z); result = (mip_data.tile_to_block_mappings.at(tile_index) != nullptr); } return result; } /** Updates page tracker (for non-resident images) OR tile-to-block mappings & tail page counteres, * as per the specified opaque image memory update properties. * * @param in_resource_offset Raw image data offset, from which the update has been performed * @param in_size Size of the updated region. * @param in_memory_block_ptr Memory block, bound to the specified region. * @param in_memory_block_start_offset Start offset relative to @param memory_block_ptr used for the update. * @param in_memory_block_owned_by_image TODO **/ void Anvil::Image::on_memory_backing_opaque_update(VkDeviceSize in_resource_offset, VkDeviceSize in_size, Anvil::MemoryBlock* in_memory_block_ptr, VkDeviceSize in_memory_block_start_offset, bool in_memory_block_owned_by_image) { const bool is_unbinding = (in_memory_block_ptr == nullptr); /* Sanity checks */ anvil_assert(m_create_info_ptr->get_residency_scope() != Anvil::SPARSE_RESIDENCY_SCOPE_UNDEFINED); if (in_memory_block_ptr != nullptr) { anvil_assert(in_memory_block_ptr->get_create_info_ptr()->get_size() <= in_memory_block_start_offset + in_size); } if (m_create_info_ptr->get_residency_scope() == Anvil::SPARSE_RESIDENCY_SCOPE_NONE) { /* Non-resident image: underlying memory is viewed as an opaque linear region. */ m_page_tracker_ptr->set_binding(in_memory_block_ptr, in_memory_block_start_offset, in_resource_offset, in_size); } else { /* The following use cases are expected to make us reach this block: * * 1) Application is about to bind a memory backing to all tiles OR unbind memory backing * from all tiles forming all aspects at once. * * 2) Application wants to bind (or unbind) a memory backing to/from miptail tile(s). * * 3) Anvil::Image has requested to bind memory to the metadata aspect. At the moment, this can only * be invoked from within the wrapper's code, and the memory block used for the operation is owned * by the Image wrapper, so there's nothing we need to do here. */ bool is_miptail_tile_binding_operation = false; auto metadata_aspect_iterator = m_sparse_aspect_props.find(VK_IMAGE_ASPECT_METADATA_BIT); if (metadata_aspect_iterator != m_sparse_aspect_props.end() ) { /* Handle case 3) */ if (in_resource_offset == metadata_aspect_iterator->second.mip_tail_offset && in_size == metadata_aspect_iterator->second.mip_tail_size) { anvil_assert(m_metadata_memory_block_ptr == nullptr); anvil_assert(in_memory_block_owned_by_image); m_metadata_memory_block_ptr = MemoryBlockUniquePtr(in_memory_block_ptr, std::default_delete() ); return; } else { /* TODO: We do not currently support cases where the application tries to bind its own memory * block to the metadata aspect. */ anvil_assert(in_resource_offset < metadata_aspect_iterator->second.mip_tail_offset); } } /* Handle case 2) */ for (auto aspect_iterator = m_sparse_aspect_page_occupancy.begin(); aspect_iterator != m_sparse_aspect_page_occupancy.end() && !is_miptail_tile_binding_operation; ++aspect_iterator) { VkImageAspectFlagBits current_aspect = aspect_iterator->first; const SparseImageAspectProperties& current_aspect_props = m_sparse_aspect_props.at(current_aspect); auto occupancy_data_ptr = aspect_iterator->second; ANVIL_REDUNDANT_VARIABLE_CONST(current_aspect_props); if ( in_resource_offset != 0 && !is_miptail_tile_binding_operation) { is_miptail_tile_binding_operation = (in_size == current_aspect_props.mip_tail_size); if (is_miptail_tile_binding_operation) { is_miptail_tile_binding_operation = false; for (uint32_t n_layer = 0; n_layer < m_create_info_ptr->get_n_layers(); ++n_layer) { auto& current_layer = occupancy_data_ptr->layers.at(n_layer); if (in_resource_offset == current_aspect_props.mip_tail_offset + current_aspect_props.mip_tail_stride * n_layer && in_size == current_aspect_props.mip_tail_size) { is_miptail_tile_binding_operation = true; memset(¤t_layer.tail_occupancy[0], (!is_unbinding) ? ~0 : 0, current_layer.tail_occupancy.size() * sizeof(current_layer.tail_occupancy[0])); if (!is_unbinding) { current_layer.tail_pages_per_binding[in_memory_block_ptr] = current_layer.n_total_tail_pages; } else { current_layer.tail_pages_per_binding.clear(); } break; } } } } } /* If not case 2) and 3), this has got to be case 1) */ if (!is_miptail_tile_binding_operation) { for (auto aspect_iterator = m_sparse_aspect_page_occupancy.begin(); aspect_iterator != m_sparse_aspect_page_occupancy.end(); ++aspect_iterator) { auto occupancy_data_ptr = aspect_iterator->second; for (auto& current_layer : occupancy_data_ptr->layers) { if (in_resource_offset == 0) { for (auto& current_mip : current_layer.mips) { const uint32_t n_mip_tiles = static_cast(current_mip.tile_to_block_mappings.size() ); for (uint32_t n_mip_tile = 0; n_mip_tile < n_mip_tiles; ++n_mip_tile) { current_mip.tile_to_block_mappings.at(n_mip_tile) = in_memory_block_ptr; } } } } } } } /* PTR_MANAGEMENT: Remove mem blocks no longer referenced by any page / til.e ! */ if (in_memory_block_owned_by_image) { m_memory_blocks_owned.push_back( Anvil::MemoryBlockUniquePtr(in_memory_block_ptr, std::default_delete() ) ); } } /** Updates page tracker (for non-resident images) OR tile-to-block mappings & tail page counteres, * as per the specified opaque image update properties. * * @param in_subresource Subresource specified for the update. * @param in_offset Offset specified for the update. * @param in_extent Extent specified for the update. * @param in_memory_block_ptr Memory block, bound to the specified region. * @param in_memory_block_start_offset Start offset relative to @param memory_block_ptr used for the update. **/ void Anvil::Image::on_memory_backing_update(const VkImageSubresource& in_subresource, VkOffset3D in_offset, VkExtent3D in_extent, Anvil::MemoryBlock* in_memory_block_ptr, VkDeviceSize in_memory_block_start_offset, bool in_memory_block_owned_by_image) { AspectPageOccupancyLayerData* aspect_layer_ptr; AspectPageOccupancyLayerMipData* aspect_layer_mip_ptr; decltype(m_sparse_aspect_page_occupancy)::iterator aspect_page_occupancy_iterator; decltype(m_sparse_aspect_props)::iterator aspect_props_iterator; anvil_assert(m_create_info_ptr->get_residency_scope() == Anvil::SPARSE_RESIDENCY_SCOPE_ALIASED || m_create_info_ptr->get_residency_scope() == Anvil::SPARSE_RESIDENCY_SCOPE_NONALIASED); ANVIL_REDUNDANT_ARGUMENT(in_memory_block_start_offset); if (in_subresource.aspectMask == VK_IMAGE_ASPECT_METADATA_BIT) { /* Metadata is not tracked since it needs to be completely bound in order for the sparse image to be usable. */ anvil_assert_fail(); return; } aspect_page_occupancy_iterator = m_sparse_aspect_page_occupancy.find(static_cast(in_subresource.aspectMask) ); aspect_props_iterator = m_sparse_aspect_props.find (static_cast(in_subresource.aspectMask) ); anvil_assert(aspect_page_occupancy_iterator != m_sparse_aspect_page_occupancy.end() ); anvil_assert(aspect_props_iterator != m_sparse_aspect_props.end() ); anvil_assert((in_offset.x % aspect_props_iterator->second.granularity.width) == 0 && (in_offset.y % aspect_props_iterator->second.granularity.height) == 0 && (in_offset.z % aspect_props_iterator->second.granularity.depth) == 0); anvil_assert((in_extent.width % aspect_props_iterator->second.granularity.width) == 0 && (in_extent.height % aspect_props_iterator->second.granularity.height) == 0 && (in_extent.depth % aspect_props_iterator->second.granularity.depth) == 0); anvil_assert(aspect_page_occupancy_iterator->second->layers.size() >= in_subresource.arrayLayer); aspect_layer_ptr = &aspect_page_occupancy_iterator->second->layers.at(in_subresource.arrayLayer); anvil_assert(aspect_layer_ptr->mips.size() > in_subresource.mipLevel); aspect_layer_mip_ptr = &aspect_layer_ptr->mips.at(in_subresource.mipLevel); const uint32_t extent_tile[] = { in_extent.width / aspect_props_iterator->second.granularity.width, in_extent.height / aspect_props_iterator->second.granularity.height, in_extent.depth / aspect_props_iterator->second.granularity.depth }; const uint32_t offset_tile[] = { in_offset.x / aspect_props_iterator->second.granularity.width, in_offset.y / aspect_props_iterator->second.granularity.height, in_offset.z / aspect_props_iterator->second.granularity.depth }; /* We're going to favor readability over performance in the loops below. */ for (uint32_t current_x_tile = offset_tile[0]; current_x_tile < offset_tile[0] + extent_tile[0]; ++current_x_tile) { for (uint32_t current_y_tile = offset_tile[1]; current_y_tile < offset_tile[1] + extent_tile[1]; ++current_y_tile) { for (uint32_t current_z_tile = offset_tile[2]; current_z_tile < offset_tile[2] + extent_tile[2]; ++current_z_tile) { const uint32_t tile_index = aspect_layer_mip_ptr->get_tile_space_xyz_to_block_mapping_index(current_x_tile, current_y_tile, current_z_tile); anvil_assert(aspect_layer_mip_ptr->tile_to_block_mappings.size() > tile_index); /* Assign the memory block (potentially null) to the tile */ aspect_layer_mip_ptr->tile_to_block_mappings.at(tile_index) = in_memory_block_ptr; } } } if (in_memory_block_owned_by_image) { m_memory_blocks_owned.push_back( MemoryBlockUniquePtr(in_memory_block_ptr, std::default_delete() ) ); } } /* Please see header for specification */ bool Anvil::Image::set_memory(MemoryBlockUniquePtr in_memory_block_ptr) { return set_memory_internal(in_memory_block_ptr.release(), true); /* in_owned_by_image */ } bool Anvil::Image::set_memory(Anvil::MemoryBlock* in_memory_block_ptr) { return set_memory_internal(in_memory_block_ptr, false); /* in_owned_by_image */ } bool Anvil::Image::set_memory_internal(Anvil::MemoryBlock* in_memory_block_ptr, bool in_owned_by_image) { const Anvil::DeviceType device_type(m_device_ptr->get_type() ); VkResult result (VK_ERROR_INITIALIZATION_FAILED); /* Sanity checks */ anvil_assert(in_memory_block_ptr != nullptr); anvil_assert(m_create_info_ptr->get_residency_scope() == Anvil::SPARSE_RESIDENCY_SCOPE_UNDEFINED); anvil_assert(m_mipmaps.size() > 0); anvil_assert(m_memory_blocks_owned.size() == 0); anvil_assert(m_create_info_ptr->get_type() != Anvil::ImageType::SWAPCHAIN_WRAPPER); /* Bind the memory object to the image object */ if (device_type == Anvil::DEVICE_TYPE_SINGLE_GPU) { lock(); { result = vkBindImageMemory(m_device_ptr->get_device_vk(), m_image, in_memory_block_ptr->get_memory(), in_memory_block_ptr->get_start_offset() ); } unlock(); } anvil_assert_vk_call_succeeded(result); if (is_vk_call_successful(result) ) { const auto& mips_to_upload = m_create_info_ptr->get_mipmaps_to_upload(); const auto tiling = m_create_info_ptr->get_tiling (); VkImageLayout src_image_layout = (tiling == VK_IMAGE_TILING_LINEAR && mips_to_upload.size() > 0) ? VK_IMAGE_LAYOUT_PREINITIALIZED : VK_IMAGE_LAYOUT_UNDEFINED; if (in_owned_by_image) { m_memory_blocks_owned.push_back( MemoryBlockUniquePtr(in_memory_block_ptr, std::default_delete() ) ); } /* Fill the storage with mipmap contents, if mipmap data was specified at input */ if (mips_to_upload.size() > 0) { upload_mipmaps(&mips_to_upload, src_image_layout, &src_image_layout); } if (m_create_info_ptr->get_post_alloc_image_layout() != m_create_info_ptr->get_post_create_image_layout() ) { const uint32_t n_mipmaps_to_upload = static_cast(mips_to_upload.size()); VkAccessFlags src_access_mask = 0; if (n_mipmaps_to_upload > 0) { if (tiling == VK_IMAGE_TILING_LINEAR) { src_access_mask = VK_ACCESS_HOST_WRITE_BIT; } else { src_access_mask = VK_ACCESS_TRANSFER_WRITE_BIT; } } transition_to_post_alloc_image_layout(src_access_mask, src_image_layout); } m_create_info_ptr->clear_mipmaps_to_upload(); } return is_vk_call_successful(result); } void Anvil::Image::transition_to_post_alloc_image_layout(VkAccessFlags in_source_access_mask, VkImageLayout in_src_layout) { const auto post_alloc_layout = m_create_info_ptr->get_post_alloc_image_layout(); anvil_assert(!m_has_transitioned_to_post_alloc_layout); change_image_layout(m_device_ptr->get_universal_queue(0), in_source_access_mask, in_src_layout, Anvil::Utils::get_access_mask_from_image_layout(post_alloc_layout), post_alloc_layout, get_subresource_range() ); m_has_transitioned_to_post_alloc_layout = true; } /** Please see header for specification */ void Anvil::Image::upload_mipmaps(const std::vector* in_mipmaps_ptr, VkImageLayout in_current_image_layout, VkImageLayout* out_new_image_layout_ptr) { std::map > image_aspect_to_mipmap_raw_data_map; VkImageAspectFlags image_aspects_touched (0); VkImageSubresourceRange image_subresource_range; const VkDeviceSize sparse_page_size ( (m_page_tracker_ptr != nullptr) ? m_page_tracker_ptr->get_page_size() : 0); Anvil::Queue* universal_queue_ptr (m_device_ptr->get_universal_queue(0) ); /* Make sure image has been assigned at least one memory block before we go ahead with the upload process */ get_memory_block(); /* Each image aspect needs to be modified separately. Iterate over the input vector and move MipmapRawData * to separate vectors corresponding to which aspect they need to update. */ for (auto mipmap_iterator = in_mipmaps_ptr->cbegin(); mipmap_iterator != in_mipmaps_ptr->cend(); ++mipmap_iterator) { image_aspect_to_mipmap_raw_data_map[mipmap_iterator->aspect].push_back(&(*mipmap_iterator)); } for (auto mipmap_iterator = in_mipmaps_ptr->cbegin(); mipmap_iterator != in_mipmaps_ptr->cend(); ++mipmap_iterator) { image_aspects_touched |= mipmap_iterator->aspect; } /* Fill the buffer memory with data, according to the specified layout requirements, * if linear tiling is used. * * For optimal tiling, we need to copy the raw data to temporary buffer * and use vkCmdCopyBufferToImage() to let the driver rearrange the data as needed. */ image_subresource_range.aspectMask = image_aspects_touched; image_subresource_range.baseArrayLayer = 0; image_subresource_range.baseMipLevel = 0; image_subresource_range.layerCount = m_create_info_ptr->get_n_layers(); image_subresource_range.levelCount = m_n_mipmaps; if (m_create_info_ptr->get_tiling() == VK_IMAGE_TILING_LINEAR) { /* TODO: Transition the subresource ranges, if necessary. */ anvil_assert(in_current_image_layout != VK_IMAGE_LAYOUT_UNDEFINED); for (auto aspect_to_mipmap_data_iterator = image_aspect_to_mipmap_raw_data_map.begin(); aspect_to_mipmap_data_iterator != image_aspect_to_mipmap_raw_data_map.end(); ++aspect_to_mipmap_data_iterator) { VkImageAspectFlagBits current_aspect = aspect_to_mipmap_data_iterator->first; const auto& mipmap_raw_data_items = aspect_to_mipmap_data_iterator->second; for (auto mipmap_raw_data_item_iterator = mipmap_raw_data_items.begin(); mipmap_raw_data_item_iterator != mipmap_raw_data_items.end(); ++mipmap_raw_data_item_iterator) { const unsigned char* current_mipmap_data_ptr = nullptr; uint32_t current_mipmap_height = 0; const auto& current_mipmap_raw_data_item_ptr = *mipmap_raw_data_item_iterator; uint32_t current_mipmap_slices = 0; uint32_t current_row_size = 0; uint32_t current_slice_size = 0; VkDeviceSize dst_slice_offset = 0; const unsigned char* src_slice_ptr = nullptr; VkImageSubresource image_subresource; VkSubresourceLayout image_subresource_layout; current_mipmap_data_ptr = (current_mipmap_raw_data_item_ptr->linear_tightly_packed_data_uchar_ptr != nullptr) ? current_mipmap_raw_data_item_ptr->linear_tightly_packed_data_uchar_ptr.get() : (current_mipmap_raw_data_item_ptr->linear_tightly_packed_data_uchar_raw_ptr != nullptr) ? current_mipmap_raw_data_item_ptr->linear_tightly_packed_data_uchar_raw_ptr : &(*current_mipmap_raw_data_item_ptr->linear_tightly_packed_data_uchar_vec_ptr)[0]; image_subresource.arrayLayer = current_mipmap_raw_data_item_ptr->n_layer; image_subresource.aspectMask = current_aspect; image_subresource.mipLevel = current_mipmap_raw_data_item_ptr->n_mipmap; vkGetImageSubresourceLayout(m_device_ptr->get_device_vk(), m_image, &image_subresource, &image_subresource_layout); /* Determine row size for the mipmap. * * NOTE: Current implementation can only handle power-of-two textures. */ const auto base_mip_height = m_create_info_ptr->get_base_mip_height(); anvil_assert(base_mip_height == 1 || (base_mip_height % 2) == 0); current_mipmap_height = base_mip_height / (1 << current_mipmap_raw_data_item_ptr->n_mipmap); if (current_mipmap_height < 1) { current_mipmap_height = 1; } current_mipmap_slices = current_mipmap_raw_data_item_ptr->n_slices; current_row_size = current_mipmap_raw_data_item_ptr->row_size; current_slice_size = (current_row_size * current_mipmap_height); if (current_mipmap_slices < 1) { current_mipmap_slices = 1; } for (unsigned int n_slice = 0; n_slice < current_mipmap_slices; ++n_slice) { dst_slice_offset = image_subresource_layout.offset + image_subresource_layout.depthPitch * n_slice; src_slice_ptr = current_mipmap_data_ptr + current_slice_size * n_slice; for (unsigned int n_row = 0; n_row < current_mipmap_height; ++n_row, dst_slice_offset += image_subresource_layout.rowPitch) { Anvil::MemoryBlock* mem_block_ptr = nullptr; VkDeviceSize write_dst_slice_offset = dst_slice_offset; if (m_create_info_ptr->get_residency_scope() == Anvil::SPARSE_RESIDENCY_SCOPE_UNDEFINED) { anvil_assert(m_memory_blocks_owned.size() == 1); mem_block_ptr = m_memory_blocks_owned.at(0).get(); } else if (m_create_info_ptr->get_residency_scope() == SPARSE_RESIDENCY_SCOPE_NONE) { const VkDeviceSize dst_slice_offset_page_aligned = Anvil::Utils::round_down(dst_slice_offset, sparse_page_size); VkDeviceSize memory_region_start_offset = UINT32_MAX; anvil_assert(sparse_page_size != 0); anvil_assert(( dst_slice_offset_page_aligned % sparse_page_size) == 0); mem_block_ptr = m_page_tracker_ptr->get_memory_block(dst_slice_offset_page_aligned, sparse_page_size, &memory_region_start_offset); anvil_assert(mem_block_ptr != nullptr); if (dst_slice_offset + image_subresource_layout.rowPitch > dst_slice_offset_page_aligned + sparse_page_size) { VkDeviceSize dummy; auto mem_block2_ptr = m_page_tracker_ptr->get_memory_block(dst_slice_offset_page_aligned + sparse_page_size, sparse_page_size, &dummy); ANVIL_REDUNDANT_VARIABLE(mem_block2_ptr); // todo: the slice spans across >1 memory blocks. need more than just one write op to handle this case correctly. anvil_assert(mem_block2_ptr == mem_block_ptr); } write_dst_slice_offset = memory_region_start_offset + (dst_slice_offset - dst_slice_offset_page_aligned); } else { /* todo */ anvil_assert_fail(); } mem_block_ptr->write(write_dst_slice_offset, current_row_size, src_slice_ptr + current_row_size * n_row); } } } } *out_new_image_layout_ptr = in_current_image_layout; } else { anvil_assert(m_create_info_ptr->get_tiling() == VK_IMAGE_TILING_OPTIMAL); Anvil::BufferUniquePtr temp_buffer_ptr; Anvil::PrimaryCommandBufferUniquePtr temp_cmdbuf_ptr; VkDeviceSize total_raw_mips_size = 0; /* Count how much space all specified mipmaps take in raw format. */ for (auto mipmap_iterator = in_mipmaps_ptr->cbegin(); mipmap_iterator != in_mipmaps_ptr->cend(); ++mipmap_iterator) { total_raw_mips_size += mipmap_iterator->n_slices * mipmap_iterator->data_size; /* Mip offsets must be rounded up to 4 due to the following ""Valid Usage"" requirement of VkBufferImageCopy struct: * * ""bufferOffset must be a multiple of 4"" */ if ((total_raw_mips_size % 4) != 0) { total_raw_mips_size = Anvil::Utils::round_up(total_raw_mips_size, static_cast(4) ); } } /* Merge data of all mips into one buffer, cache the offsets and push the merged data * to the buffer memory. */ std::vector mip_data_offsets; VkDeviceSize current_mip_offset = 0; std::unique_ptr merged_mip_storage(new char[static_cast(total_raw_mips_size)]); /* NOTE: The memcpy() call, as well as the way we implement copy op calls below, assume * POT resolution of the base mipmap */ const auto base_mip_height = m_create_info_ptr->get_base_mip_height(); anvil_assert(base_mip_height < 2 || (base_mip_height % 2) == 0); for (auto mipmap_iterator = in_mipmaps_ptr->cbegin(); mipmap_iterator != in_mipmaps_ptr->cend(); ++mipmap_iterator) { const auto& current_mipmap = *mipmap_iterator; const unsigned char* current_mipmap_data_ptr; const auto current_mipmap_data_size = current_mipmap.n_slices * current_mipmap.data_size; current_mipmap_data_ptr = (mipmap_iterator->linear_tightly_packed_data_uchar_ptr != nullptr) ? mipmap_iterator->linear_tightly_packed_data_uchar_ptr.get() : (mipmap_iterator->linear_tightly_packed_data_uchar_raw_ptr != nullptr) ? mipmap_iterator->linear_tightly_packed_data_uchar_raw_ptr : &(*mipmap_iterator->linear_tightly_packed_data_uchar_vec_ptr)[0]; mip_data_offsets.push_back(current_mip_offset); anvil_assert(current_mip_offset + current_mipmap_data_size <= total_raw_mips_size); memcpy(merged_mip_storage.get() + current_mip_offset, current_mipmap_data_ptr, current_mipmap_data_size); current_mip_offset += current_mipmap.n_slices * current_mipmap.data_size; /* Mip offset must be rounded up to 4 due to the following ""Valid Usage"" requirement of VkBufferImageCopy struct: * * ""bufferOffset must be a multiple of 4"" */ if ((current_mip_offset % 4) != 0) { current_mip_offset = Anvil::Utils::round_up(current_mip_offset, static_cast(4) ); } } { auto create_info_ptr = Anvil::BufferCreateInfo::create_nonsparse_alloc(m_device_ptr, total_raw_mips_size, Anvil::QUEUE_FAMILY_GRAPHICS_BIT, VK_SHARING_MODE_EXCLUSIVE, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, 0); /* in_memory_features */ create_info_ptr->set_client_data(merged_mip_storage.get() ); create_info_ptr->set_mt_safety (Anvil::Utils::convert_boolean_to_mt_safety_enum(is_mt_safe() )); temp_buffer_ptr = Anvil::Buffer::create(std::move(create_info_ptr) ); } merged_mip_storage.reset(); /* Set up a command buffer we will use to copy the data to the image */ temp_cmdbuf_ptr = m_device_ptr->get_command_pool_for_queue_family_index(universal_queue_ptr->get_queue_family_index() )->alloc_primary_level_command_buffer(); anvil_assert(temp_cmdbuf_ptr != nullptr); temp_cmdbuf_ptr->start_recording(true, /* one_time_submit */ false /* simultaneous_use_allowed */); { std::vector copy_regions; /* Transfer the image to the transfer_destination layout if not already in this or general layout */ if (in_current_image_layout != VK_IMAGE_LAYOUT_GENERAL && in_current_image_layout != VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) { const auto sharing_mode (m_create_info_ptr->get_sharing_mode() ); const auto queue_fam_index((sharing_mode == VK_SHARING_MODE_EXCLUSIVE) ? universal_queue_ptr->get_queue_family_index() : VK_QUEUE_FAMILY_IGNORED); Anvil::ImageBarrier image_barrier (0, /* source_access_mask */ VK_ACCESS_TRANSFER_WRITE_BIT, false, in_current_image_layout, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, queue_fam_index, queue_fam_index, this, image_subresource_range); temp_cmdbuf_ptr->record_pipeline_barrier(VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_FALSE, /* in_by_region */ 0, /* in_memory_barrier_count */ nullptr, /* in_memory_barrier_ptrs */ 0, /* in_buffer_memory_barrier_count */ nullptr, /* in_buffer_memory_barrier_ptrs */ 1, /* in_image_memory_barrier_count */ &image_barrier); *out_new_image_layout_ptr = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; } else { *out_new_image_layout_ptr = in_current_image_layout; } /* Issue the buffer->image copy op */ copy_regions.reserve(in_mipmaps_ptr->size() ); for (auto mipmap_iterator = in_mipmaps_ptr->cbegin(); mipmap_iterator != in_mipmaps_ptr->cend(); ++mipmap_iterator) { const auto base_mip_width = m_create_info_ptr->get_base_mip_width (); VkBufferImageCopy current_copy_region; const auto& current_mipmap = *mipmap_iterator; current_copy_region.bufferImageHeight = std::max(base_mip_height / (1 << current_mipmap.n_mipmap), 1u); current_copy_region.bufferOffset = mip_data_offsets[static_cast(mipmap_iterator - in_mipmaps_ptr->cbegin()) ]; current_copy_region.bufferRowLength = 0; current_copy_region.imageOffset.x = 0; current_copy_region.imageOffset.y = 0; current_copy_region.imageOffset.z = 0; current_copy_region.imageSubresource.baseArrayLayer = current_mipmap.n_layer; current_copy_region.imageSubresource.layerCount = current_mipmap.n_layers; current_copy_region.imageSubresource.aspectMask = current_mipmap.aspect; current_copy_region.imageSubresource.mipLevel = current_mipmap.n_mipmap; current_copy_region.imageExtent.depth = current_mipmap.n_slices; current_copy_region.imageExtent.height = std::max(base_mip_height / (1 << current_mipmap.n_mipmap), 1u); current_copy_region.imageExtent.width = std::max(base_mip_width / (1 << current_mipmap.n_mipmap), 1u); if (current_copy_region.imageExtent.depth < 1) { current_copy_region.imageExtent.depth = 1; } if (current_copy_region.imageExtent.height < 1) { current_copy_region.imageExtent.height = 1; } if (current_copy_region.imageExtent.width < 1) { current_copy_region.imageExtent.width = 1; } copy_regions.push_back(current_copy_region); } /* Issue the copy ops. */ const uint32_t n_copy_regions = static_cast(copy_regions.size() ); static const uint32_t n_max_copy_regions_per_copy_call = 1024; for (uint32_t n_copy_region = 0; n_copy_region < n_copy_regions; n_copy_region += n_max_copy_regions_per_copy_call) { const uint32_t n_copy_regions_to_use = std::min(n_max_copy_regions_per_copy_call, n_copy_regions - n_copy_region); temp_cmdbuf_ptr->record_copy_buffer_to_image(temp_buffer_ptr.get(), this, *out_new_image_layout_ptr, n_copy_regions_to_use, ©_regions.at(n_copy_region) ); } } temp_cmdbuf_ptr->stop_recording(); /* Execute the command buffer */ { Anvil::CommandBufferBase* cmd_buffer_raw_ptr = temp_cmdbuf_ptr.get(); universal_queue_ptr->submit( Anvil::SubmitInfo::create_execute(&cmd_buffer_raw_ptr, 1, /* in_n_cmd_buffers */ true) /* should_block */ ); } } }",16346,True,3303.5912511410584,median "[[salesforce-component]] = Salesforce Component :page-source: components/camel-salesforce/camel-salesforce-component/src/main/docs/salesforce-component.adoc *Available as of Camel version 2.12* This component supports producer and consumer endpoints to communicate with Salesforce using Java DTOs. + There is a companion maven plugin Camel Salesforce Plugin that generates these DTOs (see further below). Maven users will need to add the following dependency to their `pom.xml` for this component: [source,xml] ---- org.apache.camel camel-salesforce x.x.x ---- NOTE: Developers wishing to contribute to the component are instructed to look at the https://github.com/apache/camel/tree/master/components/camel-salesforce/camel-salesforce-component/README.md[README.md] file on instructions on how to get started and setup your environment for running integration tests. == Authenticating to Salesforce The component supports three OAuth authentication flows: * https://help.salesforce.com/articleView?id=remoteaccess_oauth_username_password_flow.htm[OAuth 2.0 Username-Password Flow] * https://help.salesforce.com/articleView?id=remoteaccess_oauth_refresh_token_flow.htm[OAuth 2.0 Refresh Token Flow] * https://help.salesforce.com/articleView?id=remoteaccess_oauth_jwt_flow.htm[OAuth 2.0 JWT Bearer Token Flow] For each of the flow different set of properties needs to be set: .Properties to set for each authentication flow |=== | Property | Where to find it on Salesforce | Flow | clientId | Connected App, Consumer Key | All flows | clientSecret | Connected App, Consumer Secret | Username-Password, Refresh Token | userName | Salesforce user username | Username-Password, JWT Bearer Token | password | Salesforce user password | Username-Password | refreshToken | From OAuth flow callback | Refresh Token | keystore | Connected App, Digital Certificate | JWT Bearer Token |=== The component auto determines what flow you're trying to configure, to be remove ambiguity set the `authenticationType` property. NOTE: Using Username-Password Flow in production is not encouraged. NOTE: The certificate used in JWT Bearer Token Flow can be a selfsigned certificate. The KeyStore holding the certificate and the private key must contain only single certificate-private key entry. == URI format When used as a consumer, receiving streaming events, the URI scheme is: [source,java] ---- salesforce:topic?options ---- When used as a producer, invoking the Salesforce REST APIs, the URI scheme is: [source,java] ---- salesforce:operationName?options ---- You can append query options to the URI in the following format, `?option=value&option=value&...` == Passing in Salesforce headers and fetching Salesforce response headers There is support to pass https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/headers.htm[Salesforce headers] via inbound message headers, header names that start with `Sforce` or `x-sfdc` on the Camel message will be passed on in the request, and response headers that start with `Sforce` will be present in the outbound message headers. For example to fetch API limits you can specify: [source,java] ---- // in your Camel route set the header before Salesforce endpoint //... .setHeader(""Sforce-Limit-Info"", constant(""api-usage"")) .to(""salesforce:getGlobalObjects"") .to(myProcessor); // myProcessor will receive `Sforce-Limit-Info` header on the outbound // message class MyProcessor implements Processor { public void process(Exchange exchange) throws Exception { Message in = exchange.getIn(); String apiLimits = in.getHeader(""Sforce-Limit-Info"", String.class); } } ---- == Supported Salesforce APIs The component supports the following Salesforce APIs Producer endpoints can use the following APIs. Most of the APIs process one record at a time, the Query API can retrieve multiple Records. === Rest API You can use the following for `operationName`: * getVersions - Gets supported Salesforce REST API versions * getResources - Gets available Salesforce REST Resource endpoints * getGlobalObjects - Gets metadata for all available SObject types * getBasicInfo - Gets basic metadata for a specific SObject type * getDescription - Gets comprehensive metadata for a specific SObject type * getSObject - Gets an SObject using its Salesforce Id * createSObject - Creates an SObject * updateSObject - Updates an SObject using Id * deleteSObject - Deletes an SObject using Id * getSObjectWithId - Gets an SObject using an external (user defined) id field * upsertSObject - Updates or inserts an SObject using an external id * deleteSObjectWithId - Deletes an SObject using an external id * query - Runs a Salesforce SOQL query * queryMore - Retrieves more results (in case of large number of results) using result link returned from the 'query' API * search - Runs a Salesforce SOSL query * limits - fetching organization API usage limits * recent - fetching recent items * approval - submit a record or records (batch) for approval process * approvals - fetch a list of all approval processes * composite - submit up to 25 possibly related REST requests and receive individual responses * composite-tree - create up to 200 records with parent-child relationships (up to 5 levels) in one go * composite-batch - submit a composition of requests in batch * queryAll - Runs a SOQL query. It returns the results that are deleted because of a merge or delete. Also returns the information about archived Task and Event records. * getBlobField - Retrieves the specified blob field from an individual record. * apexCall - Executes a user defined APEX REST API call. For example, the following producer endpoint uses the upsertSObject API, with the sObjectIdName parameter specifying 'Name' as the external id field. The request message body should be an SObject DTO generated using the maven plugin. The response message will either be `null` if an existing record was updated, or `CreateSObjectResult` with an id of the new record, or a list of errors while creating the new object. [source,java] ---- ...to(""salesforce:upsertSObject?sObjectIdName=Name"")... ---- === Rest Bulk API Producer endpoints can use the following APIs. All Job data formats, i.e. xml, csv, zip/xml, and zip/csv are supported. + The request and response have to be marshalled/unmarshalled by the route. Usually the request will be some stream source like a CSV file, + and the response may also be saved to a file to be correlated with the request. You can use the following for `operationName`: * createJob - Creates a Salesforce Bulk Job * getJob - Gets a Job using its Salesforce Id * closeJob - Closes a Job * abortJob - Aborts a Job * createBatch - Submits a Batch within a Bulk Job * getBatch - Gets a Batch using Id * getAllBatches - Gets all Batches for a Bulk Job Id * getRequest - Gets Request data (XML/CSV) for a Batch * getResults - Gets the results of the Batch when its complete * createBatchQuery - Creates a Batch from an SOQL query * getQueryResultIds - Gets a list of Result Ids for a Batch Query * getQueryResult - Gets results for a Result Id * getRecentReports - Gets up to 200 of the reports you most recently viewed by sending a GET request to the Report List resource. * getReportDescription - Retrieves the report, report type, and related metadata for a report, either in a tabular or summary or matrix format. * executeSyncReport - Runs a report synchronously with or without changing filters and returns the latest summary data. * executeAsyncReport - Runs an instance of a report asynchronously with or without filters and returns the summary data with or without details. * getReportInstances - Returns a list of instances for a report that you requested to be run asynchronously. Each item in the list is treated as a separate instance of the report. * getReportResults: Contains the results of running a report. For example, the following producer endpoint uses the createBatch API to create a Job Batch. The in message must contain a body that can be converted into an `InputStream` (usually UTF-8 CSV or XML content from a file, etc.) and header fields 'jobId' for the Job and 'contentType' for the Job content type, which can be XML, CSV, ZIP_XML or ZIP_CSV. The put message body will contain `BatchInfo` on success, or throw a `SalesforceException` on error. [source,java] ---- ...to(""salesforce:createBatchJob"").. ---- === Rest Streaming API Consumer endpoints can use the following syntax for streaming endpoints to receive Salesforce notifications on create/update. To create and subscribe to a topic [source,java] ---- from(""salesforce:CamelTestTopic?notifyForFields=ALL¬ifyForOperations=ALL&sObjectName=Merchandise__c&updateTopic=true&sObjectQuery=SELECT Id, Name FROM Merchandise__c"")... ---- To subscribe to an existing topic [source,java] ---- from(""salesforce:CamelTestTopic&sObjectName=Merchandise__c"")... ---- === Platform events To emit a platform event use `createSObject` operation. And set the message body can be JSON string or InputStream with key-value data -- in that case `sObjectName` needs to be set to the API name of the event, or a class that extends from AbstractDTOBase with the appropriate class name for the event. For example using a DTO: [source,java] ---- class Order_Event__e extends AbstractDTOBase { @JsonProperty(""OrderNumber"") private String orderNumber; // ... other properties and getters/setters } from(""timer:tick"") .process(exchange -> { final Message in = exchange.getIn(); String orderNumber = ""ORD"" + String.valueOf(in.getHeader(Exchange.TIMER_COUNTER)); Order_Event__e event = new Order_Event__e(); event.setOrderNumber(orderNumber); in.setBody(event); }) .to(""salesforce:createSObject""); ---- Or using JSON event data: [source,java] ---- from(""timer:tick"") .process(exchange -> { final Message in = exchange.getIn(); String orderNumber = ""ORD"" + String.valueOf(in.getHeader(Exchange.TIMER_COUNTER)); in.setBody(""{\\""OrderNumber\\"":\\"""" + orderNumber + ""\\""}""); }) .to(""salesforce:createSObject?sObjectName=Order_Event__e""); ---- To receive platform events use the consumer endpoint with the API name of the platform event prefixed with `event/` (or `/event/`), e.g.: `salesforce:events/Order_Event__e`. Processor consuming from that endpoint will receive either `org.apache.camel.component.salesforce.api.dto.PlatformEvent` object or `org.cometd.bayeux.Message` in the body depending on the `rawPayload` being `false` or `true` respectively. For example, in the simplest form to consume one event: [source,java] ---- PlatformEvent event = consumer.receiveBody(""salesforce:event/Order_Event__e"", PlatformEvent.class); ---- === Change data capture events On the one hand, Salesforce could be configured to emit notifications for record changes of select objects. On the other hand, the Camel Salesforce component could react to such notifications, allowing for instance to https://trailhead.salesforce.com/en/content/learn/modules/change-data-capture/understand-change-data-capture[synchronize those changes into an external system]. The notifications of interest could be specified in the `from(""salesforce:XXX"")` clause of a Camel route via the subscription channel, e.g: [source,java] ---- from(""salesforce:data/ChangeEvents?replayId=-1"").log(""being notified of all change events"") from(""salesforce:data/AccountChangeEvent?replayId=-1"").log(""being notified of change events for Account records"") from(""salesforce:data/Employee__ChangeEvent?replayId=-1"").log(""being notified of change events for Employee__c custom object"") ---- The received message contains either `java.util.Map` or `org.cometd.bayeux.Message` in the body depending on the `rawPayload` being `false` or `true` respectively. The `CamelSalesforceChangeType` header could be valued to one of `CREATE`, `UPDATE`, `DELETE` or `UNDELETE`. More details about how to use the Camel Salesforce component change data capture capabilities could be found in the https://github.com/apache/camel/tree/master/components/camel-salesforce/camel-salesforce-component/src/test/java/org/apache/camel/component/salesforce/ChangeEventsConsumerIntegrationTest.java[ChangeEventsConsumerIntegrationTest]. The https://developer.salesforce.com/docs/atlas.en-us.change_data_capture.meta/change_data_capture/cdc_intro.htm[Salesforce developer guide] is a good fit to better know the subtleties of implementing a change data capture integration application. The dynamic nature of change event body fields, high level replication steps as well as security considerations could be of interest. == Examples === Uploading a document to a ContentWorkspace Create the ContentVersion in Java, using a Processor instance: [source,java] ---- public class ContentProcessor implements Processor { public void process(Exchange exchange) throws Exception { Message message = exchange.getIn(); ContentVersion cv = new ContentVersion(); ContentWorkspace cw = getWorkspace(exchange); cv.setFirstPublishLocationId(cw.getId()); cv.setTitle(""test document""); cv.setPathOnClient(""test_doc.html""); byte[] document = message.getBody(byte[].class); ObjectMapper mapper = new ObjectMapper(); String enc = mapper.convertValue(document, String.class); cv.setVersionDataUrl(enc); message.setBody(cv); } protected ContentWorkspace getWorkSpace(Exchange exchange) { // Look up the content workspace somehow, maybe use enrich() to add it to a // header that can be extracted here .... } } ---- Give the output from the processor to the Salesforce component: [source,java] ---- from(""file:///home/camel/library"") .to(new ContentProcessor()) // convert bytes from the file into a ContentVersion SObject // for the salesforce component .to(""salesforce:createSObject""); ---- == Using Salesforce Limits API With `salesforce:limits` operation you can fetch of API limits from Salesforce and then act upon that data received. The result of `salesforce:limits` operation is mapped to `org.apache.camel.component.salesforce.api.dto.Limits` class and can be used in a custom processors or expressions. For instance, consider that you need to limit the API usage of Salesforce so that 10% of daily API requests is left for other routes. The body of output message contains an instance of `org.apache.camel.component.salesforce.api.dto.Limits` object that can be used in conjunction with Content Based Router and Content Based Router and xref:spel-language.adoc[Spring Expression Language (SpEL)] to choose when to perform queries. Notice how multiplying `1.0` with the integer value held in `body.dailyApiRequests.remaining` makes the expression evaluate as with floating point arithmetic, without it - it would end up making integral division which would result with either `0` (some API limits consumed) or `1` (no API limits consumed). [source,java] ---- from(""direct:querySalesforce"") .to(""salesforce:limits"") .choice() .when(spel(""#{1.0 * body.dailyApiRequests.remaining / body.dailyApiRequests.max < 0.1}"")) .to(""salesforce:query?..."") .otherwise() .setBody(constant(""Used up Salesforce API limits, leaving 10% for critical routes"")) .endChoice() ---- == Working with approvals All the properties are named exactly the same as in the Salesforce REST API prefixed with `approval.`. You can set approval properties by setting `approval.PropertyName` of the Endpoint these will be used as template -- meaning that any property not present in either body or header will be taken from the Endpoint configuration. Or you can set the approval template on the Endpoint by assigning `approval` property to a reference onto a bean in the Registry. You can also provide header values using the same `approval.PropertyName` in the incoming message headers. And finally body can contain one `AprovalRequest` or an `Iterable` of `ApprovalRequest` objects to process as a batch. The important thing to remember is the priority of the values specified in these three mechanisms: . value in body takes precedence before any other . value in message header takes precedence before template value . value in template is set if no other value in header or body was given For example to send one record for approval using values in headers use: Given a route: [source,java] ---- from(""direct:example1"")// .setHeader(""approval.ContextId"", simple(""${body['contextId']}"")) .setHeader(""approval.NextApproverIds"", simple(""${body['nextApproverIds']}"")) .to(""salesforce:approval?""// + ""approval.actionType=Submit""// + ""&approval.comments=this is a test""// + ""&approval.processDefinitionNameOrId=Test_Account_Process""// + ""&approval.skipEntryCriteria=true""); ---- You could send a record for approval using: [source,java] ---- final Map body = new HashMap<>(); body.put(""contextId"", accountIds.iterator().next()); body.put(""nextApproverIds"", userId); final ApprovalResult result = template.requestBody(""direct:example1"", body, ApprovalResult.class); ---- == Using Salesforce Recent Items API To fetch the recent items use `salesforce:recent` operation. This operation returns an `java.util.List` of `org.apache.camel.component.salesforce.api.dto.RecentItem` objects (`List`) that in turn contain the `Id`, `Name` and `Attributes` (with `type` and `url` properties). You can limit the number of returned items by specifying `limit` parameter set to maximum number of records to return. For example: [source,java] ---- from(""direct:fetchRecentItems"") to(""salesforce:recent"") .split().body() .log(""${body.name} at ${body.attributes.url}""); ---- == Using Salesforce Composite API to submit SObject tree To create up to 200 records including parent-child relationships use `salesforce:composite-tree` operation. This requires an instance of `org.apache.camel.component.salesforce.api.dto.composite.SObjectTree` in the input message and returns the same tree of objects in the output message. The `org.apache.camel.component.salesforce.api.dto.AbstractSObjectBase` instances within the tree get updated with the identifier values (`Id` property) or their corresponding `org.apache.camel.component.salesforce.api.dto.composite.SObjectNode` is populated with `errors` on failure. Note that for some records operation can succeed and for some it can fail -- so you need to manually check for errors. Easiest way to use this functionality is to use the DTOs generated by the `camel-salesforce-maven-plugin`, but you also have the option of customizing the references that identify the each object in the tree, for instance primary keys from your database. Lets look at an example: [source,java] ---- Account account = ... Contact president = ... Contact marketing = ... Account anotherAccount = ... Contact sales = ... Asset someAsset = ... // build the tree SObjectTree request = new SObjectTree(); request.addObject(account).addChildren(president, marketing); request.addObject(anotherAccount).addChild(sales).addChild(someAsset); final SObjectTree response = template.requestBody(""salesforce:composite-tree"", tree, SObjectTree.class); final Map> result = response.allNodes() .collect(Collectors.groupingBy(SObjectNode::hasErrors)); final List withErrors = result.get(true); final List succeeded = result.get(false); final String firstId = succeeded.get(0).getId(); ---- == Using Salesforce Composite API to submit multiple requests in a batch The Composite API batch operation (`composite-batch`) allows you to accumulate multiple requests in a batch and then submit them in one go, saving the round trip cost of multiple individual requests. Each response is then received in a list of responses with the order preserved, so that the n-th requests response is in the n-th place of the response. NOTE: The results can vary from API to API so the result of the request is given as a `java.lang.Object`. In most cases the result will be a `java.util.Map` with string keys and values or other `java.util.Map` as value. Requests made in JSON format hold some type information (i.e. it is known what values are strings and what values are numbers), so in general those will be more type friendly. Note that the responses will vary between XML and JSON, this is due to the responses from Salesforce API being different. So be careful if you switch between formats without changing the response handling code. Lets look at an example: [source,java] ---- final String acountId = ... final SObjectBatch batch = new SObjectBatch(""38.0""); final Account updates = new Account(); updates.setName(""NewName""); batch.addUpdate(""Account"", accountId, updates); final Account newAccount = new Account(); newAccount.setName(""Account created from Composite batch API""); batch.addCreate(newAccount); batch.addGet(""Account"", accountId, ""Name"", ""BillingPostalCode""); batch.addDelete(""Account"", accountId); final SObjectBatchResponse response = template.requestBody(""salesforce:composite-batch?format=JSON"", batch, SObjectBatchResponse.class); boolean hasErrors = response.hasErrors(); // if any of the requests has resulted in either 4xx or 5xx HTTP status final List results = response.getResults(); // results of three operations sent in batch final SObjectBatchResult updateResult = results.get(0); // update result final int updateStatus = updateResult.getStatusCode(); // probably 204 final Object updateResultData = updateResult.getResult(); // probably null final SObjectBatchResult createResult = results.get(1); // create result @SuppressWarnings(""unchecked"") final Map createData = (Map) createResult.getResult(); final String newAccountId = createData.get(""id""); // id of the new account, this is for JSON, for XML it would be createData.get(""Result"").get(""id"") final SObjectBatchResult retrieveResult = results.get(2); // retrieve result @SuppressWarnings(""unchecked"") final Map retrieveData = (Map) retrieveResult.getResult(); final String accountName = retrieveData.get(""Name""); // Name of the retrieved account, this is for JSON, for XML it would be createData.get(""Account"").get(""Name"") final String accountBillingPostalCode = retrieveData.get(""BillingPostalCode""); // Name of the retrieved account, this is for JSON, for XML it would be createData.get(""Account"").get(""BillingPostalCode"") final SObjectBatchResult deleteResult = results.get(3); // delete result final int updateStatus = deleteResult.getStatusCode(); // probably 204 final Object updateResultData = deleteResult.getResult(); // probably null ---- == Using Salesforce Composite API to submit multiple chained requests The `composite` operation allows submitting up to 25 requests that can be chained together, for instance identifier generated in previous request can be used in subsequent request. Individual requests and responses are linked with the provided _reference_. NOTE: Composite API supports only JSON payloads. NOTE: As with the batch API the results can vary from API to API so the result of the request is given as a `java.lang.Object`. In most cases the result will be a `java.util.Map` with string keys and values or other `java.util.Map` as value. Requests made in JSON format hold some type information (i.e. it is known what values are strings and what values are numbers), so in general those will be more type friendly. Lets look at an example: [source,java] ---- SObjectComposite composite = new SObjectComposite(""38.0"", true); // first insert operation via an external id final Account updateAccount = new TestAccount(); updateAccount.setName(""Salesforce""); updateAccount.setBillingStreet(""Landmark @ 1 Market Street""); updateAccount.setBillingCity(""San Francisco""); updateAccount.setBillingState(""California""); updateAccount.setIndustry(Account_IndustryEnum.TECHNOLOGY); composite.addUpdate(""Account"", ""001xx000003DIpcAAG"", updateAccount, ""UpdatedAccount""); final Contact newContact = new TestContact(); newContact.setLastName(""John Doe""); newContact.setPhone(""1234567890""); composite.addCreate(newContact, ""NewContact""); final AccountContactJunction__c junction = new AccountContactJunction__c(); junction.setAccount__c(""001xx000003DIpcAAG""); junction.setContactId__c(""@{NewContact.id}""); composite.addCreate(junction, ""JunctionRecord""); final SObjectCompositeResponse response = template.requestBody(""salesforce:composite?format=JSON"", composite, SObjectCompositeResponse.class); final List results = response.getCompositeResponse(); final SObjectCompositeResult accountUpdateResult = results.stream().filter(r -> ""UpdatedAccount"".equals(r.getReferenceId())).findFirst().get() final int statusCode = accountUpdateResult.getHttpStatusCode(); // should be 200 final Map accountUpdateBody = accountUpdateResult.getBody(); final SObjectCompositeResult contactCreationResult = results.stream().filter(r -> ""JunctionRecord"".equals(r.getReferenceId())).findFirst().get() ---- == Sending null values to salesforce By default, SObject fields with null values are not sent to salesforce. In order to send null values to salesforce, use the `fieldsToNull` property, as follows: [source,java] ---- accountSObject.getFieldsToNull().add(""Site""); ---- == Generating SOQL query strings `org.apache.camel.component.salesforce.api.utils.QueryHelper` contains helper methods to generate SOQL queries. For instance to fetch all custom fields from _Account_ SObject you can simply generate the SOQL SELECT by invoking: [source,java] ---- String allCustomFieldsQuery = QueryHelper.queryToFetchFilteredFieldsOf(new Account(), SObjectField::isCustom); ---- == Camel Salesforce Maven Plugin This Maven plugin generates DTOs for the Camel. For obvious security reasons it is recommended that the clientId, clientSecret, userName and password fields be not set in the pom.xml. The plugin should be configured for the rest of the properties, and can be executed using the following command: [source,java] ---- mvn camel-salesforce:generate -DcamelSalesforce.clientId= -DcamelSalesforce.clientSecret= \\ -DcamelSalesforce.userName= -DcamelSalesforce.password= ---- The generated DTOs use Jackson and XStream annotations. All Salesforce field types are supported. Date and time fields are mapped to `java.time.ZonedDateTime` by default, and picklist fields are mapped to generated Java Enumerations. Please refer to https://github.com/apache/camel/tree/master/components/camel-salesforce/camel-salesforce-maven-plugin[README.md] for details on how to generate the DTO. == Options // component options: START The Salesforce component supports 31 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *authenticationType* (security) | Explicit authentication method to be used, one of USERNAME_PASSWORD, REFRESH_TOKEN or JWT. Salesforce component can auto-determine the authentication method to use from the properties set, set this property to eliminate any ambiguity. | | AuthenticationType | *loginConfig* (security) | All authentication configuration in one nested bean, all properties set there can be set directly on the component as well | | SalesforceLoginConfig | *instanceUrl* (security) | URL of the Salesforce instance used after authentication, by default received from Salesforce on successful authentication | | String | *loginUrl* (security) | *Required* URL of the Salesforce instance used for authentication, by default set to \\https://login.salesforce.com | https://login.salesforce.com | String | *clientId* (security) | *Required* OAuth Consumer Key of the connected app configured in the Salesforce instance setup. Typically a connected app needs to be configured but one can be provided by installing a package. | | String | *clientSecret* (security) | OAuth Consumer Secret of the connected app configured in the Salesforce instance setup. | | String | *keystore* (security) | KeyStore parameters to use in OAuth JWT flow. The KeyStore should contain only one entry with private key and certificate. Salesforce does not verify the certificate chain, so this can easily be a selfsigned certificate. Make sure that you upload the certificate to the corresponding connected app. | | KeyStoreParameters | *refreshToken* (security) | Refresh token already obtained in the refresh token OAuth flow. One needs to setup a web application and configure a callback URL to receive the refresh token, or configure using the builtin callback at \\https://login.salesforce.com/services/oauth2/success or \\https://test.salesforce.com/services/oauth2/success and then retrive the refresh_token from the URL at the end of the flow. Note that in development organizations Salesforce allows hosting the callback web application at localhost. | | String | *userName* (security) | Username used in OAuth flow to gain access to access token. It's easy to get started with password OAuth flow, but in general one should avoid it as it is deemed less secure than other flows. | | String | *password* (security) | Password used in OAuth flow to gain access to access token. It's easy to get started with password OAuth flow, but in general one should avoid it as it is deemed less secure than other flows. Make sure that you append security token to the end of the password if using one. | | String | *lazyLogin* (security) | If set to true prevents the component from authenticating to Salesforce with the start of the component. You would generally set this to the (default) false and authenticate early and be immediately aware of any authentication issues. | false | boolean | *config* (common) | Global endpoint configuration - use to set values that are common to all endpoints | | SalesforceEndpoint Config | *httpClientProperties* (common) | Used to set any properties that can be configured on the underlying HTTP client. Have a look at properties of SalesforceHttpClient and the Jetty HttpClient for all available options. | | Map | *longPollingTransport Properties* (common) | Used to set any properties that can be configured on the LongPollingTransport used by the BayeuxClient (CometD) used by the streaming api | | Map | *sslContextParameters* (security) | SSL parameters to use, see SSLContextParameters class for all available options. | | SSLContextParameters | *useGlobalSslContext Parameters* (security) | Enable usage of global SSL context parameters | false | boolean | *httpClientIdleTimeout* (common) | Timeout used by the HttpClient when waiting for response from the Salesforce server. | 10000 | long | *httpClientConnection Timeout* (common) | Connection timeout used by the HttpClient when connecting to the Salesforce server. | 60000 | long | *httpProxyHost* (proxy) | Hostname of the HTTP proxy server to use. | | String | *httpProxyPort* (proxy) | Port number of the HTTP proxy server to use. | | Integer | *httpProxyUsername* (security) | Username to use to authenticate against the HTTP proxy server. | | String | *httpProxyPassword* (security) | Password to use to authenticate against the HTTP proxy server. | | String | *isHttpProxySocks4* (proxy) | If set to true the configures the HTTP proxy to use as a SOCKS4 proxy. | false | boolean | *isHttpProxySecure* (security) | If set to false disables the use of TLS when accessing the HTTP proxy. | true | boolean | *httpProxyIncluded Addresses* (proxy) | A list of addresses for which HTTP proxy server should be used. | | Set | *httpProxyExcluded Addresses* (proxy) | A list of addresses for which HTTP proxy server should not be used. | | Set | *httpProxyAuthUri* (security) | Used in authentication against the HTTP proxy server, needs to match the URI of the proxy server in order for the httpProxyUsername and httpProxyPassword to be used for authentication. | | String | *httpProxyRealm* (security) | Realm of the proxy server, used in preemptive Basic/Digest authentication methods against the HTTP proxy server. | | String | *httpProxyUseDigest Auth* (security) | If set to true Digest authentication will be used when authenticating to the HTTP proxy,otherwise Basic authorization method will be used | false | boolean | *packages* (common) | In what packages are the generated DTO classes. Typically the classes would be generated using camel-salesforce-maven-plugin. Set it if using the generated DTOs to gain the benefit of using short SObject names in parameters/header values. | | String[] | *basicPropertyBinding* (advanced) | Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean |=== // component options: END // endpoint options: START The Salesforce endpoint is configured using URI syntax: ---- salesforce:operationName:topicName ---- with the following path and query parameters: === Path Parameters (2 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *operationName* | The operation to use | | OperationName | *topicName* | The name of the topic/channel to use | | String |=== === Query Parameters (45 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *apexMethod* (common) | APEX method name | | String | *apexQueryParams* (common) | Query params for APEX method | | Map | *apexUrl* (common) | APEX method URL | | String | *apiVersion* (common) | Salesforce API version, defaults to SalesforceEndpointConfig.DEFAULT_VERSION | | String | *backoffIncrement* (common) | Backoff interval increment for Streaming connection restart attempts for failures beyond CometD auto-reconnect. | | long | *batchId* (common) | Bulk API Batch ID | | String | *contentType* (common) | Bulk API content type, one of XML, CSV, ZIP_XML, ZIP_CSV | | ContentType | *defaultReplayId* (common) | Default replayId setting if no value is found in initialReplayIdMap | | Long | *format* (common) | Payload format to use for Salesforce API calls, either JSON or XML, defaults to JSON | | PayloadFormat | *httpClient* (common) | Custom Jetty Http Client to use to connect to Salesforce. | | SalesforceHttpClient | *includeDetails* (common) | Include details in Salesforce1 Analytics report, defaults to false. | | Boolean | *initialReplayIdMap* (common) | Replay IDs to start from per channel name. | | Map | *instanceId* (common) | Salesforce1 Analytics report execution instance ID | | String | *jobId* (common) | Bulk API Job ID | | String | *limit* (common) | Limit on number of returned records. Applicable to some of the API, check the Salesforce documentation. | | Integer | *maxBackoff* (common) | Maximum backoff interval for Streaming connection restart attempts for failures beyond CometD auto-reconnect. | | long | *notFoundBehaviour* (common) | Sets the behaviour of 404 not found status received from Salesforce API. Should the body be set to NULL NotFoundBehaviour#NULL or should a exception be signaled on the exchange NotFoundBehaviour#EXCEPTION - the default. | | NotFoundBehaviour | *notifyForFields* (common) | Notify for fields, options are ALL, REFERENCED, SELECT, WHERE | | NotifyForFieldsEnum | *notifyForOperationCreate* (common) | Notify for create operation, defaults to false (API version = 29.0) | | Boolean | *notifyForOperationDelete* (common) | Notify for delete operation, defaults to false (API version = 29.0) | | Boolean | *notifyForOperations* (common) | Notify for operations, options are ALL, CREATE, EXTENDED, UPDATE (API version 29.0) | | NotifyForOperations Enum | *notifyForOperationUndelete* (common) | Notify for un-delete operation, defaults to false (API version = 29.0) | | Boolean | *notifyForOperationUpdate* (common) | Notify for update operation, defaults to false (API version = 29.0) | | Boolean | *objectMapper* (common) | Custom Jackson ObjectMapper to use when serializing/deserializing Salesforce objects. | | ObjectMapper | *rawPayload* (common) | Use raw payload String for request and response (either JSON or XML depending on format), instead of DTOs, false by default | false | boolean | *reportId* (common) | Salesforce1 Analytics report Id | | String | *reportMetadata* (common) | Salesforce1 Analytics report metadata for filtering | | ReportMetadata | *resultId* (common) | Bulk API Result ID | | String | *sObjectBlobFieldName* (common) | SObject blob field name | | String | *sObjectClass* (common) | Fully qualified SObject class name, usually generated using camel-salesforce-maven-plugin | | String | *sObjectFields* (common) | SObject fields to retrieve | | String | *sObjectId* (common) | SObject ID if required by API | | String | *sObjectIdName* (common) | SObject external ID field name | | String | *sObjectIdValue* (common) | SObject external ID field value | | String | *sObjectName* (common) | SObject name if required or supported by API | | String | *sObjectQuery* (common) | Salesforce SOQL query string | | String | *sObjectSearch* (common) | Salesforce SOSL search string | | String | *updateTopic* (common) | Whether to update an existing Push Topic when using the Streaming API, defaults to false | false | boolean | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *replayId* (consumer) | The replayId value to use when subscribing | | Long | *exceptionHandler* (consumer) | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | | ExceptionHandler | *exchangePattern* (consumer) | Sets the exchange pattern when the consumer creates an exchange. | | ExchangePattern | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *basicPropertyBinding* (advanced) | Whether the endpoint should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean | *synchronous* (advanced) | Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported). | false | boolean |=== // endpoint options: END // spring-boot-auto-configure options: START == Spring Boot Auto-Configuration When using Spring Boot make sure to use the following Maven dependency to have support for auto configuration: [source,xml] ---- org.apache.camel camel-salesforce-starter x.x.x ---- The component supports 86 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *camel.component.salesforce.authentication-type* | Explicit authentication method to be used, one of USERNAME_PASSWORD, REFRESH_TOKEN or JWT. Salesforce component can auto-determine the authentication method to use from the properties set, set this property to eliminate any ambiguity. | | AuthenticationType | *camel.component.salesforce.basic-property-binding* | Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | Boolean | *camel.component.salesforce.client-id* | OAuth Consumer Key of the connected app configured in the Salesforce instance setup. Typically a connected app needs to be configured but one can be provided by installing a package. | | String | *camel.component.salesforce.client-secret* | OAuth Consumer Secret of the connected app configured in the Salesforce instance setup. | | String | *camel.component.salesforce.config.apex-method* | APEX method name | | String | *camel.component.salesforce.config.apex-query-params* | Query params for APEX method | | Map | *camel.component.salesforce.config.apex-url* | APEX method URL | | String | *camel.component.salesforce.config.api-version* | Salesforce API version, defaults to SalesforceEndpointConfig.DEFAULT_VERSION | | String | *camel.component.salesforce.config.approval* | The approval request for Approval API. | | ApprovalRequest | *camel.component.salesforce.config.approval-action-type* | Represents the kind of action to take: Submit, Approve, or Reject. | | ApprovalRequest$Action | *camel.component.salesforce.config.approval-comments* | The comment to add to the history step associated with this request. | | String | *camel.component.salesforce.config.approval-context-actor-id* | The ID of the submitter who’s requesting the approval record. | | String | *camel.component.salesforce.config.approval-context-id* | The ID of the item that is being acted upon. | | String | *camel.component.salesforce.config.approval-next-approver-ids* | If the process requires specification of the next approval, the ID of the user to be assigned the next request. | | List | *camel.component.salesforce.config.approval-process-definition-name-or-id* | The developer name or ID of the process definition. | | String | *camel.component.salesforce.config.approval-skip-entry-criteria* | Determines whether to evaluate the entry criteria for the process (true) or not (false) if the process definition name or ID isn’t null. If the process definition name or ID isn’t specified, this argument is ignored, and standard evaluation is followed based on process order. By default, the entry criteria isn’t skipped if it’s not set by this request. | | Boolean | *camel.component.salesforce.config.backoff-increment* | Backoff interval increment for Streaming connection restart attempts for failures beyond CometD auto-reconnect. | | Long | *camel.component.salesforce.config.batch-id* | Bulk API Batch ID | | String | *camel.component.salesforce.config.content-type* | Bulk API content type, one of XML, CSV, ZIP_XML, ZIP_CSV | | ContentType | *camel.component.salesforce.config.default-replay-id* | Default replayId setting if no value is found in {@link #initialReplayIdMap} | | Long | *camel.component.salesforce.config.format* | Payload format to use for Salesforce API calls, either JSON or XML, defaults to JSON | | PayloadFormat | *camel.component.salesforce.config.http-client* | Custom Jetty Http Client to use to connect to Salesforce. | | SalesforceHttpClient | *camel.component.salesforce.config.include-details* | Include details in Salesforce1 Analytics report, defaults to false. | | Boolean | *camel.component.salesforce.config.initial-replay-id-map* | Replay IDs to start from per channel name. | | Map | *camel.component.salesforce.config.instance-id* | Salesforce1 Analytics report execution instance ID | | String | *camel.component.salesforce.config.job-id* | Bulk API Job ID | | String | *camel.component.salesforce.config.limit* | Limit on number of returned records. Applicable to some of the API, check the Salesforce documentation. | | Integer | *camel.component.salesforce.config.max-backoff* | Maximum backoff interval for Streaming connection restart attempts for failures beyond CometD auto-reconnect. | | Long | *camel.component.salesforce.config.not-found-behaviour* | Sets the behaviour of 404 not found status received from Salesforce API. Should the body be set to NULL {@link NotFoundBehaviour#NULL} or should a exception be signaled on the exchange {@link NotFoundBehaviour#EXCEPTION} - the default. | | NotFoundBehaviour | *camel.component.salesforce.config.notify-for-fields* | Notify for fields, options are ALL, REFERENCED, SELECT, WHERE | | NotifyForFieldsEnum | *camel.component.salesforce.config.notify-for-operation-create* | Notify for create operation, defaults to false (API version >= 29.0) | | Boolean | *camel.component.salesforce.config.notify-for-operation-delete* | Notify for delete operation, defaults to false (API version >= 29.0) | | Boolean | *camel.component.salesforce.config.notify-for-operation-undelete* | Notify for un-delete operation, defaults to false (API version >= 29.0) | | Boolean | *camel.component.salesforce.config.notify-for-operation-update* | Notify for update operation, defaults to false (API version >= 29.0) | | Boolean | *camel.component.salesforce.config.notify-for-operations* | Notify for operations, options are ALL, CREATE, EXTENDED, UPDATE (API version < 29.0) | | NotifyForOperations Enum | *camel.component.salesforce.config.object-mapper* | Custom Jackson ObjectMapper to use when serializing/deserializing Salesforce objects. | | ObjectMapper | *camel.component.salesforce.config.raw-payload* | Use raw payload {@link String} for request and response (either JSON or XML depending on {@code format}), instead of DTOs, false by default | false | Boolean | *camel.component.salesforce.config.report-id* | Salesforce1 Analytics report Id | | String | *camel.component.salesforce.config.report-metadata* | Salesforce1 Analytics report metadata for filtering | | ReportMetadata | *camel.component.salesforce.config.result-id* | Bulk API Result ID | | String | *camel.component.salesforce.config.s-object-blob-field-name* | SObject blob field name | | String | *camel.component.salesforce.config.s-object-class* | Fully qualified SObject class name, usually generated using camel-salesforce-maven-plugin | | String | *camel.component.salesforce.config.s-object-fields* | SObject fields to retrieve | | String | *camel.component.salesforce.config.s-object-id* | SObject ID if required by API | | String | *camel.component.salesforce.config.s-object-id-name* | SObject external ID field name | | String | *camel.component.salesforce.config.s-object-id-value* | SObject external ID field value | | String | *camel.component.salesforce.config.s-object-name* | SObject name if required or supported by API | | String | *camel.component.salesforce.config.s-object-query* | Salesforce SOQL query string | | String | *camel.component.salesforce.config.s-object-search* | Salesforce SOSL search string | | String | *camel.component.salesforce.config.update-topic* | Whether to update an existing Push Topic when using the Streaming API, defaults to false | false | Boolean | *camel.component.salesforce.enabled* | Enable salesforce component | true | Boolean | *camel.component.salesforce.http-client-connection-timeout* | Connection timeout used by the HttpClient when connecting to the Salesforce server. | 60000 | Long | *camel.component.salesforce.http-client-idle-timeout* | Timeout used by the HttpClient when waiting for response from the Salesforce server. | 10000 | Long | *camel.component.salesforce.http-client-properties* | Used to set any properties that can be configured on the underlying HTTP client. Have a look at properties of SalesforceHttpClient and the Jetty HttpClient for all available options. | | Map | *camel.component.salesforce.http-proxy-auth-uri* | Used in authentication against the HTTP proxy server, needs to match the URI of the proxy server in order for the httpProxyUsername and httpProxyPassword to be used for authentication. | | String | *camel.component.salesforce.http-proxy-excluded-addresses* | A list of addresses for which HTTP proxy server should not be used. | | Set | *camel.component.salesforce.http-proxy-host* | Hostname of the HTTP proxy server to use. | | String | *camel.component.salesforce.http-proxy-included-addresses* | A list of addresses for which HTTP proxy server should be used. | | Set | *camel.component.salesforce.http-proxy-password* | Password to use to authenticate against the HTTP proxy server. | | String | *camel.component.salesforce.http-proxy-port* | Port number of the HTTP proxy server to use. | | Integer | *camel.component.salesforce.http-proxy-realm* | Realm of the proxy server, used in preemptive Basic/Digest authentication methods against the HTTP proxy server. | | String | *camel.component.salesforce.http-proxy-use-digest-auth* | If set to true Digest authentication will be used when authenticating to the HTTP proxy,otherwise Basic authorization method will be used | false | Boolean | *camel.component.salesforce.http-proxy-username* | Username to use to authenticate against the HTTP proxy server. | | String | *camel.component.salesforce.instance-url* | URL of the Salesforce instance used after authentication, by default received from Salesforce on successful authentication | | String | *camel.component.salesforce.is-http-proxy-secure* | If set to false disables the use of TLS when accessing the HTTP proxy. | true | Boolean | *camel.component.salesforce.is-http-proxy-socks4* | If set to true the configures the HTTP proxy to use as a SOCKS4 proxy. | false | Boolean | *camel.component.salesforce.keystore* | KeyStore parameters to use in OAuth JWT flow. The KeyStore should contain only one entry with private key and certificate. Salesforce does not verify the certificate chain, so this can easily be a selfsigned certificate. Make sure that you upload the certificate to the corresponding connected app. The option is a org.apache.camel.support.jsse.KeyStoreParameters type. | | String | *camel.component.salesforce.lazy-login* | If set to true prevents the component from authenticating to Salesforce with the start of the component. You would generally set this to the (default) false and authenticate early and be immediately aware of any authentication issues. | false | Boolean | *camel.component.salesforce.login-config.client-id* | Salesforce connected application Consumer Key | | String | *camel.component.salesforce.login-config.client-secret* | Salesforce connected application Consumer Secret | | String | *camel.component.salesforce.login-config.instance-url* | Configuration object for Salesforce login properties | | String | *camel.component.salesforce.login-config.keystore* | Keystore parameters for keystore containing certificate and private key needed for OAuth 2.0 JWT Bearer Token Flow. | | KeyStoreParameters | *camel.component.salesforce.login-config.lazy-login* | Flag to enable/disable lazy OAuth, default is false. When enabled, OAuth token retrieval or generation is not done until the first API call | false | Boolean | *camel.component.salesforce.login-config.login-url* | Salesforce login URL, defaults to \\https://login.salesforce.com | https://login.salesforce.com | String | *camel.component.salesforce.login-config.password* | Salesforce account password | | String | *camel.component.salesforce.login-config.refresh-token* | Salesforce connected application Consumer token | | String | *camel.component.salesforce.login-config.type* | Salesforce connected application Consumer token | | AuthenticationType | *camel.component.salesforce.login-config.user-name* | Salesforce account user name | | String | *camel.component.salesforce.login-url* | URL of the Salesforce instance used for authentication, by default set to \\https://login.salesforce.com | https://login.salesforce.com | String | *camel.component.salesforce.long-polling-transport-properties* | Used to set any properties that can be configured on the LongPollingTransport used by the BayeuxClient (CometD) used by the streaming api | | Map | *camel.component.salesforce.packages* | In what packages are the generated DTO classes. Typically the classes would be generated using camel-salesforce-maven-plugin. Set it if using the generated DTOs to gain the benefit of using short SObject names in parameters/header values. | | String[] | *camel.component.salesforce.password* | Password used in OAuth flow to gain access to access token. It's easy to get started with password OAuth flow, but in general one should avoid it as it is deemed less secure than other flows. Make sure that you append security token to the end of the password if using one. | | String | *camel.component.salesforce.refresh-token* | Refresh token already obtained in the refresh token OAuth flow. One needs to setup a web application and configure a callback URL to receive the refresh token, or configure using the builtin callback at \\https://login.salesforce.com/services/oauth2/success or \\https://test.salesforce.com/services/oauth2/success and then retrive the refresh_token from the URL at the end of the flow. Note that in development organizations Salesforce allows hosting the callback web application at localhost. | | String | *camel.component.salesforce.ssl-context-parameters* | SSL parameters to use, see SSLContextParameters class for all available options. The option is a org.apache.camel.support.jsse.SSLContextParameters type. | | String | *camel.component.salesforce.use-global-ssl-context-parameters* | Enable usage of global SSL context parameters | false | Boolean | *camel.component.salesforce.user-name* | Username used in OAuth flow to gain access to access token. It's easy to get started with password OAuth flow, but in general one should avoid it as it is deemed less secure than other flows. | | String |=== // spring-boot-auto-configure options: END ",12158,False,2155.2650268830107,median "[[configuration-interfaces]] == Set traffic capturing options There are two main ways of deploying Packetbeat: * On dedicated servers, getting the traffic from mirror ports or tap devices. * On your existing application servers. The first option has the big advantage that there is no overhead of any kind on your application servers. But it requires dedicated networking gear, which is generally not available on cloud setups. In both cases, the sniffing performance (reading packets passively from the network) is very important. In the case of a dedicated server, better sniffing performance means that less hardware is required. When Packetbeat is installed on an existing application server, better sniffing performance means less overhead. Currently Packetbeat has several options for traffic capturing: * `pcap`, which uses the libpcap library and works on most platforms, but it's not the fastest option. * `af_packet`, which uses memory mapped sniffing. This option is faster than libpcap and doesn't require a kernel module, but it's Linux-specific. The `af_packet` option, also known as ""memory-mapped sniffing,"" makes use of a Linux-specific http://lxr.free-electrons.com/source/Documentation/networking/packet_mmap.txt[feature]. This could be the optimal sniffing mode for both the dedicated server and when Packetbeat is deployed on an existing application server. The way it works is that both the kernel and the user space program map the same memory zone, and a simple circular buffer is organized in this memory zone. The kernel writes packets into the circular buffer, and the user space program reads from it. The poll system call is used for getting a notification for the first packet available, but the remaining available packets can be simply read via memory access. The `af_packet` sniffer can be further tuned to use more memory in exchange for better performance. The larger the size of the circular buffer, the fewer system calls are needed, which means that fewer CPU cycles are consumed. The default size of the buffer is 30 MB, but you can increase it like this: [source,yaml] ------------------------------------------------------------------------------ packetbeat.interfaces.device: eth0 packetbeat.interfaces.type: af_packet packetbeat.interfaces.buffer_size_mb: 100 ------------------------------------------------------------------------------ [float] === Sniffing configuration options You can specify the following options in the `packetbeat.interfaces` section of the +{beatname_lc}.yml+ config file. Here is an example configuration: [source,yaml] ------------------------------------------------------------------------------ packetbeat.interfaces.device: any packetbeat.interfaces.snaplen: 1514 packetbeat.interfaces.type: af_packet packetbeat.interfaces.buffer_size_mb: 100 ------------------------------------------------------------------------------ [float] ==== `device` The network device to capture traffic from. The specified device is set automatically to promiscuous mode, meaning that Packetbeat can capture traffic from other hosts on the same LAN. Example: [source,yaml] ------------------------------------------------------------------------------ packetbeat.interfaces.device: eth0 ------------------------------------------------------------------------------ On Linux, you can specify `any` for the device, and Packetbeat captures all messages sent or received by the server where Packetbeat is installed. NOTE: When you specify `any` for the device, the interfaces are not set to promiscuous mode. The `device` option also accepts specifying the device by its index in the list of devices available for sniffing. To obtain the list of available devices, run Packetbeat with the following command: [""source"",""sh"",subs=""attributes,callouts""] ---------------------------------------------------------------------- packetbeat devices ---------------------------------------------------------------------- This command returns a list that looks something like the following: [""source"",""sh"",subs=""attributes,callouts""] ---------------------------------------------------------------------- 0: en0 (No description available) 1: awdl0 (No description available) 2: bridge0 (No description available) 3: fw0 (No description available) 4: en1 (No description available) 5: en2 (No description available) 6: p2p0 (No description available) 7: en4 (No description available) 8: lo0 (No description available) ---------------------------------------------------------------------- The following example sets up sniffing on the first interface in the list: [source,yaml] ------------------------------------------------------------------------------ packetbeat.interfaces.device: 0 ------------------------------------------------------------------------------ Specifying the index is especially useful on Windows where device names can be long. [float] ==== `snaplen` The maximum size of the packets to capture. The default is 65535, which is large enough for almost all networks and interface types. If you sniff on a physical network interface, the optimal setting is the MTU size. On virtual interfaces, however, it's safer to accept the default value. Example: [source,yaml] ------------------------------------------------------------------------------ packetbeat.interfaces.device: eth0 packetbeat.interfaces.snaplen: 1514 ------------------------------------------------------------------------------ [float] ==== `type` Packetbeat supports these sniffer types: * `pcap`, which uses the libpcap library and works on most platforms, but it's not the fastest option. * `af_packet`, which uses memory-mapped sniffing. This option is faster than libpcap and doesn't require a kernel module, but it's Linux-specific. The default sniffer type is `pcap`. Here is an example configuration that specifies the `af_packet` sniffing type: [source,yaml] ------------------------------------------------------------------------------ packetbeat.interfaces.device: eth0 packetbeat.interfaces.type: af_packet ------------------------------------------------------------------------------ On Linux, if you are trying to optimize the CPU usage of Packetbeat, we recommend trying the `af_packet` option. If you use the `af_packet` sniffer, you can tune its behaviour by specifying the following options: [float] ==== `buffer_size_mb` The maximum size of the shared memory buffer to use between the kernel and user space. A bigger buffer usually results in lower CPU usage, but consumes more memory. This setting is only available for the `af_packet` sniffer type. The default is 30 MB. Example: [source,yaml] ------------------------------------------------------------------------------ packetbeat.interfaces.device: eth0 packetbeat.interfaces.type: af_packet packetbeat.interfaces.buffer_size_mb: 100 ------------------------------------------------------------------------------ [float] ==== `auto_promisc_mode` With `auto_promisc_mode` Packetbeat puts interface in promiscuous mode automatically on startup. This option does not work with `any` interface device. The default option is false and requires manual set-up of promiscuous mode. Warning: under some circumstances (e.g beat crash) promiscuous mode can stay enabled even after beat is shut down. Example: [source,yaml] ------------------------------------------------------------------------------ packetbeat.interfaces.device: eth0 packetbeat.interfaces.type: af_packet packetbeat.interfaces.buffer_size_mb: 100 packetbeat.interfaces.auto_promisc_mode: true ------------------------------------------------------------------------------ [float] ==== `with_vlans` Packetbeat automatically generates a https://en.wikipedia.org/wiki/Berkeley_Packet_Filter[BPF] for capturing only the traffic on ports where it expects to find known protocols. For example, if you have configured port 80 for HTTP and port 3306 for MySQL, Packetbeat generates the following BPF filter: `""port 80 or port 3306""`. However, if the traffic contains https://en.wikipedia.org/wiki/IEEE_802.1Q[VLAN] tags, the filter that Packetbeat generates is ineffective because the offset is moved by four bytes. To fix this, you can enable the `with_vlans` option, which generates a BPF filter that looks like this: `""port 80 or port 3306 or (vlan and (port 80 or port 3306))""`. [float] ==== `bpf_filter` Packetbeat automatically generates a https://en.wikipedia.org/wiki/Berkeley_Packet_Filter[BPF] for capturing only the traffic on ports where it expects to find known protocols. For example, if you have configured port 80 for HTTP and port 3306 for MySQL, Packetbeat generates the following BPF filter: `""port 80 or port 3306""`. You can use the `bpf_filter` setting to overwrite the generated BPF filter. For example: [source,yaml] ------------------------------------------------------------------------------ packetbeat.interfaces.device: eth0 packetbeat.interfaces.bpf_filter: ""net 192.168.238.0/0 and port 80 or port 3306"" ------------------------------------------------------------------------------ NOTE: This setting disables automatic generation of the BPF filter. If you use this setting, it's your responsibility to keep the BPF filters in sync with the ports defined in the `protocols` section. [float] ==== `ignore_outgoing` If the `ignore_outgoing` option is enabled, Packetbeat ignores all the transactions initiated from the server running Packetbeat. This is useful when two Packetbeat instances publish the same transactions. Because one Packetbeat sees the transaction in its outgoing queue and the other sees it in its incoming queue, you can end up with duplicate transactions. To remove the duplicates, you can enable the `packetbeat.ignore_outgoing` option on one of the servers. For example, in the following scenario, you see a 3-server architecture where a Beat is installed on each server. t1 is the transaction exchanged between Server1 and Server2, and t2 is the transaction between Server2 and Server3. image::./images/option_ignore_outgoing.png[Beats Architecture] By default, each transaction is indexed twice because Beat2 sees both transactions. So you would see the following published transactions (when `ignore_outgoing` is false): - Beat1: t1 - Beat2: t1 and t2 - Beat3: t2 To avoid duplicates, you can force your Beats to send only the incoming transactions and ignore the transactions created by the local server. So you would see the following published transactions (when `ignore_outgoing` is true): - Beat1: none - Beat2: t1 - Beat3: t2 [[configuration-flows]] == Set up flows to monitor network traffic You can configure Packetbeat to collect and report statistics on network flows. A _flow_ is a group of packets sent over the same time period that share common properties, such as the same source and destination address and protocol. You can use this feature to analyze network traffic over specific protocols on your network. For each flow, Packetbeat reports the number of packets and the total number of bytes sent from the source to the destination. Each flow event also contains information about the source and destination hosts, such as their IP address. For bi-directional flows, Packetbeat reports statistics for the reverse flow. Packetbeat collects and reports statistics up to and including the transport layer. See <> for more info about the exported data. Here's an example of flow events visualized in the Flows dashboard: image::./images/flows.png[] To configure flows, use the `packetbeat.flows` option in the +{beatname_lc}.yml+ config file. Flows are enabled by default. If this section is missing from the configuration file, network flows are disabled. [source,yaml] -------------------------------------------------------------------------------- packetbeat.flows: timeout: 30s period: 10s -------------------------------------------------------------------------------- Here’s an example of a flow information sent by Packetbeat. See <> for a description of each field. [""source"",""json"",subs=""attributes""] -------------------------------------------------------------------------------- { ""@timestamp"": ""2018-11-15T14:41:24.000Z"", ""agent"": { ""hostname"": ""host.example.com"", ""name"": ""host.example.com"", ""version"": ""{version}"" }, ""destination"": { ""bytes"": 460, ""ip"": ""198.51.100.2"", ""mac"": ""06:05:04:03:02:01"", ""packets"": 2, ""port"": 80 }, ""event"": { ""dataset"": ""flow"", ""duration"": 3000000000, ""end"": ""2018-11-15T14:41:24.000Z"", ""start"": ""2018-11-15T14:41:21.000Z"" }, ""flow"": { ""final"": true, <1> ""id"": ""FQQA/wz/Dv//////Fv8BAQEBAgMEBQYGBQQDAgGrAMsAcQPGM2QC9ZdQAA"", ""vlan"": 171 }, ""network"": { ""bytes"": 470, ""community_id"": ""1:t9T66/2c66NQyftAEsr4aMZv4Hc="", ""packets"": 3, ""transport"": ""tcp"", ""type"": ""ipv4"" }, ""source"": { ""bytes"": 10, ""ip"": ""203.0.113.3"", ""mac"": ""01:02:03:04:05:06"", ""packets"": 1, ""port"": 38901 } } -------------------------------------------------------------------------------- <1> Packetbeat sets the `flow.final` flag to `false` to indicate that the event contains an intermediate report about a flow that it's tracking. When the flow completes, Packetbeat sends one last event with `flow.final` set to `true`. If you want to aggregate sums of traffic, you need to filter on `final:true`, or use some other technique, so that you get only the latest update from each flow. You can disable intermediate reports by setting `period: -1s`. [float] === Configuration options You can specify the following options in the `packetbeat.flows` section of the +{beatname_lc}.yml+ config file: [float] ==== `enabled` Enables flows support if set to true. Set to false to disable network flows support without having to delete or comment out the flows section. The default value is true. [float] ==== `timeout` Timeout configures the lifetime of a flow. If no packets have been received for a flow within the timeout time window, the flow is killed and reported. The default value is 30s. [float] ==== `period` Configure the reporting interval. All flows are reported at the very same point in time. Periodical reporting can be disabled by setting the value to -1. If disabled, flows are still reported once being timed out. The default value is 10s. [float] [[packetbeat-configuration-flows-fields]] ==== `fields` Optional fields that you can specify to add additional information to the output. For example, you might add fields that you can use for filtering log data. Fields can be scalar values, arrays, dictionaries, or any nested combination of these. By default, the fields that you specify here will be grouped under a `fields` sub-dictionary in the output document. To store the custom fields as top-level fields, set the `fields_under_root` option to true. If a duplicate field is declared in the general configuration, then its value will be overwritten by the value declared here. [float] ==== `fields_under_root` If this option is set to true, the custom <> are stored as top-level fields in the output document instead of being grouped under a `fields` sub-dictionary. If the custom field names conflict with other field names added by Packetbeat, then the custom fields overwrite the other fields. [float] ==== `tags` A list of tags that will be sent with the protocol event. This setting is optional. [float] ==== `processors` A list of processors to apply to the data generated by the protocol. See <> for information about specifying processors in your config. [float] ==== `keep_null` If this option is set to true, fields with `null` values will be published in the output document. By default, `keep_null` is set to `false`. [[configuration-protocols]] == Specify which transaction protocols to monitor The `packetbeat.protocols` section of the +{beatname_lc}.yml+ config file contains configuration options for each supported protocol, including common options like `enabled`, `ports`, `send_request`, `send_response`, and options that are protocol-specific. Currently, Packetbeat supports the following protocols: include::./shared-protocol-list.asciidoc[] Example configuration: [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: icmp enabled: true - type: dhcpv4 ports: [67, 68] - type: dns ports: [53] - type: http ports: [80, 8080, 8000, 5000, 8002] - type: amqp ports: [5672] - type: cassandra ports: [9042] - type: memcache ports: [11211] - type: mysql ports: [3306,3307] - type: redis ports: [6379] - type: pgsql ports: [5432] - type: thrift ports: [9090] - type: tls ports: [443, 993, 995, 5223, 8443, 8883, 9243] ------------------------------------------------------------------------------ [[common-protocol-options]] === Common protocol options The following options are available for all protocols: [float] ==== `enabled` The enabled setting is a boolean setting to enable or disable protocols without having to comment out configuration sections. If set to false, the protocol is disabled. The default value is true. [float] ==== `ports` Exception: For ICMP the option `enabled` has to be used instead. The ports where Packetbeat will look to capture traffic for specific protocols. Packetbeat installs a https://en.wikipedia.org/wiki/Berkeley_Packet_Filter[BPF] filter based on the ports specified in this section. If a packet doesn't match the filter, very little CPU is required to discard the packet. Packetbeat also uses the ports specified here to determine which parser to use for each packet. [float] [[send-request-option]] ==== `send_request` If this option is enabled, the raw message of the request (`request` field) is sent to Elasticsearch. The default is false. This option is useful when you want to index the whole request. Note that for HTTP, the body is not included by default, only the HTTP headers. [float] [[send-response-option]] ==== `send_response` If this option is enabled, the raw message of the response (`response` field) is sent to Elasticsearch. The default is false. This option is useful when you want to index the whole response. Note that for HTTP, the body is not included by default, only the HTTP headers. [float] [[transaction-timeout-option]] ==== `transaction_timeout` The per protocol transaction timeout. Expired transactions will no longer be correlated to incoming responses, but sent to Elasticsearch immediately. [float] [[packetbeat-configuration-fields]] ==== `fields` Optional fields that you can specify to add additional information to the output. For example, you might add fields that you can use for filtering log data. Fields can be scalar values, arrays, dictionaries, or any nested combination of these. By default, the fields that you specify here will be grouped under a `fields` sub-dictionary in the output document. To store the custom fields as top-level fields, set the `fields_under_root` option to true. If a duplicate field is declared in the general configuration, then its value will be overwritten by the value declared here. [source,yaml] -------------------------------------------------------------------------------- packetbeat.protocols: - type: http ports: [80] fields: service_id: nginx -------------------------------------------------------------------------------- [float] [[packetbeat-fields-under-root]] ==== `fields_under_root` If this option is set to true, the custom <> are stored as top-level fields in the output document instead of being grouped under a `fields` sub-dictionary. If the custom field names conflict with other field names added by Packetbeat, then the custom fields overwrite the other fields. [float] ==== `tags` A list of tags that will be sent with the transaction event. This setting is optional. [float] ==== `processors` A list of processors to apply to the data generated by the protocol. See <> for information about specifying processors in your config. [float] ==== `keep_null` If this option is set to true, fields with `null` values will be published in the output document. By default, `keep_null` is set to `false`. [[packetbeat-icmp-options]] === Capture ICMP traffic ++++ ICMP ++++ The `icmp` section of the +{beatname_lc}.yml+ config file specifies options for the ICMP protocol. Here is a sample configuration section for ICMP: [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: icmp enabled: true ------------------------------------------------------------------------------ ==== Configuration options Also see <>. ===== `enabled` The ICMP protocol can be enabled/disabled via this option. The default is true. If enabled Packetbeat will generate the following BPF filter: `""icmp or icmp6""`. [[packetbeat-dns-options]] === Capture DNS traffic ++++ DNS ++++ The `dns` section of the +{beatname_lc}.yml+ config file specifies configuration options for the DNS protocol. The DNS protocol supports processing DNS messages on TCP and UDP. Here is a sample configuration section for DNS: [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: dns ports: [53] include_authorities: true include_additionals: true ------------------------------------------------------------------------------ ==== Configuration options Also see <>. ===== `include_authorities` If this option is enabled, dns.authority fields (authority resource records) are added to DNS events. The default is false. ===== `include_additionals` If this option is enabled, dns.additionals fields (additional resource records) are added to DNS events. The default is false. [[packetbeat-http-options]] === Capture HTTP traffic ++++ HTTP ++++ The HTTP protocol has several specific configuration options. Here is a sample configuration for the `http` section of the +{beatname_lc}.yml+ config file: [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: http ports: [80, 8080, 8000, 5000, 8002] hide_keywords: [""pass"", ""password"", ""passwd""] send_headers: [""User-Agent"", ""Cookie"", ""Set-Cookie""] split_cookie: true real_ip_header: ""X-Forwarded-For"" ------------------------------------------------------------------------------ ==== Configuration options Also see <>. ===== `hide_keywords` A list of query parameters that Packetbeat will automatically censor in the transactions that it saves. The values associated with these parameters are replaced by `'xxxxx'`. By default, no changes are made to the HTTP messages. Packetbeat has this option because, unlike SQL traffic, which typically only contains the hashes of the passwords, HTTP traffic may contain sensitive data. To reduce security risks, you can configure this option to avoid sending the contents of certain HTTP POST parameters. WARNING: This option replaces query parameters from GET requests and top-level parameters from POST requests. If sensitive data is encoded inside a parameter that you don't specify here, Packetbeat cannot censor it. Also, note that if you configure Packetbeat to save the raw request and response fields (see the <> and the <> options), sensitive data may be present in those fields. ===== `redact_authorization` When this option is enabled, Packetbeat obscures the value of `Authorization` and `Proxy-Authorization` HTTP headers, and censors those strings in the response. You should set this option to true for transactions that use Basic Authentication because they may contain the base64 unencrypted username and password. ===== `send_headers` A list of header names to capture and send to Elasticsearch. These headers are placed under the `headers` dictionary in the resulting JSON. ===== `send_all_headers` Instead of sending a white list of headers to Elasticsearch, you can send all headers by setting this option to true. The default is false. ===== `redact_headers` A list of headers to redact if present in the HTTP request. This will keep the header field present, but will redact it's value to show the header's presence. ===== `include_body_for` The list of content types for which Packetbeat exports the full HTTP payload. The HTTP body is available under `http.request.body.content` and `http.response.body.content` for these Content-Types. In addition, if <> option is enabled, then the HTTP body is exported together with the HTTP headers under `response` and if <> enabled, then `request` contains the entire HTTP message including the body. In the following example, the HTML attachments of the HTTP responses are exported under the `response` field and under `http.request.body.content` or `http.response.body.content`: [source,yml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: http ports: [80, 8080] send_response: true include_body_for: [""text/html""] ------------------------------------------------------------------------------ ===== `decode_body` A boolean flag that controls decoding of HTTP payload. It interprets the `Content-Encoding` and `Transfer-Encoding` headers and uncompresses the entity body. Supported encodings are `gzip` and `deflate`. This option is only applicable in the cases where the HTTP payload is exported, that is, when one of the `include_*_body_for` options is specified or a POST request contains url-encoded parameters. ===== `split_cookie` If the `Cookie` or `Set-Cookie` headers are sent, this option controls whether they are split into individual values. For example, with this option set, an HTTP response might result in the following JSON: [source,json] ------------------------------------------------------------------------------ ""response"": { ""code"": 200, ""headers"": { ""connection"": ""close"", ""content-language"": ""en"", ""content-type"": ""text/html; charset=utf-8"", ""date"": ""Fri, 21 Nov 2014 17:07:34 GMT"", ""server"": ""gunicorn/19.1.1"", ""set-cookie"": { <1> ""csrftoken"": ""S9ZuJF8mvIMT5CL4T1Xqn32wkA6ZSeyf"", ""expires"": ""Fri, 20-Nov-2015 17:07:34 GMT"", ""max-age"": ""31449600"", ""path"": ""/"" }, ""vary"": ""Cookie, Accept-Language"" }, ""status_phrase"": ""OK"" } ------------------------------------------------------------------------------ <1> Note that `set-cookie` is a map containing the cookie names as keys. The default is false. ===== `real_ip_header` The header field to extract the real IP from. This setting is useful when you want to capture traffic behind a reverse proxy, but you want to get the geo-location information. If this header is present and contains a valid IP addresses, the information is used for the `network.forwarded_ip` field. ===== `max_message_size` If an individual HTTP message is larger than this setting (in bytes), it will be trimmed to this size. Unless this value is very small (<1.5K), Packetbeat is able to still correctly follow the transaction and create an event for it. The default is 10485760 (10 MB). [[packetbeat-amqp-options]] === Capture AMQP traffic ++++ AMQP ++++ The `amqp` section of the +{beatname_lc}.yml+ config file specifies configuration options for the AMQP 0.9.1 protocol. Here is a sample configuration: [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: amqp ports: [5672] max_body_length: 1000 parse_headers: true parse_arguments: false hide_connection_information: true ------------------------------------------------------------------------------ ==== Configuration options Also see <>. ===== `max_body_length` The maximum size in bytes of the message displayed in the request or response fields. Messages that are bigger than the specified size are truncated. Use this option to avoid publishing huge messages when <> or <> is enabled. The default is 1000 bytes. ===== `parse_headers` If set to true, Packetbeat parses the additional arguments specified in the headers field of a message. Those arguments are key-value pairs that specify information such as the content type of the message or the message priority. The default is true. ===== `parse_arguments` If set to true, Packetbeat parses the additional arguments specified in AMQP methods. Those arguments are key-value pairs specified by the user and can be of any length. The default is true. ===== `hide_connection_information` If set to false, the connection layer methods of the protocol are also displayed, such as the opening and closing of connections and channels by clients, or the quality of service negotiation. The default is true. [[configuration-cassandra]] === Capture Cassandra traffic ++++ Cassandra ++++ The following settings are specific to the Cassandra protocol. Here is a sample configuration for the `cassandra` section of the +{beatname_lc}.yml+ config file: [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: cassandra send_request_header: true send_response_header: true compressor: ""snappy"" ignored_ops: [""SUPPORTED"",""OPTIONS""] ------------------------------------------------------------------------------ ==== Configuration options Also see <>. ===== `send_request_header` If this option is enabled, the raw message of the response (`cassandra_request.request_headers` field) is sent to Elasticsearch. The default is true. enable `send_request` first before enable this option. ===== `send_response_header` If this option is enabled, the raw message of the response (`cassandra_response.response_headers` field) is included in published events. The default is true. enable `send_response` first before enable this option. ===== `ignored_ops` This option indicates which Operator/Operators captured will be ignored. currently support: `ERROR` ,`STARTUP` ,`READY` ,`AUTHENTICATE` ,`OPTIONS` ,`SUPPORTED` , `QUERY` ,`RESULT` ,`PREPARE` ,`EXECUTE` ,`REGISTER` ,`EVENT` , `BATCH` ,`AUTH_CHALLENGE`,`AUTH_RESPONSE` ,`AUTH_SUCCESS` . ===== `compressor` Configures the default compression algorithm being used to uncompress compressed frames by name. Currently only `snappy` is can be configured. By default no compressor is configured. [[packetbeat-memcache-options]] === Capture Memcache traffic ++++ Memcache ++++ The `memcache` section of the +{beatname_lc}.yml+ config file specifies configuration options for the memcache protocol. Here is a sample configuration section for memcache: [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: memcache ports: [11211] parseunknown: false maxvalues: 0 maxbytespervalue: 100 transaction_timeout: 200 udptransactiontimeout: 200 ------------------------------------------------------------------------------ ==== Configuration options Also see <>. ===== `parseunknown` When this option is enabled, it forces the memcache text protocol parser to accept unknown commands. NOTE: The unknown commands MUST NOT contain a data part. ===== `maxvalues` The maximum number of values to store in the message (multi-get). All values will be base64 encoded. The possible settings for this option are: * `maxvalue: -1`, which stores all values (text based protocol multi-get) * `maxvalue: 0`, which stores no values (default) * `maxvalue: N`, which stores up to N values ===== `maxbytespervalue` The maximum number of bytes to be copied for each value element. NOTE: Values will be base64 encoded, so the actual size in the JSON document will be 4 times the value that you specify for `maxbytespervalue`. ===== `udptransactiontimeout` The transaction timeout in milliseconds. The defaults is 10000 milliseconds. NOTE: Quiet messages in UDP binary protocol get responses only if there is an error. The memcache protocol analyzer will wait for the number of milliseconds specified by `udptransactiontimeout` before publishing quiet messages. Non-quiet messages or quiet requests with an error response are published immediately. [[packetbeat-mysql-options]] === Capture MySQL traffic ++++ MySQL ++++ The `mysql` section of the +{beatname_lc}.yml+ config file specifies configuration options for the MySQL protocols. [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: mysql ports: [3306,3307] ------------------------------------------------------------------------------ ==== Configuration options Also see <>. ===== `max_rows` The maximum number of rows from the SQL message to publish to Elasticsearch. The default is 10 rows. ===== `max_row_length` The maximum length in bytes of a row from the SQL message to publish to Elasticsearch. The default is 1024 bytes. ==== `statement_timeout` The duration for which prepared statements are cached after their last use. Valid time units are ""ns"", ""us"" (or ""µs""), ""ms"", ""s"", ""m"", ""h"". The default is `1h`. [[packetbeat-pgsql-options]] === Capture PgSQL traffic ++++ PgSQL ++++ The `pgsql` sections of the +{beatname_lc}.yml+ config file specifies configuration options for the PgSQL protocols. [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: pgsql ports: [5432] ------------------------------------------------------------------------------ ==== Configuration options Also see <>. ===== `max_rows` The maximum number of rows from the SQL message to publish to Elasticsearch. The default is 10 rows. ===== `max_row_length` The maximum length in bytes of a row from the SQL message to publish to Elasticsearch. The default is 1024 bytes. [[configuration-thrift]] === Capture Thrift traffic ++++ Thrift ++++ https://thrift.apache.org/[Apache Thrift] is a communication protocol and RPC framework initially created at Facebook. It is sometimes used in http://martinfowler.com/articles/microservices.html[microservices] architectures because it provides better performance when compared to the more obvious HTTP/RESTful API choice, while still supporting a wide range of programming languages and frameworks. Packetbeat works based on a copy of the traffic, which means that you get performance management features without having to modify your services in any way and without any latency overhead. Packetbeat captures the transactions from the network and indexes them in Elasticsearch so that they can be analyzed and searched. Packetbeat indexes the method, parameters, return value, and exceptions of each Thrift-RPC call. You can search by and create statistics based on any of these fields. Packetbeat automatically fills in the `status` column with either `OK` or `Error`, so it's easy to find the problematic RPC calls. A transaction is put into the `Error` state if it returned an exception. Packetbeat also indexes the `event.duration` field so you can get performance analytics and find the slow RPC calls. Here is an example performance dashboard: image::./images/thrift-dashboard.png[Thrift-RPC dashboard] Thrift supports multiple http://en.wikipedia.org/wiki/Apache_Thrift[transport and protocol types]. Currently Packetbeat supports the default `TSocket` transport as well as the `TFramed` transport. From the protocol point of view, Packetbeat currently supports only the default `TBinary` protocol. Packetbeat also has several configuration options that allow you to get the right balance between visibility, disk usage, and data protection. You can, for example, choose to obfuscate all strings or to store the requests but not the responses, while still capturing the response time for each of the RPC calls. You can also choose to limit the size of strings and lists to a given number of elements, so you can fine tune how much data you want to have stored in Elasticsearch. The Thrift protocol has several specific configuration options. Here is an example configuration section for the Thrift protocol in the +{beatname_lc}.yml+ config file: [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: thrift transport_type: socket protocol_type: binary idl_files: [""tutorial.thrift"", ""shared.thrift""] string_max_size: 200 collection_max_size: 20 capture_reply: true obfuscate_strings: true drop_after_n_struct_fields: 100 ------------------------------------------------------------------------------ Providing the Thrift IDL files to Packetbeat is optional. The binary Thrift messages include the called method name and enough structural information to decode the messages without needing the IDL files. However, if you provide the IDL files, Packetbeat can also resolve the service name, arguments, and exception names. ==== Configuration options Also see <>. ===== `transport_type` The Thrift transport type. Currently this option accepts the values `socket` for TSocket, which is the default Thrift transport, and `framed` for the TFramed Thrift transport. The default is `socket`. ===== `protocol_type` The Thrift protocol type. Currently the only accepted value is `binary` for the TBinary protocol, which is the default Thrift protocol. ===== `idl_files` The Thrift interface description language (IDL) files for the service that Packetbeat is monitoring. Providing the IDL files is optional, because the Thrift messages contain enough information to decode them without having the IDL files. However, providing the IDL enables Packetbeat to include parameter and exception names. ===== `string_max_size` The maximum length for strings in parameters or return values. If a string is longer than this value, the string is automatically truncated to this length. Packetbeat adds dots at the end of the string to mark that it was truncated. The default is 200. ===== `collection_max_size` The maximum number of elements in a Thrift list, set, map, or structure. If a collection has more elements than this value, Packetbeat captures only the specified number of elements. Packetbeat adds a fictive last element `...` to the end of the collection to mark that it was truncated. The default is 15. ===== `capture_reply` If this option is set to false, Packetbeat decodes the method name from the reply and simply skips the rest of the response message. This setting can be useful for performance, disk usage, or data retention reasons. The default is true. ===== `obfuscate_strings` If this option is set to true, Packetbeat replaces all strings found in method parameters, return codes, or exception structures with the `""*""` string. ===== `drop_after_n_struct_fields` The maximum number of fields that a structure can have before Packetbeat ignores the whole transaction. This is a memory protection mechanism (so that Packetbeat's memory doesn't grow indefinitely), so you would typically set this to a relatively high value. The default is 500. [[configuration-mongodb]] === Capture MongoDB traffic ++++ MongoDB ++++ The following settings are specific to the MongoDB protocol. Here is a sample configuration for the `mongodb` section of the +{beatname_lc}.yml+ config file: [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: mongodb send_request: true send_response: true max_docs: 0 max_doc_length: 0 ------------------------------------------------------------------------------ ==== Configuration options The `max_docs` and `max_doc_length` settings are useful for limiting the amount of data Packetbeat indexes in the `response` fields. Also see <>. ===== `max_docs` The maximum number of documents from the response to index in the `response` field. The default is 10. You can set this to 0 to index an unlimited number of documents. Packetbeat adds a `[...]` line at the end to signify that there were additional documents that weren't saved because of this setting. ===== `max_doc_length` The maximum number of characters in a single document indexed in the `response` field. The default is 5000. You can set this to 0 to index an unlimited number of characters per document. If the document is trimmed because of this setting, Packetbeat adds the string `...` at the end of the document. Note that limiting documents in this way means that they are no longer correctly formatted JSON objects. [[configuration-tls]] === Capture TLS traffic ++++ TLS ++++ TLS is a cryptographic protocol that provides secure communications on top of an existing application protocol, like HTTP or MySQL. Packetbeat intercepts the initial handshake in a TLS connection and extracts useful information that helps operators diagnose problems and strengthen the security of their network and systems. It does not decrypt any information from the encapsulated protocol, nor does it reveal any sensitive information such as cryptographic keys. TLS versions 1.0 to 1.3 and SSL 3.0 are supported. It works by intercepting the client and server ""hello"" messages, which contain the negotiated parameters for the connection such as cryptographic ciphers and protocol versions. It can also intercept TLS alerts, which are sent by one of the parties to signal a problem with the negotiation, such as an expired certificate or a cryptographic error. An example of indexed event: [source,json] ------------------------------------------------------------------------------ ""tls"": { ""client"": { ""supported_ciphers"": [ ""TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"", ""TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"", ""TLS_RSA_WITH_3DES_EDE_CBC_SHA"", ""TLS_EMPTY_RENEGOTIATION_INFO_SCSV"" ], ""ja3"": ""e6573e91e6eb777c0933c5b8f97f10cd"", ""server_name"": ""example.net"" }, ""server"": { ""subject"": ""CN=www.example.org,OU=Technology,O=Internet Corporation for Assigned Names and Numbers,L=Los Angeles,ST=California,C=US"", ""issuer"": ""CN=DigiCert SHA2 Secure Server CA,O=DigiCert Inc,C=US"", ""not_before"": ""2018-11-28T00:00:00.000Z"", ""not_after"": ""2020-12-02T12:00:00.000Z"", ""hash"": { ""sha1"": ""7BB698386970363D2919CC5772846984FFD4A889"" } }, ""version"": ""1.2"", ""version_protocol"": ""tls"", ""cipher"": ""TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"", ""established"": true, ""next_protocol"": ""h2"", ""detailed"": { ""server_certificate"": { ""subject"": { ""common_name"": ""www.example.org"", ""country"": ""US"", ""organization"": ""Internet Corporation for Assigned Names and Numbers"", ""organizational_unit"": ""Technology"", ""locality"": ""Los Angeles"", ""province"": ""California"" }, ""not_after"": ""2020-12-02T12:00:00.000Z"", ""public_key_size"": 2048, ""alternative_names"": [ ""www.example.org"", ""example.com"", ""example.edu"", ""example.net"", ""example.org"", ""www.example.com"", ""www.example.edu"", ""www.example.net"" ], ""signature_algorithm"": ""SHA256-RSA"", ""version"": 3, ""issuer"": { ""organization"": ""DigiCert Inc"", ""common_name"": ""DigiCert SHA2 Secure Server CA"", ""country"": ""US"" }, ""not_before"": ""2018-11-28T00:00:00.000Z"", ""public_key_algorithm"": ""RSA"", ""serial_number"": ""21020869104500376438182461249190639870"" }, ""server_certificate_chain"": [ { ""public_key_algorithm"": ""RSA"", ""not_before"": ""2013-03-08T12:00:00.000Z"", ""not_after"": ""2023-03-08T12:00:00.000Z"", ""version"": 3, ""serial_number"": ""2646203786665923649276728595390119057"", ""issuer"": { ""organizational_unit"": ""www.digicert.com"", ""common_name"": ""DigiCert Global Root CA"", ""country"": ""US"", ""organization"": ""DigiCert Inc"" }, ""subject"": { ""country"": ""US"", ""organization"": ""DigiCert Inc"", ""common_name"": ""DigiCert SHA2 Secure Server CA"" }, ""public_key_size"": 2048, ""signature_algorithm"": ""SHA256-RSA"" }, { ""public_key_algorithm"": ""RSA"", ""subject"": { ""common_name"": ""DigiCert Global Root CA"", ""country"": ""US"", ""organization"": ""DigiCert Inc"", ""organizational_unit"": ""www.digicert.com"" }, ""issuer"": { ""country"": ""US"", ""organization"": ""DigiCert Inc"", ""organizational_unit"": ""www.digicert.com"", ""common_name"": ""DigiCert Global Root CA"" }, ""signature_algorithm"": ""SHA1-RSA"", ""serial_number"": ""10944719598952040374951832963794454346"", ""not_before"": ""2006-11-10T00:00:00.000Z"", ""not_after"": ""2031-11-10T00:00:00.000Z"", ""public_key_size"": 2048, ""version"": 3 } ], ""client_certificate_requested"": false, ""version"": ""TLS 1.2"", ""client_hello"": { ""version"": ""3.3"", ""supported_compression_methods"": [ ""NULL"" ], ""extensions"": { ""ec_points_formats"": [ ""uncompressed"" ], ""supported_groups"": [ ""x25519"", ""secp256r1"", ""secp384r1"" ], ""signature_algorithms"": [ ""rsa_pkcs1_sha512"", ""ecdsa_secp521r1_sha512"", ""(unknown:0xefef)"", ""rsa_pkcs1_sha384"", ""ecdsa_secp384r1_sha384"", ""rsa_pkcs1_sha256"", ""ecdsa_secp256r1_sha256"", ""(unknown:0xeeee)"", ""(unknown:0xeded)"", ""(unknown:0x0301)"", ""(unknown:0x0303)"", ""rsa_pkcs1_sha1"", ""ecdsa_sha1"" ], ""application_layer_protocol_negotiation"": [ ""h2"", ""http/1.1"" ], ""server_name_indication"": [ ""example.net"" ] } }, ""server_hello"": { ""version"": ""3.3"", ""session_id"": ""23bb2aed5d215e1228220b0a51d7aa220785e9e4b83b4f430229117971e9913f"", ""selected_compression_method"": ""NULL"", ""extensions"": { ""application_layer_protocol_negotiation"": [ ""h2"" ], ""_unparsed_"": [ ""renegotiation_info"", ""server_name_indication"" ], ""ec_points_formats"": [ ""uncompressed"", ""ansiX962_compressed_prime"", ""ansiX962_compressed_char2"" ] } } } } ------------------------------------------------------------------------------ The TLS events generated by {beatname_uc} follow the Elastic Common Schema (ECS) format. See {ecs-ref}/ecs-tls.html[ECS TLS fields] for a description of the populated fields. Detailed information that is not defined in ECS is added under the `tls.detailed` key. The <> configuration flag is used to control whether this information is exported. The fields under `tls.detailed.client_hello` contain the algorithms and extensions supported by the client, as well as the maximum TLS version it supports. Fields under `tls.detailed.server_hello` contain the final settings for the TLS session: The selected cipher, compression method, TLS version to use and other extensions such as application layer protocol negotiation (ALPN). See the <> section for more information. The following settings are specific to the TLS protocol. Here is a sample configuration for the `tls` section of the +{beatname_lc}.yml+ config file: [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: tls send_certificates: true include_raw_certificates: false include_detailed_fields: true fingerprints: [ md5, sha1, sha256 ] ------------------------------------------------------------------------------ ==== Configuration options The `send_certificates` and `include_detailed_fields` settings are useful for limiting the amount of data Packetbeat indexes, as multiple certificates are usually exchanged in a single transaction, and those can take a considerable amount of storage. Also see <>. ===== `send_certificates` This setting causes information about the certificates presented by the client and server to be included in the detailed fields. The server's certificate is indexed under `tls.detailed.server_certificate` and its certification chain under `tls.detailed.server_certificate_chain`. For the client, the `client_certificate` and `client_certificate_chain` fields are used. The default is true. ===== `include_raw_certificates` You can set `include_raw_certificates` to include the raw certificate chains encoded in PEM format, under the `tls.server.certificate_chain` and `tls.client.certificate_chain` fields. The default is false. [[include_detailed_fields]] ===== `include_detailed_fields` Controls whether the <> are added to exported documents. When set to `false`, only {ecs-ref}/ecs-tls.html[ECS TLS fields] are included. The default is `true`. ===== `fingerprints` Defines a list of hash algorithms to calculate the certificate's fingerprints. Valid values are `sha1`, `sha256` and `md5`. The default is to output SHA-1 fingerprints. [[packetbeat-redis-options]] === Capture Redis traffic ++++ Redis ++++ The Redis protocol has several specific configuration options. Here is a sample configuration for the `redis` section of the +{beatname_lc}.yml+ config file: [source,yaml] ------------------------------------------------------------------------------ packetbeat.protocols: - type: redis ports: [6379] queue_max_bytes: 1048576 queue_max_messages: 20000 ------------------------------------------------------------------------------ ==== Configuration options Also see <>. ===== `queue_max_bytes` and `queue_max_messages` In order for request/response correlation to work, {beatname_uc} needs to store requests in memory until a response is received. These settings impose a limit on the number of bytes (`queue_max_bytes`) and number of requests (`queue_max_messages`) that can be stored. These limits are per-connection. The default is to queue up to 1MB or 20.000 requests per connection, which allows to use request pipelining while at the same time limiting the amount of memory consumed by replication sessions. [[configuration-processes]] == Specify which processes to monitor This section of the +{beatname_lc}.yml+ config file is optional, but configuring the processes enables Packetbeat to show you not only the servers that the traffic is flowing between, but also the processes. Packetbeat can even show you the traffic between two processes running on the same host, which is particularly useful when you have many services running on the same server. By default, process enrichment is disabled. When Packetbeat starts, and then periodically afterwards, it scans the process table for processes that match the configuration file. For each of these processes, it monitors which file descriptors it has opened. When a new packet is captured, it reads the list of active TCP and UDP connections and matches the corresponding one with the list of file descriptors. All this information is available via system interfaces: The `/proc` file system in Linux and the IP Helper API (`iphlpapi.dll`) on Windows, so {beatname_uc} doesn't need a kernel module. NOTE: Process monitoring is currently only supported on Linux and Windows systems. Packetbeat automatically disables process monitoring when it detects other operating systems. Example configuration: [source,yaml] ------------------------------------------------------------------------------ packetbeat.procs.enabled: true ------------------------------------------------------------------------------ When the process monitor is enabled, it will enrich all the events whose source or destination is a local process. The `source.process` and/or `destination.process` fields will be added to an event, when the server side or client side of the connection belong to a local process, respectively. [float] === Configuration options You can specify the following process monitoring options in the `monitored` section of the +{beatname_lc}.yml+ config file to customize the name of process: [float] ==== `process` The name of the process as it will appear in the published transactions. The name doesn't have to match the name of the executable, so feel free to choose something more descriptive (for example, ""myapp"" instead of ""gunicorn""). [float] ==== `cmdline_grep` The name used to identify the process at run time. When Packetbeat starts, and then periodically afterwards, it scans the process table for processes that match the values specified for this option. The match is done against the process' command line as read from `/proc//cmdline`. [float] [[shutdown-timeout]] ==== `shutdown_timeout` How long Packetbeat waits on shutdown. By default, this option is disabled. Packetbeat will wait for `shutdown_timeout` and then close. It will not track if all events were sent previously. Example configuration: [source,yaml] ------------------------------------------------------------------------------------- packetbeat.shutdown_timeout: 5s ------------------------------------------------------------------------------------- ",12343,False,2128.4236593176056,median "// // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You 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. // Getting Started with Apache NiFi ================================ Apache NiFi Team :homepage: http://nifi.apache.org Who is This Guide For? ---------------------- This guide is written for user who have never used, have had limited exposure to, or only accomplished specific tasks within NiFi. This guide is not intended to be an exhaustive instruction manual or a reference guide. The link:user-guide.html[User Guide] provides a great deal of information and is intended to be a much more exhaustive resource and is very useful as a reference guide, as well. This guide, in comparison, is intended to provide users with just the information needed in order to understand how to work with NiFi in order to quickly and easily build powerful and agile dataflows. Because some of the information in this guide is applicable only for first-time users while other information may be applicable for those who have used NiFi a bit, this guide is broken up into several different sections, some of which may not be useful for some readers. Feel free to jump to the sections that are most appropriate for you. This guide does expect that the user has a basic understanding of what NiFi is and does not delve into this level of detail. This level of information can be found in the link:overview.html[Overview] documentation. Terminology Used in This Guide ------------------------------ In order to talk about NiFi, there are a few key terms that readers should be familiar with. We will explain those NiFi-specific terms here, at a high level. *FlowFile*: Each piece of ""User Data"" (i.e., data that the user brings into NiFi for processing and distribution) is referred to as a FlowFile. A FlowFile is made up of two parts: Attributes and Content. The Content is the User Data itself. Attributes are key-value pairs that are associated with the User Data. *Processor*: The Processor is the NiFi component that is responsible for creating, sending, receiving, transforming, routing, splitting, merging, and processing FlowFiles. It is the most important building block available to NiFi users to build their dataflows. Downloading and Installing NiFi ------------------------------- NiFi can be downloaded from the link:http://nifi.apache.org/download.html[NiFi Downloads Page]. There are two packaging options available: a ""tarball"" that is tailored more to Linux and a zip file that is more applicable for Windows users. Mac OSX users may also use the tarball or can install via Homebrew. To install via Homebrew, simply run the command `brew install nifi`. For users who are not running OSX or do not have Homebrew installed, after downloading the version of NiFi that you would like to use simply extract the archive to the location that you wish to run the application from. For information on how to configure the instance of NiFi (for instance, to configure security, data storage configuration, or the port that NiFi is running on), see the link:administration-guide.html[Admin Guide]. Starting NiFi ------------- Once NiFi has been downloaded and installed as described above, it can be started by using the mechanism appropriate for your operating system. === For Windows Users For Windows users, navigate to the folder where NiFi was installed. Within this folder is a subfolder named `bin`. Navigate to this subfolder and double-click the `run-nifi.bat` file. This will launch NiFi and leave it running in the foreground. To shut down NiFi, select the window that was launched and hold the Ctrl key while pressing C. === For Linux/Mac OSX users For Linux and OSX users, use a Terminal window to navigate to the directory where NiFi was installed. To run NiFi in the foreground, run `bin/nifi.sh run`. This will leave the application running until the user presses Ctrl-C. At that time, it will initiate shutdown of the application. To run NiFi in the background, instead run `bin/nifi.sh start`. This will initiate the application to begin running. To check the status and see if NiFi is currently running, execute the command `bin/nifi.sh status`. NiFi can be shutdown by executing the command `bin/nifi.sh stop`. === Installing as a Service Currently, installing NiFi as a service is supported only for Linux and Mac OSX users. To install the application as a service, navigate to the installation directory in a Terminal window and execute the command `bin/nifi.sh install` to install the service with the default name `nifi`. To specify a custom name for the service, execute the command with an optional second argument that is the name of the service. For example, to install NiFi as a service with the name `dataflow`, use the command `bin/nifi.sh install dataflow`. Once installed, the service can be started and stopped using the appropriate commands, such as `sudo service nifi start` and `sudo service nifi stop`. Additionally, the running status can be checked via `sudo service nifi status`. I Started NiFi. Now What? ------------------------- Now that NiFi has been started, we can bring up the User Interface (UI) in order to create and monitor our dataflow. To get started, open a web browser and navigate to `http://localhost:8080/nifi`. The port can be changed by editing the `nifi.properties` file in the NiFi `conf` directory, but the default port is 8080. This will bring up the User Interface, which at this point is a blank canvas for orchestrating a dataflow: image:new-flow.png[""New Flow""] Near the top of the UI are a few toolbars that will be very important to create your first dataflow: image:nifi-toolbar-components.png[""Toolbar Components""] === Adding a Processor We can now begin creating our dataflow by adding a Processor to our canvas. To do this, drag the Processor icon (image:iconProcessor.png[""Processor""]) from the top-left of the screen into the middle of the canvas (the graph paper-like background) and drop it there. This will give us a dialog that allows us to choose which Processor we want to add: image:add-processor.png[""Add Processor""] We have quite a few options to choose from. For the sake of becoming oriented with the system, let's say that we just want to bring in files from our local disk into NiFi. When a developer creates a Processor, the developer can assign ""tags"" to that Processor. These can be thought of as keywords. We can filter by these tags or by Processor name by typing into the Filter box in the top-right corner of the dialog. Type in the keywords that you would think of when wanting to ingest files from a local disk. Typing in keyword ""file"", for instance, will provide us a few different Processors that deal with files. Filtering by the term ""local"" will narrow down the list pretty quickly, as well. If we select a Processor from the list, we will see a brief description of the Processor near the bottom of the dialog. This should tell us exactly what the Processor does. The description of the *GetFile* Processor tells us that it pulls data from our local disk into NiFi and then removes the local file. We can then double-click the Processor type or select it and choose the `Add` button. The Processor will be added to the canvas in the location that it was dropped. === Configuring a Processor Now that we have added the GetFile Processor, we can configure it by right-clicking on the Processor and choosing the `Configure` menu item. The provided dialog allows us to configure many different options that can be read about in the link:user-guide.html[User Guide], but for the sake of this guide, we will focus on the Properties tab. Once the Properties tab has been selected, we are given a list of several different properties that we can configure for the Processor. The properties that are available depend on the type of Processor and are generally different for each type. Properties that are in bold are required properties. The Processor cannot be started until all required properties have been configured. The most important property to configure for GetFile is the directory from which to pick up files. If we set the directory name to `./data-in`, this will cause the Processor to start picking up any data in the `data-in` subdirectory of the NiFi Home directory. We can choose to configure several different Properties for this Processor. If unsure what a particular Property does, we can hover over the Help icon ( image:iconInfo.png[""Help""] ) next to the Property Name with the mouse in order to read a description of the property. Additionally, the tooltip that is displayed when hovering over the Help icon will provide the default value for that property, if one exists, information about whether or not the property supports the Expression Language (see the <> section below), and previously configured values for that property. In order for this property to be valid, create a directory named `data-in` in the NiFi home directory and then click the `Ok` button to close the dialog. === Connecting Processors Each Processor has a set of defined ""Relationships"" that it is able to send data to. When a Processor finishes handling a FlowFile, it transfers it to one of these Relationships. This allows a user to configure how to handle FlowFiles based on the result of Processing. For example, many Processors define two Relationships: `success` and `failure`. Users are then able to configure data to be routed through the flow one way if the Processor is able to successfully process the data and route the data through the flow in a completely different manner if the Processor cannot process the data for some reason. Or, depending on the use case, it may simply route both relationships to the same route through the flow. Now that we have added and configured our GetFile processor and applied the configuration, we can see in the top-left corner of the Processor an Alert icon ( image:iconAlert.png[Alert] ) signaling that the Processor is not in a valid state. Hovering over this icon, we can see that the `success` relationship has not been defined. This simply means that we have not told NiFi what to do with the data that the Processor transfers to the `success` Relationship. In order to address this, let's add another Processor that we can connect the GetFile Processor to, by following the same steps above. This time, however, we will simply log the attributes that exist for the FlowFile. To do this, we will add a LogAttributes Processor. We can now send the output of the GetFile Processor to the LogAttribute Processor. Hover over the GetFile Processor with the mouse and a Connection Icon ( image:iconConnection.png[Connection] ) will appear over the middle of the Processor. We can drag this icon from the GetFile Processor to the LogAttribute Processor. This gives us a dialog to choose which Relationships we want to include for this connection. Because GetFile has only a single Relationship, `success`, it is automatically selected for us. Clicking on the Settings tab provides a handful of options for configuring how this Connection should behave: image:connection-settings.png[Connection Settings] We can give the Connection a name, if we like. Otherwise, the Connection name will be based on the selected Relationships. We can also set an expiration for the data. By default, it is set to ""0 sec"" which indicates that the data should not expire. However, we can change the value so that when data in this Connection reaches a certain age, it will automatically be deleted (and a corresponding EXPIRE Provenance event will be created). The backpressure thresholds allow us to specify how full the queue is allowed to become before the source Processor is no longer scheduled to run. This allows us to handle cases where one Processor is capable of producing data faster than the next Processor is capable of consuming that data. If the backpressure is configured for each Connection along the way, the Processor that is bringing data into the system will eventually experience the backpressure and stop bringing in new data so that our system has the ability to recover. Finally, we have the Prioritizers on the right-hand side. This allows us to control how the data in this queue is ordered. We can drag Prioritizers from the ""Available prioritizers"" list to the ""Selected prioritizers"" list in order to active the prioritizer. If multiple prioritizers are activated, they will be evaluated such that the Prioritizer listed first will be evaluated first and if two FlowFiles are determined to be equal according to that Prioritizers, the second Prioritizer will be used. For the sake of this discussion, we can simply click `Add`. to add the Connection to our graph. We should now see that the Alert icon has changed to a Stopped icon ( image:iconStop.png[Stopped] ). The LogAttribute Processor, however, is now invalid because its `success` Relationship has not been connected to anything. Let's address this by signaling that data that is routed to `success` by LogAttribute should be ""Auto Terminated,"" meaning that NiFi should consider the FlowFile's processing complete and ""drop"" the data. To do this, we configure the LogAttribute Processor. On the Settings tab, in the right-hand side we can check the box next to the `success` Relationship to Auto Terminate the data. Clicking `OK` will close the dialog and show that both Processors are now stopped. === Starting and Stopping Processors At this point, we have two Processors on our graph, but nothing is happening. In order to start the Processors, we can click on each one individually and then right-click and choose the `Start` menu item. Alternatively, we can select the first Processor, and then hold the Shift key while selecting the other Processor in order to select both. Then, we can right-click and choose the `Start` menu item. As an alternative to using the context menu, we can select the Processors and then click the Start icon in the toolbar at the top of the screen. Once started, the icon in the top-left corner of the Processors will change from a stopped icon to a running icon. We can then stop the Processors by using the Stop icon in the toolbar or the `Stop` menu item. Once a Processor has started, we are not able to configure it anymore. Instead, when we right-click on the Processor, we are given the option to view its current configuration. In order to configure a Processor, we must first stop the Processor and wait for any tasks that may be executing to finish. The number of tasks currently executing is shown in the top-right corner of the Processor, but nothing is shown there if there are currently no tasks. === Getting More Info for a Processor With each Processor having the ability to expose multiple different Properties and Relationships, it can become quite difficult to remember how all of the different pieces work for each Processor. To address this, you are able to right-click on a Processor and choose the `Usage` menu item. This will provide you with the Processor's usage information, such as a description of the Processor, the different Relationships that are available, when the different Relationships are used, Properties that are exposed by the Processor and their documentation, as well as which FlowFile Attributes (if any) are expected on incoming FlowFiles and which Attributes (if any) are added to outgoing FlowFiles. === Other Components The toolbar that provides users the ability to drag and drop Processors onto the graph includes several other components that can be used to build a dataflow. These components include Input and Output Ports, Funnels, Process Groups, and Remote Process Groups. Due to the intended scope of this document, we will not discuss these elements here, but information is readily available in the link:user-guide.html#building-dataflow[Building a Dataflow section] of the link:user-guide.html[User Guide]. What Processors are Available ----------------------------- In order to create an effective dataflow, the users must understand what types of Processors are available to them. NiFi contains many different Processors out of the box. These Processors provide capabilities to ingest data from numerous different systems, route, transform, process, split, and aggregate data, and distribute data to many systems. The number of Processors that are available increases in nearly each release of NiFi. As a result, we will not attempt to name each of the Processors that are available, but we will highlight some of the most frequently used Processors, categorizing them by their functions. === Data Transformation - *CompressContent*: Compress or Decompress Content - *ConvertCharacterSet*: Convert the character set used to encode the content from one character set to another - *EncryptContent*: Encrypt or Decrypt Content - *ReplaceText*: Use Regular Expressions to modify textual Content - *TransformXml*: Apply an XSLT transform to XML Content - *TransformJSON*: Apply a JOLT specification to transform JSON Content === Routing and Mediation - *ControlRate*: Throttle the rate at which data can flow through one part of the flow - *DetectDuplicate*: Monitor for duplicate FlowFiles, based on some user-defined criteria. Often used in conjunction with HashContent - *DistributeLoad*: Load balance or sample data by distributing only a portion of data to each user-defined Relationship - *MonitorActivity*: Sends a notification when a user-defined period of time elapses without any data coming through a particular point in the flow. Optionally send a notification when dataflow resumes. - *RouteOnAttribute*: Route FlowFile based on the attributes that it contains. - *ScanAttribute*: Scans the user-defined set of Attributes on a FlowFile, checking to see if any of the Attributes match the terms found in a user-defined dictionary. - *RouteOnContent*: Search Content of a FlowFile to see if it matches any user-defined Regular Expression. If so, the FlowFile is routed to the configured Relationship. - *ScanContent*: Search Content of a FlowFile for terms that are present in a user-defined dictionary and route based on the presence or absence of those terms. The dictionary can consist of either textual entries or binary entries. - *ValidateXml*: Validation XML Content against an XML Schema; routes FlowFile based on whether or not the Content of the FlowFile is valid according to the user-defined XML Schema. === Database Access - *ConvertJSONToSQL*: Convert a JSON document into a SQL INSERT or UPDATE command that can then be passed to the PutSQL Processor - *ExecuteSQL*: Executes a user-defined SQL SELECT command, writing the results to a FlowFile in Avro format - *PutSQL*: Updates a database by executing the SQL DDM statement defined by the FlowFile's content - *SelectHiveQL*: Executes a user-defined HiveQL SELECT command against an Apache Hive database, writing the results to a FlowFile in Avro or CSV format - *PutHiveQL*: Updates a Hive database by executing the HiveQL DDM statement defined by the FlowFile's content [[AttributeExtraction]] === Attribute Extraction - *EvaluateJsonPath*: User supplies JSONPath Expressions (Similar to XPath, which is used for XML parsing/extraction), and these Expressions are then evaluated against the JSON Content to either replace the FlowFile Content or extract the value into the user-named Attribute. - *EvaluateXPath*: User supplies XPath Expressions, and these Expressions are then evaluated against the XML Content to either replace the FlowFile Content or extract the value into the user-named Attribute. - *EvaluateXQuery*: User supplies an XQuery query, and this query is then evaluated against the XML Content to either replace the FlowFile Content or extract the value into the user-named Attribute. - *ExtractText*: User supplies one or more Regular Expressions that are then evaluated against the textual content of the FlowFile, and the values that are extracted are then added as user-named Attributes. - *HashAttribute*: Performs a hashing function against the concatenation of a user-defined list of existing Attributes. - *HashContent*: Performs a hashing function against the content of a FlowFile and adds the hash value as an Attribute. - *IdentifyMimeType*: Evaluates the content of a FlowFile in order to determine what type of file the FlowFile encapsulates. This Processor is capable of detecting many different MIME Types, such as images, word processor documents, text, and compression formats just to name a few. - *UpdateAttribute*: Adds or updates any number of user-defined Attributes to a FlowFile. This is useful for adding statically configured values, as well as deriving Attribute values dynamically by using the Expression Language. This processor also provides an ""Advanced User Interface,"" allowing users to update Attributes conditionally, based on user-supplied rules. === System Interaction - *ExecuteProcess*: Runs the user-defined Operating System command. The Process's StdOut is redirected such that the content that is written to StdOut becomes the content of the outbound FlowFile. This Processor is a Source Processor - its output is expected to generate a new FlowFile, and the system call is expected to receive no input. In order to provide input to the process, use the ExecuteStreamCommand Processor. - *ExecuteStreamCommand*: Runs the user-defined Operating System command. The contents of the FlowFile are optionally streamed to the StdIn of the process. The content that is written to StdOut becomes the content of hte outbound FlowFile. This Processor cannot be used a Source Processor - it must be fed incoming FlowFiles in order to perform its work. To perform the same type of functionality with a Source Processor, see the ExecuteProcess Processor. === Data Ingestion - *GetFile*: Streams the contents of a file from a local disk (or network-attached disk) into NiFi and then deletes the original file. This Processor is expected to move the file from one location to another location and is not to be used for copying the data. - *GetFTP*: Downloads the contents of a remote file via FTP into NiFi and then deletes the original file. This Processor is expected to move the data from one location to another location and is not to be used for copying the data. - *GetSFTP*: Downloads the contents of a remote file via SFTP into NiFi and then deletes the original file. This Processor is expected to move the data from one location to another location and is not to be used for copying the data. - *GetJMSQueue*: Downloads a message from a JMS Queue and creates a FlowFile based on the contents of the JMS message. The JMS Properties are optionally copied over as Attributes, as well. - *GetJMSTopic*: Downloads a message from a JMS Topic and creates a FlowFile based on the contents of the JMS message. The JMS Properties are optionally copied over as Attributes, as well. This Processor supports both durable and non-durable subscriptions. - *GetHTTP*: Downloads the contents of a remote HTTP- or HTTPS-based URL into NiFi. The Processor will remember the ETag and Last-Modified Date in order to ensure that the data is not continually ingested. - *ListenHTTP*: Starts an HTTP (or HTTPS) Server and listens for incoming connections. For any incoming POST request, the contents of the request are written out as a FlowFile, and a 200 response is returned. - *ListenUDP*: Listens for incoming UDP packets and creates a FlowFile per packet or per bundle of packets (depending on configuration) and emits the FlowFile to the 'success' relationship. - *GetHDFS*: Monitors a user-specified directory in HDFS. Whenever a new file enters HDFS, it is copied into NiFi and deleted from HDFS. This Processor is expected to move the file from one location to another location and is not to be used for copying the data. This Processor is also expected to be run On Primary Node only, if run within a cluster. In order to copy the data from HDFS and leave it in-tact, or to stream the data from multiple nodes in the cluster, see the ListHDFS Processor. - *ListHDFS* / *FetchHDFS*: ListHDFS monitors a user-specified directory in HDFS and emits a FlowFile containing the filename for each file that it encounters. It then persists this state across the entire NiFi cluster by way of a Distributed Cache. These FlowFiles can then be fanned out across the cluster and sent to the FetchHDFS Processor, which is responsible for fetching the actual content of those files and emitting FlowFiles that contain the content fetched from HDFS. - *FetchS3Object*: Fetches the contents of an object from the Amazon Web Services (AWS) Simple Storage Service (S3). The outbound FlowFile contains the contents received from S3. - *GetKafka*: Consumes messages from Apache Kafka. The messages can be emitted as a FlowFile per message or can be batched together using a user-specified delimiter. - *GetMongo*: Executes a user-specified query against MongoDB and writes the contents to a new FlowFile. - *GetTwitter*: Allows Users to register a filter to listen to the Twitter ""garden hose"" or Enterprise endpoint, creating a FlowFile for each tweet that is received. === Data Egress / Sending Data - *PutEmail*: Sends an E-mail to the configured recipients. The content of the FlowFile is optionally sent as an attachment. - *PutFile*: Writes the contents of a FlowFile to a directory on the local (or network attached) file system. - *PutFTP*: Copies the contents of a FlowFile to a remote FTP Server. - *PutSFTP*: Copies the contents of a FlowFile to a remote SFTP Server. - *PutJMS*: Sends the contents of a FlowFile as a JMS message to a JMS broker, optionally adding JMS Properties based on Attributes. - *PutSQL*: Executes the contents of a FlowFile as a SQL DDL Statement (INSERT, UPDATE, or DELETE). The contents of the FlowFile must be a valid SQL statement. Attributes can be used as parameters so that the contents of the FlowFile can be parameterized SQL statements in order to avoid SQL injection attacks. - *PutKafka*: Sends the contents of a FlowFile to Kafka as a message. The FlowFile can be sent as a single message or a delimiter, such as a new-line can be specified, in order to send many messages for a single FlowFile. - *PutMongo*: Sends the contents of a FlowFile to Mongo as an INSERT or an UPDATE. === Splitting and Aggregation - *SplitText*: SplitText takes in a single FlowFile whose contents are textual and splits it into 1 or more FlowFiles based on the configured number of lines. For example, the Processor can be configured to split a FlowFile into many FlowFiles, each of which is only 1 line. - *SplitJson*: Allows the user to split a JSON object that is comprised of an array or many child objects into a FlowFile per JSON element. - *SplitXml*: Allows the user to split an XML message into many FlowFiles, each containing a segment of the original. This is generally used when several XML elements have been joined together with a ""wrapper"" element. This Processor then allows those elements to be split out into individual XML elements. - *UnpackContent*: Unpacks different types of archive formats, such as ZIP and TAR. Each file within the archive is then transferred as a single FlowFile. - *MergeContent*: This Processor is responsible for merging many FlowFiles into a single FlowFile. The FlowFiles can be merged by concatenating their content together along with optional header, footer, and demarcator, or by specifying an archive format, such as ZIP or TAR. FlowFiles can be binned together based on a common attribute, or can be ""defragmented"" if they were split apart by some other Splitting process. The minimum and maximum size of each bin is user-specified, based on number of elements or total size of FlowFiles' contents, and an optional Timeout can be assigned as well so that FlowFiles will only wait for their bin to become full for a certain amount of time. - *SegmentContent*: Segments a FlowFile into potentially many smaller FlowFiles based on some configured data size. The splitting is not performed against any sort of demarcator but rather just based on byte offsets. This is used before transmitting FlowFiles in order to provide lower latency by sending many different pieces in parallel. On the other side, these FlowFiles can then be reassembled by the MergeContent processor using the Defragment mode. - *SplitContent*: Splits a single FlowFile into potentially many FlowFiles, similarly to SegmentContent. However, with SplitContent, the splitting is not performed on arbitrary byte boundaries but rather a byte sequence is specified on which to split the content. === HTTP - *GetHTTP*: Downloads the contents of a remote HTTP- or HTTPS-based URL into NiFi. The Processor will remember the ETag and Last-Modified Date in order to ensure that the data is not continually ingested. - *ListenHTTP*: Starts an HTTP (or HTTPS) Server and listens for incoming connections. For any incoming POST request, the contents of the request are written out as a FlowFile, and a 200 response is returned. - *InvokeHTTP*: Performs an HTTP Request that is configured by the user. This Processor is much more versatile than the GetHTTP and PostHTTP but requires a bit more configuration. This Processor cannot be used as a Source Processor and is required to have incoming FlowFiles in order to be triggered to perform its task. - *PostHTTP*: Performs an HTTP POST request, sending the contents of the FlowFile as the body of the message. This is often used in conjunction with ListenHTTP in order to transfer data between two different instances of NiFi in cases where Site-to-Site cannot be used (for instance, when the nodes cannot access each other directly and are able to communicate through an HTTP proxy). - *HandleHttpRequest* / *HandleHttpResponse*: The HandleHttpRequest Processor is a Source Processor that starts an embedded HTTP(S) server similarly to ListenHTTP. However, it does not send a response to the client. Instead, the FlowFile is sent out with the body of the HTTP request as its contents and attributes for all of the typical Servlet parameters, headers, etc. as Attributes. The HandleHttpResponse then is able to send a response back to the client after the FlowFile has finished being processed. These Processors are always expected to be used in conjunction with one another and allow the user to visually create a Web Service within NiFi. This is particularly useful for adding a front-end to a non-web- based protocol or to add a simple web service around some functionality that is already performed by NiFi, such as data format conversion. === Amazon Web Services - *FetchS3Object*: Fetches the content of an object stored in Amazon Simple Storage Service (S3). The content that is retrieved from S3 is then written to the content of the FlowFile. - *PutS3Object*: Writes the contents of a FlowFile to an Amazon S3 object using the configured credentials, key, and bucket name. - *PutSNS*: Sends the contents of a FlowFile as a notification to the Amazon Simple Notification Service (SNS). - *GetSQS*: Pulls a message from the Amazon Simple Queuing Service (SQS) and writes the contents of the message to the content of the FlowFile. - *PutSQS*: Sends the contents of a FlowFile as a message to the Amazon Simple Queuing Service (SQS). - *DeleteSQS*: Deletes a message from the Amazon Simple Queuing Service (SQS). This can be used in conjunction with the GetSQS in order to receive a message from SQS, perform some processing on it, and then delete the object from the queue only after it has successfully completed processing. Working With Attributes ----------------------- Each FlowFile is created with several Attributes, and these Attributes will change over the life of the FlowFile. The concept of a FlowFile is extremely powerful and provides three primary benefits. First, it allows the user to make routing decisions in the flow so that FlowFiles that meet some criteria can be handled differently than other FlowFiles. This is done using the RouteOnAttribute and similar Processors. Secondly, Attributes are used in order to configure Processors in such a way that the configuration of the Processor is dependent on the data itself. For instance, the PutFile Processor is able to use the Attributes in order to know where to store each FlowFile, while the directory and filename Attributes may be different for each FlowFile. Finally, the Attributes provide extremely valuable context about the data. This is useful when reviewing the Provenance data for a FlowFile. This allows the user to search for Provenance data that match specific criteria, and it also allows the user to view this context when inspecting the details of a Provenance Event. By doing this, the user is then able to gain valuable insight as to why the data was processed one way or another, simply by glancing at this context that is carried along with the content. === Common Attributes Each FlowFile has a minimum set of Attributes: - *filename*: A filename that can be used to store the data to a local or remote file system - *path*: The name of a directory that can be used to store the data to a local or remote file system - *uuid*: A Universally Unique Identifier that distinguishes the FlowFile from other FlowFiles in the system. - *entryDate*: The date and time at which the FlowFile entered the system (i.e., was created). The value of this attribute is a number that represents the number of milliseconds since midnight, Jan. 1, 1970 (UTC). - *lineageStartDate*: Any time that a FlowFile is cloned, merged, or split, this results in a ""child"" FlowFile being created. As those children are then cloned, merged, or split, a chain of ancestors is built. This value represents the date and time at which the oldest ancestor entered the system. Another way to think about this is that this attribute represents the latency of the FlowFile through the system. The value is a number that represents the number of milliseconds since midnight, Jan. 1, 1970 (UTC). - *fileSize*: This attribute represents the number of bytes taken up by the FlowFile's Content. Note that the `uuid`, `entryDate`, `lineageStartDate`, and `fileSize` attributes are system-generated and cannot be changed. === Extracting Attributes NiFi provides several different Processors out of the box for extracting Attributes from FlowFiles. A list of commonly used Processors for this purpose can be found above in the <> section. This is a very common use case for building custom Processors, as well. Many Processors are written to understand a specific data format and extract pertinent information from a FlowFile's content, creating Attributes to hold that information, so that decisions can then be made about how to route or process the data. === Adding User-Defined Attributes In addition to having Processors that are able to extract particular pieces of information from FlowFile content into Attributes, it is also common for users to want to add their own user-defined Attributes to each FlowFile at a particular place in the flow. The UpdateAttribute Processor is designed specifically for this purpose. Users are able to add a new property to the Processor in the Configure dialog by clicking the ""+"" button in the top-right corner of the Properties tab. The user is then prompted to enter the name of the property and then a value. For each FlowFile that is processed by this UpdateAttribute Processor, an Attribute will be added for each user-defined property. The name of the Attribute will be the same as the name of the property that was added. The value of the Attribute will be the same as the value of the property. The value of the property may contain the Expression Language, as well. This allows Attributes to be modified or added based on other Attributes. For example, if we want to prepend the hostname that is processing a file as well as the date to a filename, we could do this by adding a property with the name `filename` and the value `${hostname()}-${now():format('yyyy-dd-MM')}-${filename}`. While this may seem confusing at first, the section below on <> will help to clear up what is going on here. In addition to always adding a defined set of Attributes, the UpdateAttribute Processor has an Advanced UI that allows the user to configure a set of rules for which Attributes should be added when. To access this capability, in the Configure dialog's Properties tab, click the `Advanced` button at the bottom of the dialog. This will provide a UI that is tailored specifically to this Processor, rather than the simple Properties table that is provided for all Processors. Within this UI, the user is able to configure a rules engine, essentially, specifying rules that must match in order to have the configured Attributes added to the FlowFile. === Routing on Attributes One of the most powerful features of NiFi is the ability to route FlowFiles based on their Attributes. The primary mechanism for doing this is the RouteOnAttribute Processor. This Processor, like UpdateAttribute, is configured by adding user-defined properties. Any number of properties can be added by clicking the ""+"" button in the top-right corner of the Properties tab in the Processor's Configure dialog. Each FlowFile's Attributes will be compared against the configured properties to determine whether or not the FlowFile meets the specified criteria. The value of each property is expected to be an Expression Language expression and return a boolean value. For more on the Expression Language, see the <> section below. After evaluating the Expression Language expressions provided against the FlowFile's Attributes, the Processor determines how to route the FlowFile based on the Routing Strategy selected. The most common strategy is the ""Route to Property name"" strategy. With this strategy selected, the Processor will expose a Relationship for each property configured. If the FlowFile's Attributes satisfy the given expression, a copy of the FlowFile will be routed to the corresponding Relationship. For example, if we had a new property with the name ""begins-with-r"" and the value ""${filename:startsWith(\\'r')}"" then any FlowFile whose filename starts with the letter 'r' will be routed to that Relationship. All other FlowFiles will be routed to 'unmatched'. [[ExpressionLanguage]] === Expression Language / Using Attributes in Property Values As we extract Attributes from FlowFiles' contents and add user-defined Attributes, they don't do us much good as an operator unless we have some mechanism by which we can use them. The NiFi Expression Language allows us to access and manipulate FlowFile Attribute values as we configure our flows. Not all Processor properties allow the Expression Language to be used, but many do. In order to determine whether or not a property supports the Expression Language, a user can hover over the Help icon ( icon:iconInfo.png[""Help""] ) in the Properties tab of the Processor Configure dialog. This will provide a tooltip that shows a description of the property, the default value, if any, and whether or not the property supports the Expression Language. For properties that do support the Expression Language, it is used by adding an expression within the opening `${` tag and the closing `}` tag. An expression can be as simple as an attribute name. For example, to reference the `uuid` Attribute, we can simply use the value `${uuid}`. If the Attribute name begins with any character other than a letter, or if it contains a character other than a number, a letter, a period (.), or an underscore (_), the Attribute name will need to be quoted. For example, `${My Attribute Name}` will be invalid, but `${'My Attribute Name'}` will refer to the Attribute `My Attribute Name`. In addition to referencing Attribute values, we can perform a number of functions and comparisons on those Attributes. For example, if we want to check if the `filename` attribute contains the letter 'r' without paying attention to case (upper case or lower case), we can do this by using the expression `${filename:toLower():contains('r')}`. Note here that the functions are separated by colons. We can chain together any number of functions to build up more complex expressions. It is also important to understand here that even though we are calling `filename:toLower()`, this does not alter the value of the `filename` Attribute in anyway but rather just gives us a new value to work with. We can also embed one expression within another. For example, if we wanted to compare the value of the `attr1` Attribute to the value of the `attr2` Attribute, we can do this with the following expression: `${attr1:equals( ${attr2} )}`. The Expression Language contains many different functions that can be used in order to perform the tasks needed for routing and manipulating Attributes. Functions exist for parsing and manipulating strings, comparing string and numeric values, manipulating and replacing values, and comparing values. A full explanation of the different functions available is out of scope of this document, but the link:expression-language-guide.html[Expression Language Guide] provides far greater detail for each of the functions. In addition, this Expression Language guide is built in to the application so that users are able to easily see which functions are available and see their documentation while typing. When setting the value of a property that supports the Expression Language, if the cursor is within the Expression Language start and end tags, pressing Ctrl + Space on the keyword will provide a pop-up of all of the available functions and will provide auto-complete functionality. Clicking on or using the keyboard to navigate to one of the functions listed in the pop-up will cause a tooltip to show, which explains what the function does, the arguments that it expects, and the return type of the function. Working With Templates ---------------------- As we use Processors to build more and more complex dataflows in NiFi, we often will find that we string together the same sequence of Processors to perform some task. This can become tedious and inefficient. To address this, NiFi provides a concept of Templates. A template can be thought of as a reusable sub-flow. To create a template, follow these steps: - Select the components to include in the template. We can select multiple components by clicking on the first component and then holding the Shift key while selecting additional components (to include the Connections between those components), or by holding the Shift key while dragging a box around the desired components on the canvas. - Select the Create Template Icon ( image:iconNewTemplate.png[New Template Icon] ) from the middle toolbar at the top of the screen. - Provide a name and optionally comments about the template. - Click the `Create` button. Once we have created a template, we can now use it as a building block in our flow, just as we would a Processor. To do this, we will click and drag the Template icon from the left-most toolbar onto our canvas. We can then choose the template that we would like to add or our canvas and click the `Add` button. Finally, we have the ability to manage our templates by using the Template Management dialog. To access this dialog, click the Template icon in the top-right toolbar. From here, we can see which templates exist and filter the templates to find the templates of interest. On the right-hand side of the table is icon to Export, or Download, the template as an XML file. This can then be provided to others so that they can use your template. To import a template into your NiFi instance, click the `Browse` button in the top-right corner of the dialog and navigate to the file on your computer. Then click the `Import` button. The template will now show up in your table, and you can drag it onto your canvas as you would any other template that you have created. There are a few important notes to remember when working with templates: - Any properties that are identified as being Sensitive Properties (such as a password that is configured in a Processor) will not be added to the template. These sensitive properties will have to be populated each time that the template is added to the canvas. - If a component that is included in the template references a Controller Service, the Controller Service will also be added to the template. This means that each time that the template is added to the graph, it will create a copy of the Controller Service. Monitoring NiFi --------------- As data flows through your dataflow in NiFi, it is important to understand how well your system is performing in order to assess if you will require more resources and in order to assess the health of your current resources. NiFi provides a few mechanisms for monitoring your system. === Status Bar Near the top of the NiFi screen is a blue bar that is referred to as the Status Bar. It contains a few important statistics about the current health of NiFi. The number of Active Threads can indicate how hard NiFi is currently working, and the Queued stat indicates how many FlowFiles are currently queued across the entire flow, as well as the total size of those FlowFiles. If the NiFi instance is in a cluster, we will also see an indicator here telling us how many nodes are in the cluster and how many are currently connected. In this case, the number of active threads and the queue size are indicative of all the sum of all nodes that are currently connected. === Component Statistics Each Processor, Process Group, and Remote Process Group on the canvas provides several statistics about how much data has been processed by the component. These statistics provide information about how much data has been processed in the past five minutes. This is a rolling window and allows us to see things like the number of FlowFiles that have been consumed by a Processor, as well as the number of FlowFiles that have been emitted by the Processor. The connections between Processors also expose the number of items that are currently queued. It may also be valuable to see historical values for these metrics and, if clustered, how the different nodes compare to one another. In order to see this information, we can right-click on a component and choose the `Stats` menu item. This will show us a graph that spans the time since NiFi was started, or up to 24 hours, whichever is less. The amount of time that is shown here can be extended or reduced by changing the configuration in the properties file. In the top-right corner is a drop-down that allows the user to select which metric they are viewing. The graph on the bottom allows the user to select a smaller portion of the graph to zoom in. === Bulletins In addition to the statistics provided by each component, a user will want to know if any problems occur. While we could monitor the logs for anything interesting, it is much more convenient to have notifications pop up on the screen. If a Processor logs anything as a WARNING or ERROR, we will see a ""Bulletin Indicator"" show up in the top-left-hand corner of the Processor. This indicator looks like a sticky note and will be shown for five minutes after the event occurs. Hovering over the bulletin provides information about what happened so that the user does not have to sift through log messages to find it. If in a cluster, the bulletin will also indicate which node in the cluster emitted the bulletin. We can also change the log level at which bulletins will occur in the Settings tab of the Configure dialog for a Processor. If the framework emits a bulletin, we will also see this bulletin indicator occur in the Status Bar at the top of the screen. The right-most icon in the NiFi Toolbar is the Bulletin Board icon. Clicking this icon will take us to the bulletin board where we can see all bulletins that occur across the NiFi instance and can filter based on the component, the message, etc. Data Provenance --------------- NiFi keeps a very granular level of detail about each piece of data that it ingests. As the data is processed through the system and is transformed, routed, split, aggregated, and distributed to other endpoints, this information is all stored within NiFi's Provenance Repository. In order to search and view this information, we can click the Data Provenance icon ( image:iconProvenance.png[Data Provenance, width=28]) in the top-right corner of the canvas. This will provide us a table that lists the Provenance events that we have searched for: image:provenance-table.png[Provenance Table] Initially, this table is populated with the most recent 1,000 Provenance Events that have occurred (though it may take a few seconds for the information to be processed after the events occur). From this dialog, there is a `Search` button that allows the user to search for events that happened by a particular Processor, for a particular FlowFile by filename or UUID, or several other fields. The `nifi.properties` file provides the ability to configure which of these properties are indexed, or made searchable. Additionally, the properties file also allows you to choose specific FlowFile Attributes that will be indexed. As a result, you can choose which Attributes will be important to your specific dataflows and make those Attributes searchable. [[EventDetails]] === Event Details Once we have performed our search, our table will be populated only with the events that match the search criteria. From here, we can choose the Info icon ( image:iconDetails.png[Details Icon] ) on the left-hand side of the table to view the details of that event: image:event-details.png[Event Details] From here, we can see exactly when that event occurred, which FlowFile the event affected, which component (Processor, etc.) performed the event, how long the event took, and the overall time that the data had been in NiFi when the event occurred (total latency). The next tab provides a listing of all Attributes that existed on the FlowFile at the time that the event occurred: image:event-attributes.png[Event Attributes] From here, we can see all the Attributes that existed on the FlowFile when the event occurred, as well as the previous values for those Attributes. This allows us to know which Attributes changed as a result of this event and how they changed. Additionally, in the right-hand corner is a checkbox that allows the user to see only those Attributes that changed. This may not be particularly useful if the FlowFile has only a handful of Attributes, but can be very helpful when a FlowFile has hundreds of Attributes. This is very important because it allows the user to understand the exact context in which the FlowFile was processed. It is helpful to understand 'why' the FlowFile was processed the way that it was, especially when the Processor was configured using the Expression Language. Finally, we have the Content tab: image:event-content.png[Event Content] This tab provides us information about where in the Content Repository the FlowFile's content was stored. If the event modified the content of the FlowFile, we will see the 'before' and 'after' content claims. We are then given the option to Download the content or to View the content within NiFi itself, if the data format is one that NiFi understands how to render. Additionally, in the Replay section of the tab, there is a 'Submit' button that allows the user to re-insert the FlowFile into the flow and re-process it from exactly the point at which the event happened. This provides a very powerful mechanism, as we are able to modify our flow in real time, re-process a FlowFile, and then view the results. If they are not as expected, we can modify the flow again, and re-process the FlowFile again. We are able to perform this iterative development of the flow until it is processing the data exactly as intended. === Lineage Graph In addition to viewing the details of a Provenance event, we can also view the lineage of the FlowFile involved by clicking on the Lineage Icon ( image:iconLineage.png[Lineage] ) from the table view. This provides us with a graphical representation of exactly what happened to that piece of data as it traversed the system: image:lineage-graph-annotated.png[Lineage Graph] From here, we can right-click on any of the events represented and click the `View Details` menu item to see the <>. This graphical representation shows us exactly which events occurred to the data. There are a few ""special"" event types to be aware of. If we see a JOIN, FORK, or CLONE event, we can right-click and choose to Find Parents or Expand. This allows us to see the lineage of parent FlowFiles and children FlowFiles that were created as well. The slider in the bottom-left corner allows us to see the time at which these events occurred. By sliding it left and right, we can see which events introduced latency into the system so that we have a very good understanding of where in our system we may need to provide more resources, such as the number of Concurrent Tasks for a Processor. Or it may reveal, for example, that most of the latency was introduced by a JOIN event, in which we were waiting for more FlowFiles to join together. In either case, the ability to easily see where this is occurring is a very powerful feature that will help users to understand how the enterprise is operating. Where To Go For More Information -------------------------------- The NiFi community has built up a significant amount of documentation on how to use the software. The following guides are available, in addition to this Getting Started Guide: - link:overview.html[Apache NiFi Overview] - Provides an overview of what Apache NiFi is, what it does, and why it was created. - link:user-guide.html[Apache NiFi User Guide] - A fairly extensive guide that is often used more as a Reference Guide, as it has pretty lengthy in discussing all of the different components that comprise the application. This guide is written with the NiFi Operator as its audience. It provides information on each of the different components available in NiFi and explains how to use the different features provided by the application. - link:administration-guide.html[Administration Guide] - A guide for setting up and administering Apache NiFi for production environments. This guide provides information about the different system-level settings, such as setting up clusters of NiFi and securing access to the web UI and data. - link:expression-language-guide.html[Express Language Guide] - A far more exhaustive guide for understanding the Expression Language than is provided above. This guide is the definitive documentation for the NiFi Expression Language. It provides an introduction to the EL and an explanation of each function, its arguments, and return types as well as providing examples. - link:developer-guide.html[Developer's Guide] - While not an exhaustive guide to All Things NiFi Development, this guide does provide a comprehensive overview of the different API's available and how they should be used. In addition, it provides Best Practices for developing NiFi components and common Processor idioms to help aid in understanding the logic behind many of the existing NiFi components. - link:https://cwiki.apache.org/confluence/display/NIFI/Contributor+Guide[Contributor's Guide] - A guide for explaining how to contribute work back to the Apache NiFi community so that others can make use of it. Several blog postings have also been added to the Apache NiFi blog site: link:https://blogs.apache.org/nifi/[https://blogs.apache.org/nifi/] In addition to the blog and guides provided here, you can browse the different link:https://nifi.apache.org/mailing_lists.html[NiFi Mailing Lists] or send an e-mail to one of the mailing lists at link:mailto:users@nifi.apache.org[users@nifi.apache.org] or link:mailto:dev@nifi.apache.org[dev@nifi.apache.org]. Many of the members of the NiFi community are also available on Twitter and actively monitor for tweets that mention @apachenifi. ",12135,False,2027.873759331119,median "// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2016 The Smc-coin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include ""config/smc-coin-config.h"" #endif #include ""net.h"" #include ""addrman.h"" #include ""chainparams.h"" #include ""clientversion.h"" #include ""primitives/transaction.h"" #include ""ui_interface.h"" #include ""obfuscate.h"" #include ""wallet.h"" #ifdef WIN32 #include #else #include #endif #ifdef USE_UPNP #include #include #include #include #endif #include #include // Dump addresses to peers.dat every 15 minutes (900s) #define DUMP_ADDRESSES_INTERVAL 900 #if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL) #define MSG_NOSIGNAL 0 #endif // Fix for ancient MinGW versions, that don't have defined these in ws2tcpip.h. // Todo: Can be removed when our pull-tester is upgraded to a modern MinGW version. #ifdef WIN32 #ifndef PROTECTION_LEVEL_UNRESTRICTED #define PROTECTION_LEVEL_UNRESTRICTED 10 #endif #ifndef IPV6_PROTECTION_LEVEL #define IPV6_PROTECTION_LEVEL 23 #endif #endif using namespace boost; using namespace std; namespace { const int MAX_OUTBOUND_CONNECTIONS = 8; struct ListenSocket { SOCKET socket; bool whitelisted; ListenSocket(SOCKET socket, bool whitelisted) : socket(socket), whitelisted(whitelisted) {} }; } // // Global state variables // bool fDiscover = true; bool fListen = true; uint64_t nLocalServices = NODE_NETWORK; CCriticalSection cs_mapLocalHost; map mapLocalHost; static bool vfReachable[NET_MAX] = {}; static bool vfLimited[NET_MAX] = {}; static CNode* pnodeLocalHost = NULL; uint64_t nLocalHostNonce = 0; static std::vector vhListenSocket; CAddrMan addrman; int nMaxConnections = 125; bool fAddressesInitialized = false; vector vNodes; CCriticalSection cs_vNodes; map mapRelay; deque > vRelayExpiration; CCriticalSection cs_mapRelay; limitedmap mapAlreadyAskedFor(MAX_INV_SZ); static deque vOneShots; CCriticalSection cs_vOneShots; set setservAddNodeAddresses; CCriticalSection cs_setservAddNodeAddresses; vector vAddedNodes; CCriticalSection cs_vAddedNodes; NodeId nLastNodeId = 0; CCriticalSection cs_nLastNodeId; static CSemaphore *semOutbound = NULL; boost::condition_variable messageHandlerCondition; // Signals for message handling static CNodeSignals g_signals; CNodeSignals& GetNodeSignals() { return g_signals; } void AddOneShot(string strDest) { LOCK(cs_vOneShots); vOneShots.push_back(strDest); } unsigned short GetListenPort() { return (unsigned short)(GetArg(""-port"", Params().GetDefaultPort())); } // find 'best' local address for a particular peer bool GetLocal(CService& addr, const CNetAddr *paddrPeer) { if (!fListen) return false; int nBestScore = -1; int nBestReachability = -1; { LOCK(cs_mapLocalHost); for (map::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++) { int nScore = (*it).second.nScore; int nReachability = (*it).first.GetReachabilityFrom(paddrPeer); if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore)) { addr = CService((*it).first, (*it).second.nPort); nBestReachability = nReachability; nBestScore = nScore; } } } return nBestScore >= 0; } // get best local address for a particular peer as a CAddress // Otherwise, return the unroutable 0.0.0.0 but filled in with // the normal parameters, since the IP may be changed to a useful // one by discovery. CAddress GetLocalAddress(const CNetAddr *paddrPeer) { CAddress ret(CService(""0.0.0.0"",GetListenPort()),0); CService addr; if (GetLocal(addr, paddrPeer)) { ret = CAddress(addr); } ret.nServices = nLocalServices; ret.nTime = GetAdjustedTime(); return ret; } bool RecvLine(SOCKET hSocket, string& strLine) { strLine = """"; while (true) { char c; int nBytes = recv(hSocket, &c, 1, 0); if (nBytes > 0) { if (c == '\\n') continue; if (c == '\\r') return true; strLine += c; if (strLine.size() >= 9000) return true; } else if (nBytes <= 0) { boost::this_thread::interruption_point(); if (nBytes < 0) { int nErr = WSAGetLastError(); if (nErr == WSAEMSGSIZE) continue; if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS) { MilliSleep(10); continue; } } if (!strLine.empty()) return true; if (nBytes == 0) { // socket closed LogPrint(""net"", ""socket closed\\n""); return false; } else { // socket error int nErr = WSAGetLastError(); LogPrint(""net"", ""recv failed: %s\\n"", NetworkErrorString(nErr)); return false; } } } } int GetnScore(const CService& addr) { LOCK(cs_mapLocalHost); if (mapLocalHost.count(addr) == LOCAL_NONE) return 0; return mapLocalHost[addr].nScore; } // Is our peer's addrLocal potentially useful as an external IP source? bool IsPeerAddrLocalGood(CNode *pnode) { return fDiscover && pnode->addr.IsRoutable() && pnode->addrLocal.IsRoutable() && !IsLimited(pnode->addrLocal.GetNetwork()); } // pushes our own address to a peer void AdvertizeLocal(CNode *pnode) { if (fListen && pnode->fSuccessfullyConnected) { CAddress addrLocal = GetLocalAddress(&pnode->addr); // If discovery is enabled, sometimes give our peer the address it // tells us that it sees us as in case it has a better idea of our // address than we do. if (IsPeerAddrLocalGood(pnode) && (!addrLocal.IsRoutable() || GetRand((GetnScore(addrLocal) > LOCAL_MANUAL) ? 8:2) == 0)) { addrLocal.SetIP(pnode->addrLocal); } if (addrLocal.IsRoutable()) { pnode->PushAddress(addrLocal); } } } void SetReachable(enum Network net, bool fFlag) { LOCK(cs_mapLocalHost); vfReachable[net] = fFlag; if (net == NET_IPV6 && fFlag) vfReachable[NET_IPV4] = true; } // learn a new local address bool AddLocal(const CService& addr, int nScore) { if (!addr.IsRoutable()) return false; if (!fDiscover && nScore < LOCAL_MANUAL) return false; if (IsLimited(addr)) return false; LogPrintf(""AddLocal(%s,%i)\\n"", addr.ToString(), nScore); { LOCK(cs_mapLocalHost); bool fAlready = mapLocalHost.count(addr) > 0; LocalServiceInfo &info = mapLocalHost[addr]; if (!fAlready || nScore >= info.nScore) { info.nScore = nScore + (fAlready ? 1 : 0); info.nPort = addr.GetPort(); } SetReachable(addr.GetNetwork()); } return true; } bool AddLocal(const CNetAddr &addr, int nScore) { return AddLocal(CService(addr, GetListenPort()), nScore); } /** Make a particular network entirely off-limits (no automatic connects to it) */ void SetLimited(enum Network net, bool fLimited) { if (net == NET_UNROUTABLE) return; LOCK(cs_mapLocalHost); vfLimited[net] = fLimited; } bool IsLimited(enum Network net) { LOCK(cs_mapLocalHost); return vfLimited[net]; } bool IsLimited(const CNetAddr &addr) { return IsLimited(addr.GetNetwork()); } /** vote for a local address */ bool SeenLocal(const CService& addr) { { LOCK(cs_mapLocalHost); if (mapLocalHost.count(addr) == 0) return false; mapLocalHost[addr].nScore++; } return true; } /** check whether a given address is potentially local */ bool IsLocal(const CService& addr) { LOCK(cs_mapLocalHost); return mapLocalHost.count(addr) > 0; } /** check whether a given network is one we can probably connect to */ bool IsReachable(enum Network net) { LOCK(cs_mapLocalHost); return vfReachable[net] && !vfLimited[net]; } /** check whether a given address is in a network we can probably connect to */ bool IsReachable(const CNetAddr& addr) { enum Network net = addr.GetNetwork(); return IsReachable(net); } void AddressCurrentlyConnected(const CService& addr) { addrman.Connected(addr); } uint64_t CNode::nTotalBytesRecv = 0; uint64_t CNode::nTotalBytesSent = 0; CCriticalSection CNode::cs_totalBytesRecv; CCriticalSection CNode::cs_totalBytesSent; CNode* FindNode(const CNetAddr& ip) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if ((CNetAddr)pnode->addr == ip) return (pnode); return NULL; } CNode* FindNode(const std::string& addrName) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->addrName == addrName) return (pnode); return NULL; } CNode* FindNode(const CService& addr) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes){ if(Params().NetworkID() == CBaseChainParams::REGTEST){ //if using regtest, just check the IP if((CNetAddr)pnode->addr == (CNetAddr)addr) return (pnode); } else { if(pnode->addr == addr) return (pnode); } } return NULL; } CNode* ConnectNode(CAddress addrConnect, const char *pszDest, bool darkSendMaster) { if (pszDest == NULL) { // we clean masternode connections in CMasternodeMan::ProcessMasternodeConnections() // so should be safe to skip this and connect to local Hot MN on CActiveMasternode::ManageStatus() if (IsLocal(addrConnect) && !darkSendMaster) return NULL; // Look for an existing connection CNode* pnode = FindNode((CService)addrConnect); if (pnode) { pnode->fObfuscateMaster = darkSendMaster; pnode->AddRef(); return pnode; } } /// debug print LogPrint(""net"", ""trying connection %s lastseen=%.1fhrs\\n"", pszDest ? pszDest : addrConnect.ToString(), pszDest ? 0.0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0); // Connect SOCKET hSocket; bool proxyConnectionFailed = false; if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, Params().GetDefaultPort(), nConnectTimeout, &proxyConnectionFailed) : ConnectSocket(addrConnect, hSocket, nConnectTimeout, &proxyConnectionFailed)) { if (!IsSelectableSocket(hSocket)) { LogPrintf(""Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\\n""); CloseSocket(hSocket); return NULL; } addrman.Attempt(addrConnect); // Add node CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : """", false); pnode->AddRef(); { LOCK(cs_vNodes); vNodes.push_back(pnode); } pnode->nTimeConnected = GetTime(); if(darkSendMaster) pnode->fObfuscateMaster = true; return pnode; } else if (!proxyConnectionFailed) { // If connecting to the node failed, and failure is not caused by a problem connecting to // the proxy, mark this as an attempt. addrman.Attempt(addrConnect); } return NULL; } void CNode::CloseSocketDisconnect() { fDisconnect = true; if (hSocket != INVALID_SOCKET) { LogPrint(""net"", ""disconnecting peer=%d\\n"", id); CloseSocket(hSocket); } // in case this fails, we'll empty the recv buffer when the CNode is deleted TRY_LOCK(cs_vRecvMsg, lockRecv); if (lockRecv) vRecvMsg.clear(); } void CNode::PushVersion() { int nBestHeight = g_signals.GetHeight().get_value_or(0); /// when NTP implemented, change to just nTime = GetAdjustedTime() int64_t nTime = (fInbound ? GetAdjustedTime() : GetTime()); CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService(""0.0.0.0"",0))); CAddress addrMe = GetLocalAddress(&addr); GetRandBytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce)); if (fLogIPs) LogPrint(""net"", ""send version message: version %d, blocks=%d, us=%s, them=%s, peer=%d\\n"", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), addrYou.ToString(), id); else LogPrint(""net"", ""send version message: version %d, blocks=%d, us=%s, peer=%d\\n"", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), id); PushMessage(""version"", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe, nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector()), nBestHeight, true); } std::map CNode::setBanned; CCriticalSection CNode::cs_setBanned; void CNode::ClearBanned() { setBanned.clear(); } bool CNode::IsBanned(CNetAddr ip) { bool fResult = false; { LOCK(cs_setBanned); std::map::iterator i = setBanned.find(ip); if (i != setBanned.end()) { int64_t t = (*i).second; if (GetTime() < t) fResult = true; } } return fResult; } bool CNode::Ban(const CNetAddr &addr) { int64_t banTime = GetTime()+GetArg(""-bantime"", 60*60*24); // Default 24-hour ban { LOCK(cs_setBanned); if (setBanned[addr] < banTime) setBanned[addr] = banTime; } return true; } std::vector CNode::vWhitelistedRange; CCriticalSection CNode::cs_vWhitelistedRange; bool CNode::IsWhitelistedRange(const CNetAddr &addr) { LOCK(cs_vWhitelistedRange); BOOST_FOREACH(const CSubNet& subnet, vWhitelistedRange) { if (subnet.Match(addr)) return true; } return false; } void CNode::AddWhitelistedRange(const CSubNet &subnet) { LOCK(cs_vWhitelistedRange); vWhitelistedRange.push_back(subnet); } #undef X #define X(name) stats.name = name void CNode::copyStats(CNodeStats &stats) { stats.nodeid = this->GetId(); X(nServices); X(nLastSend); X(nLastRecv); X(nTimeConnected); X(addrName); X(nVersion); X(cleanSubVer); X(fInbound); X(nStartingHeight); X(nSendBytes); X(nRecvBytes); X(fWhitelisted); // It is common for nodes with good ping times to suddenly become lagged, // due to a new block arriving or other large transfer. // Merely reporting pingtime might fool the caller into thinking the node was still responsive, // since pingtime does not update until the ping is complete, which might take a while. // So, if a ping is taking an unusually long time in flight, // the caller can immediately detect that this is happening. int64_t nPingUsecWait = 0; if ((0 != nPingNonceSent) && (0 != nPingUsecStart)) { nPingUsecWait = GetTimeMicros() - nPingUsecStart; } // Raw ping time is in microseconds, but show it to user as whole seconds (Smc-coin users should be well used to small numbers with many decimal places by now :) stats.dPingTime = (((double)nPingUsecTime) / 1e6); stats.dPingWait = (((double)nPingUsecWait) / 1e6); // Leave string empty if addrLocal invalid (not filled in yet) stats.addrLocal = addrLocal.IsValid() ? addrLocal.ToString() : """"; } #undef X // requires LOCK(cs_vRecvMsg) bool CNode::ReceiveMsgBytes(const char *pch, unsigned int nBytes) { while (nBytes > 0) { // get current incomplete message, or create a new one if (vRecvMsg.empty() || vRecvMsg.back().complete()) vRecvMsg.push_back(CNetMessage(SER_NETWORK, nRecvVersion)); CNetMessage& msg = vRecvMsg.back(); // absorb network data int handled; if (!msg.in_data) handled = msg.readHeader(pch, nBytes); else handled = msg.readData(pch, nBytes); if (handled < 0) return false; if (msg.in_data && msg.hdr.nMessageSize > MAX_PROTOCOL_MESSAGE_LENGTH) { LogPrint(""net"", ""Oversized message from peer=%i, disconnecting"", GetId()); return false; } pch += handled; nBytes -= handled; if (msg.complete()) { msg.nTime = GetTimeMicros(); messageHandlerCondition.notify_one(); } } return true; } int CNetMessage::readHeader(const char *pch, unsigned int nBytes) { // copy data to temporary parsing buffer unsigned int nRemaining = 24 - nHdrPos; unsigned int nCopy = std::min(nRemaining, nBytes); memcpy(&hdrbuf[nHdrPos], pch, nCopy); nHdrPos += nCopy; // if header incomplete, exit if (nHdrPos < 24) return nCopy; // deserialize to CMessageHeader try { hdrbuf >> hdr; } catch (const std::exception &) { return -1; } // reject messages larger than MAX_SIZE if (hdr.nMessageSize > MAX_SIZE) return -1; // switch state to reading message data in_data = true; return nCopy; } int CNetMessage::readData(const char *pch, unsigned int nBytes) { unsigned int nRemaining = hdr.nMessageSize - nDataPos; unsigned int nCopy = std::min(nRemaining, nBytes); if (vRecv.size() < nDataPos + nCopy) { // Allocate up to 256 KiB ahead, but never more than the total message size. vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024)); } memcpy(&vRecv[nDataPos], pch, nCopy); nDataPos += nCopy; return nCopy; } // requires LOCK(cs_vSend) void SocketSendData(CNode *pnode) { std::deque::iterator it = pnode->vSendMsg.begin(); while (it != pnode->vSendMsg.end()) { const CSerializeData &data = *it; assert(data.size() > pnode->nSendOffset); int nBytes = send(pnode->hSocket, &data[pnode->nSendOffset], data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT); if (nBytes > 0) { pnode->nLastSend = GetTime(); pnode->nSendBytes += nBytes; pnode->nSendOffset += nBytes; pnode->RecordBytesSent(nBytes); if (pnode->nSendOffset == data.size()) { pnode->nSendOffset = 0; pnode->nSendSize -= data.size(); it++; } else { // could not send full message; stop sending more break; } } else { if (nBytes < 0) { // error int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) { LogPrintf(""socket send error %s\\n"", NetworkErrorString(nErr)); pnode->CloseSocketDisconnect(); } } // couldn't send anything at all break; } } if (it == pnode->vSendMsg.end()) { assert(pnode->nSendOffset == 0); assert(pnode->nSendSize == 0); } pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it); } static list vNodesDisconnected; void ThreadSocketHandler() { unsigned int nPrevNodeCount = 0; while (true) { // // Disconnect nodes // { LOCK(cs_vNodes); // Disconnect unused nodes vector vNodesCopy = vNodes; BOOST_FOREACH(CNode* pnode, vNodesCopy) { if (pnode->fDisconnect || (pnode->GetRefCount() <= 0 && pnode->vRecvMsg.empty() && pnode->nSendSize == 0 && pnode->ssSend.empty())) { // remove from vNodes vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end()); // release outbound grant (if any) pnode->grantOutbound.Release(); // close socket and cleanup pnode->CloseSocketDisconnect(); // hold in disconnected pool until all refs are released if (pnode->fNetworkNode || pnode->fInbound) pnode->Release(); vNodesDisconnected.push_back(pnode); } } } { // Delete disconnected nodes list vNodesDisconnectedCopy = vNodesDisconnected; BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy) { // wait until threads are done using it if (pnode->GetRefCount() <= 0) { bool fDelete = false; { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv) { TRY_LOCK(pnode->cs_inventory, lockInv); if (lockInv) fDelete = true; } } } if (fDelete) { vNodesDisconnected.remove(pnode); delete pnode; } } } } if(vNodes.size() != nPrevNodeCount) { nPrevNodeCount = vNodes.size(); uiInterface.NotifyNumConnectionsChanged(nPrevNodeCount); } // // Find which sockets have data to receive // struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 50000; // frequency to poll pnode->vSend fd_set fdsetRecv; fd_set fdsetSend; fd_set fdsetError; FD_ZERO(&fdsetRecv); FD_ZERO(&fdsetSend); FD_ZERO(&fdsetError); SOCKET hSocketMax = 0; bool have_fds = false; BOOST_FOREACH(const ListenSocket& hListenSocket, vhListenSocket) { FD_SET(hListenSocket.socket, &fdsetRecv); hSocketMax = max(hSocketMax, hListenSocket.socket); have_fds = true; } { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if (pnode->hSocket == INVALID_SOCKET) continue; FD_SET(pnode->hSocket, &fdsetError); hSocketMax = max(hSocketMax, pnode->hSocket); have_fds = true; // Implement the following logic: // * If there is data to send, select() for sending data. As this only // happens when optimistic write failed, we choose to first drain the // write buffer in this case before receiving more. This avoids // needlessly queueing received data, if the remote peer is not themselves // receiving data. This means properly utilizing TCP flow control signalling. // * Otherwise, if there is no (complete) message in the receive buffer, // or there is space left in the buffer, select() for receiving data. // * (if neither of the above applies, there is certainly one message // in the receiver buffer ready to be processed). // Together, that means that at least one of the following is always possible, // so we don't deadlock: // * We send some data. // * We wait for data to be received (and disconnect after timeout). // * We process a message in the buffer (message handler thread). { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend && !pnode->vSendMsg.empty()) { FD_SET(pnode->hSocket, &fdsetSend); continue; } } { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv && ( pnode->vRecvMsg.empty() || !pnode->vRecvMsg.front().complete() || pnode->GetTotalRecvSize() <= ReceiveFloodSize())) FD_SET(pnode->hSocket, &fdsetRecv); } } } int nSelect = select(have_fds ? hSocketMax + 1 : 0, &fdsetRecv, &fdsetSend, &fdsetError, &timeout); boost::this_thread::interruption_point(); if (nSelect == SOCKET_ERROR) { if (have_fds) { int nErr = WSAGetLastError(); LogPrintf(""socket select error %s\\n"", NetworkErrorString(nErr)); for (unsigned int i = 0; i <= hSocketMax; i++) FD_SET(i, &fdsetRecv); } FD_ZERO(&fdsetSend); FD_ZERO(&fdsetError); MilliSleep(timeout.tv_usec/1000); } // // Accept new connections // BOOST_FOREACH(const ListenSocket& hListenSocket, vhListenSocket) { if (hListenSocket.socket != INVALID_SOCKET && FD_ISSET(hListenSocket.socket, &fdsetRecv)) { struct sockaddr_storage sockaddr; socklen_t len = sizeof(sockaddr); SOCKET hSocket = accept(hListenSocket.socket, (struct sockaddr*)&sockaddr, &len); CAddress addr; int nInbound = 0; if (hSocket != INVALID_SOCKET) if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr)) LogPrintf(""Warning: Unknown socket family\\n""); bool whitelisted = hListenSocket.whitelisted || CNode::IsWhitelistedRange(addr); { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->fInbound) nInbound++; } if (hSocket == INVALID_SOCKET) { int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK) LogPrintf(""socket error accept failed: %s\\n"", NetworkErrorString(nErr)); } else if (!IsSelectableSocket(hSocket)) { LogPrintf(""connection from %s dropped: non-selectable socket\\n"", addr.ToString()); CloseSocket(hSocket); } else if (nInbound >= nMaxConnections - MAX_OUTBOUND_CONNECTIONS) { LogPrint(""net"", ""connection from %s dropped (full)\\n"", addr.ToString()); CloseSocket(hSocket); } else if (CNode::IsBanned(addr) && !whitelisted) { LogPrintf(""connection from %s dropped (banned)\\n"", addr.ToString()); CloseSocket(hSocket); } else { CNode* pnode = new CNode(hSocket, addr, """", true); pnode->AddRef(); pnode->fWhitelisted = whitelisted; { LOCK(cs_vNodes); vNodes.push_back(pnode); } } } } // // Service each socket // vector vNodesCopy; { LOCK(cs_vNodes); vNodesCopy = vNodes; BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->AddRef(); } BOOST_FOREACH(CNode* pnode, vNodesCopy) { boost::this_thread::interruption_point(); // // Receive // if (pnode->hSocket == INVALID_SOCKET) continue; if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError)) { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv) { { // typical socket buffer is 8K-64K char pchBuf[0x10000]; int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT); if (nBytes > 0) { if (!pnode->ReceiveMsgBytes(pchBuf, nBytes)) pnode->CloseSocketDisconnect(); pnode->nLastRecv = GetTime(); pnode->nRecvBytes += nBytes; pnode->RecordBytesRecv(nBytes); } else if (nBytes == 0) { // socket closed gracefully if (!pnode->fDisconnect) LogPrint(""net"", ""socket closed\\n""); pnode->CloseSocketDisconnect(); } else if (nBytes < 0) { // error int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) { if (!pnode->fDisconnect) LogPrintf(""socket recv error %s\\n"", NetworkErrorString(nErr)); pnode->CloseSocketDisconnect(); } } } } } // // Send // if (pnode->hSocket == INVALID_SOCKET) continue; if (FD_ISSET(pnode->hSocket, &fdsetSend)) { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) SocketSendData(pnode); } // // Inactivity checking // int64_t nTime = GetTime(); if (nTime - pnode->nTimeConnected > 60) { if (pnode->nLastRecv == 0 || pnode->nLastSend == 0) { LogPrint(""net"", ""socket no message in first 60 seconds, %d %d from %d\\n"", pnode->nLastRecv != 0, pnode->nLastSend != 0, pnode->id); pnode->fDisconnect = true; } else if (nTime - pnode->nLastSend > TIMEOUT_INTERVAL) { LogPrintf(""socket sending timeout: %is\\n"", nTime - pnode->nLastSend); pnode->fDisconnect = true; } else if (nTime - pnode->nLastRecv > (pnode->nVersion > BIP0031_VERSION ? TIMEOUT_INTERVAL : 90*60)) { LogPrintf(""socket receive timeout: %is\\n"", nTime - pnode->nLastRecv); pnode->fDisconnect = true; } else if (pnode->nPingNonceSent && pnode->nPingUsecStart + TIMEOUT_INTERVAL * 1000000 < GetTimeMicros()) { LogPrintf(""ping timeout: %fs\\n"", 0.000001 * (GetTimeMicros() - pnode->nPingUsecStart)); pnode->fDisconnect = true; } } } { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->Release(); } } } #ifdef USE_UPNP void ThreadMapPort() { std::string port = strprintf(""%u"", GetListenPort()); const char * multicastif = 0; const char * minissdpdpath = 0; struct UPNPDev * devlist = 0; char lanaddr[64]; #ifndef UPNPDISCOVER_SUCCESS /* miniupnpc 1.5 */ devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0); #else /* miniupnpc 1.6 */ int error = 0; devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error); #endif struct UPNPUrls urls; struct IGDdatas data; int r; r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr)); if (r == 1) { if (fDiscover) { char externalIPAddress[40]; r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress); if(r != UPNPCOMMAND_SUCCESS) LogPrintf(""UPnP: GetExternalIPAddress() returned %d\\n"", r); else { if(externalIPAddress[0]) { LogPrintf(""UPnP: ExternalIPAddress = %s\\n"", externalIPAddress); AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP); } else LogPrintf(""UPnP: GetExternalIPAddress failed.\\n""); } } string strDesc = ""Smc-coin "" + FormatFullVersion(); try { while (true) { #ifndef UPNPDISCOVER_SUCCESS /* miniupnpc 1.5 */ r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), ""TCP"", 0); #else /* miniupnpc 1.6 */ r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), ""TCP"", 0, ""0""); #endif if(r!=UPNPCOMMAND_SUCCESS) LogPrintf(""AddPortMapping(%s, %s, %s) failed with code %d (%s)\\n"", port, port, lanaddr, r, strupnperror(r)); else LogPrintf(""UPnP Port Mapping successful.\\n"");; MilliSleep(20*60*1000); // Refresh every 20 minutes } } catch (boost::thread_interrupted) { r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), ""TCP"", 0); LogPrintf(""UPNP_DeletePortMapping() returned : %d\\n"", r); freeUPNPDevlist(devlist); devlist = 0; FreeUPNPUrls(&urls); throw; } } else { LogPrintf(""No valid UPnP IGDs found\\n""); freeUPNPDevlist(devlist); devlist = 0; if (r != 0) FreeUPNPUrls(&urls); } } void MapPort(bool fUseUPnP) { static boost::thread* upnp_thread = NULL; if (fUseUPnP) { if (upnp_thread) { upnp_thread->interrupt(); upnp_thread->join(); delete upnp_thread; } upnp_thread = new boost::thread(boost::bind(&TraceThread, ""upnp"", &ThreadMapPort)); } else if (upnp_thread) { upnp_thread->interrupt(); upnp_thread->join(); delete upnp_thread; upnp_thread = NULL; } } #else void MapPort(bool) { // Intentionally left blank. } #endif void ThreadDNSAddressSeed() { // goal: only query DNS seeds if address need is acute if ((addrman.size() > 0) && (!GetBoolArg(""-forcednsseed"", false))) { MilliSleep(11 * 1000); LOCK(cs_vNodes); if (vNodes.size() >= 2) { LogPrintf(""P2P peers available. Skipped DNS seeding.\\n""); return; } } const vector &vSeeds = Params().DNSSeeds(); int found = 0; LogPrintf(""Loading addresses from DNS seeds (could take a while)\\n""); BOOST_FOREACH(const CDNSSeedData &seed, vSeeds) { if (HaveNameProxy()) { AddOneShot(seed.host); } else { vector vIPs; vector vAdd; if (LookupHost(seed.host.c_str(), vIPs)) { BOOST_FOREACH(CNetAddr& ip, vIPs) { int nOneDay = 24*3600; CAddress addr = CAddress(CService(ip, Params().GetDefaultPort())); addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old vAdd.push_back(addr); found++; } } addrman.Add(vAdd, CNetAddr(seed.name, true)); } } LogPrintf(""%d addresses found from DNS seeds\\n"", found); } void DumpAddresses() { int64_t nStart = GetTimeMillis(); CAddrDB adb; adb.Write(addrman); LogPrint(""net"", ""Flushed %d addresses to peers.dat %dms\\n"", addrman.size(), GetTimeMillis() - nStart); } void static ProcessOneShot() { string strDest; { LOCK(cs_vOneShots); if (vOneShots.empty()) return; strDest = vOneShots.front(); vOneShots.pop_front(); } CAddress addr; CSemaphoreGrant grant(*semOutbound, true); if (grant) { if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true)) AddOneShot(strDest); } } void ThreadOpenConnections() { // Connect to specific addresses if (mapArgs.count(""-connect"") && mapMultiArgs[""-connect""].size() > 0) { for (int64_t nLoop = 0;; nLoop++) { ProcessOneShot(); BOOST_FOREACH(string strAddr, mapMultiArgs[""-connect""]) { CAddress addr; OpenNetworkConnection(addr, NULL, strAddr.c_str()); for (int i = 0; i < 10 && i < nLoop; i++) { MilliSleep(500); } } MilliSleep(500); } } // Initiate network connections int64_t nStart = GetTime(); while (true) { ProcessOneShot(); MilliSleep(500); CSemaphoreGrant grant(*semOutbound); boost::this_thread::interruption_point(); // Add seed nodes if DNS seeds are all down (an infrastructure attack?). if (addrman.size() == 0 && (GetTime() - nStart > 60)) { static bool done = false; if (!done) { LogPrintf(""Adding fixed seed nodes as DNS doesn't seem to be available.\\n""); addrman.Add(Params().FixedSeeds(), CNetAddr(""127.0.0.1"")); done = true; } } // // Choose an address to connect to based on most recently seen // CAddress addrConnect; // Only connect out to one peer per network group (/16 for IPv4). // Do this here so we don't have to critsect vNodes inside mapAddresses critsect. int nOutbound = 0; set > setConnected; { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if (!pnode->fInbound) { setConnected.insert(pnode->addr.GetGroup()); nOutbound++; } } } int64_t nANow = GetAdjustedTime(); int nTries = 0; while (true) { CAddress addr = addrman.Select(); // if we selected an invalid address, restart if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr)) break; // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman, // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates // already-connected network ranges, ...) before trying new addrman addresses. nTries++; if (nTries > 100) break; if (IsLimited(addr)) continue; // only consider very recently tried nodes after 30 failed attempts if (nANow - addr.nLastTry < 600 && nTries < 30) continue; // do not allow non-default ports, unless after 50 invalid addresses selected already if (addr.GetPort() != Params().GetDefaultPort() && nTries < 50) continue; addrConnect = addr; break; } if (addrConnect.IsValid()) OpenNetworkConnection(addrConnect, &grant); } } void ThreadOpenAddedConnections() { { LOCK(cs_vAddedNodes); vAddedNodes = mapMultiArgs[""-addnode""]; } if (HaveNameProxy()) { while(true) { list lAddresses(0); { LOCK(cs_vAddedNodes); BOOST_FOREACH(string& strAddNode, vAddedNodes) lAddresses.push_back(strAddNode); } BOOST_FOREACH(string& strAddNode, lAddresses) { CAddress addr; CSemaphoreGrant grant(*semOutbound); OpenNetworkConnection(addr, &grant, strAddNode.c_str()); MilliSleep(500); } MilliSleep(120000); // Retry every 2 minutes } } for (unsigned int i = 0; true; i++) { list lAddresses(0); { LOCK(cs_vAddedNodes); BOOST_FOREACH(string& strAddNode, vAddedNodes) lAddresses.push_back(strAddNode); } list > lservAddressesToAdd(0); BOOST_FOREACH(string& strAddNode, lAddresses) { vector vservNode(0); if(Lookup(strAddNode.c_str(), vservNode, Params().GetDefaultPort(), fNameLookup, 0)) { lservAddressesToAdd.push_back(vservNode); { LOCK(cs_setservAddNodeAddresses); BOOST_FOREACH(CService& serv, vservNode) setservAddNodeAddresses.insert(serv); } } } // Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry // (keeping in mind that addnode entries can have many IPs if fNameLookup) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) for (list >::iterator it = lservAddressesToAdd.begin(); it != lservAddressesToAdd.end(); it++) BOOST_FOREACH(CService& addrNode, *(it)) if (pnode->addr == addrNode) { it = lservAddressesToAdd.erase(it); it--; break; } } BOOST_FOREACH(vector& vserv, lservAddressesToAdd) { CSemaphoreGrant grant(*semOutbound); OpenNetworkConnection(CAddress(vserv[i % vserv.size()]), &grant); MilliSleep(500); } MilliSleep(120000); // Retry every 2 minutes } } // if successful, this moves the passed grant to the constructed node bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *pszDest, bool fOneShot) { // // Initiate outbound network connection // boost::this_thread::interruption_point(); if (!pszDest) { if (IsLocal(addrConnect) || FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) || FindNode(addrConnect.ToStringIPPort())) return false; } else if (FindNode(pszDest)) return false; CNode* pnode = ConnectNode(addrConnect, pszDest); boost::this_thread::interruption_point(); if (!pnode) return false; if (grantOutbound) grantOutbound->MoveTo(pnode->grantOutbound); pnode->fNetworkNode = true; if (fOneShot) pnode->fOneShot = true; return true; } void ThreadMessageHandler() { boost::mutex condition_mutex; boost::unique_lock lock(condition_mutex); SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL); while (true) { vector vNodesCopy; { LOCK(cs_vNodes); vNodesCopy = vNodes; BOOST_FOREACH(CNode* pnode, vNodesCopy) { pnode->AddRef(); } } // Poll the connected nodes for messages CNode* pnodeTrickle = NULL; if (!vNodesCopy.empty()) pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())]; bool fSleep = true; BOOST_FOREACH(CNode* pnode, vNodesCopy) { if (pnode->fDisconnect) continue; // Receive messages { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv) { if (!g_signals.ProcessMessages(pnode)) pnode->CloseSocketDisconnect(); if (pnode->nSendSize < SendBufferSize()) { if (!pnode->vRecvGetData.empty() || (!pnode->vRecvMsg.empty() && pnode->vRecvMsg[0].complete())) { fSleep = false; } } } } boost::this_thread::interruption_point(); // Send messages { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) g_signals.SendMessages(pnode, pnode == pnodeTrickle || pnode->fWhitelisted); } boost::this_thread::interruption_point(); } { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->Release(); } if (fSleep) messageHandlerCondition.timed_wait(lock, boost::posix_time::microsec_clock::universal_time() + boost::posix_time::milliseconds(100)); } } bool BindListenPort(const CService &addrBind, string& strError, bool fWhitelisted) { strError = """"; int nOne = 1; // Create socket for listening for incoming connections struct sockaddr_storage sockaddr; socklen_t len = sizeof(sockaddr); if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len)) { strError = strprintf(""Error: Bind address family for %s not supported"", addrBind.ToString()); LogPrintf(""%s\\n"", strError); return false; } SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP); if (hListenSocket == INVALID_SOCKET) { strError = strprintf(""Error: Couldn't open socket for incoming connections (socket returned error %s)"", NetworkErrorString(WSAGetLastError())); LogPrintf(""%s\\n"", strError); return false; } if (!IsSelectableSocket(hListenSocket)) { strError = ""Error: Couldn't create a listenable socket for incoming connections""; LogPrintf(""%s\\n"", strError); return false; } #ifndef WIN32 #ifdef SO_NOSIGPIPE // Different way of disabling SIGPIPE on BSD setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int)); #endif // Allow binding if the port is still in TIME_WAIT state after // the program was closed and restarted. Not an issue on windows! setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int)); #endif // Set to non-blocking, incoming connections will also inherit this if (!SetSocketNonBlocking(hListenSocket, true)) { strError = strprintf(""BindListenPort: Setting listening socket to non-blocking failed, error %s\\n"", NetworkErrorString(WSAGetLastError())); LogPrintf(""%s\\n"", strError); return false; } // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option // and enable it by default or not. Try to enable it, if possible. if (addrBind.IsIPv6()) { #ifdef IPV6_V6ONLY #ifdef WIN32 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int)); #else setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int)); #endif #endif #ifdef WIN32 int nProtLevel = PROTECTION_LEVEL_UNRESTRICTED; setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_PROTECTION_LEVEL, (const char*)&nProtLevel, sizeof(int)); #endif } if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR) { int nErr = WSAGetLastError(); if (nErr == WSAEADDRINUSE) strError = strprintf(_(""Unable to bind to %s on this computer. Smc-coin Core is probably already running.""), addrBind.ToString()); else strError = strprintf(_(""Unable to bind to %s on this computer (bind returned error %s)""), addrBind.ToString(), NetworkErrorString(nErr)); LogPrintf(""%s\\n"", strError); CloseSocket(hListenSocket); return false; } LogPrintf(""Bound to %s\\n"", addrBind.ToString()); // Listen for incoming connections if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR) { strError = strprintf(_(""Error: Listening for incoming connections failed (listen returned error %s)""), NetworkErrorString(WSAGetLastError())); LogPrintf(""%s\\n"", strError); CloseSocket(hListenSocket); return false; } vhListenSocket.push_back(ListenSocket(hListenSocket, fWhitelisted)); if (addrBind.IsRoutable() && fDiscover && !fWhitelisted) AddLocal(addrBind, LOCAL_BIND); return true; } void static Discover(boost::thread_group& threadGroup) { if (!fDiscover) return; #ifdef WIN32 // Get local host IP char pszHostName[256] = """"; if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR) { vector vaddr; if (LookupHost(pszHostName, vaddr)) { BOOST_FOREACH (const CNetAddr &addr, vaddr) { if (AddLocal(addr, LOCAL_IF)) LogPrintf(""%s: %s - %s\\n"", __func__, pszHostName, addr.ToString()); } } } #else // Get local host ip struct ifaddrs* myaddrs; if (getifaddrs(&myaddrs) == 0) { for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next) { if (ifa->ifa_addr == NULL) continue; if ((ifa->ifa_flags & IFF_UP) == 0) continue; if (strcmp(ifa->ifa_name, ""lo"") == 0) continue; if (strcmp(ifa->ifa_name, ""lo0"") == 0) continue; if (ifa->ifa_addr->sa_family == AF_INET) { struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr); CNetAddr addr(s4->sin_addr); if (AddLocal(addr, LOCAL_IF)) LogPrintf(""%s: IPv4 %s: %s\\n"", __func__, ifa->ifa_name, addr.ToString()); } else if (ifa->ifa_addr->sa_family == AF_INET6) { struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr); CNetAddr addr(s6->sin6_addr); if (AddLocal(addr, LOCAL_IF)) LogPrintf(""%s: IPv6 %s: %s\\n"", __func__, ifa->ifa_name, addr.ToString()); } } freeifaddrs(myaddrs); } #endif } void StartNode(boost::thread_group& threadGroup) { uiInterface.InitMessage(_(""Loading addresses..."")); // Load addresses for peers.dat int64_t nStart = GetTimeMillis(); { CAddrDB adb; if (!adb.Read(addrman)) LogPrintf(""Invalid or missing peers.dat; recreating\\n""); } LogPrintf(""Loaded %i addresses from peers.dat %dms\\n"", addrman.size(), GetTimeMillis() - nStart); fAddressesInitialized = true; if (semOutbound == NULL) { // initialize semaphore int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, nMaxConnections); semOutbound = new CSemaphore(nMaxOutbound); } if (pnodeLocalHost == NULL) pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService(""127.0.0.1"", 0), nLocalServices)); Discover(threadGroup); // // Start threads // if (!GetBoolArg(""-dnsseed"", true)) LogPrintf(""DNS seeding disabled\\n""); else threadGroup.create_thread(boost::bind(&TraceThread, ""dnsseed"", &ThreadDNSAddressSeed)); // Map ports with UPnP MapPort(GetBoolArg(""-upnp"", DEFAULT_UPNP)); // Send and receive from sockets, accept connections threadGroup.create_thread(boost::bind(&TraceThread, ""net"", &ThreadSocketHandler)); // Initiate outbound connections from -addnode threadGroup.create_thread(boost::bind(&TraceThread, ""addcon"", &ThreadOpenAddedConnections)); // Initiate outbound connections threadGroup.create_thread(boost::bind(&TraceThread, ""opencon"", &ThreadOpenConnections)); // Process messages threadGroup.create_thread(boost::bind(&TraceThread, ""msghand"", &ThreadMessageHandler)); // Dump network addresses threadGroup.create_thread(boost::bind(&LoopForever, ""dumpaddr"", &DumpAddresses, DUMP_ADDRESSES_INTERVAL * 1000)); } bool StopNode() { LogPrintf(""StopNode()\\n""); MapPort(false); if (semOutbound) for (int i=0; ipost(); if (fAddressesInitialized) { DumpAddresses(); fAddressesInitialized = false; } return true; } class CNetCleanup { public: CNetCleanup() {} ~CNetCleanup() { // Close sockets BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->hSocket != INVALID_SOCKET) CloseSocket(pnode->hSocket); BOOST_FOREACH(ListenSocket& hListenSocket, vhListenSocket) if (hListenSocket.socket != INVALID_SOCKET) if (!CloseSocket(hListenSocket.socket)) LogPrintf(""CloseSocket(hListenSocket) failed with error %s\\n"", NetworkErrorString(WSAGetLastError())); // clean up some globals (to help leak detection) BOOST_FOREACH(CNode *pnode, vNodes) delete pnode; BOOST_FOREACH(CNode *pnode, vNodesDisconnected) delete pnode; vNodes.clear(); vNodesDisconnected.clear(); vhListenSocket.clear(); delete semOutbound; semOutbound = NULL; delete pnodeLocalHost; pnodeLocalHost = NULL; #ifdef WIN32 // Shutdown Windows Sockets WSACleanup(); #endif } } instance_of_cnetcleanup; void CExplicitNetCleanup::callCleanup() { // Explicit call to destructor of CNetCleanup because it's not implicitly called // when the wallet is restarted from within the wallet itself. CNetCleanup *tmp = new CNetCleanup(); delete tmp; // Stroustrup's gonna kill me for that } void RelayTransaction(const CTransaction& tx) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(10000); ss << tx; RelayTransaction(tx, ss); } void RelayTransaction(const CTransaction& tx, const CDataStream& ss) { CInv inv(MSG_TX, tx.GetHash()); { LOCK(cs_mapRelay); // Expire old relay messages while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime()) { mapRelay.erase(vRelayExpiration.front().second); vRelayExpiration.pop_front(); } // Save original serialized message so newer versions are preserved mapRelay.insert(std::make_pair(inv, ss)); vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv)); } LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if(!pnode->fRelayTxes) continue; LOCK(pnode->cs_filter); if (pnode->pfilter) { if (pnode->pfilter->IsRelevantAndUpdate(tx)) pnode->PushInventory(inv); } else pnode->PushInventory(inv); } } void RelayTransactionLockReq(const CTransaction& tx, bool relayToAll) { CInv inv(MSG_TXLOCK_REQUEST, tx.GetHash()); //broadcast the new lock LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if(!relayToAll && !pnode->fRelayTxes) continue; pnode->PushMessage(""ix"", tx); } } void RelayInv(CInv &inv, const int minProtoVersion) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if(pnode->nVersion >= minProtoVersion) pnode->PushInventory(inv); } void CNode::RecordBytesRecv(uint64_t bytes) { LOCK(cs_totalBytesRecv); nTotalBytesRecv += bytes; } void CNode::RecordBytesSent(uint64_t bytes) { LOCK(cs_totalBytesSent); nTotalBytesSent += bytes; } uint64_t CNode::GetTotalBytesRecv() { LOCK(cs_totalBytesRecv); return nTotalBytesRecv; } uint64_t CNode::GetTotalBytesSent() { LOCK(cs_totalBytesSent); return nTotalBytesSent; } void CNode::Fuzz(int nChance) { if (!fSuccessfullyConnected) return; // Don't fuzz initial handshake if (GetRand(nChance) != 0) return; // Fuzz 1 of every nChance messages switch (GetRand(3)) { case 0: // xor a random byte with a random value: if (!ssSend.empty()) { CDataStream::size_type pos = GetRand(ssSend.size()); ssSend[pos] ^= (unsigned char)(GetRand(256)); } break; case 1: // delete a random byte: if (!ssSend.empty()) { CDataStream::size_type pos = GetRand(ssSend.size()); ssSend.erase(ssSend.begin()+pos); } break; case 2: // insert a random byte at a random position { CDataStream::size_type pos = GetRand(ssSend.size()); char ch = (char)GetRand(256); ssSend.insert(ssSend.begin()+pos, ch); } break; } // Chance of more than one change half the time: // (more changes exponentially less likely): Fuzz(2); } // // CAddrDB // CAddrDB::CAddrDB() { pathAddr = GetDataDir() / ""peers.dat""; } bool CAddrDB::Write(const CAddrMan& addr) { // Generate random temporary filename unsigned short randv = 0; GetRandBytes((unsigned char*)&randv, sizeof(randv)); std::string tmpfn = strprintf(""peers.dat.%04x"", randv); // serialize addresses, checksum data up to that point, then append csum CDataStream ssPeers(SER_DISK, CLIENT_VERSION); ssPeers << FLATDATA(Params().MessageStart()); ssPeers << addr; uint256 hash = Hash(ssPeers.begin(), ssPeers.end()); ssPeers << hash; // open output file, and associate with CAutoFile boost::filesystem::path pathAddr = GetDataDir() / ""peers.dat""; FILE *file = fopen(pathAddr.string().c_str(), ""wb""); CAutoFile fileout(file, SER_DISK, CLIENT_VERSION); if (fileout.IsNull()) return error(""%s : Failed to open file %s"", __func__, pathAddr.string()); // Write and commit header, data try { fileout << ssPeers; } catch (std::exception &e) { return error(""%s : Serialize or I/O error - %s"", __func__, e.what()); } FileCommit(fileout.Get()); fileout.fclose(); return true; } bool CAddrDB::Read(CAddrMan& addr) { // open input file, and associate with CAutoFile FILE *file = fopen(pathAddr.string().c_str(), ""rb""); CAutoFile filein(file, SER_DISK, CLIENT_VERSION); if (filein.IsNull()) return error(""%s : Failed to open file %s"", __func__, pathAddr.string()); // use file size to size memory buffer int fileSize = boost::filesystem::file_size(pathAddr); int dataSize = fileSize - sizeof(uint256); // Don't try to resize to a negative number if file is small if (dataSize < 0) dataSize = 0; vector vchData; vchData.resize(dataSize); uint256 hashIn; // read data and checksum from file try { filein.read((char *)&vchData[0], dataSize); filein >> hashIn; } catch (std::exception &e) { return error(""%s : Deserialize or I/O error - %s"", __func__, e.what()); } filein.fclose(); CDataStream ssPeers(vchData, SER_DISK, CLIENT_VERSION); // verify stored checksum matches input data uint256 hashTmp = Hash(ssPeers.begin(), ssPeers.end()); if (hashIn != hashTmp) return error(""%s : Checksum mismatch, data corrupted"", __func__); unsigned char pchMsgTmp[4]; try { // de-serialize file header (network specific magic number) and .. ssPeers >> FLATDATA(pchMsgTmp); // ... verify the network matches ours if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp))) return error(""%s : Invalid network magic number"", __func__); // de-serialize address data into one CAddrMan object ssPeers >> addr; } catch (std::exception &e) { return error(""%s : Deserialize or I/O error - %s"", __func__, e.what()); } return true; } unsigned int ReceiveFloodSize() { return 1000*GetArg(""-maxreceivebuffer"", 5*1000); } unsigned int SendBufferSize() { return 1000*GetArg(""-maxsendbuffer"", 1*1000); } CNode::CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn, bool fInboundIn) : ssSend(SER_NETWORK, INIT_PROTO_VERSION), setAddrKnown(5000) { nServices = 0; hSocket = hSocketIn; nRecvVersion = INIT_PROTO_VERSION; nLastSend = 0; nLastRecv = 0; nSendBytes = 0; nRecvBytes = 0; nTimeConnected = GetTime(); addr = addrIn; addrName = addrNameIn == """" ? addr.ToStringIPPort() : addrNameIn; nVersion = 0; strSubVer = """"; fWhitelisted = false; fOneShot = false; fClient = false; // set by version message fInbound = fInboundIn; fNetworkNode = false; fSuccessfullyConnected = false; fDisconnect = false; nRefCount = 0; nSendSize = 0; nSendOffset = 0; hashContinue = 0; nStartingHeight = -1; fGetAddr = false; fRelayTxes = false; setInventoryKnown.max_size(SendBufferSize() / 1000); pfilter = new CBloomFilter(); nPingNonceSent = 0; nPingUsecStart = 0; nPingUsecTime = 0; fPingQueued = false; fObfuscateMaster = false; { LOCK(cs_nLastNodeId); id = nLastNodeId++; } if (fLogIPs) LogPrint(""net"", ""Added connection to %s peer=%d\\n"", addrName, id); else LogPrint(""net"", ""Added connection peer=%d\\n"", id); // Be shy and don't send version until we hear if (hSocket != INVALID_SOCKET && !fInbound) PushVersion(); GetNodeSignals().InitializeNode(GetId(), this); } CNode::~CNode() { CloseSocket(hSocket); if (pfilter) delete pfilter; GetNodeSignals().FinalizeNode(GetId()); } void CNode::AskFor(const CInv& inv) { if (mapAskFor.size() > MAPASKFOR_MAX_SZ) return; // We're using mapAskFor as a priority queue, // the key is the earliest time the request can be sent int64_t nRequestTime; limitedmap::const_iterator it = mapAlreadyAskedFor.find(inv); if (it != mapAlreadyAskedFor.end()) nRequestTime = it->second; else nRequestTime = 0; LogPrint(""net"", ""askfor %s %d (%s) peer=%d\\n"", inv.ToString(), nRequestTime, DateTimeStrFormat(""%H:%M:%S"", nRequestTime/1000000), id); // Make sure not to reuse time indexes to keep things in the same order int64_t nNow = GetTimeMicros() - 1000000; static int64_t nLastTime; ++nLastTime; nNow = std::max(nNow, nLastTime); nLastTime = nNow; // Each retry is 2 minutes after the last nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow); if (it != mapAlreadyAskedFor.end()) mapAlreadyAskedFor.update(it, nRequestTime); else mapAlreadyAskedFor.insert(std::make_pair(inv, nRequestTime)); mapAskFor.insert(std::make_pair(nRequestTime, inv)); } void CNode::BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend) { ENTER_CRITICAL_SECTION(cs_vSend); assert(ssSend.size() == 0); ssSend << CMessageHeader(pszCommand, 0); LogPrint(""net"", ""sending: %s "", SanitizeString(pszCommand)); } void CNode::AbortMessage() UNLOCK_FUNCTION(cs_vSend) { ssSend.clear(); LEAVE_CRITICAL_SECTION(cs_vSend); LogPrint(""net"", ""(aborted)\\n""); } void CNode::EndMessage() UNLOCK_FUNCTION(cs_vSend) { // The -*messagestest options are intentionally not documented in the help message, // since they are only used during development to debug the networking code and are // not intended for end-users. if (mapArgs.count(""-dropmessagestest"") && GetRand(GetArg(""-dropmessagestest"", 2)) == 0) { LogPrint(""net"", ""dropmessages DROPPING SEND MESSAGE\\n""); AbortMessage(); return; } if (mapArgs.count(""-fuzzmessagestest"")) Fuzz(GetArg(""-fuzzmessagestest"", 10)); if (ssSend.size() == 0) return; // Set the size unsigned int nSize = ssSend.size() - CMessageHeader::HEADER_SIZE; memcpy((char*)&ssSend[CMessageHeader::MESSAGE_SIZE_OFFSET], &nSize, sizeof(nSize)); // Set the checksum uint256 hash = Hash(ssSend.begin() + CMessageHeader::HEADER_SIZE, ssSend.end()); unsigned int nChecksum = 0; memcpy(&nChecksum, &hash, sizeof(nChecksum)); assert(ssSend.size () >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum)); memcpy((char*)&ssSend[CMessageHeader::CHECKSUM_OFFSET], &nChecksum, sizeof(nChecksum)); LogPrint(""net"", ""(%d bytes) peer=%d\\n"", nSize, id); std::deque::iterator it = vSendMsg.insert(vSendMsg.end(), CSerializeData()); ssSend.GetAndClear(*it); nSendSize += (*it).size(); // If write queue empty, attempt ""optimistic write"" if (it == vSendMsg.begin()) SocketSendData(this); LEAVE_CRITICAL_SECTION(cs_vSend); } ",16330,True,3056.737261366387,median "//// /** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ //// [[upgrading]] = Upgrading :doctype: book :numbered: :toc: left :icons: font :experimental: You cannot skip major versions when upgrading. If you are upgrading from version 0.98.x to 2.x, you must first go from 0.98.x to 1.2.x and then go from 1.2.x to 2.x. Review <>, in particular <>. Familiarize yourself with <>. [[hbase.versioning]] == HBase version number and compatibility [[hbase.versioning.post10]] === Aspirational Semantic Versioning Starting with the 1.0.0 release, HBase is working towards link:http://semver.org/[Semantic Versioning] for its release versioning. In summary: .Given a version number MAJOR.MINOR.PATCH, increment the: * MAJOR version when you make incompatible API changes, * MINOR version when you add functionality in a backwards-compatible manner, and * PATCH version when you make backwards-compatible bug fixes. * Additional labels for pre-release and build metadata are available as extensions to the MAJOR.MINOR.PATCH format. [[hbase.versioning.compat]] .Compatibility Dimensions In addition to the usual API versioning considerations HBase has other compatibility dimensions that we need to consider. .Client-Server wire protocol compatibility * Allows updating client and server out of sync. * We could only allow upgrading the server first. I.e. the server would be backward compatible to an old client, that way new APIs are OK. * Example: A user should be able to use an old client to connect to an upgraded cluster. .Server-Server protocol compatibility * Servers of different versions can co-exist in the same cluster. * The wire protocol between servers is compatible. * Workers for distributed tasks, such as replication and log splitting, can co-exist in the same cluster. * Dependent protocols (such as using ZK for coordination) will also not be changed. * Example: A user can perform a rolling upgrade. .File format compatibility * Support file formats backward and forward compatible * Example: File, ZK encoding, directory layout is upgraded automatically as part of an HBase upgrade. User can downgrade to the older version and everything will continue to work. .Client API compatibility * Allow changing or removing existing client APIs. * An API needs to be deprecated for a whole major version before we will change/remove it. ** An example: An API was deprecated in 2.0.1 and will be marked for deletion in 4.0.0. On the other hand, an API deprecated in 2.0.0 can be removed in 3.0.0. * APIs available in a patch version will be available in all later patch versions. However, new APIs may be added which will not be available in earlier patch versions. * New APIs introduced in a patch version will only be added in a source compatible way footnote:[See 'Source Compatibility' https://blogs.oracle.com/darcy/entry/kinds_of_compatibility]: i.e. code that implements public APIs will continue to compile. ** Example: A user using a newly deprecated API does not need to modify application code with HBase API calls until the next major version. * .Client Binary compatibility * Client code written to APIs available in a given patch release can run unchanged (no recompilation needed) against the new jars of later patch versions. * Client code written to APIs available in a given patch release might not run against the old jars from an earlier patch version. ** Example: Old compiled client code will work unchanged with the new jars. * If a Client implements an HBase Interface, a recompile MAY be required upgrading to a newer minor version (See release notes for warning about incompatible changes). All effort will be made to provide a default implementation so this case should not arise. .Server-Side Limited API compatibility (taken from Hadoop) * Internal APIs are marked as Stable, Evolving, or Unstable * This implies binary compatibility for coprocessors and plugins (pluggable classes, including replication) as long as these are only using marked interfaces/classes. * Example: Old compiled Coprocessor, Filter, or Plugin code will work unchanged with the new jars. .Dependency Compatibility * An upgrade of HBase will not require an incompatible upgrade of a dependent project, except for Apache Hadoop. * An upgrade of HBase will not require an incompatible upgrade of the Java runtime. * Example: Upgrading HBase to a version that supports _Dependency Compatibility_ won't require that you upgrade your Apache ZooKeeper service. * Example: If your current version of HBase supported running on JDK 8, then an upgrade to a version that supports _Dependency Compatibility_ will also run on JDK 8. .Hadoop Versions [TIP] ==== Previously, we tried to maintain dependency compatibility for the underly Hadoop service but over the last few years this has proven untenable. While the HBase project attempts to maintain support for older versions of Hadoop, we drop the ""supported"" designator for minor versions that fail to continue to see releases. Additionally, the Hadoop project has its own set of compatibility guidelines, which means in some cases having to update to a newer supported minor release might break some of our compatibility promises. ==== .Operational Compatibility * Metric changes * Behavioral changes of services * JMX APIs exposed via the `/jmx/` endpoint .Summary * A patch upgrade is a drop-in replacement. Any change that is not Java binary and source compatible would not be allowed.footnote:[See http://docs.oracle.com/javase/specs/jls/se7/html/jls-13.html.] Downgrading versions within patch releases may not be compatible. * A minor upgrade requires no application/client code modification. Ideally it would be a drop-in replacement but client code, coprocessors, filters, etc might have to be recompiled if new jars are used. * A major upgrade allows the HBase community to make breaking changes. .Compatibility Matrix footnote:[Note that this indicates what could break, not that it will break. We will/should add specifics in our release notes.] [cols=""1,1,1,1""] |=== | | Major | Minor | Patch |Client-Server wire Compatibility| N |Y |Y |Server-Server Compatibility |N |Y |Y |File Format Compatibility | N footnote:[comp_matrix_offline_upgrade_note,Running an offline upgrade tool without downgrade might be needed. We will typically only support migrating data from major version X to major version X+1.] | Y |Y |Client API Compatibility | N | Y |Y |Client Binary Compatibility | N | N |Y 4+|Server-Side Limited API Compatibility >| Stable | N | Y | Y >| Evolving | N |N |Y >| Unstable | N |N |N |Dependency Compatibility | N |Y |Y |Operational Compatibility | N |N |Y |=== [[hbase.client.api.surface]] ==== HBase API Surface HBase has a lot of API points, but for the compatibility matrix above, we differentiate between Client API, Limited Private API, and Private API. HBase uses link:https://yetus.apache.org/documentation/0.5.0/interface-classification/[Apache Yetus Audience Annotations] to guide downstream expectations for stability. * InterfaceAudience (link:https://yetus.apache.org/documentation/0.5.0/audience-annotations-apidocs/org/apache/yetus/audience/InterfaceAudience.html[javadocs]): captures the intended audience, possible values include: - Public: safe for end users and external projects - LimitedPrivate: used for internals we expect to be pluggable, such as coprocessors - Private: strictly for use within HBase itself Classes which are defined as `IA.Private` may be used as parameters or return values for interfaces which are declared `IA.LimitedPrivate`. Treat the `IA.Private` object as opaque; do not try to access its methods or fields directly. * InterfaceStability (link:https://yetus.apache.org/documentation/0.5.0/audience-annotations-apidocs/org/apache/yetus/audience/InterfaceStability.html[javadocs]): describes what types of interface changes are permitted. Possible values include: - Stable: the interface is fixed and is not expected to change - Evolving: the interface may change in future minor verisons - Unstable: the interface may change at any time Please keep in mind the following interactions between the `InterfaceAudience` and `InterfaceStability` annotations within the HBase project: * `IA.Public` classes are inherently stable and adhere to our stability guarantees relating to the type of upgrade (major, minor, or patch). * `IA.LimitedPrivate` classes should always be annotated with one of the given `InterfaceStability` values. If they are not, you should presume they are `IS.Unstable`. * `IA.Private` classes should be considered implicitly unstable, with no guarantee of stability between releases. [[hbase.client.api]] HBase Client API:: HBase Client API consists of all the classes or methods that are marked with InterfaceAudience.Public interface. All main classes in hbase-client and dependent modules have either InterfaceAudience.Public, InterfaceAudience.LimitedPrivate, or InterfaceAudience.Private marker. Not all classes in other modules (hbase-server, etc) have the marker. If a class is not annotated with one of these, it is assumed to be a InterfaceAudience.Private class. [[hbase.limitetprivate.api]] HBase LimitedPrivate API:: LimitedPrivate annotation comes with a set of target consumers for the interfaces. Those consumers are coprocessors, phoenix, replication endpoint implementations or similar. At this point, HBase only guarantees source and binary compatibility for these interfaces between patch versions. [[hbase.private.api]] HBase Private API:: All classes annotated with InterfaceAudience.Private or all classes that do not have the annotation are for HBase internal use only. The interfaces and method signatures can change at any point in time. If you are relying on a particular interface that is marked Private, you should open a jira to propose changing the interface to be Public or LimitedPrivate, or an interface exposed for this purpose. [[hbase.binary.compatibility]] .Binary Compatibility When we say two HBase versions are compatible, we mean that the versions are wire and binary compatible. Compatible HBase versions means that clients can talk to compatible but differently versioned servers. It means too that you can just swap out the jars of one version and replace them with the jars of another, compatible version and all will just work. Unless otherwise specified, HBase point versions are (mostly) binary compatible. You can safely do rolling upgrades between binary compatible versions; i.e. across maintenance releases: e.g. from 1.2.4 to 1.2.6. See link:[Does compatibility between versions also mean binary compatibility?] discussion on the HBase dev mailing list. [[hbase.rolling.upgrade]] === Rolling Upgrades A rolling upgrade is the process by which you update the servers in your cluster a server at a time. You can rolling upgrade across HBase versions if they are binary or wire compatible. See <> for more on what this means. Coarsely, a rolling upgrade is a graceful stop each server, update the software, and then restart. You do this for each server in the cluster. Usually you upgrade the Master first and then the RegionServers. See <> for tools that can help use the rolling upgrade process. For example, in the below, HBase was symlinked to the actual HBase install. On upgrade, before running a rolling restart over the cluster, we changed the symlink to point at the new HBase software version and then ran [source,bash] ---- $ HADOOP_HOME=~/hadoop-2.6.0-CRC-SNAPSHOT ~/hbase/bin/rolling-restart.sh --config ~/conf_hbase ---- The rolling-restart script will first gracefully stop and restart the master, and then each of the RegionServers in turn. Because the symlink was changed, on restart the server will come up using the new HBase version. Check logs for errors as the rolling upgrade proceeds. [[hbase.rolling.restart]] .Rolling Upgrade Between Versions that are Binary/Wire Compatible Unless otherwise specified, HBase minor versions are binary compatible. You can do a <> between HBase point versions. For example, you can go to 1.2.4 from 1.2.6 by doing a rolling upgrade across the cluster replacing the 1.2.4 binary with a 1.2.6 binary. In the minor version-particular sections below, we call out where the versions are wire/protocol compatible and in this case, it is also possible to do a <>. == Rollback Sometimes things don't go as planned when attempting an upgrade. This section explains how to perform a _rollback_ to an earlier HBase release. Note that this should only be needed between Major and some Minor releases. You should always be able to _downgrade_ between HBase Patch releases within the same Minor version. These instructions may require you to take steps before you start the upgrade process, so be sure to read through this section beforehand. === Caveats .Rollback vs Downgrade This section describes how to perform a _rollback_ on an upgrade between HBase minor and major versions. In this document, rollback refers to the process of taking an upgraded cluster and restoring it to the old version _while losing all changes that have occurred since upgrade_. By contrast, a cluster _downgrade_ would restore an upgraded cluster to the old version while maintaining any data written since the upgrade. We currently only offer instructions to rollback HBase clusters. Further, rollback only works when these instructions are followed prior to performing the upgrade. When these instructions talk about rollback vs downgrade of prerequisite cluster services (i.e. HDFS), you should treat leaving the service version the same as a degenerate case of downgrade. .Replication Unless you are doing an all-service rollback, the HBase cluster will lose any configured peers for HBase replication. If your cluster is configured for HBase replication, then prior to following these instructions you should document all replication peers. After performing the rollback you should then add each documented peer back to the cluster. For more information on enabling HBase replication, listing peers, and adding a peer see <>. Note also that data written to the cluster since the upgrade may or may not have already been replicated to any peers. Determining which, if any, peers have seen replication data as well as rolling back the data in those peers is out of the scope of this guide. .Data Locality Unless you are doing an all-service rollback, going through a rollback procedure will likely destroy all locality for Region Servers. You should expect degraded performance until after the cluster has had time to go through compactions to restore data locality. Optionally, you can force a compaction to speed this process up at the cost of generating cluster load. .Configurable Locations The instructions below assume default locations for the HBase data directory and the HBase znode. Both of these locations are configurable and you should verify the value used in your cluster before proceeding. In the event that you have a different value, just replace the default with the one found in your configuration * HBase data directory is configured via the key 'hbase.rootdir' and has a default value of '/hbase'. * HBase znode is configured via the key 'zookeeper.znode.parent' and has a default value of '/hbase'. === All service rollback If you will be performing a rollback of both the HDFS and ZooKeeper services, then HBase's data will be rolled back in the process. .Requirements * Ability to rollback HDFS and ZooKeeper .Before upgrade No additional steps are needed pre-upgrade. As an extra precautionary measure, you may wish to use distcp to back up the HBase data off of the cluster to be upgraded. To do so, follow the steps in the 'Before upgrade' section of 'Rollback after HDFS downgrade' but copy to another HDFS instance instead of within the same instance. .Performing a rollback . Stop HBase . Perform a rollback for HDFS and ZooKeeper (HBase should remain stopped) . Change the installed version of HBase to the previous version . Start HBase . Verify HBase contents—use the HBase shell to list tables and scan some known values. === Rollback after HDFS rollback and ZooKeeper downgrade If you will be rolling back HDFS but going through a ZooKeeper downgrade, then HBase will be in an inconsistent state. You must ensure the cluster is not started until you complete this process. .Requirements * Ability to rollback HDFS * Ability to downgrade ZooKeeper .Before upgrade No additional steps are needed pre-upgrade. As an extra precautionary measure, you may wish to use distcp to back up the HBase data off of the cluster to be upgraded. To do so, follow the steps in the 'Before upgrade' section of 'Rollback after HDFS downgrade' but copy to another HDFS instance instead of within the same instance. .Performing a rollback . Stop HBase . Perform a rollback for HDFS and a downgrade for ZooKeeper (HBase should remain stopped) . Change the installed version of HBase to the previous version . Clean out ZooKeeper information related to HBase. WARNING: This step will permanently destroy all replication peers. Please see the section on HBase Replication under Caveats for more information. + .Clean HBase information out of ZooKeeper [source,bash] ---- [hpnewton@gateway_node.example.com ~]$ zookeeper-client -server zookeeper1.example.com:2181,zookeeper2.example.com:2181,zookeeper3.example.com:2181 Welcome to ZooKeeper! JLine support is disabled rmr /hbase quit Quitting... ---- . Start HBase . Verify HBase contents—use the HBase shell to list tables and scan some known values. === Rollback after HDFS downgrade If you will be performing an HDFS downgrade, then you'll need to follow these instructions regardless of whether ZooKeeper goes through rollback, downgrade, or reinstallation. .Requirements * Ability to downgrade HDFS * Pre-upgrade cluster must be able to run MapReduce jobs * HDFS super user access * Sufficient space in HDFS for at least two copies of the HBase data directory .Before upgrade Before beginning the upgrade process, you must take a complete backup of HBase's backing data. The following instructions cover backing up the data within the current HDFS instance. Alternatively, you can use the distcp command to copy the data to another HDFS cluster. . Stop the HBase cluster . Copy the HBase data directory to a backup location using the https://hadoop.apache.org/docs/current/hadoop-distcp/DistCp.html[distcp command] as the HDFS super user (shown below on a security enabled cluster) + .Using distcp to backup the HBase data directory [source,bash] ---- [hpnewton@gateway_node.example.com ~]$ kinit -k -t hdfs.keytab hdfs@EXAMPLE.COM [hpnewton@gateway_node.example.com ~]$ hadoop distcp /hbase /hbase-pre-upgrade-backup ---- . Distcp will launch a mapreduce job to handle copying the files in a distributed fashion. Check the output of the distcp command to ensure this job completed successfully. .Performing a rollback . Stop HBase . Perform a downgrade for HDFS and a downgrade/rollback for ZooKeeper (HBase should remain stopped) . Change the installed version of HBase to the previous version . Restore the HBase data directory from prior to the upgrade as the HDFS super user (shown below on a security enabled cluster). If you backed up your data on another HDFS cluster instead of locally, you will need to use the distcp command to copy it back to the current HDFS cluster. + .Restore the HBase data directory [source,bash] ---- [hpnewton@gateway_node.example.com ~]$ kinit -k -t hdfs.keytab hdfs@EXAMPLE.COM [hpnewton@gateway_node.example.com ~]$ hdfs dfs -mv /hbase /hbase-upgrade-rollback [hpnewton@gateway_node.example.com ~]$ hdfs dfs -mv /hbase-pre-upgrade-backup /hbase ---- . Clean out ZooKeeper information related to HBase. WARNING: This step will permanently destroy all replication peers. Please see the section on HBase Replication under Caveats for more information. + .Clean HBase information out of ZooKeeper [source,bash] ---- [hpnewton@gateway_node.example.com ~]$ zookeeper-client -server zookeeper1.example.com:2181,zookeeper2.example.com:2181,zookeeper3.example.com:2181 Welcome to ZooKeeper! JLine support is disabled rmr /hbase quit Quitting... ---- . Start HBase . Verify HBase contents–use the HBase shell to list tables and scan some known values. == Upgrade Paths [[upgrade2.0]] === Upgrading from 1.x to 2.x In this section we will first call out significant changes compared to the prior stable HBase release and then go over the upgrade process. Be sure to read the former with care so you avoid suprises. ==== Changes of Note! First we'll cover deployment / operational changes that you might hit when upgrading to HBase 2.0+. After that we'll call out changes for downstream applications. Please note that Coprocessors are covered in the operational section. Also note that this section is not meant to convey information about new features that may be of interest to you. For a complete summary of changes, please see the CHANGES.txt file in the source release artifact for the version you are planning to upgrade to. [[upgrade2.0.basic.requirements]] .Update to basic prerequisite minimums in HBase 2.0+ As noted in the section <>, HBase 2.0+ requires a minimum of Java 8 and Hadoop 2.6. The HBase community recommends ensuring you have already completed any needed upgrades in prerequisites prior to upgrading your HBase version. [[upgrade2.0.hbck]] .HBCK must match HBase server version You *must not* use an HBase 1.x version of HBCK against an HBase 2.0+ cluster. HBCK is strongly tied to the HBase server version. Using the HBCK tool from an earlier release against an HBase 2.0+ cluster will destructively alter said cluster in unrecoverable ways. As of HBase 2.0, HBCK (A.K.A _HBCK1_ or _hbck1_) is a read-only tool that can report the status of some non-public system internals. You should not rely on the format nor content of these internals to remain consistent across HBase releases. To read about HBCK's replacement, see <> in <>. //// Link to a ref guide section on HBCK in 2.0 that explains use and calls out the inability of clients and server sides to detect version of each other. //// [[upgrade2.0.removed.configs]] .Configuration settings no longer in HBase 2.0+ The following configuration settings are no longer applicable or available. For details, please see the detailed release notes. * hbase.config.read.zookeeper.config (see <> for migration details) * hbase.zookeeper.useMulti (HBase now always uses ZK's multi functionality) * hbase.rpc.client.threads.max * hbase.rpc.client.nativetransport * hbase.fs.tmp.dir // These next two seem worth a call out section? * hbase.bucketcache.combinedcache.enabled * hbase.bucketcache.ioengine no longer supports the 'heap' value. * hbase.bulkload.staging.dir * hbase.balancer.tablesOnMaster wasn't removed, strictly speaking, but its meaning has fundamentally changed and users should not set it. See the section <> for details. * hbase.master.distributed.log.replay See the section <> for details * hbase.regionserver.disallow.writes.when.recovering See the section <> for details * hbase.regionserver.wal.logreplay.batch.size See the section <> for details * hbase.master.catalog.timeout * hbase.regionserver.catalog.timeout * hbase.metrics.exposeOperationTimes * hbase.metrics.showTableName * hbase.online.schema.update.enable (HBase now always supports this) * hbase.thrift.htablepool.size.max [[upgrade2.0.renamed.configs]] .Configuration properties that were renamed in HBase 2.0+ The following properties have been renamed. Attempts to set the old property will be ignored at run time. .Renamed properties [options=""header""] |============================================================================================================ |Old name |New name |hbase.rpc.server.nativetransport |hbase.netty.nativetransport |hbase.netty.rpc.server.worker.count |hbase.netty.worker.count |hbase.hfile.compactions.discharger.interval |hbase.hfile.compaction.discharger.interval |hbase.hregion.percolumnfamilyflush.size.lower.bound |hbase.hregion.percolumnfamilyflush.size.lower.bound.min |============================================================================================================ [[upgrade2.0.changed.defaults]] .Configuration settings with different defaults in HBase 2.0+ The following configuration settings changed their default value. Where applicable, the value to set to restore the behavior of HBase 1.2 is given. * hbase.security.authorization now defaults to false. set to true to restore same behavior as previous default. * hbase.client.retries.number is now set to 10. Previously it was 35. Downstream users are advised to use client timeouts as described in section <> instead. * hbase.client.serverside.retries.multiplier is now set to 3. Previously it was 10. Downstream users are advised to use client timesout as describe in section <> instead. * hbase.master.fileSplitTimeout is now set to 10 minutes. Previously it was 30 seconds. * hbase.regionserver.logroll.multiplier is now set to 0.5. Previously it was 0.95. This change is tied with the following doubling of block size. Combined, these two configuration changes should make for WALs of about the same size as those in hbase-1.x but there should be less incidence of small blocks because we fail to roll the WAL before we hit the blocksize threshold. See link:https://issues.apache.org/jira/browse/HBASE-19148[HBASE-19148] for discussion. * hbase.regionserver.hlog.blocksize defaults to 2x the HDFS default block size for the WAL dir. Previously it was equal to the HDFS default block size for the WAL dir. * hbase.client.start.log.errors.counter changed to 5. Previously it was 9. * hbase.ipc.server.callqueue.type changed to 'fifo'. In HBase versions 1.0 - 1.2 it was 'deadline'. In prior and later 1.x versions it already defaults to 'fifo'. * hbase.hregion.memstore.chunkpool.maxsize is 1.0 by default. Previously it was 0.0. Effectively, this means previously we would not use a chunk pool when our memstore is onheap and now we will. See the section <> for more infromation about the MSLAB chunk pool. * hbase.master.cleaner.interval is now set to 10 minutes. Previously it was 1 minute. * hbase.master.procedure.threads will now default to 1/4 of the number of available CPUs, but not less than 16 threads. Previously it would be number of threads equal to number of CPUs. * hbase.hstore.blockingStoreFiles is now 16. Previously it was 10. * hbase.http.max.threads is now 16. Previously it was 10. * hbase.client.max.perserver.tasks is now 2. Previously it was 5. * hbase.normalizer.period is now 5 minutes. Previously it was 30 minutes. * hbase.regionserver.region.split.policy is now SteppingSplitPolicy. Previously it was IncreasingToUpperBoundRegionSplitPolicy. * replication.source.ratio is now 0.5. Previously it was 0.1. [[upgrade2.0.regions.on.master]] .""Master hosting regions"" feature broken and unsupported The feature ""Master acts as region server"" and associated follow-on work available in HBase 1.y is non-functional in HBase 2.y and should not be used in a production setting due to deadlock on Master initialization. Downstream users are advised to treat related configuration settings as experimental and the feature as inappropriate for production settings. A brief summary of related changes: * Master no longer carries regions by default * hbase.balancer.tablesOnMaster is a boolean, default false (if it holds an HBase 1.x list of tables, will default to false) * hbase.balancer.tablesOnMaster.systemTablesOnly is boolean to keep user tables off master. default false * those wishing to replicate old list-of-servers config should deploy a stand-alone RegionServer process and then rely on Region Server Groups [[upgrade2.0.distributed.log.replay]] .""Distributed Log Replay"" feature broken and removed The Distributed Log Replay feature was broken and has been removed from HBase 2.y+. As a consequence all related configs, metrics, RPC fields, and logging have also been removed. Note that this feature was found to be unreliable in the run up to HBase 1.0, defaulted to being unused, and was effectively removed in HBase 1.2.0 when we started ignoring the config that turns it on (link:https://issues.apache.org/jira/browse/HBASE-14465[HBASE-14465]). If you are currently using the feature, be sure to perform a clean shutdown, ensure all DLR work is complete, and disable the feature prior to upgrading. [[upgrade2.0.prefix-tree.removed]] ._prefix-tree_ encoding removed The prefix-tree encoding was removed from HBase 2.0.0 (link:https://issues.apache.org/jira/browse/HBASE-19179[HBASE-19179]). It was (late!) deprecated in hbase-1.2.7, hbase-1.4.0, and hbase-1.3.2. This feature was removed because it as not being actively maintained. If interested in reviving this sweet facility which improved random read latencies at the expensive of slowed writes, write the HBase developers list at _dev at hbase dot apache dot org_. The prefix-tree encoding needs to be removed from all tables before upgrading to HBase 2.0+. To do that first you need to change the encoding from PREFIX_TREE to something else that is supported in HBase 2.0. After that you have to major compact the tables that were using PREFIX_TREE encoding before. To check which column families are using incompatible data block encoding you can use <>. [[upgrade2.0.metrics]] .Changed metrics The following metrics have changed names: * Metrics previously published under the name ""AssignmentManger"" [sic] are now published under the name ""AssignmentManager"" The following metrics have changed their meaning: * The metric 'blockCacheEvictionCount' published on a per-region server basis no longer includes blocks removed from the cache due to the invalidation of the hfiles they are from (e.g. via compaction). * The metric 'totalRequestCount' increments once per request; previously it incremented by the number of `Actions` carried in the request; e.g. if a request was a `multi` made of four Gets and two Puts, we'd increment 'totalRequestCount' by six; now we increment by one regardless. Expect to see lower values for this metric in hbase-2.0.0. * The 'readRequestCount' now counts reads that return a non-empty row where in older hbases, we'd increment 'readRequestCount' whether a Result or not. This change will flatten the profile of the read-requests graphs if requests for non-existent rows. A YCSB read-heavy workload can do this dependent on how the database was loaded. The following metrics have been removed: * Metrics related to the Distributed Log Replay feature are no longer present. They were previsouly found in the region server context under the name 'replay'. See the section <> for details. The following metrics have been added: * 'totalRowActionRequestCount' is a count of region row actions summing reads and writes. [[upgrade2.0.logging]] .Changed logging HBase-2.0.0 now uses link:https://www.slf4j.org/[slf4j] as its logging frontend. Prevously, we used link:http://logging.apache.org/log4j/1.2/[log4j (1.2)]. For most the transition should be seamless; slf4j does a good job interpreting _log4j.properties_ logging configuration files such that you should not notice any difference in your log system emissions. That said, your _log4j.properties_ may need freshening. See link:https://issues.apache.org/jira/browse/HBASE-20351[HBASE-20351] for example, where a stale log configuration file manifest as netty configuration being dumped at DEBUG level as preamble on every shell command invocation. [[upgrade2.0.zkconfig]] .ZooKeeper configs no longer read from zoo.cfg HBase no longer optionally reads the 'zoo.cfg' file for ZooKeeper related configuration settings. If you previously relied on the 'hbase.config.read.zookeeper.config' config for this functionality, you should migrate any needed settings to the hbase-site.xml file while adding the prefix 'hbase.zookeeper.property.' to each property name. [[upgrade2.0.permissions]] .Changes in permissions The following permission related changes either altered semantics or defaults: * Permissions granted to a user now merge with existing permissions for that user, rather than over-writing them. (see link:https://issues.apache.org/jira/browse/HBASE-17472[the release note on HBASE-17472] for details) * Region Server Group commands (added in 1.4.0) now require admin privileges. [[upgrade2.0.admin.commands]] .Most Admin APIs don't work against an HBase 2.0+ cluster from pre-HBase 2.0 clients A number of admin commands are known to not work when used from a pre-HBase 2.0 client. This includes an HBase Shell that has the library jars from pre-HBase 2.0. You will need to plan for an outage of use of admin APIs and commands until you can also update to the needed client version. The following client operations do not work against HBase 2.0+ cluster when executed from a pre-HBase 2.0 client: * list_procedures * split * merge_region * list_quotas * enable_table_replication * disable_table_replication * Snapshot related commands .Deprecated in 1.0 admin commands have been removed. The following commands that were deprecated in 1.0 have been removed. Where applicable the replacement command is listed. * The 'hlog' command has been removed. Downstream users should rely on the 'wal' command instead. [[upgrade2.0.memory]] .Region Server memory consumption changes. Users upgrading from versions prior to HBase 1.4 should read the instructions in section <>. Additionally, HBase 2.0 has changed how memstore memory is tracked for flushing decisions. Previously, both the data size and overhead for storage were used to calculate utilization against the flush threashold. Now, only data size is used to make these per-region decisions. Globally the addition of the storage overhead is used to make decisions about forced flushes. [[upgrade2.0.ui.splitmerge.by.row]] .Web UI for splitting and merging operate on row prefixes Previously, the Web UI included functionality on table status pages to merge or split based on an encoded region name. In HBase 2.0, instead this functionality works by taking a row prefix. [[upgrade2.0.replication]] .Special upgrading for Replication users from pre-HBase 1.4 User running versions of HBase prior to the 1.4.0 release that make use of replication should be sure to read the instructions in the section <>. [[upgrade2.0.shell]] .HBase shell changes The HBase shell command relies on a bundled JRuby instance. This bundled JRuby been updated from version 1.6.8 to version 9.1.10.0. The represents a change from Ruby 1.8 to Ruby 2.3.3, which introduces non-compatible language changes for user scripts. The HBase shell command now ignores the '--return-values' flag that was present in early HBase 1.4 releases. Instead the shell always behaves as though that flag were passed. If you wish to avoid having expression results printed in the console you should alter your IRB configuration as noted in the section <>. [[upgrade2.0.coprocessors]] .Coprocessor APIs have changed in HBase 2.0+ All Coprocessor APIs have been refactored to improve supportability around binary API compatibility for future versions of HBase. If you or applications you rely on have custom HBase coprocessors, you should read link:https://issues.apache.org/jira/browse/HBASE-18169[the release notes for HBASE-18169] for details of changes you will need to make prior to upgrading to HBase 2.0+. For example, if you had a BaseRegionObserver in HBase 1.2 then at a minimum you will need to update it to implement both RegionObserver and RegionCoprocessor and add the method [source,java] ---- ... @Override public Optional getRegionObserver() { return Optional.of(this); } ... ---- //// This would be a good place to link to a coprocessor migration guide //// [[upgrade2.0.hfile3.only]] .HBase 2.0+ can no longer write HFile v2 files. HBase has simplified our internal HFile handling. As a result, we can no longer write HFile versions earlier than the default of version 3. Upgrading users should ensure that hfile.format.version is not set to 2 in hbase-site.xml before upgrading. Failing to do so will cause Region Server failure. HBase can still read HFiles written in the older version 2 format. [[upgrade2.0.pb.wal.only]] .HBase 2.0+ can no longer read Sequence File based WAL file. HBase can no longer read the deprecated WAL files written in the Apache Hadoop Sequence File format. The hbase.regionserver.hlog.reader.impl and hbase.regionserver.hlog.reader.impl configuration entries should be set to use the Protobuf based WAL reader / writer classes. This implementation has been the default since HBase 0.96, so legacy WAL files should not be a concern for most downstream users. A clean cluster shutdown should ensure there are no WAL files. If you are unsure of a given WAL file's format you can use the `hbase wal` command to parse files while the HBase cluster is offline. In HBase 2.0+, this command will not be able to read a Sequence File based WAL. For more information on the tool see the section <>. [[upgrade2.0.filters]] .Change in behavior for filters The Filter ReturnCode NEXT_ROW has been redefined as skipping to next row in current family, not to next row in all family. it’s more reasonable, because ReturnCode is a concept in store level, not in region level. [[upgrade2.0.shaded.client.preferred]] .Downstream HBase 2.0+ users should use the shaded client Downstream users are strongly urged to rely on the Maven coordinates org.apache.hbase:hbase-shaded-client for their runtime use. This artifact contains all the needed implementation details for talking to an HBase cluster while minimizing the number of third party dependencies exposed. Note that this artifact exposes some classes in the org.apache.hadoop package space (e.g. o.a.h.configuration.Configuration) so that we can maintain source compatibility with our public API. Those classes are included so that they can be altered to use the same relocated third party dependencies as the rest of the HBase client code. In the event that you need to *also* use Hadoop in your code, you should ensure all Hadoop related jars precede the HBase client jar in your classpath. [[upgrade2.0.mapreduce.module]] .Downstream HBase 2.0+ users of MapReduce must switch to new artifact Downstream users of HBase's integration for Apache Hadoop MapReduce must switch to relying on the org.apache.hbase:hbase-shaded-mapreduce module for their runtime use. Historically, downstream users relied on either the org.apache.hbase:hbase-server or org.apache.hbase:hbase-shaded-server artifacts for these classes. Both uses are no longer supported and in the vast majority of cases will fail at runtime. Note that this artifact exposes some classes in the org.apache.hadoop package space (e.g. o.a.h.configuration.Configuration) so that we can maintain source compatibility with our public API. Those classes are included so that they can be altered to use the same relocated third party dependencies as the rest of the HBase client code. In the event that you need to *also* use Hadoop in your code, you should ensure all Hadoop related jars precede the HBase client jar in your classpath. [[upgrade2.0.dependencies]] .Significant changes to runtime classpath A number of internal dependencies for HBase were updated or removed from the runtime classpath. Downstream client users who do not follow the guidance in <> will have to examine the set of dependencies Maven pulls in for impact. Downstream users of LimitedPrivate Coprocessor APIs will need to examine the runtime environment for impact. For details on our new handling of third party libraries that have historically been a problem with respect to harmonizing compatible runtime versions, see the reference guide section <>. [[upgrade2.0.public.api]] .Multiple breaking changes to source and binary compatibility for client API The Java client API for HBase has a number of changes that break both source and binary compatibility for details see the Compatibility Check Report for the release you'll be upgrading to. [[upgrade2.0.tracing]] .Tracing implementation changes The backing implementation of HBase's tracing features was updated from Apache HTrace 3 to HTrace 4, which includes several breaking changes. While HTrace 3 and 4 can coexist in the same runtime, they will not integrate with each other, leading to disjoint trace information. The internal changes to HBase during this upgrade were sufficient for compilation, but it has not been confirmed that there are no regressions in tracing functionality. Please consider this feature expiremental for the immediate future. If you previously relied on client side tracing integrated with HBase operations, it is recommended that you upgrade your usage to HTrace 4 as well. [[upgrade2.0.hfile.compatability]] .HFile lose forward compatability HFiles generated by 2.0.0, 2.0.1, 2.1.0 are not forward compatible to 1.4.6-, 1.3.2.1-, 1.2.6.1-, and other inactive releases. Why HFile lose compatability is hbase in new versions (2.0.0, 2.0.1, 2.1.0) use protobuf to serialize/deserialize TimeRangeTracker (TRT) while old versions use DataInput/DataOutput. To solve this, We have to put link:https://jira.apache.org/jira/browse/HBASE-21012[HBASE-21012] to 2.x and put link:https://jira.apache.org/jira/browse/HBASE-21013[HBASE-21013] in 1.x. For more information, please check link:https://jira.apache.org/jira/browse/HBASE-21008[HBASE-21008]. [[upgrade2.0.perf]] .Performance You will likely see a change in the performance profile on upgrade to hbase-2.0.0 given read and write paths have undergone significant change. On release, writes may be slower with reads about the same or much better, dependent on context. Be prepared to spend time re-tuning (See <>). Performance is also an area that is now under active review so look forward to improvement in coming releases (See link:https://issues.apache.org/jira/browse/HBASE-20188[HBASE-20188 TESTING Performance]). [[upgrade2.0.it.kerberos]] .Integration Tests and Kerberos Integration Tests (`IntegrationTests*`) used to rely on the Kerberos credential cache for authentication against secured clusters. This used to lead to tests failing due to authentication failures when the tickets in the credential cache expired. As of hbase-2.0.0 (and hbase-1.3.0+), the integration test clients will make use of the configuration properties `hbase.client.keytab.file` and `hbase.client.kerberos.principal`. They are required. The clients will perform a login from the configured keytab file and automatically refresh the credentials in the background for the process lifetime (See link:https://issues.apache.org/jira/browse/HBASE-16231[HBASE-16231]). //// This would be a good place to link to an appendix on migrating applications //// [[upgrade2.0.coprocessors]] ==== Upgrading Coprocessors to 2.0 Coprocessors have changed substantially in 2.0 ranging from top level design changes in class hierarchies to changed/removed methods, interfaces, etc. (Parent jira: link:https://issues.apache.org/jira/browse/HBASE-18169[HBASE-18169 Coprocessor fix and cleanup before 2.0.0 release]). Some of the reasons for such widespread changes: . Pass Interfaces instead of Implementations; e.g. TableDescriptor instead of HTableDescriptor and Region instead of HRegion (link:https://issues.apache.org/jira/browse/HBASE-18241[HBASE-18241] Change client.Table and client.Admin to not use HTableDescriptor). . Design refactor so implementers need to fill out less boilerplate and so we can do more compile-time checking (link:https://issues.apache.org/jira/browse/HBASE-17732[HBASE-17732]) . Purge Protocol Buffers from Coprocessor API (link:https://issues.apache.org/jira/browse/HBASE-18859[HBASE-18859], link:https://issues.apache.org/jira/browse/HBASE-16769[HBASE-16769], etc) . Cut back on what we expose to Coprocessors removing hooks on internals that were too private to expose (for eg. link:https://issues.apache.org/jira/browse/HBASE-18453[HBASE-18453] CompactionRequest should not be exposed to user directly; link:https://issues.apache.org/jira/browse/HBASE-18298[HBASE-18298] RegionServerServices Interface cleanup for CP expose; etc) To use coprocessors in 2.0, they should be rebuilt against new API otherwise they will fail to load and HBase processes will die. Suggested order of changes to upgrade the coprocessors: . Directly implement observer interfaces instead of extending Base*Observer classes. Change `Foo extends BaseXXXObserver` to `Foo implements XXXObserver`. (link:https://issues.apache.org/jira/browse/HBASE-17312[HBASE-17312]). . Adapt to design change from Inheritence to Composition (link:https://issues.apache.org/jira/browse/HBASE-17732[HBASE-17732]) by following link:https://github.com/apache/hbase/blob/master/dev-support/design-docs/Coprocessor_Design_Improvements-Use_composition_instead_of_inheritance-HBASE-17732.adoc#migrating-existing-cps-to-new-design[this example]. . getTable() has been removed from the CoprocessorEnvrionment, coprocessors should self-manage Table instances. Some examples of writing coprocessors with new API can be found in hbase-example module link:https://github.com/apache/hbase/tree/branch-2.0/hbase-examples/src/main/java/org/apache/hadoop/hbase/coprocessor/example[here] . Lastly, if an api has been changed/removed that breaks you in an irreparable way, and if there's a good justification to add it back, bring it our notice (dev@hbase.apache.org). [[upgrade2.0.rolling.upgrades]] ==== Rolling Upgrade from 1.x to 2.x Rolling upgrades are currently an experimental feature. They have had limited testing. There are likely corner cases as yet uncovered in our limited experience so you should be careful if you go this route. The stop/upgrade/start described in the next section, <>, is the safest route. That said, the below is a prescription for a rolling upgrade of a 1.4 cluster. .Pre-Requirements * Upgrade to the latest 1.4.x release. Pre 1.4 releases may also work but are not tested, so please upgrade to 1.4.3+ before upgrading to 2.x, unless you are an expert and familiar with the region assignment and crash processing. See the section <> on how to upgrade to 1.4.x. * Make sure that the zk-less assignment is enabled, i.e, set `hbase.assignment.usezk` to `false`. This is the most important thing. It allows the 1.x master to assign/unassign regions to/from 2.x region servers. See the release note section of link:https://issues.apache.org/jira/browse/HBASE-11059[HBASE-11059] on how to migrate from zk based assignment to zk less assignment. * We have tested rolling upgrading from 1.4.3 to 2.1.0, but it should also work if you want to upgrade to 2.0.x. .Instructions . Unload a region server and upgrade it to 2.1.0. With link:https://issues.apache.org/jira/browse/HBASE-17931[HBASE-17931] in place, the meta region and regions for other system tables will be moved to this region server immediately. If not, please move them manually to the new region server. This is very important because ** The schema of meta region is hard coded, if meta is on an old region server, then the new region servers can not access it as it does not have some families, for example, table state. ** Client with lower version can communicate with server with higher version, but not vice versa. If the meta region is on an old region server, the new region server will use a client with higher version to communicate with a server with lower version, this may introduce strange problems. . Rolling upgrade all other region servers. . Upgrading masters. It is OK that during the rolling upgrading there are region server crashes. The 1.x master can assign regions to both 1.x and 2.x region servers, and link:https://issues.apache.org/jira/browse/HBASE-19166[HBASE-19166] fixed a problem so that 1.x region server can also read the WALs written by 2.x region server and split them. NOTE: please read the <> section carefully before rolling upgrading. Make sure that you do not use the removed features in 2.0, for example, the prefix-tree encoding, the old hfile format, etc. They could both fail the upgrading and leave the cluster in an intermediate state and hard to recover. NOTE: If you have success running this prescription, please notify the dev list with a note on your experience and/or update the above with any deviations you may have taken so others going this route can benefit from your efforts. [[upgrade2.0.process]] ==== Upgrade process from 1.x to 2.x To upgrade an existing HBase 1.x cluster, you should: * Clean shutdown of existing 1.x cluster * Update coprocessors * Upgrade Master roles first * Upgrade RegionServers * (Eventually) Upgrade Clients [[upgrade1.4]] === Upgrading from pre-1.4 to 1.4+ [[upgrade1.4.memory]] ==== Region Server memory consumption changes. Users upgrading from versions prior to HBase 1.4 should be aware that the estimates of heap usage by the memstore objects (KeyValue, object and array header sizes, etc) have been made more accurate for heap sizes up to 32G (using CompressedOops), resulting in them dropping by 10-50% in practice. This also results in less number of flushes and compactions due to ""fatter"" flushes. YMMV. As a result, the actual heap usage of the memstore before being flushed may increase by up to 100%. If configured memory limits for the region server had been tuned based on observed usage, this change could result in worse GC behavior or even OutOfMemory errors. Set the environment property (not hbase-site.xml) ""hbase.memorylayout.use.unsafe"" to false to disable. [[upgrade1.4.replication]] ==== Replication peer's TableCFs config Before 1.4, the table name can't include namespace for replication peer's TableCFs config. It was fixed by add TableCFs to ReplicationPeerConfig which was stored on Zookeeper. So when upgrade to 1.4, you have to update the original ReplicationPeerConfig data on Zookeeper firstly. There are four steps to upgrade when your cluster have a replication peer with TableCFs config. * Disable the replication peer. * If master has permission to write replication peer znode, then rolling update master directly. If not, use TableCFsUpdater tool to update the replication peer's config. [source,bash] ---- $ bin/hbase org.apache.hadoop.hbase.replication.master.TableCFsUpdater update ---- * Rolling update regionservers. * Enable the replication peer. Notes: * Can't use the old client(before 1.4) to change the replication peer's config. Because the client will write config to Zookeeper directly, the old client will miss TableCFs config. And the old client write TableCFs config to the old tablecfs znode, it will not work for new version regionserver. [[upgrade1.4.rawscan]] ==== Raw scan now ignores TTL Doing a raw scan will now return results that have expired according to TTL settings. [[upgrade1.3]] === Upgrading from pre-1.3 to 1.3+ If running Integration Tests under Kerberos, see <>. [[upgrade1.0]] === Upgrading to 1.x Please consult the documentation published specifically for the version of HBase that you are upgrading to for details on the upgrade process. ",12184,False,2108.9152192886063,median "//// This guide is maintained in the main Quarkus repository and pull requests should be submitted there: https://github.com/quarkusio/quarkus/tree/master/docs/src/main/asciidoc //// = Quarkus - Writing REST Services with RESTEasy Reactive include::./attributes.adoc[] :jaxrsapi: https://javadoc.io/doc/javax.ws.rs/javax.ws.rs-api/2.1.1 :jaxrsspec: /specs/jaxrs/2.1/index.html :jdkapi: https://docs.oracle.com/en/java/javase/11/docs/api/java.base :mutinyapi: https://smallrye.io/smallrye-mutiny/apidocs :httpspec: https://tools.ietf.org/html/rfc7231 :jsonpapi: https://javadoc.io/doc/javax.json/javax.json-api/1.1.4 :vertxapi: https://javadoc.io/static/io.vertx/vertx-core/3.9.4 This guide explains how to write REST Services with RESTEasy Reactive in Quarkus. == What is RESTEasy Reactive? RESTEasy Reactive is a new link:{jaxrsspec}[JAX-RS] implementation written from the ground up to work on our common https://vertx.io/[Vert.x] layer and is thus fully reactive, while also being very tightly integrated with Quarkus and consequently moving a lot of work to build time. You should be able to use it in place of any JAX-RS implementation, but on top of that it has great performance for both blocking and non-blocking endpoints, and a lot of new features on top of what JAX-RS provides. == Writing endpoints === Getting started Add the following import to your `pom.xml` file: [source,xml] ---- io.quarkus quarkus-resteasy-reactive ---- You can now write your first endpoint in the `org.acme.rest.Endpoint` class: [source,java] ---- package org.acme.rest; import javax.ws.rs.GET; import javax.ws.rs.Path; @Path("""") public class Endpoint { @GET public String hello(){ return ""Hello, World!""; } } ---- === Terminology REST:: https://en.wikipedia.org/wiki/Representational_state_transfer[REpresentational State Transfer] Endpoint:: Java method which is called to serve a REST call URL / URI (Uniform Resource Locator / Identifier):: Used to identify the location of REST resources (https://tools.ietf.org/html/rfc7230#section-2.7[specification]) Resource:: Represents your domain object. This is what your API serves and modifies. Also called an `entity` in JAX-RS. Representation:: How your resource is represented on the wire, can vary depending on content types Content type:: Designates a particular representation (also called a media type), for example `text/plain` or `application/json` HTTP:: Underlying wire protocol for routing REST calls (see https://tools.ietf.org/html/rfc7230[HTTP specifications]) HTTP request:: the request part of the HTTP call, consisting of an HTTP method, a target URI, headers and an optional message body HTTP response:: the response part of the HTTP call, consisting of an HTTP response status, headers and an optional message body === Declaring endpoints: URI mapping Any class annotated with a link:{jaxrsapi}/javax/ws/rs/Path.html[`@Path`] annotation can have its methods exposed as REST endpoints, provided they have an HTTP method annotation (see below). That link:{jaxrsapi}/javax/ws/rs/Path.html[`@Path`] annotation defines the URI prefix under which those methods will be exposed. It can be empty, or contain a prefix such as `rest` or `rest/V1`. Each exposed endpoint method can in turn have another link:{jaxrsapi}/javax/ws/rs/Path.html[`@Path`] annotation which adds to its containing class annotation. For example, this defines a `rest/hello` endpoint: [source,java] ---- package org.acme.rest; import javax.ws.rs.GET; import javax.ws.rs.Path; @Path(""rest"") public class Endpoint { @Path(""hello"") @GET public String hello(){ return ""Hello, World!""; } } ---- See <> for more information about URI mapping. You can set the root path for all rest endpoints using the `@ApplicationPath` annotation, as shown below. [source,java] ---- package org.acme.rest; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; @ApplicationPath(""/api"") public static class MyApplication extends Application { } ---- This will cause all rest endpoints to be resolve relative to `/api`, so the endpoint above with `@Path(""rest"")` would be accessible at `/api/rest/. You can also set the `quarkus.rest.path` build time property to set the root path if you don't want to use an annotation. === Declaring endpoints: HTTP methods Each endpoint method must be annotated with one of the following annotations, which defines which HTTP method will be mapped to the method: .Table HTTP method annotations |=== |Annotation|Usage |link:{jaxrsapi}/javax/ws/rs/GET.html[`@GET`] |Obtain a resource representation, should not modify state, link:{httpspec}#section-4.2.2[idempotent] (link:{httpspec}#section-4.3.1[HTTP docs]) |link:{jaxrsapi}/javax/ws/rs/HEAD.html[`@HEAD`] |Obtain metadata about a resource, similar to `GET` with no body (link:{httpspec}#section-4.3.2[HTTP docs]) |link:{jaxrsapi}/javax/ws/rs/POST.html[`@POST`] |Create a resource and obtain a link to it (link:{httpspec}#section-4.3.3[HTTP docs]) |link:{jaxrsapi}/javax/ws/rs/PUT.html[`@PUT`] |Replace a resource or create one, should be link:{httpspec}#section-4.2.2[idempotent] (link:{httpspec}#section-4.3.4[HTTP docs]) |link:{jaxrsapi}/javax/ws/rs/DELETE.html[`@DELETE`] |Delete an existing resource, link:{httpspec}#section-4.2.2[idempotent] (link:{httpspec}#section-4.3.5[HTTP docs]) |link:{jaxrsapi}/javax/ws/rs/OPTIONS.html[`@OPTIONS`] |Obtain information about a resource, link:{httpspec}#section-4.2.2[idempotent] (link:{httpspec}#section-4.3.7[HTTP docs]) |link:{jaxrsapi}/javax/ws/rs/PATCH.html[`@PATCH`] |Update a resource, or create one, not link:{httpspec}#section-4.2.2[idempotent] (https://tools.ietf.org/html/rfc5789#section-2[HTTP docs]) |=== You can also declare other HTTP methods by declaring them as an annotation with the link:{jaxrsapi}/javax/ws/rs/HttpMethod.html[`@HttpMethod`] annotation: [source,java] ---- package org.acme.rest; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import javax.ws.rs.HttpMethod; import javax.ws.rs.Path; @Retention(RetentionPolicy.RUNTIME) @HttpMethod(""FROMAGE"") @interface FROMAGE { } @Path("""") public class Endpoint { @FROMAGE public String hello(){ return ""Hello, Cheese World!""; } } ---- === Declaring endpoints: representation / content types Each endpoint method may consume or produce specific resource representations, which are indicated by the HTTP link:{httpspec}#section-3.1.1.5[`Content-Type`] header, which in turn contains link:{httpspec}#section-3.1.1.1[MIME (Media Type)] values, such as the following: - `text/plain` which is the default for any endpoint returning a `String`. - `text/html` for HTML (such as with link:qute[Qute templating]) - `application/json` for a <> - `text/*` which is a sub-type wildcard for any text media type - `\\*/*` which is a wildcard for any media type You may annotate your endpoint class with the link:{jaxrsapi}/javax/ws/rs/Produces.html[`@Produces`] or link:{jaxrsapi}/javax/ws/rs/Consumes.html[`@Consumes`] annotations, which allow you to specify one or more media types that your endpoint may accept as HTTP request body or produce as HTTP response body. Those class annotations apply to each method. Any method may also be annotated with the link:{jaxrsapi}/javax/ws/rs/Produces.html[`@Produces`] or link:{jaxrsapi}/javax/ws/rs/Consumes.html[`@Consumes`] annotations, in which case they override any eventual class annotation. The link:{jaxrsapi}/javax/ws/rs/core/MediaType.html[`MediaType`] class has many constants you can use to point to specific pre-defined media types. See <> for more information. === Accessing request parameters [[request-parameters]] NOTE: don't forget to configure your compiler to generate parameter name information with `-parameters` (javac) or `` or `` (https://maven.apache.org/plugins/maven-compiler-plugin/compile-mojo.html#parameters[Maven]). The following HTTP request elements may be obtained by your endpoint method: .Table HTTP request parameter annotations |=== |HTTP element|Annotation|Usage |[[path-parameter]]Path parameter |`@RestPath` (or nothing) |URI template parameter (simplified version of the https://tools.ietf.org/html/rfc6570[URI Template specification]), see <> for more information. |Query parameter |`@RestQuery` |The value of an https://tools.ietf.org/html/rfc3986#section-3.4[URI query parameter] |Header |`@RestHeader` |The value of an https://tools.ietf.org/html/rfc7230#section-3.2[HTTP header] |Cookie |`@RestCookie` |The value of an https://tools.ietf.org/html/rfc6265#section-4.2[HTTP cookie] |Form parameter |`@RestForm` |The value of an https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST[HTTP URL-encoded FORM] |Matrix parameter |`@RestMatrix` |The value of an https://tools.ietf.org/html/rfc3986#section-3.3[URI path segment parameter] |=== For each of those annotations, you may specify the name of the element they refer to, otherwise they will use the name of the annotated method parameter. If a client made the following HTTP call: [source,http] ---- POST /cheeses;variant=goat/tomme?age=matured HTTP/1.1 Content-Type: application/x-www-form-urlencoded Cookie: level=hardcore X-Cheese-Secret-Handshake: fist-bump smell=strong ---- Then you could obtain all the various parameters with this endpoint method: [source,java] ---- package org.acme.rest; import javax.ws.rs.POST; import javax.ws.rs.Path; import org.jboss.resteasy.reactive.RestCookie; import org.jboss.resteasy.reactive.RestForm; import org.jboss.resteasy.reactive.RestHeader; import org.jboss.resteasy.reactive.RestMatrix; import org.jboss.resteasy.reactive.RestPath; import org.jboss.resteasy.reactive.RestQuery; @Path(""/cheeses/{type}"") public class Endpoint { @POST public String allParams(@RestPath String type, @RestMatrix String variant, @RestQuery String age, @RestCookie String level, @RestHeader(""X-Cheese-Secret-Handshake"") String secretHandshake, @RestForm String smell){ return type + ""/"" + variant + ""/"" + age + ""/"" + level + ""/"" + secretHandshake + ""/"" + smell; } } ---- NOTE: the `@RestPath` annotation is optional: any parameter whose name matches an existing URI template variable will be automatically assumed to have `@RestPath`. You can also use any of the JAX-RS annotations link:{jaxrsapi}/javax/ws/rs/PathParam.html[`@PathParam`], link:{jaxrsapi}/javax/ws/rs/QueryParam.html[`@QueryParam`], link:{jaxrsapi}/javax/ws/rs/HeaderParam.html[`@HeaderParam`], link:{jaxrsapi}/javax/ws/rs/CookieParam.html[`@CookieParam`], link:{jaxrsapi}/javax/ws/rs/FormParam.html[`@FormParam`] or link:{jaxrsapi}/javax/ws/rs/MatrixParam.html[`@MatrixParam`] for this, but they require you to specify the parameter name. See <> for more advanced use-cases. === Declaring URI parameters [[uri-parameters]] You can declare URI parameters and use regular expressions in your path, so for instance the following endpoint will serve requests for `/hello/stef/23` and `/hello` but not `/hello/stef/0x23`: [source,java] ---- package org.acme.rest; import javax.ws.rs.GET; import javax.ws.rs.Path; @Path(""hello"") public class Endpoint { @Path(""{name}/{age:\\\\d+}"") @GET public String personalisedHello(String name, int age){ return ""Hello "" + name + "" is your age really "" + age + ""?""; } @GET public String genericHello(){ return ""Hello stranger""; } } ---- === Accessing the request body Any method parameter with no annotation will receive the method body.footnote:[Unless it is a <> or a <>.], after it has been mapped from its HTTP representation to the Java type of the parameter. The following parameter types will be supported out of the box: [[resource-types]] .Table Request body parameter type |=== |Type|Usage |link:{jdkapi}/java/io/File.html[`File`] |The entire request body in a temporary file |`byte[]` |The entire request body, not decoded |`char[]` |The entire request body, decoded |link:{jdkapi}/java/lang/String.html[`String`] |The entire request body, decoded |link:{jdkapi}/java/io/InputStream.html[`InputStream`] |The request body in a blocking stream |link:{jdkapi}/java/io/Reader.html[`Reader`] |The request body in a blocking stream |All Java primitives and their wrapper classes |Java primitive types |link:{jdkapi}/java/math/BigDecimal.html[`BigDecimal`], link:{jdkapi}/java/math/BigInteger.html[`BigInteger`] |Large integers and decimals. |link:{jsonpapi}/javax/json/JsonArray.html[`JsonArray`], link:{jsonpapi}/javax/json/JsonArray.html[`JsonObject`], link:{jsonpapi}/javax/json/JsonArray.html[`JsonStructure`], link:{jsonpapi}/javax/json/JsonArray.html[`JsonValue`] |JSON value types |link:{vertxapi}io/vertx/core/buffer/Buffer.html[`Buffer`] |Vert.x Buffer |any other type |Will be <> |=== NOTE: You can add support for more <>. === Returning a response body In order to return an HTTP response, simply return the resource you want from your method. The method return type and its optional content type will be used to decide how to serialise it to the HTTP response (see <> for more advanced information). You can return any of the pre-defined types that you can read from the <>, and any other type will be mapped <>. Alternately, you can also return a <> such as link:{mutinyapi}/io/smallrye/mutiny/Uni.html[`Uni`], link:{mutinyapi}/io/smallrye/mutiny/Multi.html[`Multi`] or link:{jdkapi}/java/util/concurrent/CompletionStage.html[`CompletionStage`] that resolve to one of the mentioned return types. === Setting other response properties If you need to set more properties on the HTTP response than just the body, such as the status code or headers, you can make your method return the link:{jaxrsapi}/javax/ws/rs/core/Response.html[`Response`] type: [source,java] ---- package org.acme.rest; import java.time.Duration; import java.time.Instant; import java.util.Date; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.NewCookie; import javax.ws.rs.core.Response; @Path("""") public class Endpoint { @GET public Response hello() { // HTTP OK status with text/plain content type return Response.ok(""Hello, World!"", MediaType.TEXT_PLAIN_TYPE) // set a response header .header(""X-FroMage"", ""Camembert"") // set the Expires response header to two days from now .expires(Date.from(Instant.now().plus(Duration.ofDays(2)))) // send a new cookie .cookie(new NewCookie(""Flavour"", ""praliné"")) // end of builder API .build(); } } ---- === Async/reactive support [[reactive]] If your endpoint method needs to accomplish an asynchronous or reactive task before being able to answer, you can declare your method to return the link:{mutinyapi}/io/smallrye/mutiny/Uni.html[`Uni`] type (from https://smallrye.io/smallrye-mutiny/[Mutiny]), in which case the current HTTP request will be automatically suspended after your method, until the returned link:{mutinyapi}/io/smallrye/mutiny/Uni.html[`Uni`] instance resolves to a value, which will be mapped to a response exactly according to the previously described rules: [source,java] ---- package org.acme.rest; import javax.ws.rs.GET; import javax.ws.rs.Path; import io.smallrye.mutiny.Uni; @Path(""escoffier"") public class Endpoint { @GET public Uni culinaryGuide(){ return Book.findByIsbn(""978-2081229297""); } } ---- This allows you to not block the event-loop thread while the book is being fetched from the database, and allows Quarkus to serve more requests until your book is ready to be sent to the client and terminate this request. Check out our <> for more information. The link:{jdkapi}/java/util/concurrent/CompletionStage.html[`CompletionStage`] return type is also supported. === Streaming support If you want to stream your response element by element, you can make your endpoint method return a link:{mutinyapi}/io/smallrye/mutiny/Multi.html[`Multi`] type (from https://smallrye.io/smallrye-mutiny/[Mutiny]). This is especially useful for streaming text or binary data. This example, using link:reactive-messaging-http[Reactive Messaging] shows how to stream text data: [source,java] ---- package org.acme.rest; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import org.eclipse.microprofile.reactive.messaging.Channel; import io.smallrye.mutiny.Multi; @Path(""logs"") public class Endpoint { @Inject @Channel(""log-out"") Multi logs; @GET public Multi streamLogs() { return logs; } } ---- === Server-Sent Event (SSE) support If you want to stream JSON objects in your response, you can use https://html.spec.whatwg.org/multipage/server-sent-events.html[Server-Sent Events] by just annotating your endpoint method with link:{jaxrsapi}/javax/ws/rs/Produces.html[`@Produces(MediaType.SERVER_SENT_EVENTS)`] and specifying that each element should be <> with `@RestSseElementType(MediaType.APPLICATION_JSON)`. [source,java] ---- package org.acme.rest; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.jboss.resteasy.reactive.RestSseElementType; import io.smallrye.mutiny.Multi; import io.smallrye.mutiny.Uni; import io.smallrye.reactive.messaging.annotations.Channel; @Path(""escoffier"") public class Endpoint { // Inject our Book channel @Inject @Channel(""book-out"") Multi books; @GET // Send the stream over SSE @Produces(MediaType.SERVER_SENT_EVENTS) // Each element will be sent as JSON @RestSseElementType(MediaType.APPLICATION_JSON) public Multi stream() { return books; } } ---- === Accessing context objects [[context-objects]] There are a number of contextual objects that the framework will give you, if your endpoint method takes parameters of the following type: .Table Context object |=== |Type|Usage |link:{jaxrsapi}/javax/ws/rs/core/HttpHeaders.html[`HttpHeaders`] |All the request headers |link:{jaxrsapi}/javax/ws/rs/container/ResourceInfo.html[`ResourceInfo`] |Information about the current endpoint method and class (requires reflection) |link:{jaxrsapi}/javax/ws/rs/core/SecurityContext.html[`SecurityContext`] |Access to the current user and roles |`SimpleResourceInfo` |Information about the current endpoint method and class (no reflection required) |link:{jaxrsapi}/javax/ws/rs/core/UriInfo.html[`UriInfo`] |Provides information about the current endpoint and application URI |link:{jaxrsapi}/javax/ws/rs/core/Application.html[`Application`] |Advanced: Current JAX-RS application class |link:{jaxrsapi}/javax/ws/rs/core/Configuration.html[`Configuration`] |Advanced: Configuration about the deployed JAX-RS application |link:{jaxrsapi}/javax/ws/rs/ext/Providers.html[`Providers`] |Advanced: Runtime access to JAX-RS providers |link:{jaxrsapi}/javax/ws/rs/core/Request.html[`Request`] |Advanced: Access to the current HTTP method and <> |link:{jaxrsapi}/javax/ws/rs/core/ResourceContext.html[`ResourceContext`] |Advanced: access to instances of endpoints |`ServerRequestContext` |Advanced: RESTEasy Reactive access to the current request/response |link:{jaxrsapi}/javax/ws/rs/sse/Sse.html[`Sse`] |Advanced: Complex SSE use-cases |=== For example, here is how you can return the name of the currently logged-in user: [source,java] ---- package org.acme.rest; import java.security.Principal; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.SecurityContext; @Path(""user"") public class Endpoint { @GET public String userName(SecurityContext security) { Principal user = security.getUserPrincipal(); return user != null ? user.getName() : """"; } } ---- You can also inject those context objects using https://javadoc.io/static/javax.inject/javax.inject/1/javax/inject/Inject.html[`@Inject`] on fields of the same type: [source,java] ---- package org.acme.rest; import java.security.Principal; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.SecurityContext; @Path(""user"") public class Endpoint { @Inject SecurityContext security; @GET public String userName() { Principal user = security.getUserPrincipal(); return user != null ? user.getName() : """"; } } ---- Or even on your endpoint constructor: [source,java] ---- package org.acme.rest; import java.security.Principal; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.SecurityContext; @Path(""user"") public class Endpoint { SecurityContext security; Endpoint(SecurityContext security){ this.security = security; } @GET public String userName() { Principal user = security.getUserPrincipal(); return user != null ? user.getName() : """"; } } ---- === JSON serialisation [[json]] Instead of importing `io.quarkus:quarkus-resteasy-reactive`, you can import either of the following modules to get support for JSON: .Table Context object |=== |GAV|Usage |`io.quarkus:quarkus-resteasy-reactive-jackson` |https://github.com/FasterXML/jackson[Jackson support] |`io.quarkus:quarkus-resteasy-reactive-jsonb` |http://json-b.net/[JSONB support] |=== In both cases, importing those modules will allow HTTP message bodies to be read from JSON and serialised to JSON, for <>. ==== Advanced Jackson-specific features When using the `quarkus-resteasy-reactive-jackson` extension there are some advanced features that RESTEasy Reactive supports. ===== @JsonView support JAX-RS methods can be annotated with https://fasterxml.github.io/jackson-annotations/javadoc/2.10/com/fasterxml/jackson/annotation/JsonView.html[@JsonView] in order to customize the serialization of the returned POJO, on a per method-basis. This is best explained with an example. A typical use of `@JsonView` is to hide certain fields on certain methods. In that vein, let's define two views: [source,java] ---- public class Views { public static class Public { } public static class Private extends Public { } } ---- Let's assume we have the `User` POJO on which we want to hide some field during serialization. A simple example of this is: [source,java] ---- public class User { @JsonView(Views.Private.class) public int id; @JsonView(Views.Public.class) public String name; } ---- Depending on the JAX-RS method that returns this user, we might want to exclude the `id` field from serialization - for example you might want an insecure method to not expose this field. The way we can achieve that in RESTEasy Reactive is shown in the following example: [source,java] ---- @JsonView(Views.Public.class) @GET @Path(""/public"") public User userPublic() { return testUser(); } @JsonView(Views.Private.class) @GET @Path(""/private"") public User userPrivate() { return testUser(); } ---- When the result the `userPublic` method is serialized, the `id` field will not be contained in the response as the `Public` view does not include it. The result of `userPrivate` however will include the `id` as expected when serialized. ===== Completely customized per method serialization There are times when you need to completely customize the serialization of a POJO on a per JAX-RS method basis. For such use cases, the `@io.quarkus.resteasy.reactive.jackson.CustomSerialization` annotation is a great tool, as it allows you to configure a per-method `com.fasterxml.jackson.databind.ObjectWriter` which can be configured at will. Here is an example use case: [source,java] ---- @CustomSerialization(UnquotedFields.class) @GET @Path(""/invalid-use-of-custom-serializer"") public User invalidUseOfCustomSerializer() { return testUser(); } ---- where `UnquotedFields` is a `BiFunction` defined as so: [source,java] ---- public static class UnquotedFields implements BiFunction { @Override public ObjectWriter apply(ObjectMapper objectMapper, Type type) { return objectMapper.writer().without(JsonWriteFeature.QUOTE_FIELD_NAMES); } } ---- Essentially what this class does is force Jackson to not include quotes in the field names. It is important to note that this customization is only performed for the serialization of the JAX-RS methods that use `@CustomSerialization(UnquotedFields.class)`. == More advanced usage Here are some more advanced topics that you may not need to know about initially, but could prove useful for more complex use cases. === Execution model, blocking, non-blocking [[execution-model]] RESTEasy Reactive is implemented using two main thread types: - Event-loop threads: which are responsible, among other things, for reading bytes from the HTTP request and writing bytes back to the HTTP response - Worker threads: they are pooled and can be used to offload long-running operations The event-loop threads (also called IO threads) are responsible for actually performing all the IO operations in an asynchronous way, and to trigger any listener interested in the completion of those IO operations. By default, RESTEasy Reactive will run endpoint methods on the event-loop threads, on the assumption that they are going to be fast and only invoke non-blocking operations. This is the model of execution that leads to best performance if your endpoints do not do any blocking operation (such as blocking IO, blocking on an asynchronous operation, or sleeping). If your endpoint method needs to do any of those blocking operations, you should add the https://javadoc.io/doc/io.smallrye.common/smallrye-common-annotation/1.5.0/io/smallrye/common/annotation/Blocking.html[`@Blocking`] annotation on your endpoint and it will instead be invoked on a worker thread. Your endpoint method code can remain exactly the same, and it will be allowed to block: [source,java] ---- package org.acme.rest; import javax.ws.rs.GET; import javax.ws.rs.Path; import io.smallrye.common.annotation.Blocking; @Path(""yawn"") public class Endpoint { @Blocking @GET public String blockingHello() throws InterruptedException { // do a blocking operation Thread.sleep(1000); return ""Yaaaawwwwnnnnnn…""; } } ---- Most of the time, there are ways to achieve the same blocking operations in an asynchronous/reactive way, using https://smallrye.io/smallrye-mutiny/[Mutiny], http://hibernate.org/reactive/[Hibernate Reactive] or any of the link:getting-started-reactive[Quarkus Reactive extensions] for example: [source,java] ---- package org.acme.rest; import java.time.Duration; import javax.ws.rs.GET; import javax.ws.rs.Path; import io.smallrye.mutiny.Uni; @Path(""yawn"") public class Endpoint { @GET public Uni blockingHello() throws InterruptedException { return Uni.createFrom().item(""Yaaaawwwwnnnnnn…"") // do a non-blocking sleep .onItem().delayIt().by(Duration.ofSeconds(2)); } } ---- === Exception mapping If your application needs to return non-nominal HTTP codes in error cases, the best is to throw exceptions that will result in the proper HTTP response being sent by the framework using link:{jaxrsapi}/javax/ws/rs/WebApplicationException.html[`WebApplicationException`] or any of its subtypes: [source,java] ---- package org.acme.rest; import javax.ws.rs.BadRequestException; import javax.ws.rs.GET; import javax.ws.rs.NotFoundException; import javax.ws.rs.Path; @Path(""fromages/{fromage}"") public class Endpoint { @GET public String findFromage(String fromage) { if(fromage == null) // send a 400 throw new BadRequestException(); if(!fromage.equals(""camembert"")) // send a 404 throw new NotFoundException(""Unknown cheese: "" + fromage); return ""Camembert is a very nice cheese""; } } ---- If your endpoint method is delegating calls to another service layer which does not know of JAX-RS, you need a way to turn service exceptions to an HTTP response, and you can do that using the `@ServerExceptionMapper` annotation on a method, with one parameter of the exception type you want to handle, and turning that exception into a link:{jaxrsapi}/javax/ws/rs/core/Response.html[`Response`] (or a link:{mutinyapi}/io/smallrye/mutiny/Uni.html[`Uni`]): [source,java] ---- package org.acme.rest; import java.util.Map; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.ws.rs.BadRequestException; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Response; import org.jboss.resteasy.reactive.server.ServerExceptionMapper; class UnknownCheeseException extends RuntimeException { public final String name; public UnknownCheeseException(String name) { this.name = name; } } @ApplicationScoped class CheeseService { private static final Map cheeses = Map.of(""camembert"", ""Camembert is a very nice cheese"", ""gouda"", ""Gouda is acceptable too, especially with cumin""); public String findCheese(String name) { String ret = cheeses.get(name); if(ret != null) return ret; throw new UnknownCheeseException(name); } } @Path(""fromages/{fromage}"") public class Endpoint { @Inject CheeseService cheeses; @ServerExceptionMapper public Response mapException(UnknownCheeseException x) { return Response.status(Response.Status.NOT_FOUND) .entity(""Unknown cheese: "" + x.name) .build(); } @GET public String findFromage(String fromage) { if(fromage == null) // send a 400 throw new BadRequestException(); return cheeses.findCheese(fromage); } } ---- NOTE: exception mappers defined in REST endpoint classes will only be called if the exception is thrown in the same class. If you want to define global exception mappers, simply define them outside a REST endpoint class: [source,java] ---- package org.acme.rest; import javax.ws.rs.core.Response; import org.jboss.resteasy.reactive.server.ServerExceptionMapper; class ExceptionMappers { @ServerExceptionMapper public Response mapException(UnknownCheeseException x) { return Response.status(Response.Status.NOT_FOUND) .entity(""Unknown cheese: "" + x.name) .build(); } } ---- You can also declare link:{jaxrsspec}#exceptionmapper[exception mappers in the JAX-RS way]. Your exception mapper may declare any of the following parameter types: .Table Exception mapper parameters |=== |Type|Usage |An exception type |Defines the exception type you want to handle |Any of the <> | |link:{jaxrsapi}/javax/ws/rs/container/ContainerRequestContext.html[`ContainerRequestContext`] |A context object to access the current request |=== It may declare any of the following return types: .Table Exception mapper return types |=== |Type|Usage |link:{jaxrsapi}/javax/ws/rs/core/Response.html[`Response`] |The response to send to the client when the exception occurs |link:{mutinyapi}/io/smallrye/mutiny/Uni.html[`Uni`] |An asynchronous response to send to the client when the exception occurs |=== === Request or response filters You can declare functions which are invoked in the following phases of the request processing: - Before the endpoint method is identified: pre-routing request filter - After routing, but before the endpoint method is called: normal request filter - After the endpoint method is called: response filter These filters allow you to do various things such as examine the request URI, HTTP method, influence routing, look or change request headers, abort the request, or modify the response. Request filters can be declared with the `@ServerRequestFilter` annotation: [source,java] ---- class Filters { @ServerRequestFilter(preMatching = true) public void preMatchingFilter(ContainerRequestContext requestContext) { // make sure we don't lose cheese lovers if(""yes"".equals(requestContext.getHeaderString(""Cheese""))) { requestContext.setRequestUri(URI.create(""/cheese"")); } } @ServerRequestFilter public void getFilter(ContainerRequestContext ctx) { // only allow GET methods for now if(ctx.getMethod().equals(HttpMethod.GET)) { ctx.abortWith(Response.status(Response.Status.METHOD_NOT_ALLOWED).build()); } } } ---- Similarly, response filters can be declared with the `@ServerResponseFilter` annotation: [source,java] ---- class Filters { @ServerResponseFilter public void getFilter(ContainerResponseContext responseContext) { Object entity = responseContext.getEntity(); if(entity instanceof String) { // make it shout responseContext.setEntity(((String)entity).toUpperCase()); } } } ---- You can also link:{jaxrsspec}#filters[declare request and response filters in the JAX-RS way]. Your filters may declare any of the following parameter types: .Table Filter parameters |=== |Type|Usage |Any of the <> | |link:{jaxrsapi}/javax/ws/rs/container/ContainerRequestContext.html[`ContainerRequestContext`] |A context object to access the current request |link:{jaxrsapi}/javax/ws/rs/container/ContainerResponseContext.html[`ContainerResponseContext`] |A context object to access the current response |link:{jdkapi}/java/lang/Throwable.html[`Throwable`] |Any thrown exception, or `null` (only for response filters) |=== It may declare any of the following return types: .Table Filter return types |=== |Type|Usage |link:{jaxrsapi}/javax/ws/rs/core/Response.html[`Response`] |The response to send to the client instead of continuing the filter chain, or `null` if the filter chain should proceed |link:{jdkapi}/java/util/Optional.html[`Optional`] |An optional response to send to the client instead of continuing the filter chain, or an empty value if the filter chain should proceed |link:{mutinyapi}/io/smallrye/mutiny/Uni.html[`Uni`] |An asynchronous response to send to the client instead of continuing the filter chain, or `null` if the filter chain should proceed |=== === Readers and Writers: mapping entities and HTTP bodies [[readers-writers]] Whenever your endpoint methods return a object (of when they return a link:{jaxrsapi}/javax/ws/rs/core/Response.html[`Response`] with an entity), RESTEasy Reactive will look for a way to map that into an HTTP response body. Similarly, whenever your endpoint method takes an object as parameter, we will look for a way to map the HTTP request body into that object. This is done via a pluggable system of link:{jaxrsapi}/javax/ws/rs/ext/MessageBodyReader.html[`MessageBodyReader`] and link:{jaxrsapi}/javax/ws/rs/ext/MessageBodyWriter.html[`MessageBodyWriter`] interfaces, which are responsible for defining which Java type they map from/to, for which media types, and how they turn HTTP bodies to/from Java instances of that type. For example, if we have our own `FroMage` type on our endpoint: [source,java] ---- package org.acme.rest; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; class FroMage { public String name; public FroMage(String name) { this.name = name; } } @Path(""cheese"") public class Endpoint { @GET public FroMage sayCheese() { return new FroMage(""Cheeeeeese""); } @PUT public void addCheese(FroMage fromage) { System.err.println(""Received a new cheese: "" + fromage.name); } } ---- Then we can define how to read and write it with our body reader/writers, annotated with link:{jaxrsapi}/javax/ws/rs/ext/Provider.html[`@Provider`]: [source,java] ---- package org.acme.rest; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; import javax.ws.rs.ext.Provider; @Provider public class FroMageBodyHandler implements MessageBodyReader, MessageBodyWriter { @Override public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return type == FroMage.class; } @Override public void writeTo(FroMage t, Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { entityStream.write((""[FroMageV1]"" + t.name) .getBytes(StandardCharsets.UTF_8)); } @Override public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return type == FroMage.class; } @Override public FroMage readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { String body = new String(entityStream.readAllBytes(), StandardCharsets.UTF_8); if(body.startsWith(""[FroMageV1]"")) return new FroMage(body.substring(11)); throw new IOException(""Invalid fromage: "" + body); } } ---- If you want to get the most performance our of your writer, you can extend `ServerMessageBodyWriter` instead of link:{jaxrsapi}/javax/ws/rs/ext/MessageBodyWriter.html[`MessageBodyWriter`] where you will be able to use less reflection and bypass the blocking IO layer: [source,java] ---- package org.acme.rest; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.Provider; import org.jboss.resteasy.reactive.server.spi.ResteasyReactiveResourceInfo; import org.jboss.resteasy.reactive.server.spi.ServerMessageBodyWriter; import org.jboss.resteasy.reactive.server.spi.ServerRequestContext; @Provider public class FroMageBodyHandler implements MessageBodyReader, ServerMessageBodyWriter { // … @Override public boolean isWriteable(Class type, ResteasyReactiveResourceInfo target, MediaType mediaType) { return type == FroMage.class; } @Override public void writeResponse(FroMage t, ServerRequestContext context) throws WebApplicationException, IOException { context.serverResponse().end(""[FroMageV1]"" + t.name); } } ---- NOTE: You can restrict which content-types your reader/writer apply to by adding link:{jaxrsapi}/javax/ws/rs/Consumes.html[`Consumes`]/link:{jaxrsapi}/javax/ws/rs/Produces.html[`Produces`] annotations on your provider class. === Reader and Writer interceptors Just as you can intercept requests and responses, you can also intercept readers and writers, by extending the link:{jaxrsapi}/javax/ws/rs/ext/ReaderInterceptor.html[`ReaderInterceptor`] or link:{jaxrsapi}/javax/ws/rs/ext/WriterInterceptor.html[`WriterInterceptor`] on a class annotated with link:{jaxrsapi}/javax/ws/rs/ext/Provider.html[`@Provider`]. If we look at this endpoint: [source,java] ---- package org.acme.rest; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; @Path(""cheese"") public class Endpoint { @GET public String sayCheese() { return ""Cheeeeeese""; } @PUT public void addCheese(String fromage) { System.err.println(""Received a new cheese: "" + fromage); } } ---- We can add reader and writer interceptors like this: [source,java] ---- package org.acme.rest; import java.io.IOException; import javax.ws.rs.WebApplicationException; import javax.ws.rs.ext.Provider; import javax.ws.rs.ext.ReaderInterceptor; import javax.ws.rs.ext.ReaderInterceptorContext; import javax.ws.rs.ext.WriterInterceptor; import javax.ws.rs.ext.WriterInterceptorContext; @Provider public class FroMageIOInterceptor implements ReaderInterceptor, WriterInterceptor { @Override public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException { System.err.println(""Before writing "" + context.getEntity()); context.proceed(); System.err.println(""After writing "" + context.getEntity()); } @Override public Object aroundReadFrom(ReaderInterceptorContext context) throws IOException, WebApplicationException { System.err.println(""Before reading "" + context.getGenericType()); Object entity = context.proceed(); System.err.println(""After reading "" + entity); return entity; } } ---- === Parameter mapping All <> can be declared as link:{jdkapi}/java/lang/String.html[`String`], but also any of the following types: - Types for which a link:{jaxrsapi}/javax/ws/rs/ext/ParamConverter.html[`ParamConverter`] is available via a registered link:{jaxrsapi}/javax/ws/rs/ext/ParamConverterProvider.html[`ParamConverterProvider`]. - Primitive types. - Types that have a constructor that accepts a single link:{jdkapi}/java/lang/String.html[`String`] argument. - Types that have a static method named `valueOf` or `fromString` with a single link:{jdkapi}/java/lang/String.html[`String`] argument that return an instance of the type. If both methods are present then `valueOf` will be used unless the type is an `enum` in which case `fromString` will be used. - link:{jdkapi}/java/util/List.html[`List`], link:{jdkapi}/java/util/Set.html[`Set`], or link:{jdkapi}/java/util/SortedSet.html[`SortedSet`], where `T` satisfies any above criterion. The following example illustrates all those possibilities: [source,java] ---- package org.acme.rest; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.List; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.ext.ParamConverter; import javax.ws.rs.ext.ParamConverterProvider; import javax.ws.rs.ext.Provider; import org.jboss.resteasy.reactive.RestQuery; @Provider class MyConverterProvider implements ParamConverterProvider { @Override public ParamConverter getConverter(Class rawType, Type genericType, Annotation[] annotations) { // declare a converter for this type if(rawType == Converter.class) { return (ParamConverter) new MyConverter(); } return null; } } // this is my custom converter class MyConverter implements ParamConverter { @Override public Converter fromString(String value) { return new Converter(value); } @Override public String toString(Converter value) { return value.value; } } // this uses a converter class Converter { String value; Converter(String value) { this.value = value; } } class Constructor { String value; // this will use the constructor public Constructor(String value) { this.value = value; } } class ValueOf { String value; private ValueOf(String value) { this.value = value; } // this will use the valueOf method public static ValueOf valueOf(String value) { return new ValueOf(value); } } @Path(""hello"") public class Endpoint { @Path(""{converter}/{constructor}/{primitive}/{valueOf}"") @GET public String convertions(Converter converter, Constructor constructor, int primitive, ValueOf valueOf, @RestQuery List list){ return converter + ""/"" + constructor + ""/"" + primitive + ""/"" + valueOf + ""/"" + list; } } ---- === Preconditions https://tools.ietf.org/html/rfc7232[HTTP allows requests to be conditional], based on a number of conditions, such as: - Date of last resource modification - A resource tag, similar to a hash code of the resource to designate its state or version Let's see how you can do conditional request validation using the link:{jaxrsapi}/javax/ws/rs/core/Request.html[`Request`] context object: [source,java] ---- package org.acme.rest; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.time.temporal.TemporalUnit; import java.util.Date; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.core.EntityTag; import javax.ws.rs.core.Request; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; @Path(""conditional"") public class Endpoint { // It's important to keep our date on seconds because that's how it's sent to the // user in the Last-Modified header private Date date = Date.from(Instant.now().truncatedTo(ChronoUnit.SECONDS)); private int version = 1; private EntityTag tag = new EntityTag(""v1""); private String resource = ""Some resource""; @GET public Response get(Request request){ // first evaluate preconditions ResponseBuilder conditionalResponse = request.evaluatePreconditions(date, tag); if(conditionalResponse != null) return conditionalResponse.build(); // preconditions are OK return Response.ok(resource) .lastModified(date) .tag(tag) .build(); } @PUT public Response put(Request request, String body){ // first evaluate preconditions ResponseBuilder conditionalResponse = request.evaluatePreconditions(date, tag); if(conditionalResponse != null) return conditionalResponse.build(); // preconditions are OK, we can update our resource resource = body; date = Date.from(Instant.now().truncatedTo(ChronoUnit.SECONDS)); version++; tag = new EntityTag(""v"" + version); return Response.ok(resource) .lastModified(date) .tag(tag) .build(); } } ---- When we call `GET /conditional` the first time, we will get this response: [source] ---- HTTP/1.1 200 OK Content-Type: text/plain;charset=UTF-8 ETag: ""v1"" Last-Modified: Wed, 09 Dec 2020 16:10:19 GMT Content-Length: 13 Some resource ---- So now if we want to check if we need to fetch a new version, we can make the following request: [source] ---- GET /conditional HTTP/1.1 Host: localhost:8080 If-Modified-Since: Wed, 09 Dec 2020 16:10:19 GMT ---- And we would get the following response: [source] ---- HTTP/1.1 304 Not Modified ---- Because the resource has not been modified since that date. This saves on sending the resource, but can also help your users detect concurrent modification, for example, let's suppose that one client wants to update the resource, but another user has modified it since. You can follow the previous `GET` request with this update: [source] ---- PUT /conditional HTTP/1.1 Host: localhost:8080 If-Unmodified-Since: Wed, 09 Dec 2020 16:25:43 GMT If-Match: v1 Content-Length: 8 Content-Type: text/plain newstuff ---- And if some other user has modified the resource between your `GET` and your `PUT` you would get this answer back: [source] ---- HTTP/1.1 412 Precondition Failed ETag: ""v2"" Content-Length: 0 ---- === Negotiation One of the main ideas of REST (https://tools.ietf.org/html/rfc7231#section-3.4[and HTTP]) is that your resource is independent from its representation, and that both the client and server are free to represent their resources in as many media types as they want. This allows the server to declare support for multiple representations and let the client declare which ones it supports and get served something appropriate. The following endpoint supports serving cheese in plain text or JSON: [source,java] ---- package org.acme.rest; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import com.fasterxml.jackson.annotation.JsonCreator; class FroMage { public String name; @JsonCreator public FroMage(String name) { this.name = name; } @Override public String toString() { return ""Cheese: "" + name; } } @Path(""negotiated"") public class Endpoint { @Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN}) @GET public FroMage get(){ return new FroMage(""Morbier""); } @Consumes(MediaType.TEXT_PLAIN) @PUT public FroMage putString(String cheese){ return new FroMage(cheese); } @Consumes(MediaType.APPLICATION_JSON) @PUT public FroMage putJson(FroMage fromage){ return fromage; } } ---- The user will be able to select which representation it gets with the link:{httpspec}#section-5.3.2[`Accept`] header, in the case of JSON: [source,sh] ---- > GET /negotiated HTTP/1.1 > Host: localhost:8080 > Accept: application/json < HTTP/1.1 200 OK < Content-Type: application/json < Content-Length: 18 < < {""name"":""Morbier""} ---- And for text: [source,sh] ---- > GET /negotiated HTTP/1.1 > Host: localhost:8080 > Accept: text/plain > < HTTP/1.1 200 OK < Content-Type: text/plain < Content-Length: 15 < < Cheese: Morbier ---- Similarly, you can `PUT` two different representations. JSON: [source,sh] ---- > PUT /negotiated HTTP/1.1 > Host: localhost:8080 > Content-Type: application/json > Content-Length: 16 > > {""name"": ""brie""} < HTTP/1.1 200 OK < Content-Type: application/json;charset=UTF-8 < Content-Length: 15 < < {""name"":""brie""} ---- Or plain text: [source,sh] ---- > PUT /negotiated HTTP/1.1 > Host: localhost:8080 > Content-Type: text/plain > Content-Length: 9 > > roquefort < HTTP/1.1 200 OK < Content-Type: application/json;charset=UTF-8 < Content-Length: 20 < < {""name"":""roquefort""} ---- ",12134,False,2152.285282534604,median "/***************************************************************************** * McPAT * SOFTWARE LICENSE AGREEMENT * Copyright 2012 Hewlett-Packard Development Company, L.P. * All Rights Reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ""AS IS"" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.” * ***************************************************************************/ #include ""logic.h"" //selection_logic selection_logic::selection_logic( bool _is_default, int win_entries_, int issue_width_, const InputParameter *configure_interface, enum Device_ty device_ty_, enum Core_type core_ty_) //const ParseXML *_XML_interface) :is_default(_is_default), win_entries(win_entries_), issue_width(issue_width_), device_ty(device_ty_), core_ty(core_ty_) { //uca_org_t result2; l_ip=*configure_interface; local_result = init_interface(&l_ip); //init_tech_params(l_ip.F_sz_um, false); //win_entries=numIBEntries;//IQentries; //issue_width=issueWidth; selection_power(); double sckRation = g_tp.sckt_co_eff; power.readOp.dynamic *= sckRation; power.writeOp.dynamic *= sckRation; power.searchOp.dynamic *= sckRation; double long_channel_device_reduction = longer_channel_device_reduction(device_ty,core_ty); power.readOp.longer_channel_leakage = power.readOp.leakage*long_channel_device_reduction; double pg_reduction = power_gating_leakage_reduction(false); power.readOp.power_gated_leakage = power.readOp.leakage*pg_reduction; power.readOp.power_gated_with_long_channel_leakage = power.readOp.power_gated_leakage * long_channel_device_reduction; } void selection_logic::selection_power() {//based on cost effective superscalar processor TR pp27-31 double Ctotal, Cor, Cpencode; int num_arbiter; double WSelORn, WSelORprequ, WSelPn, WSelPp, WSelEnn, WSelEnp; //TODO: the 0.8um process data is used. WSelORn = 12.5 * l_ip.F_sz_um;//this was 10 micron for the 0.8 micron process WSelORprequ = 50 * l_ip.F_sz_um;//this was 40 micron for the 0.8 micron process WSelPn = 12.5 * l_ip.F_sz_um;//this was 10mcron for the 0.8 micron process WSelPp = 18.75 * l_ip.F_sz_um;//this was 15 micron for the 0.8 micron process WSelEnn = 6.25 * l_ip.F_sz_um;//this was 5 micron for the 0.8 micron process WSelEnp = 12.5 * l_ip.F_sz_um;//this was 10 micron for the 0.8 micron process Ctotal=0; num_arbiter=1; while(win_entries > 4) { win_entries = (int)ceil((double)win_entries / 4.0); num_arbiter += win_entries; } //the 4-input OR logic to generate anyreq Cor = 4 * drain_C_(WSelORn,NCH,1,1, g_tp.cell_h_def) + drain_C_(WSelORprequ,PCH,1,1, g_tp.cell_h_def); power.readOp.gate_leakage = cmos_Ig_leakage(WSelORn, WSelORprequ, 4, nor)*g_tp.peri_global.Vdd; //The total capacity of the 4-bit priority encoder Cpencode = drain_C_(WSelPn,NCH,1, 1, g_tp.cell_h_def) + drain_C_(WSelPp,PCH,1, 1, g_tp.cell_h_def) + 2*drain_C_(WSelPn,NCH,1, 1, g_tp.cell_h_def) + drain_C_(WSelPp,PCH,2, 1, g_tp.cell_h_def) + 3*drain_C_(WSelPn,NCH,1, 1, g_tp.cell_h_def) + drain_C_(WSelPp,PCH,3, 1, g_tp.cell_h_def) + 4*drain_C_(WSelPn,NCH,1, 1, g_tp.cell_h_def) + drain_C_(WSelPp,PCH,4, 1, g_tp.cell_h_def) +//precompute priority logic 2*4*gate_C(WSelEnn+WSelEnp,20.0)+ 4*drain_C_(WSelEnn,NCH,1, 1, g_tp.cell_h_def) + 2*4*drain_C_(WSelEnp,PCH,1, 1, g_tp.cell_h_def)+//enable logic (2*4+2*3+2*2+2)*gate_C(WSelPn+WSelPp,10.0);//requests signal Ctotal += issue_width * num_arbiter*(Cor+Cpencode); power.readOp.dynamic = Ctotal*g_tp.peri_global.Vdd*g_tp.peri_global.Vdd*2;//2 means the abitration signal need to travel round trip power.readOp.leakage = issue_width * num_arbiter * (cmos_Isub_leakage(WSelPn, WSelPp, 2, nor)/*approximate precompute with a nor gate*///grant1p + cmos_Isub_leakage(WSelPn, WSelPp, 3, nor)//grant2p + cmos_Isub_leakage(WSelPn, WSelPp, 4, nor)//grant3p + cmos_Isub_leakage(WSelEnn, WSelEnp, 2, nor)*4//enable logic + cmos_Isub_leakage(WSelEnn, WSelEnp, 1, inv)*2*3//for each grant there are two inverters, there are 3 grant sIsubnals )*g_tp.peri_global.Vdd; power.readOp.gate_leakage = issue_width * num_arbiter * (cmos_Ig_leakage(WSelPn, WSelPp, 2, nor)/*approximate precompute with a nor gate*///grant1p + cmos_Ig_leakage(WSelPn, WSelPp, 3, nor)//grant2p + cmos_Ig_leakage(WSelPn, WSelPp, 4, nor)//grant3p + cmos_Ig_leakage(WSelEnn, WSelEnp, 2, nor)*4//enable logic + cmos_Ig_leakage(WSelEnn, WSelEnp, 1, inv)*2*3//for each grant there are two inverters, there are 3 grant signals )*g_tp.peri_global.Vdd; } dep_resource_conflict_check::dep_resource_conflict_check( const InputParameter *configure_interface, const CoreDynParam & dyn_p_, int compare_bits_, bool _is_default) : l_ip(*configure_interface), coredynp(dyn_p_), compare_bits(compare_bits_), is_default(_is_default) { Wcompn = 25 * l_ip.F_sz_um;//this was 20.0 micron for the 0.8 micron process Wevalinvp = 25 * l_ip.F_sz_um;//this was 20.0 micron for the 0.8 micron process Wevalinvn = 100 * l_ip.F_sz_um;//this was 80.0 mcron for the 0.8 micron process Wcomppreequ = 50 * l_ip.F_sz_um;//this was 40.0 micron for the 0.8 micron process WNORn = 6.75 * l_ip.F_sz_um;//this was 5.4 micron for the 0.8 micron process WNORp = 38.125 * l_ip.F_sz_um;//this was 30.5 micron for the 0.8 micron process local_result = init_interface(&l_ip); if (coredynp.core_ty==Inorder) compare_bits += 16 + 8 + 8;//TODO: opcode bits + log(shared resources) + REG TAG BITS-->opcode comparator else compare_bits += 16 + 8 + 8; conflict_check_power(); double sckRation = g_tp.sckt_co_eff; power.readOp.dynamic *= sckRation; power.writeOp.dynamic *= sckRation; power.searchOp.dynamic *= sckRation; } void dep_resource_conflict_check::conflict_check_power() { double Ctotal; int num_comparators; num_comparators = 3*((coredynp.decodeW) * (coredynp.decodeW)-coredynp.decodeW);//2(N*N-N) is used for source to dest comparison, (N*N-N) is used for dest to dest comparision. //When decode-width ==1, no dcl logic Ctotal = num_comparators * compare_cap(); //printf(""%i,%s\\n"",XML_interface->sys.core[0].predictor.predictor_entries,XML_interface->sys.core[0].predictor.prediction_scheme); power.readOp.dynamic=Ctotal*/*CLOCKRATE*/g_tp.peri_global.Vdd*g_tp.peri_global.Vdd/*AF*/; power.readOp.leakage=num_comparators*compare_bits*2*simplified_nmos_leakage(Wcompn, false); double long_channel_device_reduction = longer_channel_device_reduction(Core_device, coredynp.core_ty); power.readOp.longer_channel_leakage = power.readOp.leakage*long_channel_device_reduction; power.readOp.gate_leakage=num_comparators*compare_bits*2*cmos_Ig_leakage(Wcompn, 0, 2, nmos); double pg_reduction = power_gating_leakage_reduction(false); power.readOp.power_gated_leakage = power.readOp.leakage*pg_reduction; power.readOp.power_gated_with_long_channel_leakage = power.readOp.power_gated_leakage * long_channel_device_reduction; } /* estimate comparator power consumption (this comparator is similar to the tag-match structure in a CAM */ double dep_resource_conflict_check::compare_cap() { double c1, c2; WNORp = WNORp * compare_bits/2.0;//resize the big NOR gate at the DCL according to fan in. /* bottom part of comparator */ c2 = (compare_bits)*(drain_C_(Wcompn,NCH,1,1, g_tp.cell_h_def)+drain_C_(Wcompn,NCH,2,1, g_tp.cell_h_def))+ drain_C_(Wevalinvp,PCH,1,1, g_tp.cell_h_def) + drain_C_(Wevalinvn,NCH,1,1, g_tp.cell_h_def); /* top part of comparator */ c1 = (compare_bits)*(drain_C_(Wcompn,NCH,1,1, g_tp.cell_h_def)+drain_C_(Wcompn,NCH,2,1, g_tp.cell_h_def)+ drain_C_(Wcomppreequ,NCH,1,1, g_tp.cell_h_def)) + gate_C(WNORn + WNORp,10.0) + drain_C_(WNORp,NCH,2,1, g_tp.cell_h_def) + compare_bits*drain_C_(WNORn,NCH,2,1, g_tp.cell_h_def); return(c1 + c2); } void dep_resource_conflict_check::leakage_feedback(double temperature) { l_ip.temp = (unsigned int)round(temperature/10.0)*10; uca_org_t init_result = init_interface(&l_ip); // init_result is dummy // This is part of conflict_check_power() int num_comparators = 3*((coredynp.decodeW) * (coredynp.decodeW)-coredynp.decodeW);//2(N*N-N) is used for source to dest comparison, (N*N-N) is used for dest to dest comparision. power.readOp.leakage=num_comparators*compare_bits*2*simplified_nmos_leakage(Wcompn, false); double long_channel_device_reduction = longer_channel_device_reduction(Core_device, coredynp.core_ty); power.readOp.longer_channel_leakage = power.readOp.leakage*long_channel_device_reduction; power.readOp.gate_leakage=num_comparators*compare_bits*2*cmos_Ig_leakage(Wcompn, 0, 2, nmos); double pg_reduction = power_gating_leakage_reduction(false); power.readOp.power_gated_leakage = power.readOp.leakage*pg_reduction; power.readOp.power_gated_with_long_channel_leakage = power.readOp.power_gated_leakage * long_channel_device_reduction; } //TODO: add inverter and transmission gate base DFF. DFFCell::DFFCell( bool _is_dram, double _WdecNANDn, double _WdecNANDp, double _cell_load, const InputParameter *configure_interface) :is_dram(_is_dram), cell_load(_cell_load), WdecNANDn(_WdecNANDn), WdecNANDp(_WdecNANDp) {//this model is based on the NAND2 based DFF. l_ip=*configure_interface; // area.set_area(730*l_ip.F_sz_um*l_ip.F_sz_um); area.set_area(5*compute_gate_area(NAND, 2,WdecNANDn,WdecNANDp, g_tp.cell_h_def) + compute_gate_area(NAND, 2,WdecNANDn,WdecNANDn, g_tp.cell_h_def)); } double DFFCell::fpfp_node_cap(unsigned int fan_in, unsigned int fan_out) { double Ctotal = 0; //printf(""WdecNANDn = %E\\n"", WdecNANDn); /* part 1: drain cap of NAND gate */ Ctotal += drain_C_(WdecNANDn, NCH, 2, 1, g_tp.cell_h_def, is_dram) + fan_in * drain_C_(WdecNANDp, PCH, 1, 1, g_tp.cell_h_def, is_dram); /* part 2: gate cap of NAND gates */ Ctotal += fan_out * gate_C(WdecNANDn + WdecNANDp, 0, is_dram); return Ctotal; } void DFFCell::compute_DFF_cell() { double c1, c2, c3, c4, c5, c6; /* node 5 and node 6 are identical to node 1 in capacitance */ c1 = c5 = c6 = fpfp_node_cap(2, 1); c2 = fpfp_node_cap(2, 3); c3 = fpfp_node_cap(3, 2); c4 = fpfp_node_cap(2, 2); //cap-load of the clock signal in each Dff, actually the clock signal only connected to one NAND2 clock_cap= 2 * gate_C(WdecNANDn + WdecNANDp, 0, is_dram); e_switch.readOp.dynamic += (c4 + c1 + c2 + c3 + c5 + c6 + 2*cell_load)*0.5*g_tp.peri_global.Vdd * g_tp.peri_global.Vdd;; /* no 1/2 for e_keep and e_clock because clock signal switches twice in one cycle */ e_keep_1.readOp.dynamic += c3 * g_tp.peri_global.Vdd * g_tp.peri_global.Vdd ; e_keep_0.readOp.dynamic += c2 * g_tp.peri_global.Vdd * g_tp.peri_global.Vdd ; e_clock.readOp.dynamic += clock_cap* g_tp.peri_global.Vdd * g_tp.peri_global.Vdd;; /* static power */ e_switch.readOp.leakage += (cmos_Isub_leakage(WdecNANDn, WdecNANDp, 2, nand)*5//5 NAND2 and 1 NAND3 in a DFF + cmos_Isub_leakage(WdecNANDn, WdecNANDn, 3, nand))*g_tp.peri_global.Vdd; e_switch.readOp.gate_leakage += (cmos_Ig_leakage(WdecNANDn, WdecNANDp, 2, nand)*5//5 NAND2 and 1 NAND3 in a DFF + cmos_Ig_leakage(WdecNANDn, WdecNANDn, 3, nand))*g_tp.peri_global.Vdd; //printf(""leakage =%E\\n"",cmos_Ileak(1, is_dram) ); } Pipeline::Pipeline( const InputParameter *configure_interface, const CoreDynParam & dyn_p_, enum Device_ty device_ty_, bool _is_core_pipeline, bool _is_default) : l_ip(*configure_interface), coredynp(dyn_p_), device_ty(device_ty_), is_core_pipeline(_is_core_pipeline), is_default(_is_default), num_piperegs(0.0) { local_result = init_interface(&l_ip); if (!coredynp.Embedded) process_ind = true; else process_ind = false; WNANDn = (process_ind)? 25 * l_ip.F_sz_um : g_tp.min_w_nmos_ ;//this was 20 micron for the 0.8 micron process WNANDp = (process_ind)? 37.5 * l_ip.F_sz_um : g_tp.min_w_nmos_*pmos_to_nmos_sz_ratio();//this was 30 micron for the 0.8 micron process load_per_pipeline_stage = 2*gate_C(WNANDn + WNANDp, 0, false); compute(); } void Pipeline::compute() { compute_stage_vector(); DFFCell pipe_reg(false, WNANDn,WNANDp, load_per_pipeline_stage, &l_ip); pipe_reg.compute_DFF_cell(); double clock_power_pipereg = num_piperegs * pipe_reg.e_clock.readOp.dynamic; //******************pipeline power: currently, we average all the possibilities of the states of DFFs in the pipeline. A better way to do it is to consider //the harming distance of two consecutive signals, However McPAT does not have plan to do this in near future as it focuses on worst case power. double pipe_reg_power = num_piperegs * (pipe_reg.e_switch.readOp.dynamic+pipe_reg.e_keep_0.readOp.dynamic+pipe_reg.e_keep_1.readOp.dynamic)/3+clock_power_pipereg; double pipe_reg_leakage = num_piperegs * pipe_reg.e_switch.readOp.leakage; double pipe_reg_gate_leakage = num_piperegs * pipe_reg.e_switch.readOp.gate_leakage; power.readOp.dynamic +=pipe_reg_power; power.readOp.leakage +=pipe_reg_leakage; power.readOp.gate_leakage +=pipe_reg_gate_leakage; area.set_area(num_piperegs * pipe_reg.area.get_area()); double long_channel_device_reduction = longer_channel_device_reduction(device_ty, coredynp.core_ty); power.readOp.longer_channel_leakage = power.readOp.leakage*long_channel_device_reduction; double pg_reduction = power_gating_leakage_reduction(false); power.readOp.power_gated_leakage = power.readOp.leakage*pg_reduction; power.readOp.power_gated_with_long_channel_leakage = power.readOp.power_gated_leakage * long_channel_device_reduction; double sckRation = g_tp.sckt_co_eff; power.readOp.dynamic *= sckRation; power.writeOp.dynamic *= sckRation; power.searchOp.dynamic *= sckRation; double macro_layout_overhead = g_tp.macro_layout_overhead; if (!coredynp.Embedded) area.set_area(area.get_area()*macro_layout_overhead); } void Pipeline::compute_stage_vector() { double num_stages, tot_stage_vector, per_stage_vector; int opcode_length = coredynp.x86? coredynp.micro_opcode_length:coredynp.opcode_length; //Hthread = thread_clock_gated? 1:num_thread; if (!is_core_pipeline) { num_piperegs=l_ip.pipeline_stages*l_ip.per_stage_vector;//The number of pipeline stages are calculated based on the achievable throughput and required throughput } else { if (coredynp.core_ty==Inorder) { /* assume 6 pipe stages and try to estimate bits per pipe stage */ /* pipe stage 0/IF */ num_piperegs += coredynp.pc_width*2*coredynp.num_hthreads; /* pipe stage IF/ID */ num_piperegs += coredynp.fetchW*(coredynp.instruction_length + coredynp.pc_width)*coredynp.num_hthreads; /* pipe stage IF/ThreadSEL */ if (coredynp.multithreaded) num_piperegs += coredynp.num_hthreads*coredynp.perThreadState; //8 bit thread states /* pipe stage ID/EXE */ num_piperegs += coredynp.decodeW*(coredynp.instruction_length + coredynp.pc_width + pow(2.0,opcode_length)+ 2*coredynp.int_data_width)*coredynp.num_hthreads; /* pipe stage EXE/MEM */ num_piperegs += coredynp.issueW*(3 * coredynp.arch_ireg_width + pow(2.0,opcode_length) + 8*2*coredynp.int_data_width/*+2*powers (2,reg_length)*/); /* pipe stage MEM/WB the 2^opcode_length means the total decoded signal for the opcode*/ num_piperegs += coredynp.issueW*(2*coredynp.int_data_width + pow(2.0,opcode_length) + 8*2*coredynp.int_data_width/*+2*powers (2,reg_length)*/); // /* pipe stage 5/6 */ // num_piperegs += issueWidth*(data_width + powers (2,opcode_length)/*+2*powers (2,reg_length)*/); // /* pipe stage 6/7 */ // num_piperegs += issueWidth*(data_width + powers (2,opcode_length)/*+2*powers (2,reg_length)*/); // /* pipe stage 7/8 */ // num_piperegs += issueWidth*(data_width + powers (2,opcode_length)/**2*powers (2,reg_length)*/); // /* assume 50% extra in control signals (rule of thumb) */ num_stages=6; } else { /* assume 12 stage pipe stages and try to estimate bits per pipe stage */ /*OOO: Fetch, decode, rename, IssueQ, dispatch, regread, EXE, MEM, WB, CM */ /* pipe stage 0/1F*/ num_piperegs += coredynp.pc_width*2*coredynp.num_hthreads ;//PC and Next PC /* pipe stage IF/ID */ num_piperegs += coredynp.fetchW*(coredynp.instruction_length + coredynp.pc_width)*coredynp.num_hthreads;//PC is used to feed branch predictor in ID /* pipe stage 1D/Renaming*/ num_piperegs += coredynp.decodeW*(coredynp.instruction_length + coredynp.pc_width)*coredynp.num_hthreads;//PC is for branch exe in later stage. /* pipe stage Renaming/wire_drive */ num_piperegs += coredynp.decodeW*(coredynp.instruction_length + coredynp.pc_width); /* pipe stage Renaming/IssueQ */ num_piperegs += coredynp.issueW*(coredynp.instruction_length + coredynp.pc_width + 3*coredynp.phy_ireg_width)*coredynp.num_hthreads;//3*coredynp.phy_ireg_width means 2 sources and 1 dest /* pipe stage IssueQ/Dispatch */ num_piperegs += coredynp.issueW*(coredynp.instruction_length + 3 * coredynp.phy_ireg_width); /* pipe stage Dispatch/EXE */ num_piperegs += coredynp.issueW*(3 * coredynp.phy_ireg_width + coredynp.pc_width + pow(2.0,opcode_length)/*+2*powers (2,reg_length)*/); /* 2^opcode_length means the total decoded signal for the opcode*/ num_piperegs += coredynp.issueW*(2*coredynp.int_data_width + pow(2.0,opcode_length)/*+2*powers (2,reg_length)*/); /*2 source operands in EXE; Assume 2EXE stages* since we do not really distinguish OP*/ num_piperegs += coredynp.issueW*(2*coredynp.int_data_width + pow(2.0,opcode_length)/*+2*powers (2,reg_length)*/); /* pipe stage EXE/MEM, data need to be read/write, address*/ num_piperegs += coredynp.issueW*(coredynp.int_data_width + coredynp.v_address_width + pow(2.0,opcode_length)/*+2*powers (2,reg_length)*/);//memory Opcode still need to be passed /* pipe stage MEM/WB; result data, writeback regs */ num_piperegs += coredynp.issueW*(coredynp.int_data_width + coredynp.phy_ireg_width /* powers (2,opcode_length) + (2,opcode_length)+2*powers (2,reg_length)*/); /* pipe stage WB/CM ; result data, regs need to be updated, address for resolve memory ops in ROB's top*/ num_piperegs += coredynp.commitW*(coredynp.int_data_width + coredynp.v_address_width + coredynp.phy_ireg_width/*+ powers (2,opcode_length)*2*powers (2,reg_length)*/)*coredynp.num_hthreads; // if (multithreaded) // { // // } num_stages=12; } /* assume 50% extra in control registers and interrupt registers (rule of thumb) */ num_piperegs = num_piperegs * 1.5; tot_stage_vector=num_piperegs; per_stage_vector=tot_stage_vector/num_stages; if (coredynp.core_ty==Inorder) { if (coredynp.pipeline_stages>6) num_piperegs= per_stage_vector*coredynp.pipeline_stages; } else//OOO { if (coredynp.pipeline_stages>12) num_piperegs= per_stage_vector*coredynp.pipeline_stages; } } } FunctionalUnit::FunctionalUnit(ParseXML *XML_interface, int ithCore_, InputParameter* interface_ip_,const CoreDynParam & dyn_p_, enum FU_type fu_type_) :XML(XML_interface), ithCore(ithCore_), interface_ip(*interface_ip_), coredynp(dyn_p_), fu_type(fu_type_) { double area_t;//, leakage, gate_leakage; double pmos_to_nmos_sizing_r = pmos_to_nmos_sz_ratio(); clockRate = coredynp.clockRate; executionTime = coredynp.executionTime; //XML_interface=_XML_interface; uca_org_t result2; result2 = init_interface(&interface_ip); if (XML->sys.Embedded) { if (fu_type == FPU) { num_fu=coredynp.num_fpus; //area_t = 8.47*1e6*g_tp.scaling_factor.logic_scaling_co_eff;//this is um^2 area_t = 4.47*1e6*(g_ip->F_sz_nm*g_ip->F_sz_nm/90.0/90.0);//this is um^2 The base number //4.47 contains both VFP and NEON processing unit, VFP is about 40% and NEON is about 60% if (g_ip->F_sz_nm>90) area_t = 4.47*1e6*g_tp.scaling_factor.logic_scaling_co_eff;//this is um^2 leakage = area_t *(g_tp.scaling_factor.core_tx_density)*cmos_Isub_leakage(5*g_tp.min_w_nmos_, 5*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd/2;//unit W gate_leakage = area_t *(g_tp.scaling_factor.core_tx_density)*cmos_Ig_leakage(5*g_tp.min_w_nmos_, 5*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd/2;//unit W //energy = 0.3529/10*1e-9;//this is the energy(nJ) for a FP instruction in FPU usually it can have up to 20 cycles. // base_energy = coredynp.core_ty==Inorder? 0: 89e-3*3; //W The base energy of ALU average numbers from Intel 4G and 773Mhz (Wattch) // base_energy *=(g_tp.peri_global.Vdd*g_tp.peri_global.Vdd/1.2/1.2); base_energy = 0; per_access_energy = 1.15/1e9/4/1.3/1.3*g_tp.peri_global.Vdd*g_tp.peri_global.Vdd*(g_ip->F_sz_nm/90.0);//g_tp.peri_global.Vdd*g_tp.peri_global.Vdd/1.2/1.2);//0.00649*1e-9; //This is per Hz energy(nJ) //FPU power from Sandia's processor sizing tech report FU_height=(18667*num_fu)*interface_ip.F_sz_um;//FPU from Sun's data } else if (fu_type == ALU) { num_fu=coredynp.num_alus; area_t = 280*260*g_tp.scaling_factor.logic_scaling_co_eff;//this is um^2 ALU + MUl leakage = area_t *(g_tp.scaling_factor.core_tx_density)*cmos_Isub_leakage(20*g_tp.min_w_nmos_, 20*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd/2;//unit W gate_leakage = area_t*(g_tp.scaling_factor.core_tx_density)*cmos_Ig_leakage(20*g_tp.min_w_nmos_, 20*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd/2; // base_energy = coredynp.core_ty==Inorder? 0:89e-3; //W The base energy of ALU average numbers from Intel 4G and 773Mhz (Wattch) // base_energy *=(g_tp.peri_global.Vdd*g_tp.peri_global.Vdd/1.2/1.2); base_energy = 0; per_access_energy = 1.15/3/1e9/4/1.3/1.3*g_tp.peri_global.Vdd*g_tp.peri_global.Vdd*(g_ip->F_sz_nm/90.0);//(g_tp.peri_global.Vdd*g_tp.peri_global.Vdd/1.2/1.2);//0.00649*1e-9; //This is per cycle energy(nJ) FU_height=(6222*num_fu)*interface_ip.F_sz_um;//integer ALU } else if (fu_type == MUL) { num_fu=coredynp.num_muls; area_t = 280*260*3*g_tp.scaling_factor.logic_scaling_co_eff;//this is um^2 ALU + MUl leakage = area_t *(g_tp.scaling_factor.core_tx_density)*cmos_Isub_leakage(20*g_tp.min_w_nmos_, 20*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd/2;//unit W gate_leakage = area_t*(g_tp.scaling_factor.core_tx_density)*cmos_Ig_leakage(20*g_tp.min_w_nmos_, 20*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd/2; // base_energy = coredynp.core_ty==Inorder? 0:89e-3*2; //W The base energy of ALU average numbers from Intel 4G and 773Mhz (Wattch) // base_energy *=(g_tp.peri_global.Vdd*g_tp.peri_global.Vdd/1.2/1.2); base_energy = 0; per_access_energy = 1.15*2/3/1e9/4/1.3/1.3*g_tp.peri_global.Vdd*g_tp.peri_global.Vdd*(g_ip->F_sz_nm/90.0);//(g_tp.peri_global.Vdd*g_tp.peri_global.Vdd/1.2/1.2);//0.00649*1e-9; //This is per cycle energy(nJ), coefficient based on Wattch FU_height=(9334*num_fu )*interface_ip.F_sz_um;//divider/mul from Sun's data } else { cout<<""Unknown Functional Unit Type""<F_sz_nm*g_ip->F_sz_nm/40.0/40.0);//this is um^2 if (g_ip->F_sz_nm>90) area_t = 8.47*1e6*g_tp.scaling_factor.logic_scaling_co_eff;//this is um^2 leakage = area_t *(g_tp.scaling_factor.core_tx_density)*cmos_Isub_leakage(5*g_tp.min_w_nmos_, 5*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd/2;//unit W gate_leakage = area_t *(g_tp.scaling_factor.core_tx_density)*cmos_Ig_leakage(5*g_tp.min_w_nmos_, 5*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd/2;//unit W //energy = 0.3529/10*1e-9;//this is the energy(nJ) for a FP instruction in FPU usually it can have up to 20 cycles. base_energy = coredynp.core_ty==Inorder? 0: 89e-3*3; //W The base energy of ALU average numbers from Intel 4G and 773Mhz (Wattch) base_energy *=(g_tp.peri_global.Vdd*g_tp.peri_global.Vdd/1.2/1.2); per_access_energy = (average_energy)/(0.9*0.9)*g_tp.peri_global.Vdd*g_tp.peri_global.Vdd*(g_ip->F_sz_nm/40.0);//g_tp.peri_global.Vdd*g_tp.peri_global.Vdd/1.2/1.2);//0.00649*1e-9; //This is per op energy(nJ) FU_height=(38667*num_fu)*interface_ip.F_sz_um;//FPU from Sun's data } else if (fu_type == ALU) { // Combined 2xadder, multiplier, and 2xshifter. Assuming divider = mul. double adder_area = 273*2; double mul_area = 6008.4; double shifter_area = 374.44*2; double div_area = mul_area; double adder_dyn_energy = 0.10218e-12; double mul_dyn_energy = 9.1375e-12; double div_dyn_energy = 9.1375e-12; double shift_dyn_energy = 0.57410e-12; double adder_leakage = (0.002353e-3)*2; double mul_leakage = 0.07827e-3; double div_leakage = mul_leakage; double shift_leakage = (0.002916e-3)*2; double average_energy = (adder_dyn_energy + mul_dyn_energy + shift_dyn_energy + div_dyn_energy)/4; num_fu=1; // We're lumping everything together into a single unit. area_t = (adder_area + mul_area + shifter_area + div_area)*g_tp.scaling_factor.logic_scaling_co_eff;//this is um^2 ALU + MUl // leakage = area_t *(g_tp.scaling_factor.core_tx_density)*cmos_Isub_leakage(20*g_tp.min_w_nmos_, 20*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd/2;//unit W leakage = adder_leakage + mul_leakage + div_leakage + shift_leakage; gate_leakage = area_t*(g_tp.scaling_factor.core_tx_density)*cmos_Ig_leakage(20*g_tp.min_w_nmos_, 20*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd/2; base_energy = coredynp.core_ty==Inorder? 0:89e-3; //W base_energy *=(g_tp.peri_global.Vdd*g_tp.peri_global.Vdd/1.2/1.2); per_access_energy = (average_energy)/0.9/0.9*g_tp.peri_global.Vdd*g_tp.peri_global.Vdd*(g_ip->F_sz_nm/40.0);//(g_tp.peri_global.Vdd*g_tp.peri_global.Vdd/1.2/1.2);//0.00649*1e-9; //This is per cycle energy(nJ) FU_height=(6222*num_fu)*interface_ip.F_sz_um;//integer ALU } else if (fu_type == MUL) { // Ignore this - we will lump everything into int ALU or FPU. num_fu=0; area_t = 0; leakage = 0; gate_leakage = 0; base_energy = 0; per_access_energy = 0; FU_height=0; } else { cout<<""Unknown Functional Unit Type""< 0) { double macro_layout_overhead = g_tp.macro_layout_overhead; area.set_area(area.get_area()*macro_layout_overhead); } } void FunctionalUnit::computeEnergy(bool is_tdp) { double pppm_t[4] = {1,1,1,1}; double FU_duty_cycle; if (is_tdp) { set_pppm(pppm_t, 2, 2, 2, 2);//2 means two source operands needs to be passed for each int instruction. if (fu_type == FPU) { stats_t.readAc.access = num_fu; tdp_stats = stats_t; FU_duty_cycle = coredynp.FPU_duty_cycle; } else if (fu_type == ALU) { stats_t.readAc.access = 1*num_fu; tdp_stats = stats_t; FU_duty_cycle = coredynp.ALU_duty_cycle; } else if (fu_type == MUL) { stats_t.readAc.access = num_fu; tdp_stats = stats_t; FU_duty_cycle = coredynp.MUL_duty_cycle; } //power.readOp.dynamic = base_energy/clockRate + energy*stats_t.readAc.access; power.readOp.dynamic = per_access_energy*stats_t.readAc.access + base_energy/clockRate; double sckRation = g_tp.sckt_co_eff; power.readOp.dynamic *= sckRation*FU_duty_cycle; power.writeOp.dynamic *= sckRation; power.searchOp.dynamic *= sckRation; power.readOp.leakage = leakage; power.readOp.gate_leakage = gate_leakage; double long_channel_device_reduction = longer_channel_device_reduction(Core_device, coredynp.core_ty); power.readOp.longer_channel_leakage = power.readOp.leakage*long_channel_device_reduction; double pg_reduction = power_gating_leakage_reduction(false); power.readOp.power_gated_leakage = power.readOp.leakage*pg_reduction; power.readOp.power_gated_with_long_channel_leakage = power.readOp.power_gated_leakage * long_channel_device_reduction; } else { if (fu_type == FPU) { stats_t.readAc.access = XML->sys.core[ithCore].fpu_accesses; rtp_stats = stats_t; } else if (fu_type == ALU) { stats_t.readAc.access = XML->sys.core[ithCore].ialu_accesses; rtp_stats = stats_t; } else if (fu_type == MUL) { stats_t.readAc.access = XML->sys.core[ithCore].mul_accesses; rtp_stats = stats_t; } //rt_power.readOp.dynamic = base_energy*executionTime + energy*stats_t.readAc.access; rt_power.readOp.dynamic = per_access_energy*stats_t.readAc.access + base_energy*executionTime; double sckRation = g_tp.sckt_co_eff; rt_power.readOp.dynamic *= sckRation; rt_power.writeOp.dynamic *= sckRation; rt_power.searchOp.dynamic *= sckRation; } } void FunctionalUnit::displayEnergy(uint32_t indent,int plevel,bool is_tdp) { string indent_str(indent, ' '); string indent_str_next(indent+2, ' '); bool long_channel = XML->sys.longer_channel_device; bool power_gating = XML->sys.power_gating; // cout << indent_str_next << ""Results Broadcast Bus Area = "" << bypass->area.get_area() *1e-6 << "" mm^2"" << endl; if (is_tdp) { if (fu_type == FPU) { cout << indent_str << ""Floating Point Units (FPUs) (Count: ""<< coredynp.num_fpus <<"" ):"" << endl; cout << indent_str_next << ""Area = "" << area.get_area()*1e-6 << "" mm^2"" << endl; cout << indent_str_next << ""Peak Dynamic = "" << power.readOp.dynamic*clockRate << "" W"" << endl; // cout << indent_str_next << ""Subthreshold Leakage = "" << power.readOp.leakage << "" W"" << endl; cout << indent_str_next<< ""Subthreshold Leakage = "" << (long_channel? power.readOp.longer_channel_leakage:power.readOp.leakage) <<"" W"" << endl; if (power_gating) cout << indent_str_next << ""Subthreshold Leakage with power gating = "" << (long_channel? power.readOp.power_gated_with_long_channel_leakage : power.readOp.power_gated_leakage) << "" W"" << endl; cout << indent_str_next << ""Gate Leakage = "" << power.readOp.gate_leakage << "" W"" << endl; cout << indent_str_next << ""Runtime Dynamic = "" << rt_power.readOp.dynamic/executionTime << "" W"" << endl; cout <F_sz_nm*g_ip->F_sz_nm/90.0/90.0);//this is um^2 The base number if (g_ip->F_sz_nm>90) area_t = 4.47*1e6*g_tp.scaling_factor.logic_scaling_co_eff;//this is um^2 leakage = area_t *(g_tp.scaling_factor.core_tx_density)*cmos_Isub_leakage(5*g_tp.min_w_nmos_, 5*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd/2;//unit W gate_leakage = area_t *(g_tp.scaling_factor.core_tx_density)*cmos_Ig_leakage(5*g_tp.min_w_nmos_, 5*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd/2;//unit W } else if (fu_type == ALU) { area_t = 280*260*2*num_fu*g_tp.scaling_factor.logic_scaling_co_eff;//this is um^2 ALU + MUl leakage = area_t *(g_tp.scaling_factor.core_tx_density)*cmos_Isub_leakage(20*g_tp.min_w_nmos_, 20*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd/2;//unit W gate_leakage = area_t*(g_tp.scaling_factor.core_tx_density)*cmos_Ig_leakage(20*g_tp.min_w_nmos_, 20*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd/2; } else if (fu_type == MUL) { area_t = 280*260*2*3*num_fu*g_tp.scaling_factor.logic_scaling_co_eff;//this is um^2 ALU + MUl leakage = area_t *(g_tp.scaling_factor.core_tx_density)*cmos_Isub_leakage(20*g_tp.min_w_nmos_, 20*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd/2;//unit W gate_leakage = area_t*(g_tp.scaling_factor.core_tx_density)*cmos_Ig_leakage(20*g_tp.min_w_nmos_, 20*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd/2; } else { cout<<""Unknown Functional Unit Type""<sys.Embedded), pipeline_stage(coredynp.pipeline_stages), num_hthreads(coredynp.num_hthreads), issue_width(coredynp.issueW), exist(exist_) // is_default(_is_default) { if (!exist) return; double undifferentiated_core=0; double core_tx_density=0; double pmos_to_nmos_sizing_r = pmos_to_nmos_sz_ratio(); double undifferentiated_core_coe; //XML_interface=_XML_interface; uca_org_t result2; result2 = init_interface(&interface_ip); //Compute undifferentiated core area at 90nm. if (embedded==false) { //Based on the results of polynomial/log curve fitting based on undifferentiated core of Niagara, Niagara2, Merom, Penyrn, Prescott, Opteron die measurements if (core_ty==OOO) { //undifferentiated_core = (0.0764*pipeline_stage*pipeline_stage -2.3685*pipeline_stage + 10.405);//OOO undifferentiated_core = (3.57*log(pipeline_stage)-1.2643)>0?(3.57*log(pipeline_stage)-1.2643):0; } else if (core_ty==Inorder) { //undifferentiated_core = (0.1238*pipeline_stage + 7.2572)*0.9;//inorder undifferentiated_core = (-2.19*log(pipeline_stage)+6.55)>0?(-2.19*log(pipeline_stage)+6.55):0; } else { cout<<""invalid core type""<sys.opt_clockrate) undifferentiated_core_coe = 0.05; else undifferentiated_core_coe = 0; undifferentiated_core = (0.4109* pipeline_stage - 0.776)*undifferentiated_core_coe; undifferentiated_core *= (1+ logtwo(num_hthreads)* 0.0426); } undifferentiated_core *= g_tp.scaling_factor.logic_scaling_co_eff*1e6;//change from mm^2 to um^2 core_tx_density = g_tp.scaling_factor.core_tx_density; //undifferentiated_core = 3*1e6; //undifferentiated_core *= g_tp.scaling_factor.logic_scaling_co_eff;//(g_ip->F_sz_um*g_ip->F_sz_um/0.09/0.09)*; power.readOp.leakage = undifferentiated_core*(core_tx_density)*cmos_Isub_leakage(5*g_tp.min_w_nmos_, 5*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd;//unit W power.readOp.gate_leakage = undifferentiated_core*(core_tx_density)*cmos_Ig_leakage(5*g_tp.min_w_nmos_, 5*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd; double long_channel_device_reduction = longer_channel_device_reduction(Core_device, coredynp.core_ty); power.readOp.longer_channel_leakage = power.readOp.leakage*long_channel_device_reduction; double pg_reduction = power_gating_leakage_reduction(false); power.readOp.power_gated_leakage = power.readOp.leakage*pg_reduction; power.readOp.power_gated_with_long_channel_leakage = power.readOp.power_gated_leakage * long_channel_device_reduction; area.set_area(undifferentiated_core); scktRatio = g_tp.sckt_co_eff; power.readOp.dynamic *= scktRatio; power.writeOp.dynamic *= scktRatio; power.searchOp.dynamic *= scktRatio; macro_PR_overhead = g_tp.macro_layout_overhead; area.set_area(area.get_area()*macro_PR_overhead); // double vt=g_tp.peri_global.Vth; // double velocity_index=1.1; // double c_in=gate_C(g_tp.min_w_nmos_, g_tp.min_w_nmos_*pmos_to_nmos_sizing_r , 0.0, false); // double c_out= drain_C_(g_tp.min_w_nmos_, NCH, 2, 1, g_tp.cell_h_def, false) + drain_C_(g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, PCH, 1, 1, g_tp.cell_h_def, false) + c_in; // double w_nmos=g_tp.min_w_nmos_; // double w_pmos=g_tp.min_w_nmos_*pmos_to_nmos_sizing_r; // double i_on_n=1.0; // double i_on_p=1.0; // double i_on_n_in=1.0; // double i_on_p_in=1; // double vdd=g_tp.peri_global.Vdd; // power.readOp.sc=shortcircuit_simple(vt, velocity_index, c_in, c_out, w_nmos,w_pmos, i_on_n, i_on_p,i_on_n_in, i_on_p_in, vdd); // power.readOp.dynamic=c_out*vdd*vdd/2; // cout<sys.longer_channel_device; bool power_gating = XML->sys.power_gating; if (is_tdp) { cout << indent_str << ""UndiffCore:"" << endl; cout << indent_str_next << ""Area = "" << area.get_area()*1e-6<< "" mm^2"" << endl; cout << indent_str_next << ""Peak Dynamic = "" << power.readOp.dynamic*clockRate << "" W"" << endl; //cout << indent_str_next << ""Subthreshold Leakage = "" << power.readOp.leakage <<"" W"" << endl; cout << indent_str_next<< ""Subthreshold Leakage = "" << (long_channel? power.readOp.longer_channel_leakage:power.readOp.leakage) <<"" W"" << endl; if (power_gating) cout << indent_str_next << ""Subthreshold Leakage with power gating = "" << (long_channel? power.readOp.power_gated_with_long_channel_leakage : power.readOp.power_gated_leakage) << "" W"" << endl; cout << indent_str_next << ""Gate Leakage = "" << power.readOp.gate_leakage << "" W"" << endl; //cout << indent_str_next << ""Runtime Dynamic = "" << rt_power.readOp.dynamic/executionTime << "" W"" << endl; cout < 18) opcode_length = 18; num_decoded_signals= (int)pow(2.0,opcode_length); pmos_to_nmos_sizing_r = pmos_to_nmos_sz_ratio(); load_nmos_width=g_tp.max_w_nmos_ /2; load_pmos_width= g_tp.max_w_nmos_ * pmos_to_nmos_sizing_r; C_driver_load = 1024*gate_C(load_nmos_width + load_pmos_width, 0, is_dram); //TODO: this number 1024 needs to be revisited R_wire_load = 3000*l_ip.F_sz_um * g_tp.wire_outside_mat.R_per_um; final_dec = new Decoder( num_decoded_signals, false, C_driver_load, R_wire_load, false/*is_fa*/, false/*is_dram*/, false/*wl_tr*/, //to use peri device cell); PredecBlk * predec_blk1 = new PredecBlk( num_decoded_signals, final_dec, 0,//Assuming predec and dec are back to back 0, 1,//Each Predec only drives one final dec false/*is_dram*/, true); PredecBlk * predec_blk2 = new PredecBlk( num_decoded_signals, final_dec, 0,//Assuming predec and dec are back to back 0, 1,//Each Predec only drives one final dec false/*is_dram*/, false); PredecBlkDrv * predec_blk_drv1 = new PredecBlkDrv(0, predec_blk1, false); PredecBlkDrv * predec_blk_drv2 = new PredecBlkDrv(0, predec_blk2, false); pre_dec = new Predec(predec_blk_drv1, predec_blk_drv2); double area_decoder = final_dec->area.get_area() * num_decoded_signals * num_decoder_segments*num_decoders; //double w_decoder = area_decoder / area.get_h(); double area_pre_dec = (predec_blk_drv1->area.get_area() + predec_blk_drv2->area.get_area() + predec_blk1->area.get_area() + predec_blk2->area.get_area())* num_decoder_segments*num_decoders; area.set_area(area.get_area()+ area_decoder + area_pre_dec); double macro_layout_overhead = g_tp.macro_layout_overhead; double chip_PR_overhead = g_tp.chip_layout_overhead; area.set_area(area.get_area()*macro_layout_overhead*chip_PR_overhead); inst_decoder_delay_power(); double sckRation = g_tp.sckt_co_eff; power.readOp.dynamic *= sckRation; power.writeOp.dynamic *= sckRation; power.searchOp.dynamic *= sckRation; double long_channel_device_reduction = longer_channel_device_reduction(device_ty,core_ty); power.readOp.longer_channel_leakage = power.readOp.leakage*long_channel_device_reduction; double pg_reduction = power_gating_leakage_reduction(false); power.readOp.power_gated_leakage = power.readOp.leakage*pg_reduction; power.readOp.power_gated_with_long_channel_leakage = power.readOp.power_gated_leakage * long_channel_device_reduction; } void inst_decoder::inst_decoder_delay_power() { double dec_outrisetime; double inrisetime=0, outrisetime; double pppm_t[4] = {1,1,1,1}; double squencer_passes = x86?2:1; outrisetime = pre_dec->compute_delays(inrisetime); dec_outrisetime = final_dec->compute_delays(outrisetime); set_pppm(pppm_t, squencer_passes*num_decoder_segments, num_decoder_segments, squencer_passes*num_decoder_segments, num_decoder_segments); power = power + pre_dec->power*pppm_t; set_pppm(pppm_t, squencer_passes*num_decoder_segments, num_decoder_segments*num_decoded_signals, num_decoder_segments*num_decoded_signals, squencer_passes*num_decoder_segments); power = power + final_dec->power*pppm_t; } void inst_decoder::leakage_feedback(double temperature) { l_ip.temp = (unsigned int)round(temperature/10.0)*10; uca_org_t init_result = init_interface(&l_ip); // init_result is dummy final_dec->leakage_feedback(temperature); pre_dec->leakage_feedback(temperature); double pppm_t[4] = {1,1,1,1}; double squencer_passes = x86?2:1; set_pppm(pppm_t, squencer_passes*num_decoder_segments, num_decoder_segments, squencer_passes*num_decoder_segments, num_decoder_segments); power = pre_dec->power*pppm_t; set_pppm(pppm_t, squencer_passes*num_decoder_segments, num_decoder_segments*num_decoded_signals,num_decoder_segments*num_decoded_signals, squencer_passes*num_decoder_segments); power = power + final_dec->power*pppm_t; double sckRation = g_tp.sckt_co_eff; power.readOp.dynamic *= sckRation; power.writeOp.dynamic *= sckRation; power.searchOp.dynamic *= sckRation; double long_channel_device_reduction = longer_channel_device_reduction(device_ty,core_ty); power.readOp.longer_channel_leakage = power.readOp.leakage*long_channel_device_reduction; double pg_reduction = power_gating_leakage_reduction(false); power.readOp.power_gated_leakage = power.readOp.leakage*pg_reduction; power.readOp.power_gated_with_long_channel_leakage = power.readOp.power_gated_leakage * long_channel_device_reduction; } inst_decoder::~inst_decoder() { local_result.cleanup(); delete final_dec; delete pre_dec->blk1; delete pre_dec->blk2; delete pre_dec->drv1; delete pre_dec->drv2; delete pre_dec; } ",16205,True,3091.1183171459543,median "[[netty-component]] = Netty Component :docTitle: Netty :artifactId: camel-netty :description: Socket level networking using TCP or UDP with the Netty 4.x. :since: 2.14 :supportLevel: Stable :component-header: Both producer and consumer are supported *Since Camel {since}* *{component-header}* The Netty component in Camel is a socket communication component, based on the http://netty.io/[Netty] project version 4. + Netty is a NIO client server framework which enables quick and easy development of networkServerInitializerFactory applications such as protocol servers and clients. + Netty greatly simplifies and streamlines network programming such as TCP and UDP socket server. This camel component supports both producer and consumer endpoints. The Netty component has several options and allows fine-grained control of a number of TCP/UDP communication parameters (buffer sizes, keepAlives, tcpNoDelay, etc) and facilitates both In-Only and In-Out communication on a Camel route. Maven users will need to add the following dependency to their `pom.xml` for this component: [source,xml] ---- org.apache.camel camel-netty x.x.x ---- == URI format The URI scheme for a netty component is as follows [source,text] ---- netty:tcp://0.0.0.0:99999[?options] netty:udp://remotehost:99999/[?options] ---- This component supports producer and consumer endpoints for both TCP and UDP. You can append query options to the URI in the following format, `?option=value&option=value&...` == Options // component options: START The Netty component supports 72 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *configuration* (common) | To use the NettyConfiguration as configuration when creating endpoints. | | NettyConfiguration | *disconnect* (common) | Whether or not to disconnect(close) from Netty Channel right after use. Can be used for both consumer and producer. | false | boolean | *keepAlive* (common) | Setting to ensure socket is not closed due to inactivity | true | boolean | *reuseAddress* (common) | Setting to facilitate socket multiplexing | true | boolean | *reuseChannel* (common) | This option allows producers and consumers (in client mode) to reuse the same Netty Channel for the lifecycle of processing the Exchange. This is useful if you need to call a server multiple times in a Camel route and want to use the same network connection. When using this, the channel is not returned to the connection pool until the Exchange is done; or disconnected if the disconnect option is set to true. The reused Channel is stored on the Exchange as an exchange property with the key NettyConstants#NETTY_CHANNEL which allows you to obtain the channel during routing and use it as well. | false | boolean | *sync* (common) | Setting to set endpoint as one-way or request-response | true | boolean | *tcpNoDelay* (common) | Setting to improve TCP protocol performance | true | boolean | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *broadcast* (consumer) | Setting to choose Multicast over UDP | false | boolean | *clientMode* (consumer) | If the clientMode is true, netty consumer will connect the address as a TCP client. | false | boolean | *reconnect* (consumer) | Used only in clientMode in consumer, the consumer will attempt to reconnect on disconnection if this is enabled | true | boolean | *reconnectInterval* (consumer) | Used if reconnect and clientMode is enabled. The interval in milli seconds to attempt reconnection | 10000 | int | *backlog* (consumer) | Allows to configure a backlog for netty consumer (server). Note the backlog is just a best effort depending on the OS. Setting this option to a value such as 200, 500 or 1000, tells the TCP stack how long the accept queue can be If this option is not configured, then the backlog depends on OS setting. | | int | *bossCount* (consumer) | When netty works on nio mode, it uses default bossCount parameter from Netty, which is 1. User can use this option to override the default bossCount from Netty | 1 | int | *bossGroup* (consumer) | Set the BossGroup which could be used for handling the new connection of the server side across the NettyEndpoint | | EventLoopGroup | *disconnectOnNoReply* (consumer) | If sync is enabled then this option dictates NettyConsumer if it should disconnect where there is no reply to send back. | true | boolean | *executorService* (consumer) | To use the given EventExecutorGroup. | | EventExecutorGroup | *maximumPoolSize* (consumer) | Sets a maximum thread pool size for the netty consumer ordered thread pool. The default size is 2 x cpu_core plus 1. Setting this value to eg 10 will then use 10 threads unless 2 x cpu_core plus 1 is a higher value, which then will override and be used. For example if there are 8 cores, then the consumer thread pool will be 17. This thread pool is used to route messages received from Netty by Camel. We use a separate thread pool to ensure ordering of messages and also in case some messages will block, then nettys worker threads (event loop) wont be affected. | | int | *nettyServerBootstrapFactory* (consumer) | To use a custom NettyServerBootstrapFactory | | NettyServerBootstrapFactory | *networkInterface* (consumer) | When using UDP then this option can be used to specify a network interface by its name, such as eth0 to join a multicast group. | | String | *noReplyLogLevel* (consumer) | If sync is enabled this option dictates NettyConsumer which logging level to use when logging a there is no reply to send back. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverClosedChannelException CaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an java.nio.channels.ClosedChannelException then its logged using this logging level. This is used to avoid logging the closed channel exceptions, as clients can disconnect abruptly and then cause a flood of closed exceptions in the Netty server. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | DEBUG | LoggingLevel | *serverExceptionCaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an exception then its logged using this logging level. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverInitializerFactory* (consumer) | To use a custom ServerInitializerFactory | | ServerInitializerFactory | *usingExecutorService* (consumer) | Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. | true | boolean | *connectTimeout* (producer) | Time to wait for a socket connection to be available. Value is in milliseconds. | 10000 | int | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *requestTimeout* (producer) | Allows to use a timeout for the Netty producer when calling a remote server. By default no timeout is in use. The value is in milli seconds, so eg 30000 is 30 seconds. The requestTimeout is using Netty's ReadTimeoutHandler to trigger the timeout. | | long | *clientInitializerFactory* (producer) | To use a custom ClientInitializerFactory | | ClientInitializerFactory | *correlationManager* (producer) | To use a custom correlation manager to manage how request and reply messages are mapped when using request/reply with the netty producer. This should only be used if you have a way to map requests together with replies such as if there is correlation ids in both the request and reply messages. This can be used if you want to multiplex concurrent messages on the same channel (aka connection) in netty. When doing this you must have a way to correlate the request and reply messages so you can store the right reply on the inflight Camel Exchange before its continued routed. We recommend extending the TimeoutCorrelationManagerSupport when you build custom correlation managers. This provides support for timeout and other complexities you otherwise would need to implement as well. See also the producerPoolEnabled option for more details. | | NettyCamelStateCorrelationManager | *lazyChannelCreation* (producer) | Channels can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. | true | boolean | *producerPoolEnabled* (producer) | Whether producer pool is enabled or not. Important: If you turn this off then a single shared connection is used for the producer, also if you are doing request/reply. That means there is a potential issue with interleaved responses if replies comes back out-of-order. Therefore you need to have a correlation id in both the request and reply messages so you can properly correlate the replies to the Camel callback that is responsible for continue processing the message in Camel. To do this you need to implement NettyCamelStateCorrelationManager as correlation manager and configure it via the correlationManager option. See also the correlationManager option for more details. | true | boolean | *producerPoolMaxActive* (producer) | Sets the cap on the number of objects that can be allocated by the pool (checked out to clients, or idle awaiting checkout) at a given time. Use a negative value for no limit. | -1 | int | *producerPoolMaxIdle* (producer) | Sets the cap on the number of idle instances in the pool. | 100 | int | *producerPoolMinEvictableIdle* (producer) | Sets the minimum amount of time (value in millis) an object may sit idle in the pool before it is eligible for eviction by the idle object evictor. | 300000 | long | *producerPoolMinIdle* (producer) | Sets the minimum number of instances allowed in the producer pool before the evictor thread (if active) spawns new objects. | | int | *udpConnectionlessSending* (producer) | This option supports connection less udp sending which is a real fire and forget. A connected udp send receive the PortUnreachableException if no one is listen on the receiving port. | false | boolean | *useByteBuf* (producer) | If the useByteBuf is true, netty producer will turn the message body into ByteBuf before sending it out. | false | boolean | *allowSerializedHeaders* (advanced) | Only used for TCP when transferExchange is true. When set to true, serializable objects in headers and properties will be added to the exchange. Otherwise Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *basicPropertyBinding* (advanced) | *Deprecated* Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean | *channelGroup* (advanced) | To use a explicit ChannelGroup. | | ChannelGroup | *nativeTransport* (advanced) | Whether to use native transport instead of NIO. Native transport takes advantage of the host operating system and is only supported on some platforms. You need to add the netty JAR for the host operating system you are using. See more details at: \\http://netty.io/wiki/native-transports.html | false | boolean | *options* (advanced) | Allows to configure additional netty options using option. as prefix. For example option.child.keepAlive=false to set the netty option child.keepAlive=false. See the Netty documentation for possible options that can be used. | | Map | *receiveBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during inbound communication. Size is bytes. | 65536 | int | *receiveBufferSizePredictor* (advanced) | Configures the buffer size predictor. See details at Jetty documentation and this mail thread. | | int | *sendBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during outbound communication. Size is bytes. | 65536 | int | *transferExchange* (advanced) | Only used for TCP. You can transfer the exchange over the wire instead of just the body. The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *udpByteArrayCodec* (advanced) | For UDP only. If enabled the using byte array codec instead of Java serialization protocol. | false | boolean | *workerCount* (advanced) | When netty works on nio mode, it uses default workerCount parameter from Netty (which is cpu_core_threads x 2). User can use this option to override the default workerCount from Netty. | | int | *workerGroup* (advanced) | To use a explicit EventLoopGroup as the boss thread pool. For example to share a thread pool with multiple consumers or producers. By default each consumer or producer has their own worker pool with 2 x cpu count core threads. | | EventLoopGroup | *allowDefaultCodec* (codec) | The netty component installs a default codec if both, encoder/decoder is null and textline is false. Setting allowDefaultCodec to false prevents the netty component from installing a default codec as the first element in the filter chain. | true | boolean | *autoAppendDelimiter* (codec) | Whether or not to auto append missing end delimiter when sending using the textline codec. | true | boolean | *decoderMaxLineLength* (codec) | The max line length to use for the textline codec. | 1024 | int | *decoders* (codec) | A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *delimiter* (codec) | The delimiter to use for the textline codec. Possible values are LINE and NULL. There are 2 enums and the value can be one of: LINE, NULL | LINE | TextLineDelimiter | *encoders* (codec) | A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *encoding* (codec) | The encoding (a charset name) to use for the textline codec. If not provided, Camel will use the JVM default Charset. | | String | *textline* (codec) | Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; if not specified or the value is false, then Object Serialization is assumed over TCP - however only Strings are allowed to be serialized by default. | false | boolean | *enabledProtocols* (security) | Which protocols to enable when using SSL | TLSv1,TLSv1.1,TLSv1.2 | String | *keyStoreFile* (security) | Client side certificate keystore to be used for encryption | | File | *keyStoreFormat* (security) | Keystore format to be used for payload encryption. Defaults to JKS if not set | | String | *keyStoreResource* (security) | Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String | *needClientAuth* (security) | Configures whether the server needs client authentication when using SSL. | false | boolean | *passphrase* (security) | Password setting to use in order to encrypt/decrypt payloads sent using SSH | | String | *securityProvider* (security) | Security provider to be used for payload encryption. Defaults to SunX509 if not set. | | String | *ssl* (security) | Setting to specify whether SSL encryption is applied to this endpoint | false | boolean | *sslClientCertHeaders* (security) | When enabled and in SSL mode, then the Netty consumer will enrich the Camel Message with headers having information about the client certificate such as subject name, issuer name, serial number, and the valid date range. | false | boolean | *sslContextParameters* (security) | To configure security using SSLContextParameters | | SSLContextParameters | *sslHandler* (security) | Reference to a class that could be used to return an SSL Handler | | SslHandler | *trustStoreFile* (security) | Server side certificate keystore to be used for encryption | | File | *trustStoreResource* (security) | Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String | *useGlobalSslContextParameters* (security) | Enable usage of global SSL context parameters. | false | boolean |=== // component options: END // endpoint options: START The Netty endpoint is configured using URI syntax: ---- netty:protocol:host:port ---- with the following path and query parameters: === Path Parameters (3 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *protocol* | *Required* The protocol to use which can be tcp or udp. There are 2 enums and the value can be one of: tcp, udp | | String | *host* | *Required* The hostname. For the consumer the hostname is localhost or 0.0.0.0. For the producer the hostname is the remote host to connect to | | String | *port* | *Required* The host port number | | int |=== === Query Parameters (71 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *disconnect* (common) | Whether or not to disconnect(close) from Netty Channel right after use. Can be used for both consumer and producer. | false | boolean | *keepAlive* (common) | Setting to ensure socket is not closed due to inactivity | true | boolean | *reuseAddress* (common) | Setting to facilitate socket multiplexing | true | boolean | *reuseChannel* (common) | This option allows producers and consumers (in client mode) to reuse the same Netty Channel for the lifecycle of processing the Exchange. This is useful if you need to call a server multiple times in a Camel route and want to use the same network connection. When using this, the channel is not returned to the connection pool until the Exchange is done; or disconnected if the disconnect option is set to true. The reused Channel is stored on the Exchange as an exchange property with the key NettyConstants#NETTY_CHANNEL which allows you to obtain the channel during routing and use it as well. | false | boolean | *sync* (common) | Setting to set endpoint as one-way or request-response | true | boolean | *tcpNoDelay* (common) | Setting to improve TCP protocol performance | true | boolean | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *broadcast* (consumer) | Setting to choose Multicast over UDP | false | boolean | *clientMode* (consumer) | If the clientMode is true, netty consumer will connect the address as a TCP client. | false | boolean | *reconnect* (consumer) | Used only in clientMode in consumer, the consumer will attempt to reconnect on disconnection if this is enabled | true | boolean | *reconnectInterval* (consumer) | Used if reconnect and clientMode is enabled. The interval in milli seconds to attempt reconnection | 10000 | int | *backlog* (consumer) | Allows to configure a backlog for netty consumer (server). Note the backlog is just a best effort depending on the OS. Setting this option to a value such as 200, 500 or 1000, tells the TCP stack how long the accept queue can be If this option is not configured, then the backlog depends on OS setting. | | int | *bossCount* (consumer) | When netty works on nio mode, it uses default bossCount parameter from Netty, which is 1. User can use this option to override the default bossCount from Netty | 1 | int | *bossGroup* (consumer) | Set the BossGroup which could be used for handling the new connection of the server side across the NettyEndpoint | | EventLoopGroup | *disconnectOnNoReply* (consumer) | If sync is enabled then this option dictates NettyConsumer if it should disconnect where there is no reply to send back. | true | boolean | *exceptionHandler* (consumer) | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | | ExceptionHandler | *exchangePattern* (consumer) | Sets the exchange pattern when the consumer creates an exchange. There are 3 enums and the value can be one of: InOnly, InOut, InOptionalOut | | ExchangePattern | *nettyServerBootstrapFactory* (consumer) | To use a custom NettyServerBootstrapFactory | | NettyServerBootstrapFactory | *networkInterface* (consumer) | When using UDP then this option can be used to specify a network interface by its name, such as eth0 to join a multicast group. | | String | *noReplyLogLevel* (consumer) | If sync is enabled this option dictates NettyConsumer which logging level to use when logging a there is no reply to send back. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverClosedChannelException CaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an java.nio.channels.ClosedChannelException then its logged using this logging level. This is used to avoid logging the closed channel exceptions, as clients can disconnect abruptly and then cause a flood of closed exceptions in the Netty server. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | DEBUG | LoggingLevel | *serverExceptionCaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an exception then its logged using this logging level. There are 6 enums and the value can be one of: TRACE, DEBUG, INFO, WARN, ERROR, OFF | WARN | LoggingLevel | *serverInitializerFactory* (consumer) | To use a custom ServerInitializerFactory | | ServerInitializerFactory | *usingExecutorService* (consumer) | Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. | true | boolean | *connectTimeout* (producer) | Time to wait for a socket connection to be available. Value is in milliseconds. | 10000 | int | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *requestTimeout* (producer) | Allows to use a timeout for the Netty producer when calling a remote server. By default no timeout is in use. The value is in milli seconds, so eg 30000 is 30 seconds. The requestTimeout is using Netty's ReadTimeoutHandler to trigger the timeout. | | long | *clientInitializerFactory* (producer) | To use a custom ClientInitializerFactory | | ClientInitializerFactory | *correlationManager* (producer) | To use a custom correlation manager to manage how request and reply messages are mapped when using request/reply with the netty producer. This should only be used if you have a way to map requests together with replies such as if there is correlation ids in both the request and reply messages. This can be used if you want to multiplex concurrent messages on the same channel (aka connection) in netty. When doing this you must have a way to correlate the request and reply messages so you can store the right reply on the inflight Camel Exchange before its continued routed. We recommend extending the TimeoutCorrelationManagerSupport when you build custom correlation managers. This provides support for timeout and other complexities you otherwise would need to implement as well. See also the producerPoolEnabled option for more details. | | NettyCamelStateCorrelationManager | *lazyChannelCreation* (producer) | Channels can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. | true | boolean | *producerPoolEnabled* (producer) | Whether producer pool is enabled or not. Important: If you turn this off then a single shared connection is used for the producer, also if you are doing request/reply. That means there is a potential issue with interleaved responses if replies comes back out-of-order. Therefore you need to have a correlation id in both the request and reply messages so you can properly correlate the replies to the Camel callback that is responsible for continue processing the message in Camel. To do this you need to implement NettyCamelStateCorrelationManager as correlation manager and configure it via the correlationManager option. See also the correlationManager option for more details. | true | boolean | *producerPoolMaxActive* (producer) | Sets the cap on the number of objects that can be allocated by the pool (checked out to clients, or idle awaiting checkout) at a given time. Use a negative value for no limit. | -1 | int | *producerPoolMaxIdle* (producer) | Sets the cap on the number of idle instances in the pool. | 100 | int | *producerPoolMinEvictableIdle* (producer) | Sets the minimum amount of time (value in millis) an object may sit idle in the pool before it is eligible for eviction by the idle object evictor. | 300000 | long | *producerPoolMinIdle* (producer) | Sets the minimum number of instances allowed in the producer pool before the evictor thread (if active) spawns new objects. | | int | *udpConnectionlessSending* (producer) | This option supports connection less udp sending which is a real fire and forget. A connected udp send receive the PortUnreachableException if no one is listen on the receiving port. | false | boolean | *useByteBuf* (producer) | If the useByteBuf is true, netty producer will turn the message body into ByteBuf before sending it out. | false | boolean | *allowSerializedHeaders* (advanced) | Only used for TCP when transferExchange is true. When set to true, serializable objects in headers and properties will be added to the exchange. Otherwise Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *basicPropertyBinding* (advanced) | Whether the endpoint should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean | *channelGroup* (advanced) | To use a explicit ChannelGroup. | | ChannelGroup | *nativeTransport* (advanced) | Whether to use native transport instead of NIO. Native transport takes advantage of the host operating system and is only supported on some platforms. You need to add the netty JAR for the host operating system you are using. See more details at: \\http://netty.io/wiki/native-transports.html | false | boolean | *options* (advanced) | Allows to configure additional netty options using option. as prefix. For example option.child.keepAlive=false to set the netty option child.keepAlive=false. See the Netty documentation for possible options that can be used. | | Map | *receiveBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during inbound communication. Size is bytes. | 65536 | int | *receiveBufferSizePredictor* (advanced) | Configures the buffer size predictor. See details at Jetty documentation and this mail thread. | | int | *sendBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during outbound communication. Size is bytes. | 65536 | int | *synchronous* (advanced) | Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported). | false | boolean | *transferExchange* (advanced) | Only used for TCP. You can transfer the exchange over the wire instead of just the body. The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *udpByteArrayCodec* (advanced) | For UDP only. If enabled the using byte array codec instead of Java serialization protocol. | false | boolean | *workerCount* (advanced) | When netty works on nio mode, it uses default workerCount parameter from Netty (which is cpu_core_threads x 2). User can use this option to override the default workerCount from Netty. | | int | *workerGroup* (advanced) | To use a explicit EventLoopGroup as the boss thread pool. For example to share a thread pool with multiple consumers or producers. By default each consumer or producer has their own worker pool with 2 x cpu count core threads. | | EventLoopGroup | *allowDefaultCodec* (codec) | The netty component installs a default codec if both, encoder/decoder is null and textline is false. Setting allowDefaultCodec to false prevents the netty component from installing a default codec as the first element in the filter chain. | true | boolean | *autoAppendDelimiter* (codec) | Whether or not to auto append missing end delimiter when sending using the textline codec. | true | boolean | *decoderMaxLineLength* (codec) | The max line length to use for the textline codec. | 1024 | int | *decoders* (codec) | A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *delimiter* (codec) | The delimiter to use for the textline codec. Possible values are LINE and NULL. There are 2 enums and the value can be one of: LINE, NULL | LINE | TextLineDelimiter | *encoders* (codec) | A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *encoding* (codec) | The encoding (a charset name) to use for the textline codec. If not provided, Camel will use the JVM default Charset. | | String | *textline* (codec) | Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; if not specified or the value is false, then Object Serialization is assumed over TCP - however only Strings are allowed to be serialized by default. | false | boolean | *enabledProtocols* (security) | Which protocols to enable when using SSL | TLSv1,TLSv1.1,TLSv1.2 | String | *keyStoreFile* (security) | Client side certificate keystore to be used for encryption | | File | *keyStoreFormat* (security) | Keystore format to be used for payload encryption. Defaults to JKS if not set | | String | *keyStoreResource* (security) | Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String | *needClientAuth* (security) | Configures whether the server needs client authentication when using SSL. | false | boolean | *passphrase* (security) | Password setting to use in order to encrypt/decrypt payloads sent using SSH | | String | *securityProvider* (security) | Security provider to be used for payload encryption. Defaults to SunX509 if not set. | | String | *ssl* (security) | Setting to specify whether SSL encryption is applied to this endpoint | false | boolean | *sslClientCertHeaders* (security) | When enabled and in SSL mode, then the Netty consumer will enrich the Camel Message with headers having information about the client certificate such as subject name, issuer name, serial number, and the valid date range. | false | boolean | *sslContextParameters* (security) | To configure security using SSLContextParameters | | SSLContextParameters | *sslHandler* (security) | Reference to a class that could be used to return an SSL Handler | | SslHandler | *trustStoreFile* (security) | Server side certificate keystore to be used for encryption | | File | *trustStoreResource* (security) | Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String |=== // endpoint options: END == Registry based Options Codec Handlers and SSL Keystores can be enlisted in the Registry, such as in the Spring XML file. The values that could be passed in, are the following: [width=""100%"",cols=""10%,90%"",options=""header"",] |=== |Name |Description |`passphrase` |password setting to use in order to encrypt/decrypt payloads sent using SSH |`keyStoreFormat` |keystore format to be used for payload encryption. Defaults to ""JKS"" if not set |`securityProvider` |Security provider to be used for payload encryption. Defaults to ""SunX509"" if not set. |`keyStoreFile` |*deprecated:* Client side certificate keystore to be used for encryption |`trustStoreFile` |*deprecated:* Server side certificate keystore to be used for encryption |`keyStoreResource` |Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with `""classpath:""`, `""file:""`, or `""http:""` to load the resource from different systems. |`trustStoreResource` |Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with `""classpath:""`, `""file:""`, or `""http:""` to load the resource from different systems. |`sslHandler` |Reference to a class that could be used to return an SSL Handler |`encoder` |A custom `ChannelHandler` class that can be used to perform special marshalling of outbound payloads. Must override io.netty.channel.ChannelInboundHandlerAdapter. |`encoders` |A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. |`decoder` |A custom `ChannelHandler` class that can be used to perform special marshalling of inbound payloads. Must override io.netty.channel.ChannelOutboundHandlerAdapter. |`decoders` |A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. |=== [NOTE] ==== Read below about using non shareable encoders/decoders. ==== === Using non shareable encoders or decoders If your encoders or decoders are not shareable (e.g. they don't have the @Shareable class annotation), then your encoder/decoder must implement the `org.apache.camel.component.netty.ChannelHandlerFactory` interface, and return a new instance in the `newChannelHandler` method. This is to ensure the encoder/decoder can safely be used. If this is not the case, then the Netty component will log a WARN when an endpoint is created. The Netty component offers a `org.apache.camel.component.netty.ChannelHandlerFactories` factory class, that has a number of commonly used methods. == Sending Messages to/from a Netty endpoint === Netty Producer In Producer mode, the component provides the ability to send payloads to a socket endpoint using either TCP or UDP protocols (with optional SSL support). The producer mode supports both one-way and request-response based operations. === Netty Consumer In Consumer mode, the component provides the ability to: * listen on a specified socket using either TCP or UDP protocols (with optional SSL support), * receive requests on the socket using text/xml, binary and serialized object based payloads and * send them along on a route as message exchanges. The consumer mode supports both one-way and request-response based operations. == Examples === A UDP Netty endpoint using Request-Reply and serialized object payload Note that Object serialization is not allowed by default, and so a decoder must be configured. [source,java] ---- @BindToRegistry(""decoder"") public ChannelHandler getDecoder() throws Exception { return new DefaultChannelHandlerFactory() { @Override public ChannelHandler newChannelHandler() { return new DatagramPacketObjectDecoder(ClassResolvers.weakCachingResolver(null)); } }; } RouteBuilder builder = new RouteBuilder() { public void configure() { from(""netty:udp://0.0.0.0:5155?sync=true&decoders=#decoder"") .process(new Processor() { public void process(Exchange exchange) throws Exception { Poetry poetry = (Poetry) exchange.getIn().getBody(); // Process poetry in some way exchange.getOut().setBody(""Message received); } } } }; ---- === A TCP based Netty consumer endpoint using One-way communication [source,java] ---- RouteBuilder builder = new RouteBuilder() { public void configure() { from(""netty:tcp://0.0.0.0:5150"") .to(""mock:result""); } }; ---- === An SSL/TCP based Netty consumer endpoint using Request-Reply communication [[Netty-UsingtheJSSEConfigurationUtility]] Using the JSSE Configuration Utility The Netty component supports SSL/TLS configuration through the xref:manual::camel-configuration-utilities.adoc[Camel JSSE Configuration Utility]. This utility greatly decreases the amount of component specific code you need to write and is configurable at the endpoint and component levels. The following examples demonstrate how to use the utility with the Netty component. [[Netty-Programmaticconfigurationofthecomponent]] Programmatic configuration of the component [source,java] ---- KeyStoreParameters ksp = new KeyStoreParameters(); ksp.setResource(""/users/home/server/keystore.jks""); ksp.setPassword(""keystorePassword""); KeyManagersParameters kmp = new KeyManagersParameters(); kmp.setKeyStore(ksp); kmp.setKeyPassword(""keyPassword""); SSLContextParameters scp = new SSLContextParameters(); scp.setKeyManagers(kmp); NettyComponent nettyComponent = getContext().getComponent(""netty"", NettyComponent.class); nettyComponent.setSslContextParameters(scp); ---- [[Netty-SpringDSLbasedconfigurationofendpoint]] Spring DSL based configuration of endpoint [source,xml] ---- ... ... ... ... ---- [[Netty-UsingBasicSSLTLSconfigurationontheJettyComponent]] Using Basic SSL/TLS configuration on the Jetty Component [source,java] ---- Registry registry = context.getRegistry(); registry.bind(""password"", ""changeit""); registry.bind(""ksf"", new File(""src/test/resources/keystore.jks"")); registry.bind(""tsf"", new File(""src/test/resources/keystore.jks"")); context.addRoutes(new RouteBuilder() { public void configure() { String netty_ssl_endpoint = ""netty:tcp://0.0.0.0:5150?sync=true&ssl=true&passphrase=#password"" + ""&keyStoreFile=#ksf&trustStoreFile=#tsf""; String return_string = ""When You Go Home, Tell Them Of Us And Say,"" + ""For Your Tomorrow, We Gave Our Today.""; from(netty_ssl_endpoint) .process(new Processor() { public void process(Exchange exchange) throws Exception { exchange.getOut().setBody(return_string); } } } }); ---- [[Netty-GettingaccesstoSSLSessionandtheclientcertificate]] Getting access to SSLSession and the client certificate You can get access to the `javax.net.ssl.SSLSession` if you eg need to get details about the client certificate. When `ssl=true` then the xref:netty-component.adoc[Netty] component will store the `SSLSession` as a header on the Camel Message as shown below: [source,java] ---- SSLSession session = exchange.getIn().getHeader(NettyConstants.NETTY_SSL_SESSION, SSLSession.class); // get the first certificate which is client certificate javax.security.cert.X509Certificate cert = session.getPeerCertificateChain()[0]; Principal principal = cert.getSubjectDN(); ---- Remember to set `needClientAuth=true` to authenticate the client, otherwise `SSLSession` cannot access information about the client certificate, and you may get an exception `javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated`. You may also get this exception if the client certificate is expired or not valid etc. [TIP] ==== The option `sslClientCertHeaders` can be set to `true` which then enriches the Camel Message with headers having details about the client certificate. For example the subject name is readily available in the header `CamelNettySSLClientCertSubjectName`. ==== === Using Multiple Codecs In certain cases it may be necessary to add chains of encoders and decoders to the netty pipeline. To add multpile codecs to a camel netty endpoint the 'encoders' and 'decoders' uri parameters should be used. Like the 'encoder' and 'decoder' parameters they are used to supply references (lists of ChannelUpstreamHandlers and ChannelDownstreamHandlers) that should be added to the pipeline. Note that if encoders is specified then the encoder param will be ignored, similarly for decoders and the decoder param. [NOTE] ==== Read further above about using non shareable encoders/decoders. ==== The lists of codecs need to be added to the Camel's registry so they can be resolved when the endpoint is created. [source,java] ---- ChannelHandlerFactory lengthDecoder = ChannelHandlerFactories.newLengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4); StringDecoder stringDecoder = new StringDecoder(); registry.bind(""length-decoder"", lengthDecoder); registry.bind(""string-decoder"", stringDecoder); LengthFieldPrepender lengthEncoder = new LengthFieldPrepender(4); StringEncoder stringEncoder = new StringEncoder(); registry.bind(""length-encoder"", lengthEncoder); registry.bind(""string-encoder"", stringEncoder); List decoders = new ArrayList(); decoders.add(lengthDecoder); decoders.add(stringDecoder); List encoders = new ArrayList(); encoders.add(lengthEncoder); encoders.add(stringEncoder); registry.bind(""encoders"", encoders); registry.bind(""decoders"", decoders); ---- Spring's native collections support can be used to specify the codec lists in an application context [source,xml] ---- ---- The bean names can then be used in netty endpoint definitions either as a comma separated list or contained in a List e.g. [source,java] ---- from(""direct:multiple-codec"").to(""netty:tcp://0.0.0.0:{{port}}?encoders=#encoders&sync=false""); from(""netty:tcp://0.0.0.0:{{port}}?decoders=#length-decoder,#string-decoder&sync=false"").to(""mock:multiple-codec""); ---- or via XML. [source,xml] ---- ---- == Closing Channel When Complete When acting as a server you sometimes want to close the channel when, for example, a client conversion is finished. + You can do this by simply setting the endpoint option `disconnect=true`. However you can also instruct Camel on a per message basis as follows. + To instruct Camel to close the channel, you should add a header with the key `CamelNettyCloseChannelWhenComplete` set to a boolean `true` value. + For instance, the example below will close the channel after it has written the bye message back to the client: [source,java] ---- from(""netty:tcp://0.0.0.0:8080"").process(new Processor() { public void process(Exchange exchange) throws Exception { String body = exchange.getIn().getBody(String.class); exchange.getOut().setBody(""Bye "" + body); // some condition which determines if we should close if (close) { exchange.getOut().setHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, true); } } }); ---- [[Netty-Addingcustomchannelpipelinefactoriestogaincompletecontroloveracreatedpipeline]] Adding custom channel pipeline factories to gain complete control over a created pipeline == Custom pipeline Custom channel pipelines provide complete control to the user over the handler/interceptor chain by inserting custom handler(s), encoder(s) & decoder(s) without having to specify them in the Netty Endpoint URL in a very simple way. In order to add a custom pipeline, a custom channel pipeline factory must be created and registered with the context via the context registry (Registry, or the camel-spring ApplicationContextRegistry etc). A custom pipeline factory must be constructed as follows * A Producer linked channel pipeline factory must extend the abstract class `ClientPipelineFactory`. * A Consumer linked channel pipeline factory must extend the abstract class `ServerInitializerFactory`. * The classes should override the initChannel() method in order to insert custom handler(s), encoder(s) and decoder(s). Not overriding the `initChannel()` method creates a pipeline with no handlers, encoders or decoders wired to the pipeline. The example below shows how ServerInitializerFactory factory may be created === Using custom pipeline factory [source,java] ---- public class SampleServerInitializerFactory extends ServerInitializerFactory { private int maxLineSize = 1024; protected void initChannel(Channel ch) throws Exception { ChannelPipeline channelPipeline = ch.pipeline(); channelPipeline.addLast(""encoder-SD"", new StringEncoder(CharsetUtil.UTF_8)); channelPipeline.addLast(""decoder-DELIM"", new DelimiterBasedFrameDecoder(maxLineSize, true, Delimiters.lineDelimiter())); channelPipeline.addLast(""decoder-SD"", new StringDecoder(CharsetUtil.UTF_8)); // here we add the default Camel ServerChannelHandler for the consumer, to allow Camel to route the message etc. channelPipeline.addLast(""handler"", new ServerChannelHandler(consumer)); } } ---- The custom channel pipeline factory can then be added to the registry and instantiated/utilized on a camel route in the following way [source,java] ---- Registry registry = camelContext.getRegistry(); ServerInitializerFactory factory = new TestServerInitializerFactory(); registry.bind(""spf"", factory); context.addRoutes(new RouteBuilder() { public void configure() { String netty_ssl_endpoint = ""netty:tcp://0.0.0.0:5150?serverInitializerFactory=#spf"" String return_string = ""When You Go Home, Tell Them Of Us And Say,"" + ""For Your Tomorrow, We Gave Our Today.""; from(netty_ssl_endpoint) .process(new Processor() { public void process(Exchange exchange) throws Exception { exchange.getOut().setBody(return_string); } } } }); ---- == Reusing Netty boss and worker thread pools Netty has two kind of thread pools: boss and worker. By default each Netty consumer and producer has their private thread pools. If you want to reuse these thread pools among multiple consumers or producers then the thread pools must be created and enlisted in the Registry. For example using Spring XML we can create a shared worker thread pool using the `NettyWorkerPoolBuilder` with 2 worker threads as shown below: [source,xml] ---- ---- [TIP] ==== For boss thread pool there is a `org.apache.camel.component.netty.NettyServerBossPoolBuilder` builder for Netty consumers, and a `org.apache.camel.component.netty.NettyClientBossPoolBuilder` for the Netty producers. ==== Then in the Camel routes we can refer to this worker pools by configuring the `workerPool` option in the URI as shown below: [source,xml] ---- ... ---- And if we have another route we can refer to the shared worker pool: [source,xml] ---- ... ---- and so forth. == Multiplexing concurrent messages over a single connection with request/reply When using Netty for request/reply messaging via the netty producer then by default each message is sent via a non-shared connection (pooled). This ensures that replies are automatic being able to map to the correct request thread for further routing in Camel. In other words correlation between request/reply messages happens out-of-the-box because the replies comes back on the same connection that was used for sending the request; and this connection is not shared with others. When the response comes back, the connection is returned back to the connection pool, where it can be reused by others. However if you want to multiplex concurrent request/responses on a single shared connection, then you need to turn off the connection pooling by setting `producerPoolEnabled=false`. Now this means there is a potential issue with interleaved responses if replies comes back out-of-order. Therefore you need to have a correlation id in both the request and reply messages so you can properly correlate the replies to the Camel callback that is responsible for continue processing the message in Camel. To do this you need to implement `NettyCamelStateCorrelationManager` as correlation manager and configure it via the `correlationManager=#myManager` option. [NOTE] ==== We recommend extending the `TimeoutCorrelationManagerSupport` when you build custom correlation managers. This provides support for timeout and other complexities you otherwise would need to implement as well. ==== You can find an example with the Apache Camel source code in the examples directory under the `camel-example-netty-custom-correlation` directory. include::camel-spring-boot::page$netty-starter.adoc[] ",12399,False,2343.712116374031,median "class ZCL_TE_FLIGHT_DPC definition public inheriting from /IWBEP/CL_MGW_PUSH_ABS_DATA abstract create public . public section. interfaces /IWBEP/IF_SB_DPC_COMM_SERVICES . interfaces /IWBEP/IF_SB_GEN_DPC_INJECTION . interfaces IF_SADL_GW_DPC_UTIL . methods /IWBEP/IF_MGW_APPL_SRV_RUNTIME~GET_ENTITYSET redefinition . methods /IWBEP/IF_MGW_APPL_SRV_RUNTIME~GET_ENTITY redefinition . methods /IWBEP/IF_MGW_APPL_SRV_RUNTIME~UPDATE_ENTITY redefinition . methods /IWBEP/IF_MGW_APPL_SRV_RUNTIME~CREATE_ENTITY redefinition . methods /IWBEP/IF_MGW_APPL_SRV_RUNTIME~DELETE_ENTITY redefinition . methods /IWBEP/IF_MGW_APPL_SRV_RUNTIME~CHANGESET_BEGIN redefinition . methods /IWBEP/IF_MGW_APPL_SRV_RUNTIME~CHANGESET_PROCESS redefinition . methods /IWBEP/IF_MGW_APPL_SRV_RUNTIME~CREATE_DEEP_ENTITY redefinition . methods /IWBEP/IF_MGW_APPL_SRV_RUNTIME~EXECUTE_ACTION redefinition . methods /IWBEP/IF_MGW_APPL_SRV_RUNTIME~GET_EXPANDED_ENTITY redefinition . methods /IWBEP/IF_MGW_APPL_SRV_RUNTIME~GET_EXPANDED_ENTITYSET redefinition . methods /IWBEP/IF_MGW_APPL_SRV_RUNTIME~PATCH_ENTITY redefinition . protected section. data mo_injection type ref to /IWBEP/IF_SB_GEN_DPC_INJECTION . methods ZI_TE_CONNECTION_UPDATE_ENTITY importing !IV_ENTITY_NAME type STRING !IV_ENTITY_SET_NAME type STRING !IV_SOURCE_NAME type STRING !IT_KEY_TAB type /IWBEP/T_MGW_NAME_VALUE_PAIR !IO_TECH_REQUEST_CONTEXT type ref to /IWBEP/IF_MGW_REQ_ENTITY_U optional !IT_NAVIGATION_PATH type /IWBEP/T_MGW_NAVIGATION_PATH !IO_DATA_PROVIDER type ref to /IWBEP/IF_MGW_ENTRY_PROVIDER optional exporting !ER_ENTITY type ZCL_TE_FLIGHT_MPC=>TS_ZI_TE_CONNECTIONTYPE raising /IWBEP/CX_MGW_BUSI_EXCEPTION /IWBEP/CX_MGW_TECH_EXCEPTION . methods ZI_TE_CONNECTION_GET_ENTITYSET importing !IV_ENTITY_NAME type STRING !IV_ENTITY_SET_NAME type STRING !IV_SOURCE_NAME type STRING !IT_FILTER_SELECT_OPTIONS type /IWBEP/T_MGW_SELECT_OPTION !IS_PAGING type /IWBEP/S_MGW_PAGING !IT_KEY_TAB type /IWBEP/T_MGW_NAME_VALUE_PAIR !IT_NAVIGATION_PATH type /IWBEP/T_MGW_NAVIGATION_PATH !IT_ORDER type /IWBEP/T_MGW_SORTING_ORDER !IV_FILTER_STRING type STRING !IV_SEARCH_STRING type STRING !IO_TECH_REQUEST_CONTEXT type ref to /IWBEP/IF_MGW_REQ_ENTITYSET optional exporting !ET_ENTITYSET type ZCL_TE_FLIGHT_MPC=>TT_ZI_TE_CONNECTIONTYPE !ES_RESPONSE_CONTEXT type /IWBEP/IF_MGW_APPL_SRV_RUNTIME=>TY_S_MGW_RESPONSE_CONTEXT raising /IWBEP/CX_MGW_BUSI_EXCEPTION /IWBEP/CX_MGW_TECH_EXCEPTION . methods ZI_TE_CONNECTION_GET_ENTITY importing !IV_ENTITY_NAME type STRING !IV_ENTITY_SET_NAME type STRING !IV_SOURCE_NAME type STRING !IT_KEY_TAB type /IWBEP/T_MGW_NAME_VALUE_PAIR !IO_REQUEST_OBJECT type ref to /IWBEP/IF_MGW_REQ_ENTITY optional !IO_TECH_REQUEST_CONTEXT type ref to /IWBEP/IF_MGW_REQ_ENTITY optional !IT_NAVIGATION_PATH type /IWBEP/T_MGW_NAVIGATION_PATH exporting !ER_ENTITY type ZCL_TE_FLIGHT_MPC=>TS_ZI_TE_CONNECTIONTYPE !ES_RESPONSE_CONTEXT type /IWBEP/IF_MGW_APPL_SRV_RUNTIME=>TY_S_MGW_RESPONSE_ENTITY_CNTXT raising /IWBEP/CX_MGW_BUSI_EXCEPTION /IWBEP/CX_MGW_TECH_EXCEPTION . methods ZI_TE_CONNECTION_DELETE_ENTITY importing !IV_ENTITY_NAME type STRING !IV_ENTITY_SET_NAME type STRING !IV_SOURCE_NAME type STRING !IT_KEY_TAB type /IWBEP/T_MGW_NAME_VALUE_PAIR !IO_TECH_REQUEST_CONTEXT type ref to /IWBEP/IF_MGW_REQ_ENTITY_D optional !IT_NAVIGATION_PATH type /IWBEP/T_MGW_NAVIGATION_PATH raising /IWBEP/CX_MGW_BUSI_EXCEPTION /IWBEP/CX_MGW_TECH_EXCEPTION . methods ZI_TE_CONNECTION_CREATE_ENTITY importing !IV_ENTITY_NAME type STRING !IV_ENTITY_SET_NAME type STRING !IV_SOURCE_NAME type STRING !IT_KEY_TAB type /IWBEP/T_MGW_NAME_VALUE_PAIR !IO_TECH_REQUEST_CONTEXT type ref to /IWBEP/IF_MGW_REQ_ENTITY_C optional !IT_NAVIGATION_PATH type /IWBEP/T_MGW_NAVIGATION_PATH !IO_DATA_PROVIDER type ref to /IWBEP/IF_MGW_ENTRY_PROVIDER optional exporting !ER_ENTITY type ZCL_TE_FLIGHT_MPC=>TS_ZI_TE_CONNECTIONTYPE raising /IWBEP/CX_MGW_BUSI_EXCEPTION /IWBEP/CX_MGW_TECH_EXCEPTION . methods ZI_TE_CARRIER_UPDATE_ENTITY importing !IV_ENTITY_NAME type STRING !IV_ENTITY_SET_NAME type STRING !IV_SOURCE_NAME type STRING !IT_KEY_TAB type /IWBEP/T_MGW_NAME_VALUE_PAIR !IO_TECH_REQUEST_CONTEXT type ref to /IWBEP/IF_MGW_REQ_ENTITY_U optional !IT_NAVIGATION_PATH type /IWBEP/T_MGW_NAVIGATION_PATH !IO_DATA_PROVIDER type ref to /IWBEP/IF_MGW_ENTRY_PROVIDER optional exporting !ER_ENTITY type ZCL_TE_FLIGHT_MPC=>TS_ZI_TE_CARRIERTYPE raising /IWBEP/CX_MGW_BUSI_EXCEPTION /IWBEP/CX_MGW_TECH_EXCEPTION . methods ZI_TE_CARRIER_GET_ENTITYSET importing !IV_ENTITY_NAME type STRING !IV_ENTITY_SET_NAME type STRING !IV_SOURCE_NAME type STRING !IT_FILTER_SELECT_OPTIONS type /IWBEP/T_MGW_SELECT_OPTION !IS_PAGING type /IWBEP/S_MGW_PAGING !IT_KEY_TAB type /IWBEP/T_MGW_NAME_VALUE_PAIR !IT_NAVIGATION_PATH type /IWBEP/T_MGW_NAVIGATION_PATH !IT_ORDER type /IWBEP/T_MGW_SORTING_ORDER !IV_FILTER_STRING type STRING !IV_SEARCH_STRING type STRING !IO_TECH_REQUEST_CONTEXT type ref to /IWBEP/IF_MGW_REQ_ENTITYSET optional exporting !ET_ENTITYSET type ZCL_TE_FLIGHT_MPC=>TT_ZI_TE_CARRIERTYPE !ES_RESPONSE_CONTEXT type /IWBEP/IF_MGW_APPL_SRV_RUNTIME=>TY_S_MGW_RESPONSE_CONTEXT raising /IWBEP/CX_MGW_BUSI_EXCEPTION /IWBEP/CX_MGW_TECH_EXCEPTION . methods ZI_TE_CARRIER_GET_ENTITY importing !IV_ENTITY_NAME type STRING !IV_ENTITY_SET_NAME type STRING !IV_SOURCE_NAME type STRING !IT_KEY_TAB type /IWBEP/T_MGW_NAME_VALUE_PAIR !IO_REQUEST_OBJECT type ref to /IWBEP/IF_MGW_REQ_ENTITY optional !IO_TECH_REQUEST_CONTEXT type ref to /IWBEP/IF_MGW_REQ_ENTITY optional !IT_NAVIGATION_PATH type /IWBEP/T_MGW_NAVIGATION_PATH exporting !ER_ENTITY type ZCL_TE_FLIGHT_MPC=>TS_ZI_TE_CARRIERTYPE !ES_RESPONSE_CONTEXT type /IWBEP/IF_MGW_APPL_SRV_RUNTIME=>TY_S_MGW_RESPONSE_ENTITY_CNTXT raising /IWBEP/CX_MGW_BUSI_EXCEPTION /IWBEP/CX_MGW_TECH_EXCEPTION . methods ZI_TE_CARRIER_DELETE_ENTITY importing !IV_ENTITY_NAME type STRING !IV_ENTITY_SET_NAME type STRING !IV_SOURCE_NAME type STRING !IT_KEY_TAB type /IWBEP/T_MGW_NAME_VALUE_PAIR !IO_TECH_REQUEST_CONTEXT type ref to /IWBEP/IF_MGW_REQ_ENTITY_D optional !IT_NAVIGATION_PATH type /IWBEP/T_MGW_NAVIGATION_PATH raising /IWBEP/CX_MGW_BUSI_EXCEPTION /IWBEP/CX_MGW_TECH_EXCEPTION . methods ZI_TE_CARRIER_CREATE_ENTITY importing !IV_ENTITY_NAME type STRING !IV_ENTITY_SET_NAME type STRING !IV_SOURCE_NAME type STRING !IT_KEY_TAB type /IWBEP/T_MGW_NAME_VALUE_PAIR !IO_TECH_REQUEST_CONTEXT type ref to /IWBEP/IF_MGW_REQ_ENTITY_C optional !IT_NAVIGATION_PATH type /IWBEP/T_MGW_NAVIGATION_PATH !IO_DATA_PROVIDER type ref to /IWBEP/IF_MGW_ENTRY_PROVIDER optional exporting !ER_ENTITY type ZCL_TE_FLIGHT_MPC=>TS_ZI_TE_CARRIERTYPE raising /IWBEP/CX_MGW_BUSI_EXCEPTION /IWBEP/CX_MGW_TECH_EXCEPTION . methods ZI_TE_AIRPORT_UPDATE_ENTITY importing !IV_ENTITY_NAME type STRING !IV_ENTITY_SET_NAME type STRING !IV_SOURCE_NAME type STRING !IT_KEY_TAB type /IWBEP/T_MGW_NAME_VALUE_PAIR !IO_TECH_REQUEST_CONTEXT type ref to /IWBEP/IF_MGW_REQ_ENTITY_U optional !IT_NAVIGATION_PATH type /IWBEP/T_MGW_NAVIGATION_PATH !IO_DATA_PROVIDER type ref to /IWBEP/IF_MGW_ENTRY_PROVIDER optional exporting !ER_ENTITY type ZCL_TE_FLIGHT_MPC=>TS_ZI_TE_AIRPORTTYPE raising /IWBEP/CX_MGW_BUSI_EXCEPTION /IWBEP/CX_MGW_TECH_EXCEPTION . methods ZI_TE_AIRPORT_GET_ENTITYSET importing !IV_ENTITY_NAME type STRING !IV_ENTITY_SET_NAME type STRING !IV_SOURCE_NAME type STRING !IT_FILTER_SELECT_OPTIONS type /IWBEP/T_MGW_SELECT_OPTION !IS_PAGING type /IWBEP/S_MGW_PAGING !IT_KEY_TAB type /IWBEP/T_MGW_NAME_VALUE_PAIR !IT_NAVIGATION_PATH type /IWBEP/T_MGW_NAVIGATION_PATH !IT_ORDER type /IWBEP/T_MGW_SORTING_ORDER !IV_FILTER_STRING type STRING !IV_SEARCH_STRING type STRING !IO_TECH_REQUEST_CONTEXT type ref to /IWBEP/IF_MGW_REQ_ENTITYSET optional exporting !ET_ENTITYSET type ZCL_TE_FLIGHT_MPC=>TT_ZI_TE_AIRPORTTYPE !ES_RESPONSE_CONTEXT type /IWBEP/IF_MGW_APPL_SRV_RUNTIME=>TY_S_MGW_RESPONSE_CONTEXT raising /IWBEP/CX_MGW_BUSI_EXCEPTION /IWBEP/CX_MGW_TECH_EXCEPTION . methods ZI_TE_AIRPORT_GET_ENTITY importing !IV_ENTITY_NAME type STRING !IV_ENTITY_SET_NAME type STRING !IV_SOURCE_NAME type STRING !IT_KEY_TAB type /IWBEP/T_MGW_NAME_VALUE_PAIR !IO_REQUEST_OBJECT type ref to /IWBEP/IF_MGW_REQ_ENTITY optional !IO_TECH_REQUEST_CONTEXT type ref to /IWBEP/IF_MGW_REQ_ENTITY optional !IT_NAVIGATION_PATH type /IWBEP/T_MGW_NAVIGATION_PATH exporting !ER_ENTITY type ZCL_TE_FLIGHT_MPC=>TS_ZI_TE_AIRPORTTYPE !ES_RESPONSE_CONTEXT type /IWBEP/IF_MGW_APPL_SRV_RUNTIME=>TY_S_MGW_RESPONSE_ENTITY_CNTXT raising /IWBEP/CX_MGW_BUSI_EXCEPTION /IWBEP/CX_MGW_TECH_EXCEPTION . methods ZI_TE_AIRPORT_DELETE_ENTITY importing !IV_ENTITY_NAME type STRING !IV_ENTITY_SET_NAME type STRING !IV_SOURCE_NAME type STRING !IT_KEY_TAB type /IWBEP/T_MGW_NAME_VALUE_PAIR !IO_TECH_REQUEST_CONTEXT type ref to /IWBEP/IF_MGW_REQ_ENTITY_D optional !IT_NAVIGATION_PATH type /IWBEP/T_MGW_NAVIGATION_PATH raising /IWBEP/CX_MGW_BUSI_EXCEPTION /IWBEP/CX_MGW_TECH_EXCEPTION . methods ZI_TE_AIRPORT_CREATE_ENTITY importing !IV_ENTITY_NAME type STRING !IV_ENTITY_SET_NAME type STRING !IV_SOURCE_NAME type STRING !IT_KEY_TAB type /IWBEP/T_MGW_NAME_VALUE_PAIR !IO_TECH_REQUEST_CONTEXT type ref to /IWBEP/IF_MGW_REQ_ENTITY_C optional !IT_NAVIGATION_PATH type /IWBEP/T_MGW_NAVIGATION_PATH !IO_DATA_PROVIDER type ref to /IWBEP/IF_MGW_ENTRY_PROVIDER optional exporting !ER_ENTITY type ZCL_TE_FLIGHT_MPC=>TS_ZI_TE_AIRPORTTYPE raising /IWBEP/CX_MGW_BUSI_EXCEPTION /IWBEP/CX_MGW_TECH_EXCEPTION . methods ZC_TE_FLIGHT_UPDATE_ENTITY importing !IV_ENTITY_NAME type STRING !IV_ENTITY_SET_NAME type STRING !IV_SOURCE_NAME type STRING !IT_KEY_TAB type /IWBEP/T_MGW_NAME_VALUE_PAIR !IO_TECH_REQUEST_CONTEXT type ref to /IWBEP/IF_MGW_REQ_ENTITY_U optional !IT_NAVIGATION_PATH type /IWBEP/T_MGW_NAVIGATION_PATH !IO_DATA_PROVIDER type ref to /IWBEP/IF_MGW_ENTRY_PROVIDER optional exporting !ER_ENTITY type ZCL_TE_FLIGHT_MPC=>TS_ZC_TE_FLIGHTTYPE raising /IWBEP/CX_MGW_BUSI_EXCEPTION /IWBEP/CX_MGW_TECH_EXCEPTION . methods ZC_TE_FLIGHT_GET_ENTITYSET importing !IV_ENTITY_NAME type STRING !IV_ENTITY_SET_NAME type STRING !IV_SOURCE_NAME type STRING !IT_FILTER_SELECT_OPTIONS type /IWBEP/T_MGW_SELECT_OPTION !IS_PAGING type /IWBEP/S_MGW_PAGING !IT_KEY_TAB type /IWBEP/T_MGW_NAME_VALUE_PAIR !IT_NAVIGATION_PATH type /IWBEP/T_MGW_NAVIGATION_PATH !IT_ORDER type /IWBEP/T_MGW_SORTING_ORDER !IV_FILTER_STRING type STRING !IV_SEARCH_STRING type STRING !IO_TECH_REQUEST_CONTEXT type ref to /IWBEP/IF_MGW_REQ_ENTITYSET optional exporting !ET_ENTITYSET type ZCL_TE_FLIGHT_MPC=>TT_ZC_TE_FLIGHTTYPE !ES_RESPONSE_CONTEXT type /IWBEP/IF_MGW_APPL_SRV_RUNTIME=>TY_S_MGW_RESPONSE_CONTEXT raising /IWBEP/CX_MGW_BUSI_EXCEPTION /IWBEP/CX_MGW_TECH_EXCEPTION . methods ZC_TE_FLIGHT_GET_ENTITY importing !IV_ENTITY_NAME type STRING !IV_ENTITY_SET_NAME type STRING !IV_SOURCE_NAME type STRING !IT_KEY_TAB type /IWBEP/T_MGW_NAME_VALUE_PAIR !IO_REQUEST_OBJECT type ref to /IWBEP/IF_MGW_REQ_ENTITY optional !IO_TECH_REQUEST_CONTEXT type ref to /IWBEP/IF_MGW_REQ_ENTITY optional !IT_NAVIGATION_PATH type /IWBEP/T_MGW_NAVIGATION_PATH exporting !ER_ENTITY type ZCL_TE_FLIGHT_MPC=>TS_ZC_TE_FLIGHTTYPE !ES_RESPONSE_CONTEXT type /IWBEP/IF_MGW_APPL_SRV_RUNTIME=>TY_S_MGW_RESPONSE_ENTITY_CNTXT raising /IWBEP/CX_MGW_BUSI_EXCEPTION /IWBEP/CX_MGW_TECH_EXCEPTION . methods ZC_TE_FLIGHT_DELETE_ENTITY importing !IV_ENTITY_NAME type STRING !IV_ENTITY_SET_NAME type STRING !IV_SOURCE_NAME type STRING !IT_KEY_TAB type /IWBEP/T_MGW_NAME_VALUE_PAIR !IO_TECH_REQUEST_CONTEXT type ref to /IWBEP/IF_MGW_REQ_ENTITY_D optional !IT_NAVIGATION_PATH type /IWBEP/T_MGW_NAVIGATION_PATH raising /IWBEP/CX_MGW_BUSI_EXCEPTION /IWBEP/CX_MGW_TECH_EXCEPTION . methods ZC_TE_FLIGHT_CREATE_ENTITY importing !IV_ENTITY_NAME type STRING !IV_ENTITY_SET_NAME type STRING !IV_SOURCE_NAME type STRING !IT_KEY_TAB type /IWBEP/T_MGW_NAME_VALUE_PAIR !IO_TECH_REQUEST_CONTEXT type ref to /IWBEP/IF_MGW_REQ_ENTITY_C optional !IT_NAVIGATION_PATH type /IWBEP/T_MGW_NAVIGATION_PATH !IO_DATA_PROVIDER type ref to /IWBEP/IF_MGW_ENTRY_PROVIDER optional exporting !ER_ENTITY type ZCL_TE_FLIGHT_MPC=>TS_ZC_TE_FLIGHTTYPE raising /IWBEP/CX_MGW_BUSI_EXCEPTION /IWBEP/CX_MGW_TECH_EXCEPTION . methods ZC_TE_BOOKINGS_UPDATE_ENTITY importing !IV_ENTITY_NAME type STRING !IV_ENTITY_SET_NAME type STRING !IV_SOURCE_NAME type STRING !IT_KEY_TAB type /IWBEP/T_MGW_NAME_VALUE_PAIR !IO_TECH_REQUEST_CONTEXT type ref to /IWBEP/IF_MGW_REQ_ENTITY_U optional !IT_NAVIGATION_PATH type /IWBEP/T_MGW_NAVIGATION_PATH !IO_DATA_PROVIDER type ref to /IWBEP/IF_MGW_ENTRY_PROVIDER optional exporting !ER_ENTITY type ZCL_TE_FLIGHT_MPC=>TS_ZC_TE_BOOKINGSTYPE raising /IWBEP/CX_MGW_BUSI_EXCEPTION /IWBEP/CX_MGW_TECH_EXCEPTION . methods ZC_TE_BOOKINGS_GET_ENTITYSET importing !IV_ENTITY_NAME type STRING !IV_ENTITY_SET_NAME type STRING !IV_SOURCE_NAME type STRING !IT_FILTER_SELECT_OPTIONS type /IWBEP/T_MGW_SELECT_OPTION !IS_PAGING type /IWBEP/S_MGW_PAGING !IT_KEY_TAB type /IWBEP/T_MGW_NAME_VALUE_PAIR !IT_NAVIGATION_PATH type /IWBEP/T_MGW_NAVIGATION_PATH !IT_ORDER type /IWBEP/T_MGW_SORTING_ORDER !IV_FILTER_STRING type STRING !IV_SEARCH_STRING type STRING !IO_TECH_REQUEST_CONTEXT type ref to /IWBEP/IF_MGW_REQ_ENTITYSET optional exporting !ET_ENTITYSET type ZCL_TE_FLIGHT_MPC=>TT_ZC_TE_BOOKINGSTYPE !ES_RESPONSE_CONTEXT type /IWBEP/IF_MGW_APPL_SRV_RUNTIME=>TY_S_MGW_RESPONSE_CONTEXT raising /IWBEP/CX_MGW_BUSI_EXCEPTION /IWBEP/CX_MGW_TECH_EXCEPTION . methods ZC_TE_BOOKINGS_GET_ENTITY importing !IV_ENTITY_NAME type STRING !IV_ENTITY_SET_NAME type STRING !IV_SOURCE_NAME type STRING !IT_KEY_TAB type /IWBEP/T_MGW_NAME_VALUE_PAIR !IO_REQUEST_OBJECT type ref to /IWBEP/IF_MGW_REQ_ENTITY optional !IO_TECH_REQUEST_CONTEXT type ref to /IWBEP/IF_MGW_REQ_ENTITY optional !IT_NAVIGATION_PATH type /IWBEP/T_MGW_NAVIGATION_PATH exporting !ER_ENTITY type ZCL_TE_FLIGHT_MPC=>TS_ZC_TE_BOOKINGSTYPE !ES_RESPONSE_CONTEXT type /IWBEP/IF_MGW_APPL_SRV_RUNTIME=>TY_S_MGW_RESPONSE_ENTITY_CNTXT raising /IWBEP/CX_MGW_BUSI_EXCEPTION /IWBEP/CX_MGW_TECH_EXCEPTION . methods ZC_TE_BOOKINGS_DELETE_ENTITY importing !IV_ENTITY_NAME type STRING !IV_ENTITY_SET_NAME type STRING !IV_SOURCE_NAME type STRING !IT_KEY_TAB type /IWBEP/T_MGW_NAME_VALUE_PAIR !IO_TECH_REQUEST_CONTEXT type ref to /IWBEP/IF_MGW_REQ_ENTITY_D optional !IT_NAVIGATION_PATH type /IWBEP/T_MGW_NAVIGATION_PATH raising /IWBEP/CX_MGW_BUSI_EXCEPTION /IWBEP/CX_MGW_TECH_EXCEPTION . methods ZC_TE_BOOKINGS_CREATE_ENTITY importing !IV_ENTITY_NAME type STRING !IV_ENTITY_SET_NAME type STRING !IV_SOURCE_NAME type STRING !IT_KEY_TAB type /IWBEP/T_MGW_NAME_VALUE_PAIR !IO_TECH_REQUEST_CONTEXT type ref to /IWBEP/IF_MGW_REQ_ENTITY_C optional !IT_NAVIGATION_PATH type /IWBEP/T_MGW_NAVIGATION_PATH !IO_DATA_PROVIDER type ref to /IWBEP/IF_MGW_ENTRY_PROVIDER optional exporting !ER_ENTITY type ZCL_TE_FLIGHT_MPC=>TS_ZC_TE_BOOKINGSTYPE raising /IWBEP/CX_MGW_BUSI_EXCEPTION /IWBEP/CX_MGW_TECH_EXCEPTION . methods CHECK_SUBSCRIPTION_AUTHORITY redefinition . private section. ENDCLASS. CLASS ZCL_TE_FLIGHT_DPC IMPLEMENTATION. method /IWBEP/IF_MGW_APPL_SRV_RUNTIME~CHANGESET_BEGIN. if_sadl_gw_dpc_util~get_dpc( )->begin_changeset( EXPORTING it_operation_info = it_operation_info CHANGING cv_defer_mode = cv_defer_mode ). endmethod. method /IWBEP/IF_MGW_APPL_SRV_RUNTIME~CHANGESET_PROCESS. if_sadl_gw_dpc_util~get_dpc( )->process_changeset( EXPORTING it_changeset_request = it_changeset_request CHANGING ct_changeset_response = ct_changeset_response ). endmethod. method /IWBEP/IF_MGW_APPL_SRV_RUNTIME~CREATE_DEEP_ENTITY. CAST /iwbep/if_mgw_appl_srv_runtime( if_sadl_gw_dpc_util~get_dpc( ) )->create_deep_entity( EXPORTING io_tech_request_context = io_tech_request_context io_data_provider = io_data_provider io_expand = io_expand IMPORTING er_deep_entity = er_deep_entity ). endmethod. method /IWBEP/IF_MGW_APPL_SRV_RUNTIME~CREATE_ENTITY. *&----------------------------------------------------------------------------------------------* *& Include /IWBEP/DPC_TEMP_CRT_ENTITY_BASE *&* This class has been generated on 16.08.2017 19:12:50 in client 001 *&* *&* WARNING--> NEVER MODIFY THIS CLASS <--WARNING *&* If you want to change the DPC implementation, use the *&* generated methods inside the DPC provider subclass - ZCL_TE_FLIGHT_DPC_EXT *&-----------------------------------------------------------------------------------------------* DATA zc_te_bookings_create_entity TYPE zcl_te_flight_mpc=>ts_zc_te_bookingstype. DATA zi_te_airport_create_entity TYPE zcl_te_flight_mpc=>ts_zi_te_airporttype. DATA zi_te_carrier_create_entity TYPE zcl_te_flight_mpc=>ts_zi_te_carriertype. DATA zi_te_connection_create_entity TYPE zcl_te_flight_mpc=>ts_zi_te_connectiontype. DATA zc_te_flight_create_entity TYPE zcl_te_flight_mpc=>ts_zc_te_flighttype. DATA lv_entityset_name TYPE string. lv_entityset_name = io_tech_request_context->get_entity_set_name( ). CASE lv_entityset_name. *-------------------------------------------------------------------------* * EntitySet - Zc_Te_Bookings *-------------------------------------------------------------------------* WHEN 'Zc_Te_Bookings'. * Call the entity set generated method zc_te_bookings_create_entity( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name io_data_provider = io_data_provider it_key_tab = it_key_tab it_navigation_path = it_navigation_path io_tech_request_context = io_tech_request_context IMPORTING er_entity = zc_te_bookings_create_entity ). * Send specific entity data to the caller interfaces copy_data_to_ref( EXPORTING is_data = zc_te_bookings_create_entity CHANGING cr_data = er_entity ). *-------------------------------------------------------------------------* * EntitySet - Zi_Te_Airport *-------------------------------------------------------------------------* WHEN 'Zi_Te_Airport'. * Call the entity set generated method zi_te_airport_create_entity( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name io_data_provider = io_data_provider it_key_tab = it_key_tab it_navigation_path = it_navigation_path io_tech_request_context = io_tech_request_context IMPORTING er_entity = zi_te_airport_create_entity ). * Send specific entity data to the caller interfaces copy_data_to_ref( EXPORTING is_data = zi_te_airport_create_entity CHANGING cr_data = er_entity ). *-------------------------------------------------------------------------* * EntitySet - Zi_Te_Carrier *-------------------------------------------------------------------------* WHEN 'Zi_Te_Carrier'. * Call the entity set generated method zi_te_carrier_create_entity( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name io_data_provider = io_data_provider it_key_tab = it_key_tab it_navigation_path = it_navigation_path io_tech_request_context = io_tech_request_context IMPORTING er_entity = zi_te_carrier_create_entity ). * Send specific entity data to the caller interfaces copy_data_to_ref( EXPORTING is_data = zi_te_carrier_create_entity CHANGING cr_data = er_entity ). *-------------------------------------------------------------------------* * EntitySet - Zi_Te_Connection *-------------------------------------------------------------------------* WHEN 'Zi_Te_Connection'. * Call the entity set generated method zi_te_connection_create_entity( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name io_data_provider = io_data_provider it_key_tab = it_key_tab it_navigation_path = it_navigation_path io_tech_request_context = io_tech_request_context IMPORTING er_entity = zi_te_connection_create_entity ). * Send specific entity data to the caller interfaces copy_data_to_ref( EXPORTING is_data = zi_te_connection_create_entity CHANGING cr_data = er_entity ). *-------------------------------------------------------------------------* * EntitySet - Zc_Te_Flight *-------------------------------------------------------------------------* WHEN 'Zc_Te_Flight'. * Call the entity set generated method zc_te_flight_create_entity( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name io_data_provider = io_data_provider it_key_tab = it_key_tab it_navigation_path = it_navigation_path io_tech_request_context = io_tech_request_context IMPORTING er_entity = zc_te_flight_create_entity ). * Send specific entity data to the caller interfaces copy_data_to_ref( EXPORTING is_data = zc_te_flight_create_entity CHANGING cr_data = er_entity ). when others. super->/iwbep/if_mgw_appl_srv_runtime~create_entity( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name io_data_provider = io_data_provider it_key_tab = it_key_tab it_navigation_path = it_navigation_path IMPORTING er_entity = er_entity ). ENDCASE. endmethod. method /IWBEP/IF_MGW_APPL_SRV_RUNTIME~DELETE_ENTITY. *&----------------------------------------------------------------------------------------------* *& Include /IWBEP/DPC_TEMP_DEL_ENTITY_BASE *&* This class has been generated on 16.08.2017 19:12:50 in client 001 *&* *&* WARNING--> NEVER MODIFY THIS CLASS <--WARNING *&* If you want to change the DPC implementation, use the *&* generated methods inside the DPC provider subclass - ZCL_TE_FLIGHT_DPC_EXT *&-----------------------------------------------------------------------------------------------* DATA lv_entityset_name TYPE string. lv_entityset_name = io_tech_request_context->get_entity_set_name( ). CASE lv_entityset_name. *-------------------------------------------------------------------------* * EntitySet - Zi_Te_Airport *-------------------------------------------------------------------------* when 'Zi_Te_Airport'. * Call the entity set generated method zi_te_airport_delete_entity( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name it_key_tab = it_key_tab it_navigation_path = it_navigation_path io_tech_request_context = io_tech_request_context ). *-------------------------------------------------------------------------* * EntitySet - Zc_Te_Bookings *-------------------------------------------------------------------------* when 'Zc_Te_Bookings'. * Call the entity set generated method zc_te_bookings_delete_entity( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name it_key_tab = it_key_tab it_navigation_path = it_navigation_path io_tech_request_context = io_tech_request_context ). *-------------------------------------------------------------------------* * EntitySet - Zi_Te_Carrier *-------------------------------------------------------------------------* when 'Zi_Te_Carrier'. * Call the entity set generated method zi_te_carrier_delete_entity( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name it_key_tab = it_key_tab it_navigation_path = it_navigation_path io_tech_request_context = io_tech_request_context ). *-------------------------------------------------------------------------* * EntitySet - Zi_Te_Connection *-------------------------------------------------------------------------* when 'Zi_Te_Connection'. * Call the entity set generated method zi_te_connection_delete_entity( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name it_key_tab = it_key_tab it_navigation_path = it_navigation_path io_tech_request_context = io_tech_request_context ). *-------------------------------------------------------------------------* * EntitySet - Zc_Te_Flight *-------------------------------------------------------------------------* when 'Zc_Te_Flight'. * Call the entity set generated method zc_te_flight_delete_entity( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name it_key_tab = it_key_tab it_navigation_path = it_navigation_path io_tech_request_context = io_tech_request_context ). when others. super->/iwbep/if_mgw_appl_srv_runtime~delete_entity( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name it_key_tab = it_key_tab it_navigation_path = it_navigation_path ). ENDCASE. endmethod. method /IWBEP/IF_MGW_APPL_SRV_RUNTIME~EXECUTE_ACTION. if_sadl_gw_dpc_util~get_dpc( )->execute_action( EXPORTING io_tech_request_context = io_tech_request_context IMPORTING er_data = er_data ). endmethod. method /IWBEP/IF_MGW_APPL_SRV_RUNTIME~GET_ENTITY. *&-----------------------------------------------------------------------------------------------* *& Include /IWBEP/DPC_TEMP_GETENTITY_BASE *&* This class has been generated on 16.08.2017 19:12:50 in client 001 *&* *&* WARNING--> NEVER MODIFY THIS CLASS <--WARNING *&* If you want to change the DPC implementation, use the *&* generated methods inside the DPC provider subclass - ZCL_TE_FLIGHT_DPC_EXT *&-----------------------------------------------------------------------------------------------* DATA zc_te_bookings_get_entity TYPE zcl_te_flight_mpc=>ts_zc_te_bookingstype. DATA zi_te_carrier_get_entity TYPE zcl_te_flight_mpc=>ts_zi_te_carriertype. DATA zi_te_connection_get_entity TYPE zcl_te_flight_mpc=>ts_zi_te_connectiontype. DATA zc_te_flight_get_entity TYPE zcl_te_flight_mpc=>ts_zc_te_flighttype. DATA zi_te_airport_get_entity TYPE zcl_te_flight_mpc=>ts_zi_te_airporttype. DATA lv_entityset_name TYPE string. DATA lr_entity TYPE REF TO data. lv_entityset_name = io_tech_request_context->get_entity_set_name( ). CASE lv_entityset_name. *-------------------------------------------------------------------------* * EntitySet - Zc_Te_Bookings *-------------------------------------------------------------------------* WHEN 'Zc_Te_Bookings'. * Call the entity set generated method zc_te_bookings_get_entity( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name it_key_tab = it_key_tab it_navigation_path = it_navigation_path io_tech_request_context = io_tech_request_context IMPORTING er_entity = zc_te_bookings_get_entity es_response_context = es_response_context ). IF zc_te_bookings_get_entity IS NOT INITIAL. * Send specific entity data to the caller interface copy_data_to_ref( EXPORTING is_data = zc_te_bookings_get_entity CHANGING cr_data = er_entity ). ELSE. * In case of initial values - unbind the entity reference er_entity = lr_entity. ENDIF. *-------------------------------------------------------------------------* * EntitySet - Zi_Te_Carrier *-------------------------------------------------------------------------* WHEN 'Zi_Te_Carrier'. * Call the entity set generated method zi_te_carrier_get_entity( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name it_key_tab = it_key_tab it_navigation_path = it_navigation_path io_tech_request_context = io_tech_request_context IMPORTING er_entity = zi_te_carrier_get_entity es_response_context = es_response_context ). IF zi_te_carrier_get_entity IS NOT INITIAL. * Send specific entity data to the caller interface copy_data_to_ref( EXPORTING is_data = zi_te_carrier_get_entity CHANGING cr_data = er_entity ). ELSE. * In case of initial values - unbind the entity reference er_entity = lr_entity. ENDIF. *-------------------------------------------------------------------------* * EntitySet - Zi_Te_Connection *-------------------------------------------------------------------------* WHEN 'Zi_Te_Connection'. * Call the entity set generated method zi_te_connection_get_entity( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name it_key_tab = it_key_tab it_navigation_path = it_navigation_path io_tech_request_context = io_tech_request_context IMPORTING er_entity = zi_te_connection_get_entity es_response_context = es_response_context ). IF zi_te_connection_get_entity IS NOT INITIAL. * Send specific entity data to the caller interface copy_data_to_ref( EXPORTING is_data = zi_te_connection_get_entity CHANGING cr_data = er_entity ). ELSE. * In case of initial values - unbind the entity reference er_entity = lr_entity. ENDIF. *-------------------------------------------------------------------------* * EntitySet - Zc_Te_Flight *-------------------------------------------------------------------------* WHEN 'Zc_Te_Flight'. * Call the entity set generated method zc_te_flight_get_entity( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name it_key_tab = it_key_tab it_navigation_path = it_navigation_path io_tech_request_context = io_tech_request_context IMPORTING er_entity = zc_te_flight_get_entity es_response_context = es_response_context ). IF zc_te_flight_get_entity IS NOT INITIAL. * Send specific entity data to the caller interface copy_data_to_ref( EXPORTING is_data = zc_te_flight_get_entity CHANGING cr_data = er_entity ). ELSE. * In case of initial values - unbind the entity reference er_entity = lr_entity. ENDIF. *-------------------------------------------------------------------------* * EntitySet - Zi_Te_Airport *-------------------------------------------------------------------------* WHEN 'Zi_Te_Airport'. * Call the entity set generated method zi_te_airport_get_entity( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name it_key_tab = it_key_tab it_navigation_path = it_navigation_path io_tech_request_context = io_tech_request_context IMPORTING er_entity = zi_te_airport_get_entity es_response_context = es_response_context ). IF zi_te_airport_get_entity IS NOT INITIAL. * Send specific entity data to the caller interface copy_data_to_ref( EXPORTING is_data = zi_te_airport_get_entity CHANGING cr_data = er_entity ). ELSE. * In case of initial values - unbind the entity reference er_entity = lr_entity. ENDIF. WHEN OTHERS. super->/iwbep/if_mgw_appl_srv_runtime~get_entity( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name it_key_tab = it_key_tab it_navigation_path = it_navigation_path IMPORTING er_entity = er_entity ). ENDCASE. endmethod. method /IWBEP/IF_MGW_APPL_SRV_RUNTIME~GET_ENTITYSET. *&----------------------------------------------------------------------------------------------* *& Include /IWBEP/DPC_TMP_ENTITYSET_BASE *&* This class has been generated on 16.08.2017 19:12:50 in client 001 *&* *&* WARNING--> NEVER MODIFY THIS CLASS <--WARNING *&* If you want to change the DPC implementation, use the *&* generated methods inside the DPC provider subclass - ZCL_TE_FLIGHT_DPC_EXT *&-----------------------------------------------------------------------------------------------* DATA zc_te_bookings_get_entityset TYPE zcl_te_flight_mpc=>tt_zc_te_bookingstype. DATA zi_te_carrier_get_entityset TYPE zcl_te_flight_mpc=>tt_zi_te_carriertype. DATA zi_te_connection_get_entityset TYPE zcl_te_flight_mpc=>tt_zi_te_connectiontype. DATA zc_te_flight_get_entityset TYPE zcl_te_flight_mpc=>tt_zc_te_flighttype. DATA zi_te_airport_get_entityset TYPE zcl_te_flight_mpc=>tt_zi_te_airporttype. DATA lv_entityset_name TYPE string. lv_entityset_name = io_tech_request_context->get_entity_set_name( ). CASE lv_entityset_name. *-------------------------------------------------------------------------* * EntitySet - Zc_Te_Bookings *-------------------------------------------------------------------------* WHEN 'Zc_Te_Bookings'. * Call the entity set generated method zc_te_bookings_get_entityset( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name it_filter_select_options = it_filter_select_options it_order = it_order is_paging = is_paging it_navigation_path = it_navigation_path it_key_tab = it_key_tab iv_filter_string = iv_filter_string iv_search_string = iv_search_string io_tech_request_context = io_tech_request_context IMPORTING et_entityset = zc_te_bookings_get_entityset es_response_context = es_response_context ). * Send specific entity data to the caller interface copy_data_to_ref( EXPORTING is_data = zc_te_bookings_get_entityset CHANGING cr_data = er_entityset ). *-------------------------------------------------------------------------* * EntitySet - Zi_Te_Carrier *-------------------------------------------------------------------------* WHEN 'Zi_Te_Carrier'. * Call the entity set generated method zi_te_carrier_get_entityset( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name it_filter_select_options = it_filter_select_options it_order = it_order is_paging = is_paging it_navigation_path = it_navigation_path it_key_tab = it_key_tab iv_filter_string = iv_filter_string iv_search_string = iv_search_string io_tech_request_context = io_tech_request_context IMPORTING et_entityset = zi_te_carrier_get_entityset es_response_context = es_response_context ). * Send specific entity data to the caller interface copy_data_to_ref( EXPORTING is_data = zi_te_carrier_get_entityset CHANGING cr_data = er_entityset ). *-------------------------------------------------------------------------* * EntitySet - Zi_Te_Connection *-------------------------------------------------------------------------* WHEN 'Zi_Te_Connection'. * Call the entity set generated method zi_te_connection_get_entityset( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name it_filter_select_options = it_filter_select_options it_order = it_order is_paging = is_paging it_navigation_path = it_navigation_path it_key_tab = it_key_tab iv_filter_string = iv_filter_string iv_search_string = iv_search_string io_tech_request_context = io_tech_request_context IMPORTING et_entityset = zi_te_connection_get_entityset es_response_context = es_response_context ). * Send specific entity data to the caller interface copy_data_to_ref( EXPORTING is_data = zi_te_connection_get_entityset CHANGING cr_data = er_entityset ). *-------------------------------------------------------------------------* * EntitySet - Zc_Te_Flight *-------------------------------------------------------------------------* WHEN 'Zc_Te_Flight'. * Call the entity set generated method zc_te_flight_get_entityset( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name it_filter_select_options = it_filter_select_options it_order = it_order is_paging = is_paging it_navigation_path = it_navigation_path it_key_tab = it_key_tab iv_filter_string = iv_filter_string iv_search_string = iv_search_string io_tech_request_context = io_tech_request_context IMPORTING et_entityset = zc_te_flight_get_entityset es_response_context = es_response_context ). * Send specific entity data to the caller interface copy_data_to_ref( EXPORTING is_data = zc_te_flight_get_entityset CHANGING cr_data = er_entityset ). *-------------------------------------------------------------------------* * EntitySet - Zi_Te_Airport *-------------------------------------------------------------------------* WHEN 'Zi_Te_Airport'. * Call the entity set generated method zi_te_airport_get_entityset( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name it_filter_select_options = it_filter_select_options it_order = it_order is_paging = is_paging it_navigation_path = it_navigation_path it_key_tab = it_key_tab iv_filter_string = iv_filter_string iv_search_string = iv_search_string io_tech_request_context = io_tech_request_context IMPORTING et_entityset = zi_te_airport_get_entityset es_response_context = es_response_context ). * Send specific entity data to the caller interface copy_data_to_ref( EXPORTING is_data = zi_te_airport_get_entityset CHANGING cr_data = er_entityset ). WHEN OTHERS. super->/iwbep/if_mgw_appl_srv_runtime~get_entityset( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name it_filter_select_options = it_filter_select_options it_order = it_order is_paging = is_paging it_navigation_path = it_navigation_path it_key_tab = it_key_tab iv_filter_string = iv_filter_string iv_search_string = iv_search_string io_tech_request_context = io_tech_request_context IMPORTING er_entityset = er_entityset ). ENDCASE. endmethod. method /IWBEP/IF_MGW_APPL_SRV_RUNTIME~GET_EXPANDED_ENTITY. if_sadl_gw_dpc_util~get_dpc( )->get_expanded_entity( EXPORTING io_expand_node = io_expand io_tech_request_context = io_tech_request_context IMPORTING er_entity = er_entity et_expanded_tech_clauses = et_expanded_tech_clauses es_response_context = es_response_context ev_entity_mapped_by_sadl = DATA(lv_entity_mapped) ). endmethod. method /IWBEP/IF_MGW_APPL_SRV_RUNTIME~GET_EXPANDED_ENTITYSET. if_sadl_gw_dpc_util~get_dpc( )->get_expanded_entityset( EXPORTING io_expand_node = io_expand io_tech_request_context = io_tech_request_context IMPORTING er_entityset = er_entityset et_expanded_tech_clauses = et_expanded_tech_clauses es_response_context = es_response_context ev_entity_mapped_by_sadl = DATA(lv_entity_mapped) ). endmethod. method /IWBEP/IF_MGW_APPL_SRV_RUNTIME~PATCH_ENTITY. super->/iwbep/if_mgw_appl_srv_runtime~patch_entity( EXPORTING io_tech_request_context = io_tech_request_context io_data_provider = io_data_provider iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name it_key_tab = it_key_tab it_navigation_path = it_navigation_path IMPORTING er_entity = er_entity ). endmethod. method /IWBEP/IF_MGW_APPL_SRV_RUNTIME~UPDATE_ENTITY. *&----------------------------------------------------------------------------------------------* *& Include /IWBEP/DPC_TEMP_UPD_ENTITY_BASE *&* This class has been generated on 16.08.2017 19:12:50 in client 001 *&* *&* WARNING--> NEVER MODIFY THIS CLASS <--WARNING *&* If you want to change the DPC implementation, use the *&* generated methods inside the DPC provider subclass - ZCL_TE_FLIGHT_DPC_EXT *&-----------------------------------------------------------------------------------------------* DATA zi_te_airport_update_entity TYPE zcl_te_flight_mpc=>ts_zi_te_airporttype. DATA zc_te_flight_update_entity TYPE zcl_te_flight_mpc=>ts_zc_te_flighttype. DATA zi_te_connection_update_entity TYPE zcl_te_flight_mpc=>ts_zi_te_connectiontype. DATA zi_te_carrier_update_entity TYPE zcl_te_flight_mpc=>ts_zi_te_carriertype. DATA zc_te_bookings_update_entity TYPE zcl_te_flight_mpc=>ts_zc_te_bookingstype. DATA lv_entityset_name TYPE string. DATA lr_entity TYPE REF TO data. lv_entityset_name = io_tech_request_context->get_entity_set_name( ). CASE lv_entityset_name. *-------------------------------------------------------------------------* * EntitySet - Zi_Te_Airport *-------------------------------------------------------------------------* WHEN 'Zi_Te_Airport'. * Call the entity set generated method zi_te_airport_update_entity( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name io_data_provider = io_data_provider it_key_tab = it_key_tab it_navigation_path = it_navigation_path io_tech_request_context = io_tech_request_context IMPORTING er_entity = zi_te_airport_update_entity ). IF zi_te_airport_update_entity IS NOT INITIAL. * Send specific entity data to the caller interface copy_data_to_ref( EXPORTING is_data = zi_te_airport_update_entity CHANGING cr_data = er_entity ). ELSE. * In case of initial values - unbind the entity reference er_entity = lr_entity. ENDIF. *-------------------------------------------------------------------------* * EntitySet - Zc_Te_Flight *-------------------------------------------------------------------------* WHEN 'Zc_Te_Flight'. * Call the entity set generated method zc_te_flight_update_entity( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name io_data_provider = io_data_provider it_key_tab = it_key_tab it_navigation_path = it_navigation_path io_tech_request_context = io_tech_request_context IMPORTING er_entity = zc_te_flight_update_entity ). IF zc_te_flight_update_entity IS NOT INITIAL. * Send specific entity data to the caller interface copy_data_to_ref( EXPORTING is_data = zc_te_flight_update_entity CHANGING cr_data = er_entity ). ELSE. * In case of initial values - unbind the entity reference er_entity = lr_entity. ENDIF. *-------------------------------------------------------------------------* * EntitySet - Zi_Te_Connection *-------------------------------------------------------------------------* WHEN 'Zi_Te_Connection'. * Call the entity set generated method zi_te_connection_update_entity( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name io_data_provider = io_data_provider it_key_tab = it_key_tab it_navigation_path = it_navigation_path io_tech_request_context = io_tech_request_context IMPORTING er_entity = zi_te_connection_update_entity ). IF zi_te_connection_update_entity IS NOT INITIAL. * Send specific entity data to the caller interface copy_data_to_ref( EXPORTING is_data = zi_te_connection_update_entity CHANGING cr_data = er_entity ). ELSE. * In case of initial values - unbind the entity reference er_entity = lr_entity. ENDIF. *-------------------------------------------------------------------------* * EntitySet - Zi_Te_Carrier *-------------------------------------------------------------------------* WHEN 'Zi_Te_Carrier'. * Call the entity set generated method zi_te_carrier_update_entity( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name io_data_provider = io_data_provider it_key_tab = it_key_tab it_navigation_path = it_navigation_path io_tech_request_context = io_tech_request_context IMPORTING er_entity = zi_te_carrier_update_entity ). IF zi_te_carrier_update_entity IS NOT INITIAL. * Send specific entity data to the caller interface copy_data_to_ref( EXPORTING is_data = zi_te_carrier_update_entity CHANGING cr_data = er_entity ). ELSE. * In case of initial values - unbind the entity reference er_entity = lr_entity. ENDIF. *-------------------------------------------------------------------------* * EntitySet - Zc_Te_Bookings *-------------------------------------------------------------------------* WHEN 'Zc_Te_Bookings'. * Call the entity set generated method zc_te_bookings_update_entity( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name io_data_provider = io_data_provider it_key_tab = it_key_tab it_navigation_path = it_navigation_path io_tech_request_context = io_tech_request_context IMPORTING er_entity = zc_te_bookings_update_entity ). IF zc_te_bookings_update_entity IS NOT INITIAL. * Send specific entity data to the caller interface copy_data_to_ref( EXPORTING is_data = zc_te_bookings_update_entity CHANGING cr_data = er_entity ). ELSE. * In case of initial values - unbind the entity reference er_entity = lr_entity. ENDIF. WHEN OTHERS. super->/iwbep/if_mgw_appl_srv_runtime~update_entity( EXPORTING iv_entity_name = iv_entity_name iv_entity_set_name = iv_entity_set_name iv_source_name = iv_source_name io_data_provider = io_data_provider it_key_tab = it_key_tab it_navigation_path = it_navigation_path IMPORTING er_entity = er_entity ). ENDCASE. endmethod. method /IWBEP/IF_SB_DPC_COMM_SERVICES~COMMIT_WORK. * Call RFC commit work functionality DATA lt_message TYPE bapiret2. DATA lv_message_text TYPE BAPI_MSG. DATA lo_logger TYPE REF TO /iwbep/cl_cos_logger. DATA lv_subrc TYPE syst-subrc. lo_logger = /iwbep/if_mgw_conv_srv_runtime~get_logger( ). IF iv_rfc_dest IS INITIAL OR iv_rfc_dest EQ 'NONE'. CALL FUNCTION 'BAPI_TRANSACTION_COMMIT' EXPORTING wait = abap_true IMPORTING return = lt_message. ELSE. CALL FUNCTION 'BAPI_TRANSACTION_COMMIT' DESTINATION iv_rfc_dest EXPORTING wait = abap_true IMPORTING return = lt_message EXCEPTIONS communication_failure = 1000 MESSAGE lv_message_text system_failure = 1001 MESSAGE lv_message_text OTHERS = 1002. IF sy-subrc <> 0. lv_subrc = sy-subrc. /iwbep/cl_sb_gen_dpc_rt_util=>rfc_exception_handling( EXPORTING iv_subrc = lv_subrc iv_exp_message_text = lv_message_text io_logger = lo_logger ). EXIT. ENDIF. ENDIF. endmethod. method /IWBEP/IF_SB_DPC_COMM_SERVICES~GET_GENERATION_STRATEGY. * Get generation strategy rv_generation_strategy = '1'. endmethod. method /IWBEP/IF_SB_DPC_COMM_SERVICES~LOG_MESSAGE. * Log message in the application log DATA lo_logger TYPE REF TO /iwbep/cl_cos_logger. DATA lv_text TYPE /iwbep/sup_msg_longtext. MESSAGE ID iv_msg_id TYPE iv_msg_type NUMBER iv_msg_number WITH iv_msg_v1 iv_msg_v2 iv_msg_v3 iv_msg_v4 INTO lv_text. lo_logger = mo_context->get_logger( ). lo_logger->log_message( EXPORTING iv_msg_type = iv_msg_type iv_msg_id = iv_msg_id iv_msg_number = iv_msg_number iv_msg_text = lv_text iv_msg_v1 = iv_msg_v1 iv_msg_v2 = iv_msg_v2 iv_msg_v3 = iv_msg_v3 iv_msg_v4 = iv_msg_v4 iv_agent = 'DPC' ). endmethod. method /IWBEP/IF_SB_DPC_COMM_SERVICES~RFC_EXCEPTION_HANDLING. * RFC call exception handling DATA lo_logger TYPE REF TO /iwbep/cl_cos_logger. lo_logger = /iwbep/if_mgw_conv_srv_runtime~get_logger( ). /iwbep/cl_sb_gen_dpc_rt_util=>rfc_exception_handling( EXPORTING iv_subrc = iv_subrc iv_exp_message_text = iv_exp_message_text io_logger = lo_logger ). endmethod. method /IWBEP/IF_SB_DPC_COMM_SERVICES~RFC_SAVE_LOG. DATA lo_logger TYPE REF TO /iwbep/cl_cos_logger. DATA lo_message_container TYPE REF TO /iwbep/if_message_container. lo_logger = /iwbep/if_mgw_conv_srv_runtime~get_logger( ). lo_message_container = /iwbep/if_mgw_conv_srv_runtime~get_message_container( ). "" Save the RFC call log in the application log /iwbep/cl_sb_gen_dpc_rt_util=>rfc_save_log( EXPORTING is_return = is_return iv_entity_type = iv_entity_type it_return = it_return it_key_tab = it_key_tab io_logger = lo_logger io_message_container = lo_message_container ). endmethod. method /IWBEP/IF_SB_DPC_COMM_SERVICES~SET_INJECTION. * Unit test injection IF io_unit IS BOUND. mo_injection = io_unit. ELSE. mo_injection = me. ENDIF. endmethod. method CHECK_SUBSCRIPTION_AUTHORITY. RAISE EXCEPTION TYPE /iwbep/cx_mgw_not_impl_exc EXPORTING textid = /iwbep/cx_mgw_not_impl_exc=>method_not_implemented method = 'CHECK_SUBSCRIPTION_AUTHORITY'. endmethod. method IF_SADL_GW_DPC_UTIL~GET_DPC. TYPES ty_zc_te_bookings_1 TYPE zc_te_bookings ##NEEDED. "" reference for where-used list TYPES ty_zc_te_flight_2 TYPE zc_te_flight ##NEEDED. "" reference for where-used list TYPES ty_zi_te_airport_3 TYPE zi_te_airport ##NEEDED. "" reference for where-used list TYPES ty_zi_te_carrier_4 TYPE zi_te_carrier ##NEEDED. "" reference for where-used list TYPES ty_zi_te_connection_5 TYPE zi_te_connection ##NEEDED. "" reference for where-used list DATA(lv_sadl_xml) = || & || & | | & | | & | | & | | & | | & || & || & | | & | | & || & || & | | & | | & || & || & | | & | | & || & || & | | & | | & | | & | | & | | & | | & || & || & | | & | | & || & || & || . ro_dpc = cl_sadl_gw_dpc_factory=>create_for_sadl( iv_sadl_xml = lv_sadl_xml iv_timestamp = '20170816091248' iv_uuid = 'ZTE_FLIGHT' io_context = me->mo_context ). endmethod. method ZC_TE_BOOKINGS_CREATE_ENTITY. if_sadl_gw_dpc_util~get_dpc( )->create_entity( EXPORTING io_data_provider = io_data_provider io_tech_request_context = io_tech_request_context IMPORTING es_data = er_entity ). endmethod. method ZC_TE_BOOKINGS_DELETE_ENTITY. if_sadl_gw_dpc_util~get_dpc( )->delete_entity( io_tech_request_context ). endmethod. method ZC_TE_BOOKINGS_GET_ENTITY. if_sadl_gw_dpc_util~get_dpc( )->get_entity( EXPORTING io_tech_request_context = io_tech_request_context IMPORTING es_data = er_entity ). endmethod. method ZC_TE_BOOKINGS_GET_ENTITYSET. if_sadl_gw_dpc_util~get_dpc( )->get_entityset( EXPORTING io_tech_request_context = io_tech_request_context IMPORTING et_data = et_entityset es_response_context = es_response_context ). endmethod. method ZC_TE_BOOKINGS_UPDATE_ENTITY. if_sadl_gw_dpc_util~get_dpc( )->update_entity( EXPORTING io_tech_request_context = io_tech_request_context io_data_provider = io_data_provider IMPORTING es_data = er_entity ). endmethod. method ZC_TE_FLIGHT_CREATE_ENTITY. if_sadl_gw_dpc_util~get_dpc( )->create_entity( EXPORTING io_data_provider = io_data_provider io_tech_request_context = io_tech_request_context IMPORTING es_data = er_entity ). endmethod. method ZC_TE_FLIGHT_DELETE_ENTITY. if_sadl_gw_dpc_util~get_dpc( )->delete_entity( io_tech_request_context ). endmethod. method ZC_TE_FLIGHT_GET_ENTITY. if_sadl_gw_dpc_util~get_dpc( )->get_entity( EXPORTING io_tech_request_context = io_tech_request_context IMPORTING es_data = er_entity ). endmethod. method ZC_TE_FLIGHT_GET_ENTITYSET. if_sadl_gw_dpc_util~get_dpc( )->get_entityset( EXPORTING io_tech_request_context = io_tech_request_context IMPORTING et_data = et_entityset es_response_context = es_response_context ). endmethod. method ZC_TE_FLIGHT_UPDATE_ENTITY. if_sadl_gw_dpc_util~get_dpc( )->update_entity( EXPORTING io_tech_request_context = io_tech_request_context io_data_provider = io_data_provider IMPORTING es_data = er_entity ). endmethod. method ZI_TE_AIRPORT_CREATE_ENTITY. if_sadl_gw_dpc_util~get_dpc( )->create_entity( EXPORTING io_data_provider = io_data_provider io_tech_request_context = io_tech_request_context IMPORTING es_data = er_entity ). endmethod. method ZI_TE_AIRPORT_DELETE_ENTITY. if_sadl_gw_dpc_util~get_dpc( )->delete_entity( io_tech_request_context ). endmethod. method ZI_TE_AIRPORT_GET_ENTITY. if_sadl_gw_dpc_util~get_dpc( )->get_entity( EXPORTING io_tech_request_context = io_tech_request_context IMPORTING es_data = er_entity ). endmethod. method ZI_TE_AIRPORT_GET_ENTITYSET. if_sadl_gw_dpc_util~get_dpc( )->get_entityset( EXPORTING io_tech_request_context = io_tech_request_context IMPORTING et_data = et_entityset es_response_context = es_response_context ). endmethod. method ZI_TE_AIRPORT_UPDATE_ENTITY. if_sadl_gw_dpc_util~get_dpc( )->update_entity( EXPORTING io_tech_request_context = io_tech_request_context io_data_provider = io_data_provider IMPORTING es_data = er_entity ). endmethod. method ZI_TE_CARRIER_CREATE_ENTITY. if_sadl_gw_dpc_util~get_dpc( )->create_entity( EXPORTING io_data_provider = io_data_provider io_tech_request_context = io_tech_request_context IMPORTING es_data = er_entity ). endmethod. method ZI_TE_CARRIER_DELETE_ENTITY. if_sadl_gw_dpc_util~get_dpc( )->delete_entity( io_tech_request_context ). endmethod. method ZI_TE_CARRIER_GET_ENTITY. if_sadl_gw_dpc_util~get_dpc( )->get_entity( EXPORTING io_tech_request_context = io_tech_request_context IMPORTING es_data = er_entity ). endmethod. method ZI_TE_CARRIER_GET_ENTITYSET. if_sadl_gw_dpc_util~get_dpc( )->get_entityset( EXPORTING io_tech_request_context = io_tech_request_context IMPORTING et_data = et_entityset es_response_context = es_response_context ). endmethod. method ZI_TE_CARRIER_UPDATE_ENTITY. if_sadl_gw_dpc_util~get_dpc( )->update_entity( EXPORTING io_tech_request_context = io_tech_request_context io_data_provider = io_data_provider IMPORTING es_data = er_entity ). endmethod. method ZI_TE_CONNECTION_CREATE_ENTITY. if_sadl_gw_dpc_util~get_dpc( )->create_entity( EXPORTING io_data_provider = io_data_provider io_tech_request_context = io_tech_request_context IMPORTING es_data = er_entity ). endmethod. method ZI_TE_CONNECTION_DELETE_ENTITY. if_sadl_gw_dpc_util~get_dpc( )->delete_entity( io_tech_request_context ). endmethod. method ZI_TE_CONNECTION_GET_ENTITY. if_sadl_gw_dpc_util~get_dpc( )->get_entity( EXPORTING io_tech_request_context = io_tech_request_context IMPORTING es_data = er_entity ). endmethod. method ZI_TE_CONNECTION_GET_ENTITYSET. if_sadl_gw_dpc_util~get_dpc( )->get_entityset( EXPORTING io_tech_request_context = io_tech_request_context IMPORTING et_data = et_entityset es_response_context = es_response_context ). endmethod. method ZI_TE_CONNECTION_UPDATE_ENTITY. if_sadl_gw_dpc_util~get_dpc( )->update_entity( EXPORTING io_tech_request_context = io_tech_request_context io_data_provider = io_data_provider IMPORTING es_data = er_entity ). endmethod. ENDCLASS. ",15804,True,3060.3034956573038,median "[[cluster-nodes-stats]] === Nodes stats API ++++ Nodes stats ++++ Returns cluster nodes statistics. [[cluster-nodes-stats-api-request]] ==== {api-request-title} `GET /_nodes/stats` + `GET /_nodes//stats` + `GET/_nodes/stats/` + `GET/_nodes//stats/` + `GET /_nodes/stats//` + `GET /_nodes//stats//` [[cluster-nodes-stats-api-desc]] ==== {api-description-title} You can use the cluster nodes stats API to retrieve statistics for nodes in a cluster. All the nodes selective options are explained <>. By default, all stats are returned. You can limit the returned information by using metrics. [[cluster-nodes-stats-api-path-params]] ==== {api-path-parms-title} ``:: (Optional, string) Limits the information returned to the specific metrics. A comma-separated list of the following options: + -- `adaptive_selection`:: Statistics about <>. `breaker`:: Statistics about the field data circuit breaker. `discovery`:: Statistics about the discovery. `fs`:: File system information, data path, free disk space, read/write stats. `http`:: HTTP connection information. `indexing_pressure`:: Statistics about the node's indexing load and related rejections. `indices`:: Indices stats about size, document count, indexing and deletion times, search times, field cache size, merges and flushes. `ingest`:: Statistics about ingest preprocessing. `jvm`:: JVM stats, memory pool information, garbage collection, buffer pools, number of loaded/unloaded classes. `os`:: Operating system stats, load average, mem, swap. `process`:: Process statistics, memory consumption, cpu usage, open file descriptors. `thread_pool`:: Statistics about each thread pool, including current size, queue and rejected tasks. `transport`:: Transport statistics about sent and received bytes in cluster communication. -- ``:: (Optional, string) Limit the information returned for `indices` metric to the specific index metrics. It can be used only if `indices` (or `all`) metric is specified. Supported metrics are: + -- * `completion` * `docs` * `fielddata` * `flush` * `get` * `indexing` * `merge` * `query_cache` * `recovery` * `refresh` * `request_cache` * `search` * `segments` * `store` * `translog` * `warmer` -- include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=node-id] [[cluster-nodes-stats-api-query-params]] ==== {api-query-parms-title} include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=completion-fields] include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=fielddata-fields] include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=fields] include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=groups] include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=level] `types`:: (Optional, string) A comma-separated list of document types for the `indexing` index metric. include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=timeoutparms] include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=include-segment-file-sizes] [role=""child_attributes""] [[cluster-nodes-stats-api-response-body]] ==== {api-response-body-title} `_nodes`:: (object) Contains statistics about the number of nodes selected by the request. + .Properties of `_nodes` [%collapsible%open] ==== `total`:: (integer) Total number of nodes selected by the request. `successful`:: (integer) Number of nodes that responded successfully to the request. `failed`:: (integer) Number of nodes that rejected the request or failed to respond. If this value is not `0`, a reason for the rejection or failure is included in the response. ==== `cluster_name`:: (string) Name of the cluster. Based on the <> setting. `nodes`:: (object) Contains statistics for the nodes selected by the request. + .Properties of `nodes` [%collapsible%open] ==== ``:: (object) Contains statistics for the node. + .Properties of `` [%collapsible%open] ===== `timestamp`:: (integer) Time the node stats were collected for this response. Recorded in milliseconds since the {wikipedia}/Unix_time[Unix Epoch]. `name`:: (string) Human-readable identifier for the node. Based on the <> setting. `transport_address`:: (string) Host and port for the <>, used for internal communication between nodes in a cluster. `host`:: (string) Network host for the node, based on the <> setting. `ip`:: (string) IP address and port for the node. `roles`:: (array of strings) Roles assigned to the node. See <>. `attributes`:: (object) Contains a list of attributes for the node. [[cluster-nodes-stats-api-response-body-indices]] `indices`:: (object) Contains statistics about indices with shards assigned to the node. + .Properties of `indices` [%collapsible%open] ====== `docs`:: (object) Contains statistics about documents across all primary shards assigned to the node. + .Properties of `docs` [%collapsible%open] ======= `count`:: (integer) include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=docs-count] `deleted`:: (integer) include::{es-repo-dir}/rest-api/common-parms.asciidoc[tag=docs-deleted] ======= `store`:: (object) Contains statistics about the size of shards assigned to the node. + .Properties of `store` [%collapsible%open] ======= `size`:: (<>) Total size of all shards assigned to the node. `size_in_bytes`:: (integer) Total size, in bytes, of all shards assigned to the node. `reserved`:: (<>) A prediction of how much larger the shard stores on this node will eventually grow due to ongoing peer recoveries, restoring snapshots, and similar activities. A value of `-1b` indicates that this is not available. `reserved_in_bytes`:: (integer) A prediction, in bytes, of how much larger the shard stores on this node will eventually grow due to ongoing peer recoveries, restoring snapshots, and similar activities. A value of `-1` indicates that this is not available. ======= `indexing`:: (object) Contains statistics about indexing operations for the node. + .Properties of `indexing` [%collapsible%open] ======= `index_total`:: (integer) Total number of indexing operations. `index_time`:: (<>) Total time spent performing indexing operations. `index_time_in_millis`:: (integer) Total time in milliseconds spent performing indexing operations. `index_current`:: (integer) Number of indexing operations currently running. `index_failed`:: (integer) Number of failed indexing operations. `delete_total`:: (integer) Total number of deletion operations. `delete_time`:: (<>) Time spent performing deletion operations. `delete_time_in_millis`:: (integer) Time in milliseconds spent performing deletion operations. `delete_current`:: (integer) Number of deletion operations currently running. `noop_update_total`:: (integer) Total number of noop operations. `is_throttled`:: (boolean) Number of times operations were throttled. `throttle_time`:: (<>) Total time spent throttling operations. `throttle_time_in_millis`:: (integer) Total time in milliseconds spent throttling operations. ======= `get`:: (object) Contains statistics about get operations for the node. + .Properties of `get` [%collapsible%open] ======= `total`:: (integer) Total number of get operations. `getTime`:: (<>) Time spent performing get operations. `time_in_millis`:: (integer) Time in milliseconds spent performing get operations. `exists_total`:: (integer) Total number of successful get operations. `exists_time`:: (<>) Time spent performing successful get operations. `exists_time_in_millis`:: (integer) Time in milliseconds spent performing successful get operations. `missing_total`:: (integer) Total number of failed get operations. `missing_time`:: (<>) Time spent performing failed get operations. `missing_time_in_millis`:: (integer) Time in milliseconds spent performing failed get operations. `current`:: (integer) Number of get operations currently running. ======= `search`:: (object) Contains statistics about search operations for the node. + .Properties of `search` [%collapsible%open] ======= `open_contexts`:: (integer) Number of open search contexts. `query_total`:: (integer) Total number of query operations. `query_time`:: (<>) Time spent performing query operations. `query_time_in_millis`:: (integer) Time in milliseconds spent performing query operations. `query_current`:: (integer) Number of query operations currently running. `fetch_total`:: (integer) Total number of fetch operations. `fetch_time`:: (<>) Time spent performing fetch operations. `fetch_time_in_millis`:: (integer) Time in milliseconds spent performing fetch operations. `fetch_current`:: (integer) Number of fetch operations currently running. `scroll_total`:: (integer) Total number of scroll operations. `scroll_time`:: (<>) Time spent performing scroll operations. `scroll_time_in_millis`:: (integer) Time in milliseconds spent performing scroll operations. `scroll_current`:: (integer) Number of scroll operations currently running. `suggest_total`:: (integer) Total number of suggest operations. `suggest_time`:: (<>) Time spent performing suggest operations. `suggest_time_in_millis`:: (integer) Time in milliseconds spent performing suggest operations. `suggest_current`:: (integer) Number of suggest operations currently running. ======= `merges`:: (object) Contains statistics about merge operations for the node. + .Properties of `merges` [%collapsible%open] ======= `current`:: (integer) Number of merge operations currently running. `current_docs`:: (integer) Number of document merges currently running. `current_size`:: (<>) Memory used performing current document merges. `current_size_in_bytes`:: (integer) Memory, in bytes, used performing current document merges. `total`:: (integer) Total number of merge operations. `total_time`:: (<>) Total time spent performing merge operations. `total_time_in_millis`:: (integer) Total time in milliseconds spent performing merge operations. `total_docs`:: (integer) Total number of merged documents. `total_size`:: (<>) Total size of document merges. `total_size_in_bytes`:: (integer) Total size of document merges in bytes. `total_stopped_time`:: (<>) Total time spent stopping merge operations. `total_stopped_time_in_millis`:: (integer) Total time in milliseconds spent stopping merge operations. `total_throttled_time`:: (<>) Total time spent throttling merge operations. `total_throttled_time_in_millis`:: (integer) Total time in milliseconds spent throttling merge operations. `total_auto_throttle`:: (<>) Size of automatically throttled merge operations. `total_auto_throttle_in_bytes`:: (integer) Size, in bytes, of automatically throttled merge operations. ======= `refresh`:: (object) Contains statistics about refresh operations for the node. + .Properties of `refresh` [%collapsible%open] ======= `total`:: (integer) Total number of refresh operations. `total_time`:: (<>) Total time spent performing refresh operations. `total_time_in_millis`:: (integer) Total time in milliseconds spent performing refresh operations. `external_total`:: (integer) Total number of external refresh operations. `external_total_time`:: (<>) Total time spent performing external operations. `external_total_time_in_millis`:: (integer) Total time in milliseconds spent performing external operations. `listeners`:: (integer) Number of refresh listeners. ======= `flush`:: (object) Contains statistics about flush operations for the node. + .Properties of `flush` [%collapsible%open] ======= `total`:: (integer) Number of flush operations. `periodic`:: (integer) Number of flush periodic operations. `total_time`:: (<>) Total time spent performing flush operations. `total_time_in_millis`:: (integer) Total time in milliseconds spent performing flush operations. ======= `warmer`:: (object) Contains statistics about index warming operations for the node. + .Properties of `warmer` [%collapsible%open] ======= `current`:: (integer) Number of active index warmers. `total`:: (integer) Total number of index warmers. `total_time`:: (<>) Total time spent performing index warming operations. `total_time_in_millis`:: (integer) Total time in milliseconds spent performing index warming operations. ======= `query_cache`:: (object) Contains statistics about the query cache across all shards assigned to the node. + .Properties of `query_cache` [%collapsible%open] ======= `memory_size`:: (<>) Total amount of memory used for the query cache across all shards assigned to the node. `memory_size_in_bytes`:: (integer) Total amount of memory, in bytes, used for the query cache across all shards assigned to the node. `total_count`:: (integer) Total count of hits, misses, and cached queries in the query cache. `hit_count`:: (integer) Number of query cache hits. `miss_count`:: (integer) Number of query cache misses. `cache_size`:: (integer) Size, in bytes, of the query cache. `cache_count`:: (integer) Count of queries in the query cache. `evictions`:: (integer) Number of query cache evictions. ======= `fielddata`:: (object) Contains statistics about the field data cache across all shards assigned to the node. + .Properties of `fielddata` [%collapsible%open] ======= `memory_size`:: (<>) Total amount of memory used for the field data cache across all shards assigned to the node. `memory_size_in_bytes`:: (integer) Total amount of memory, in bytes, used for the field data cache across all shards assigned to the node. `evictions`:: (integer) Number of fielddata evictions. ======= `completion`:: (object) Contains statistics about completions across all shards assigned to the node. + .Properties of `completion` [%collapsible%open] ======= `size`:: (<>) Total amount of memory used for completion across all shards assigned to the node. `size_in_bytes`:: (integer) Total amount of memory, in bytes, used for completion across all shards assigned to the node. ======= `segments`:: (object) Contains statistics about segments across all shards assigned to the node. + .Properties of `segments` [%collapsible%open] ======= `count`:: (integer) Number of segments. `memory`:: (<>) Total amount of memory used for segments across all shards assigned to the node. `memory_in_bytes`:: (integer) Total amount of memory, in bytes, used for segments across all shards assigned to the node. `terms_memory`:: (<>) Total amount of memory used for terms across all shards assigned to the node. `terms_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used for terms across all shards assigned to the node. `stored_fields_memory`:: (<>) Total amount of memory used for stored fields across all shards assigned to the node. `stored_fields_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used for stored fields across all shards assigned to the node. `term_vectors_memory`:: (<>) Total amount of memory used for term vectors across all shards assigned to the node. `term_vectors_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used for term vectors across all shards assigned to the node. `norms_memory`:: (<>) Total amount of memory used for normalization factors across all shards assigned to the node. `norms_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used for normalization factors across all shards assigned to the node. `points_memory`:: (<>) Total amount of memory used for points across all shards assigned to the node. `points_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used for points across all shards assigned to the node. `doc_values_memory`:: (<>) Total amount of memory used for doc values across all shards assigned to the node. `doc_values_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used for doc values across all shards assigned to the node. `index_writer_memory`:: (<>) Total amount of memory used by all index writers across all shards assigned to the node. `index_writer_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used by all index writers across all shards assigned to the node. `version_map_memory`:: (<>) Total amount of memory used by all version maps across all shards assigned to the node. `version_map_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used by all version maps across all shards assigned to the node. `fixed_bit_set`:: (<>) Total amount of memory used by fixed bit sets across all shards assigned to the node. + Fixed bit sets are used for nested object field types and type filters for <> fields. `fixed_bit_set_memory_in_bytes`:: (integer) Total amount of memory, in bytes, used by fixed bit sets across all shards assigned to the node. + Fixed bit sets are used for nested object field types and type filters for <> fields. `max_unsafe_auto_id_timestamp`:: (integer) Time of the most recently retried indexing request. Recorded in milliseconds since the {wikipedia}/Unix_time[Unix Epoch]. `file_sizes`:: (object) Contains statistics about the size of the segment file. + .Properties of `file_sizes` [%collapsible%open] ======== `size`:: (<>) Size of the segment file. `size_in_bytes`:: (integer) Size, in bytes, of the segment file. `description`:: (string) Description of the segment file. ======== ======= `translog`:: (object) Contains statistics about transaction log operations for the node. + .Properties of `translog` [%collapsible%open] ======= `operations`:: (integer) Number of transaction log operations. `size`:: (<>) Size of the transaction log. `size_in_bytes`:: (integer) Size, in bytes, of the transaction log. `uncommitted_operations`:: (integer) Number of uncommitted transaction log operations. `uncommitted_size`:: (<>) Size of uncommitted transaction log operations. `uncommitted_size_in_bytes`:: (integer) Size, in bytes, of uncommitted transaction log operations. `earliest_last_modified_age`:: (integer) Earliest last modified age for the transaction log. ======= `request_cache`:: (object) Contains statistics about the request cache across all shards assigned to the node. + .Properties of `request_cache` [%collapsible%open] ======= `memory_size`:: (<>) Memory used by the request cache. `memory_size_in_bytes`:: (integer) Memory, in bytes, used by the request cache. `evictions`:: (integer) Number of request cache operations. `hit_count`:: (integer) Number of request cache hits. `miss_count`:: (integer) Number of request cache misses. ======= `recovery`:: (object) Contains statistics about recovery operations for the node. + .Properties of `recovery` [%collapsible%open] ======= `current_as_source`:: (integer) Number of recoveries that used an index shard as a source. `current_as_target`:: (integer) Number of recoveries that used an index shard as a target. `throttle_time`:: (<>) Time by which recovery operations were delayed due to throttling. `throttle_time_in_millis`:: (integer) Time in milliseconds recovery operations were delayed due to throttling. ======= ====== [[cluster-nodes-stats-api-response-body-os]] `os`:: (object) Contains statistics about the operating system for the node. + .Properties of `os` [%collapsible%open] ====== `timestamp`:: (integer) Last time the operating system statistics were refreshed. Recorded in milliseconds since the {wikipedia}/Unix_time[Unix Epoch]. `cpu`:: (object) Contains statistics about CPU usage for the node. + .Properties of `cpu` [%collapsible%open] ======= `percent`:: (integer) Recent CPU usage for the whole system, or `-1` if not supported. `load_average`:: (object) Contains statistics about load averages on the system. + .Properties of `load_average` [%collapsible%open] ======== `1m`:: (float) One-minute load average on the system (field is not present if one-minute load average is not available). `5m`:: (float) Five-minute load average on the system (field is not present if five-minute load average is not available). `15m`:: (float) Fifteen-minute load average on the system (field is not present if fifteen-minute load average is not available). ======== ======= `mem`:: (object) Contains statistics about memory usage for the node. + .Properties of `mem` [%collapsible%open] ======= `total`:: (<>) Total amount of physical memory. `total_in_bytes`:: (integer) Total amount of physical memory in bytes. `free`:: (<>) Amount of free physical memory. `free_in_bytes`:: (integer) Amount of free physical memory in bytes. `used`:: (<>) Amount of used physical memory. `used_in_bytes`:: (integer) Amount of used physical memory in bytes. `free_percent`:: (integer) Percentage of free memory. `used_percent`:: (integer) Percentage of used memory. ======= `swap`:: (object) Contains statistics about swap space for the node. + .Properties of `swap` [%collapsible%open] ======= `total`:: (<>) Total amount of swap space. `total_in_bytes`:: (integer) Total amount of swap space in bytes. `free`:: (<>) Amount of free swap space. `free_in_bytes`:: (integer) Amount of free swap space in bytes. `used`:: (<>) Amount of used swap space. `used_in_bytes`:: (integer) Amount of used swap space in bytes. ======= `cgroup` (Linux only):: (object) Contains cgroup statistics for the node. + NOTE: For the cgroup stats to be visible, cgroups must be compiled into the kernel, the `cpu` and `cpuacct` cgroup subsystems must be configured and stats must be readable from `/sys/fs/cgroup/cpu` and `/sys/fs/cgroup/cpuacct`. + .Properties of `cgroup` [%collapsible%open] ======= `cpuacct` (Linux only):: (object) Contains statistics about `cpuacct` control group for the node. + .Properties of `cpuacct` [%collapsible%open] ======== `control_group` (Linux only):: (string) The `cpuacct` control group to which the {es} process belongs. `usage_nanos` (Linux only):: (integer) The total CPU time (in nanoseconds) consumed by all tasks in the same cgroup as the {es} process. ======== `cpu` (Linux only):: (object) Contains statistics about `cpu` control group for the node. + .Properties of `cpu` [%collapsible%open] ======== `control_group` (Linux only):: (string) The `cpu` control group to which the {es} process belongs. `cfs_period_micros` (Linux only):: (integer) The period of time (in microseconds) for how regularly all tasks in the same cgroup as the {es} process should have their access to CPU resources reallocated. `cfs_quota_micros` (Linux only):: (integer) The total amount of time (in microseconds) for which all tasks in the same cgroup as the {es} process can run during one period `cfs_period_micros`. `stat` (Linux only):: (object) Contains CPU statistics for the node. + .Properties of `stat` [%collapsible%open] ========= `number_of_elapsed_periods` (Linux only):: (integer) The number of reporting periods (as specified by `cfs_period_micros`) that have elapsed. `number_of_times_throttled` (Linux only):: (integer) The number of times all tasks in the same cgroup as the {es} process have been throttled. `time_throttled_nanos` (Linux only):: (integer) The total amount of time (in nanoseconds) for which all tasks in the same cgroup as the {es} process have been throttled. ========= ======== `memory` (Linux only):: (object) Contains statistics about the `memory` control group for the node. + .Properties of `memory` [%collapsible%open] ======== `control_group` (Linux only):: (string) The `memory` control group to which the {es} process belongs. `limit_in_bytes` (Linux only):: (string) The maximum amount of user memory (including file cache) allowed for all tasks in the same cgroup as the {es} process. This value can be too big to store in a `long`, so is returned as a string so that the value returned can exactly match what the underlying operating system interface returns. Any value that is too large to parse into a `long` almost certainly means no limit has been set for the cgroup. `usage_in_bytes` (Linux only):: (string) The total current memory usage by processes in the cgroup (in bytes) by all tasks in the same cgroup as the {es} process. This value is stored as a string for consistency with `limit_in_bytes`. ======== ======= ====== [[cluster-nodes-stats-api-response-body-process]] `process`:: (object) Contains process statistics for the node. + .Properties of `process` [%collapsible%open] ====== `timestamp`:: (integer) Last time the statistics were refreshed. Recorded in milliseconds since the {wikipedia}/Unix_time[Unix Epoch]. `open_file_descriptors`:: (integer) Number of opened file descriptors associated with the current or `-1` if not supported. `max_file_descriptors`:: (integer) Maximum number of file descriptors allowed on the system, or `-1` if not supported. `cpu`:: (object) Contains CPU statistics for the node. + .Properties of `cpu` [%collapsible%open] ======= `percent`:: (integer) CPU usage in percent, or `-1` if not known at the time the stats are computed. `total`:: (<>) CPU time used by the process on which the Java virtual machine is running. `total_in_millis`:: (integer) CPU time (in milliseconds) used by the process on which the Java virtual machine is running, or `-1` if not supported. ======= `mem`:: (object) Contains virtual memory statistics for the node. + .Properties of `mem` [%collapsible%open] ======= `total_virtual`:: (<>) Size of virtual memory that is guaranteed to be available to the running process. `total_virtual_in_bytes`:: (integer) Size in bytes of virtual memory that is guaranteed to be available to the running process. ======= ====== [[cluster-nodes-stats-api-response-body-jvm]] `jvm`:: (object) Contains Java Virtual Machine (JVM) statistics for the node. + .Properties of `jvm` [%collapsible%open] ====== `timestamp`:: (integer) Last time JVM statistics were refreshed. `uptime`:: (<>) JVM uptime. `uptime_in_millis`:: (integer) JVM uptime in milliseconds. `mem`:: (object) Contains JVM memory usage statistics for the node. + .Properties of `mem` [%collapsible%open] ======= `heap_used`:: (<>) Memory currently in use by the heap. `heap_used_in_bytes`:: (integer) Memory, in bytes, currently in use by the heap. `heap_used_percent`:: (integer) Percentage of memory currently in use by the heap. `heap_committed`:: (<>) Amount of memory available for use by the heap. `heap_committed_in_bytes`:: (integer) Amount of memory, in bytes, available for use by the heap. `heap_max`:: (<>) Maximum amount of memory available for use by the heap. `heap_max_in_bytes`:: (integer) Maximum amount of memory, in bytes, available for use by the heap. `non_heap_used`:: (<>) Non-heap memory used. `non_heap_used_in_bytes`:: (integer) Non-heap memory used, in bytes. `non_heap_committed`:: (<>) Amount of non-heap memory available. `non_heap_committed_in_bytes`:: (integer) Amount of non-heap memory available, in bytes. `pools`:: (object) Contains statistics about heap memory usage for the node. + .Properties of `pools` [%collapsible%open] ======== `young`:: (object) Contains statistics about memory usage by the young generation heap for the node. + .Properties of `young` [%collapsible%open] ========= `used`:: (<>) Memory used by the young generation heap. `used_in_bytes`:: (integer) Memory, in bytes, used by the young generation heap. `max`:: (<>) Maximum amount of memory available for use by the young generation heap. `max_in_bytes`:: (integer) Maximum amount of memory, in bytes, available for use by the young generation heap. `peak_used`:: (<>) Largest amount of memory historically used by the young generation heap. `peak_used_in_bytes`:: (integer) Largest amount of memory, in bytes, historically used by the young generation heap. `peak_max`:: (<>) Largest amount of memory historically used by the young generation heap. `peak_max_in_bytes`:: (integer) Largest amount of memory, in bytes, historically used by the young generation heap. ========= `survivor`:: (object) Contains statistics about memory usage by the survivor space for the node. + .Properties of `survivor` [%collapsible%open] ========= `used`:: (<>) Memory used by the survivor space. `used_in_bytes`:: (integer) Memory, in bytes, used by the survivor space. `max`:: (<>) Maximum amount of memory available for use by the survivor space. `max_in_bytes`:: (integer) Maximum amount of memory, in bytes, available for use by the survivor space. `peak_used`:: (<>) Largest amount of memory historically used by the survivor space. `peak_used_in_bytes`:: (integer) Largest amount of memory, in bytes, historically used by the survivor space. `peak_max`:: (<>) Largest amount of memory historically used by the survivor space. `peak_max_in_bytes`:: (integer) Largest amount of memory, in bytes, historically used by the survivor space. ========= `old`:: (object) Contains statistics about memory usage by the old generation heap for the node. + .Properties of `old` [%collapsible%open] ========= `used`:: (<>) Memory used by the old generation heap. `used_in_bytes`:: (integer) Memory, in bytes, used by the old generation heap. `max`:: (<>) Maximum amount of memory available for use by the old generation heap. `max_in_bytes`:: (integer) Maximum amount of memory, in bytes, available for use by the old generation heap. `peak_used`:: (<>) Largest amount of memory historically used by the old generation heap. `peak_used_in_bytes`:: (integer) Largest amount of memory, in bytes, historically used by the old generation heap. `peak_max`:: (<>) Highest memory limit historically available for use by the old generation heap. `peak_max_in_bytes`:: (integer) Highest memory limit, in bytes, historically available for use by the old generation heap. ========= ======== ======= `threads`:: (object) Contains statistics about JVM thread usage for the node. + .Properties of `threads` [%collapsible%open] ======= `count`:: (integer) Number of active threads in use by JVM. `peak_count`:: (integer) Highest number of threads used by JVM. ======= `gc`:: (object) Contains statistics about JVM garbage collectors for the node. + .Properties of `gc` [%collapsible%open] ======= `collectors`:: (object) Contains statistics about JVM garbage collectors for the node. + .Properties of `collectors` [%collapsible%open] ======== `young`:: (object) Contains statistics about JVM garbage collectors that collect young generation objects for the node. + .Properties of `young` [%collapsible%open] ========= `collection_count`:: (integer) Number of JVM garbage collectors that collect young generation objects. `collection_time`:: (<>) Total time spent by JVM collecting young generation objects. `collection_time_in_millis`:: (integer) Total time in milliseconds spent by JVM collecting young generation objects. ========= `old`:: (object) Contains statistics about JVM garbage collectors that collect old generation objects for the node. + .Properties of `old` [%collapsible%open] ========= `collection_count`:: (integer) Number of JVM garbage collectors that collect old generation objects. `collection_time`:: (<>) Total time spent by JVM collecting old generation objects. `collection_time_in_millis`:: (integer) Total time in milliseconds spent by JVM collecting old generation objects. ========= ======== ======= `buffer_pools`:: (object) Contains statistics about JVM buffer pools for the node. + .Properties of `buffer_pools` [%collapsible%open] ======= `mapped`:: (object) Contains statistics about mapped JVM buffer pools for the node. + .Properties of `mapped` [%collapsible%open] ======== `count`:: (integer) Number of mapped buffer pools. `used`:: (<>) Size of mapped buffer pools. `used_in_bytes`:: (integer) Size, in bytes, of mapped buffer pools. `total_capacity`:: (<>) Total capacity of mapped buffer pools. `total_capacity_in_bytes`:: (integer) Total capacity, in bytes, of mapped buffer pools. ======== `direct`:: (object) Contains statistics about direct JVM buffer pools for the node. + .Properties of `direct` [%collapsible%open] ======== `count`:: (integer) Number of direct buffer pools. `used`:: (<>) Size of direct buffer pools. `used_in_bytes`:: (integer) Size, in bytes, of direct buffer pools. `total_capacity`:: (<>) Total capacity of direct buffer pools. `total_capacity_in_bytes`:: (integer) Total capacity, in bytes, of direct buffer pools. ======== ======= `classes`:: (object) Contains statistics about classes loaded by JVM for the node. + .Properties of `classes` [%collapsible%open] ======= `current_loaded_count`:: (integer) Number of classes currently loaded by JVM. `total_loaded_count`:: (integer) Total number of classes loaded since the JVM started. `total_unloaded_count`:: (integer) Total number of classes unloaded since the JVM started. ======= ====== [[cluster-nodes-stats-api-response-body-threadpool]] `thread_pool`:: (object) Contains thread pool statistics for the node + .Properties of `thread_pool` [%collapsible%open] ====== ``:: (object) Contains statistics about the thread pool for the node. + .Properties of `` [%collapsible%open] ======= `threads`:: (integer) Number of threads in the thread pool. `queue`:: (integer) Number of tasks in queue for the thread pool. `active`:: (integer) Number of active threads in the thread pool. `rejected`:: (integer) Number of tasks rejected by the thread pool executor. `largest`:: (integer) Highest number of active threads in the thread pool. `completed`:: (integer) Number of tasks completed by the thread pool executor. ======= ====== [[cluster-nodes-stats-api-response-body-fs]] `fs`:: (object) Contains file store statistics for the node. + .Properties of `fs` [%collapsible%open] ====== `timestamp`:: (integer) Last time the file stores statistics were refreshed. Recorded in milliseconds since the {wikipedia}/Unix_time[Unix Epoch]. `total`:: (object) Contains statistics for all file stores of the node. + .Properties of `total` [%collapsible%open] ======= `total`:: (<>) Total size of all file stores. `total_in_bytes`:: (integer) Total size (in bytes) of all file stores. `free`:: (<>) Total unallocated disk space in all file stores. `free_in_bytes`:: (integer) Total number of unallocated bytes in all file stores. `available`:: (<>) Total disk space available to this Java virtual machine on all file stores. Depending on OS or process level restrictions, this might appear less than `free`. This is the actual amount of free disk space the {es} node can utilise. `available_in_bytes`:: (integer) Total number of bytes available to this Java virtual machine on all file stores. Depending on OS or process level restrictions, this might appear less than `free_in_bytes`. This is the actual amount of free disk space the {es} node can utilise. ======= [[cluster-nodes-stats-fs-data]] `data`:: (array of objects) List of all file stores. + .Properties of `data` [%collapsible%open] ======= `path`:: (string) Path to the file store. `mount`:: (string) Mount point of the file store (ex: /dev/sda2). `type`:: (string) Type of the file store (ex: ext4). `total`:: (<>) Total size of the file store. `total_in_bytes`:: (integer) Total size (in bytes) of the file store. `free`:: (<>) Total amount of unallocated disk space in the file store. `free_in_bytes`:: (integer) Total number of unallocated bytes in the file store. `available`:: (<>) Total amount of disk space available to this Java virtual machine on this file store. `available_in_bytes`:: (integer) Total number of bytes available to this Java virtual machine on this file store. ======= `io_stats` (Linux only):: (objects) Contains I/O statistics for the node. + .Properties of `io_stats` [%collapsible%open] ======= `devices` (Linux only):: (array) Array of disk metrics for each device that is backing an {es} data path. These disk metrics are probed periodically and averages between the last probe and the current probe are computed. + .Properties of `devices` [%collapsible%open] ======== `device_name` (Linux only):: (string) The Linux device name. `operations` (Linux only):: (integer) The total number of read and write operations for the device completed since starting {es}. `read_operations` (Linux only):: (integer) The total number of read operations for the device completed since starting {es}. `write_operations` (Linux only):: (integer) The total number of write operations for the device completed since starting {es}. `read_kilobytes` (Linux only):: (integer) The total number of kilobytes read for the device since starting {es}. `write_kilobytes` (Linux only):: (integer) The total number of kilobytes written for the device since starting {es}. ======== `operations` (Linux only):: (integer) The total number of read and write operations across all devices used by {es} completed since starting {es}. `read_operations` (Linux only):: (integer) The total number of read operations for across all devices used by {es} completed since starting {es}. `write_operations` (Linux only):: (integer) The total number of write operations across all devices used by {es} completed since starting {es}. `read_kilobytes` (Linux only):: (integer) The total number of kilobytes read across all devices used by {es} since starting {es}. `write_kilobytes` (Linux only):: (integer) The total number of kilobytes written across all devices used by {es} since starting {es}. ======= ====== [[cluster-nodes-stats-api-response-body-transport]] `transport`:: (object) Contains transport statistics for the node. + .Properties of `transport` [%collapsible%open] ====== `server_open`:: (integer) Current number of inbound TCP connections used for internal communication between nodes. `total_outbound_connections`:: (integer) The cumulative number of outbound transport connections that this node has opened since it started. Each transport connection may comprise multiple TCP connections but is only counted once in this statistic. Transport connections are typically <> so this statistic should remain constant in a stable cluster. `rx_count`:: (integer) Total number of RX (receive) packets received by the node during internal cluster communication. `rx_size`:: (<>) Size of RX packets received by the node during internal cluster communication. `rx_size_in_bytes`:: (integer) Size, in bytes, of RX packets received by the node during internal cluster communication. `tx_count`:: (integer) Total number of TX (transmit) packets sent by the node during internal cluster communication. `tx_size`:: (<>) Size of TX packets sent by the node during internal cluster communication. `tx_size_in_bytes`:: (integer) Size, in bytes, of TX packets sent by the node during internal cluster communication. ====== [[cluster-nodes-stats-api-response-body-http]] `http`:: (object) Contains http statistics for the node. + .Properties of `http` [%collapsible%open] ====== `current_open`:: (integer) Current number of open HTTP connections for the node. `total_opened`:: (integer) Total number of HTTP connections opened for the node. ====== [[cluster-nodes-stats-api-response-body-breakers]] `breakers`:: (object) Contains circuit breaker statistics for the node. + .Properties of `breakers` [%collapsible%open] ====== ``:: (object) Contains statistics for the circuit breaker. + .Properties of `` [%collapsible%open] ======= `limit_size_in_bytes`:: (integer) Memory limit, in bytes, for the circuit breaker. `limit_size`:: (<>) Memory limit for the circuit breaker. `estimated_size_in_bytes`:: (integer) Estimated memory used, in bytes, for the operation. `estimated_size`:: (<>) Estimated memory used for the operation. `overhead`:: (float) A constant that all estimates for the circuit breaker are multiplied with to calculate a final estimate. `tripped`:: (integer) Total number of times the circuit breaker has been triggered and prevented an out of memory error. ======= ====== [[cluster-nodes-stats-api-response-body-script]] `script`:: (object) Contains script statistics for the node. + .Properties of `script` [%collapsible%open] ====== `compilations`:: (integer) Total number of inline script compilations performed by the node. `cache_evictions`:: (integer) Total number of times the script cache has evicted old data. `compilation_limit_triggered`:: (integer) Total number of times the <> circuit breaker has limited inline script compilations. ====== [[cluster-nodes-stats-api-response-body-discovery]] `discovery`:: (object) Contains node discovery statistics for the node. + .Properties of `discovery` [%collapsible%open] ====== `cluster_state_queue`:: (object) Contains statistics for the cluster state queue of the node. + .Properties of `cluster_state_queue` [%collapsible%open] ======= `total`:: (integer) Total number of cluster states in queue. `pending`:: (integer) Number of pending cluster states in queue. `committed`:: (integer) Number of committed cluster states in queue. ======= `published_cluster_states`:: (object) Contains statistics for the published cluster states of the node. + .Properties of `published_cluster_states` [%collapsible%open] ======= `full_states`:: (integer) Number of published cluster states. `incompatible_diffs`:: (integer) Number of incompatible differences between published cluster states. `compatible_diffs`:: (integer) Number of compatible differences between published cluster states. ======= ====== [[cluster-nodes-stats-api-response-body-ingest]] `ingest`:: (object) Contains ingest statistics for the node. + .Properties of `ingest` [%collapsible%open] ====== `total`:: (object) Contains statistics about ingest operations for the node. + .Properties of `total` [%collapsible%open] ======= `count`:: (integer) Total number of documents ingested during the lifetime of this node. `time`:: (<>) Total time spent preprocessing ingest documents during the lifetime of this node. `time_in_millis`:: (integer) Total time, in milliseconds, spent preprocessing ingest documents during the lifetime of this node. `current`:: (integer) Total number of documents currently being ingested. `failed`:: (integer) Total number of failed ingest operations during the lifetime of this node. ======= `pipelines`:: (object) Contains statistics about ingest pipelines for the node. + .Properties of `pipelines` [%collapsible%open] ======= ``:: (object) Contains statistics about the ingest pipeline. + .Properties of `` [%collapsible%open] ======== `count`:: (integer) Number of documents preprocessed by the ingest pipeline. `time`:: (<>) Total time spent preprocessing documents in the ingest pipeline. `time_in_millis`:: (integer) Total time, in milliseconds, spent preprocessing documents in the ingest pipeline. `failed`:: (integer) Total number of failed operations for the ingest pipeline. `processors`:: (array of objects) Contains statistics for the ingest processors for the ingest pipeline. + .Properties of `processors` [%collapsible%open] ========= ``:: (object) Contains statistics for the ingest processor. + .Properties of `` [%collapsible%open] ========== `count`:: (integer) Number of documents transformed by the processor. `time`:: (<>) Time spent by the processor transforming documents. `time_in_millis`:: (integer) Time, in milliseconds, spent by the processor transforming documents. `current`:: (integer) Number of documents currently being transformed by the processor. `failed`:: (integer) Number of failed operations for the processor. ========== ========= ======== ======= ====== [[cluster-nodes-stats-api-response-body-indexing-pressure]] `indexing_pressure`:: (object) Contains <> statistics for the node. + .Properties of `indexing_pressure` [%collapsible%open] ====== `memory`:: (object) Contains statistics for memory consumption from indexing load. + .Properties of `` [%collapsible%open] ======= `current`:: (object) Contains statistics for current indexing load. + .Properties of `` [%collapsible%open] ======== `combined_coordinating_and_primary`:: (<>) Memory consumed by indexing requests in the coordinating or primary stage. This value is not the sum of coordinating and primary as a node can reuse the coordinating memory if the primary stage is executed locally. `combined_coordinating_and_primary_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the coordinating or primary stage. This value is not the sum of coordinating and primary as a node can reuse the coordinating memory if the primary stage is executed locally. `coordinating`:: (<>) Memory consumed by indexing requests in the coordinating stage. `coordinating_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the coordinating stage. `primary`:: (<>) Memory consumed by indexing requests in the primary stage. `primary_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the primary stage. `replica`:: (<>) Memory consumed by indexing requests in the replica stage. `replica_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the replica stage. `all`:: (<>) Memory consumed by indexing requests in the coordinating, primary, or replica stage. `all_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the coordinating, primary, or replica stage. ======== `total`:: (object) Contains statistics for the cumulative indexing load since the node started. + .Properties of `` [%collapsible%open] ======== `combined_coordinating_and_primary`:: (<>) Memory consumed by indexing requests in the coordinating or primary stage. This value is not the sum of coordinating and primary as a node can reuse the coordinating memory if the primary stage is executed locally. `combined_coordinating_and_primary_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the coordinating or primary stage. This value is not the sum of coordinating and primary as a node can reuse the coordinating memory if the primary stage is executed locally. `coordinating`:: (<>) Memory consumed by indexing requests in the coordinating stage. `coordinating_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the coordinating stage. `primary`:: (<>) Memory consumed by indexing requests in the primary stage. `primary_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the primary stage. `replica`:: (<>) Memory consumed by indexing requests in the replica stage. `replica_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the replica stage. `all`:: (<>) Memory consumed by indexing requests in the coordinating, primary, or replica stage. `all_in_bytes`:: (integer) Memory consumed, in bytes, by indexing requests in the coordinating, primary, or replica stage. `coordinating_rejections`:: (integer) Number of indexing requests rejected in the coordinating stage. `primary_rejections`:: (integer) Number of indexing requests rejected in the primary stage. `replica_rejections`:: (integer) Number of indexing requests rejected in the replica stage. ======== `limit`:: (<>) Configured memory limit for the indexing requests. Replica requests have an automatic limit that is 1.5x this value. `limit_in_bytes`:: (integer) Configured memory limit, in bytes, for the indexing requests. Replica requests have an automatic limit that is 1.5x this value. ======= ====== [[cluster-nodes-stats-api-response-body-adaptive-selection]] `adaptive_selection`:: (object) Contains adaptive selection statistics for the node. + .Properties of `adaptive_selection` [%collapsible%open] ====== `outgoing_searches`:: (integer) The number of outstanding search requests from the node these stats are for to the keyed node. `avg_queue_size`:: (integer) The exponentially weighted moving average queue size of search requests on the keyed node. `avg_service_time`:: (<>) The exponentially weighted moving average service time of search requests on the keyed node. `avg_service_time_ns`:: (integer) The exponentially weighted moving average service time, in nanoseconds, of search requests on the keyed node. `avg_response_time`:: (<>) The exponentially weighted moving average response time of search requests on the keyed node. `avg_response_time_ns`:: (integer) The exponentially weighted moving average response time, in nanoseconds, of search requests on the keyed node. `rank`:: (string) The rank of this node; used for shard selection when routing search requests. ====== ===== ==== [[cluster-nodes-stats-api-example]] ==== {api-examples-title} [source,console] -------------------------------------------------- # return just indices GET /_nodes/stats/indices # return just os and process GET /_nodes/stats/os,process # return just process for node with IP address 10.0.0.1 GET /_nodes/10.0.0.1/stats/process -------------------------------------------------- All stats can be explicitly requested via `/_nodes/stats/_all` or `/_nodes/stats?metric=_all`. You can get information about indices stats on `node`, `indices`, or `shards` level. [source,console] -------------------------------------------------- # Fielddata summarized by node GET /_nodes/stats/indices/fielddata?fields=field1,field2 # Fielddata summarized by node and index GET /_nodes/stats/indices/fielddata?level=indices&fields=field1,field2 # Fielddata summarized by node, index, and shard GET /_nodes/stats/indices/fielddata?level=shards&fields=field1,field2 # You can use wildcards for field names GET /_nodes/stats/indices/fielddata?fields=field* -------------------------------------------------- You can get statistics about search groups for searches executed on this node. [source,console] -------------------------------------------------- # All groups with all stats GET /_nodes/stats?groups=_all # Some groups from just the indices stats GET /_nodes/stats/indices?groups=foo,bar -------------------------------------------------- [[cluster-nodes-stats-ingest-ex]] ===== Retrieve ingest statistics only To return only ingest-related node statistics, set the `` path parameter to `ingest` and use the <> query parameter. [source,console] -------------------------------------------------- GET /_nodes/stats/ingest?filter_path=nodes.*.ingest -------------------------------------------------- You can use the `metric` and `filter_path` query parameters to get the same response. [source,console] -------------------------------------------------- GET /_nodes/stats?metric=ingest&filter_path=nodes.*.ingest -------------------------------------------------- To further refine the response, change the `filter_path` value. For example, the following request only returns ingest pipeline statistics. [source,console] -------------------------------------------------- GET /_nodes/stats?metric=ingest&filter_path=nodes.*.ingest.pipelines -------------------------------------------------- ",12276,True,2566.849739418258,median "--- title: Συχνές Ερωτήσεις Σχετικά με τις Λίστες Ηλεκτρονικού Ταχυδρομείου του FreeBSD authors: - author: Η Ομάδα Τεκμηρίωσης του FreeBSD --- = Συχνές Ερωτήσεις Σχετικά με τις Λίστες Ηλεκτρονικού Ταχυδρομείου του FreeBSD :doctype: article :toc: macro :toclevels: 1 :icons: font :sectnums: :sectnumlevels: 6 :source-highlighter: rouge :experimental: :images-path: articles/mailing-list-faq/ ifdef::env-beastie[] ifdef::backend-html5[] include::shared/authors.adoc[] include::shared/mirrors.adoc[] include::shared/releases.adoc[] include::shared/attributes/attributes-{{% lang %}}.adoc[] include::shared/{{% lang %}}/teams.adoc[] include::shared/{{% lang %}}/mailing-lists.adoc[] include::shared/{{% lang %}}/urls.adoc[] :imagesdir: ../../../images/{images-path} endif::[] ifdef::backend-pdf,backend-epub3[] include::../../../../shared/asciidoctor.adoc[] endif::[] endif::[] ifndef::env-beastie[] include::../../../../../shared/asciidoctor.adoc[] endif::[] [.abstract-title] Περίληψη Το άρθρο αυτό αποτελεί τις συχνές ερωτήσεις για τις λίστες ταχυδρομείου του FreeBSD. Αν ενδιαφέρεστε να βοηθήσετε σε αυτό το έργο, στείλτε ένα email στην {freebsd-doc}. Η τελευταία έκδοση αυτού του εγγράφου είναι πάντοτε διαθέσιμη στην extref:{mailing-list-faq}[Δικτυακή τοποθεσία του FreeBSD]. Μπορείτε επίσης να το κατεβάσετε ως ένα μεγάλο αρχείο link:.[HTML] ή και ως απλό κείμενο, PostScript, PDF, κ.λ.π. από τον link:ftp://ftp.FreeBSD.org/pub/FreeBSD/doc/[Διακομιστή FTP του FreeBSD]. Μπορεί επίσης να θέλετε να link:https://www.FreeBSD.org/search/[ψάξετε σε αυτό το άρθρο]. ''' toc::[] [[introduction]] == Εισαγωγή Όπως συνηθίζεται στα κείμενα των Συχνών Ερωτήσεων (FAQ), το κείμενο αυτό περιέχει τις πιο συχνές ερωτήσεις που σχετίζονται με τις λίστες ταχυδρομείου του FreeBSD (και φυσικά τις απαντάει!). Αν και ο αρχικός σκοπός των FAQ ήταν να μειώσουν το εύρος ζώνης που απαιτείται από την συνεχόμενη απάντηση των ίδιων και ίδιων ερωτήσεων, τα FAQ τελικά καθιερώθηκαν ως μια πολύ χρήσιμη αυτόνομη πηγή πληροφοριών. Το κείμενο αυτό προσπαθεί να αντιπροσωπεύσει την κοινά αποδεκτή γνώμη της κοινότητας και ως τέτοιο, δεν μπορεί σε καμιά περίπτωση να θεωρηθεί ότι είναι απόλυτα __έγκυρο__. Αν ωστόσο βρείτε τεχνικά λάθη ή έχετε να προτείνετε θέματα που πρέπει να προστεθούν, παρακαλούμε στείλτε μας μια αναφορά προβλήματος (PR) ή ένα email στην {freebsd-doc}. Ευχαριστούμε! === Ποιος είναι ο σκοπός των λιστών ταχυδρομείου του FreeBSD; Οι λίστες ταχυδρομείου του FreeBSD αποτελούν το βασικό κανάλι επικοινωνίας για την κοινότητα του FreeBSD. Καλύπτουν πολλές διαφορετικές περιοχές θεμάτων και ενδιαφερόντων. === Ποιο είναι το κοινό για τις λίστες ταχυδρομείου του FreeBSD; Αυτό εξαρτάται από τον κανονισμό της κάθε λίστας. Μερικές λίστες είναι περισσότερο προσανατολισμένες στους προγραμματιστές. Άλλες προσανατολίζονται περισσότερο στην κοινότητα του FreeBSD ως σύνολο. Παρακαλούμε δείτε http://lists.FreeBSD.org/mailman/listinfo[αυτή τη λίστα] για την τρέχουσα περίληψη. === Είναι όλες οι λίστες του FreeBSD ανοιχτές για συμμετοχή από τον καθένα; Και πάλι, αυτό εξαρτάται από τον κανονισμό της κάθε λίστας. Σας παρακαλούμε να διαβάσετε τον κανονισμό της λίστας που σας ενδιαφέρει πριν αρχίσετε να δημοσιεύετε σε αυτήν και να τον σέβεστε σε κάθε δημοσίευση σας. Αυτό βοηθάει όλους τους συμμετέχοντες να έχουν την καλύτερη δυνατή εμπειρία από τις λίστες μας. Αν διαβάζοντας τους κανονισμούς για τις παραπάνω λίστες, δεν μπορείτε ακόμα να αποφασίσετε σε ποια λίστα να στείλετε την ερώτηση σας, μάλλον θα πρέπει να την στείλετε στην {freebsd-questions} (αλλά δείτε πρώτα παρακάτω). Σημειώστε επίσης ότι κατά παράδοση οι λίστες είναι ανοιχτές και σε άτομα που δεν έχουν εγγραφεί σε αυτές. Αυτή η επιλογή είναι εσκεμμένη, με σκοπό να βοηθήσει τους νέους χρήστες να εισέλθουν πιο εύκολα στην κοινότητα του FreeBSD, και να ενισχύσει την ανοιχτή ανταλλαγή ιδεών. Ωστόσο, λόγω κακής χρήσης από συγκεκριμένα άτομα, κάποιες λίστες έχουν τώρα τον περιορισμό ότι κάθε μήνυμα από μη-μέλος θα πρέπει να ελέγχεται χειροκίνητα για να εξασφαλιστεί ότι είναι κατάλληλο. === Πως μπορώ να εγγραφώ; Μπορείτε να χρησιμοποιήσετε την http://lists.FreeBSD.org/mailman/listinfo[διεπαφή Web του Mailman] για να γραφείτε σε οποιαδήποτε από τις δημόσιες λίστες. === Πως μπορώ να διαγραφώ; Με τον ίδιο τρόπο που εγγραφήκατε. Ή μπορείτε επίσης να ακολουθήσετε τις οδηγίες που βρίσκονται στο τέλος κάθε μηνύματος που στέλνει η λίστα. Σας παρακαλούμε μη στέλνετε μηνύματα διαγραφής απευθείας σε δημόσιες λίστες. Πρώτα από όλα, αυτό δεν θα επιτύχει το σκοπό σας, και δεύτερον θα εκνευρίσει τους υπάρχοντες συνδρομητές οι οποίοι θα λογομαχήσουν εναντίον σας. Πρόκειται για κλασικό λάθος κατά τη χρήση λιστών ταχυδρομείου και σας παρακαλούμε να προσπαθήσετε να το αποφύγετε. === Είναι διαθέσιμα τα αρχεία των λιστών; Ναι. Μπορείτε να τα βρείτε http://docs.FreeBSD.org/mail/[εδώ], ταξινομημένα κατά θέμα. === Είναι διαθέσιμες οι λίστες σε μορφή περίληψης; Ναι. Δείτε http://lists.FreeBSD.org/mailman/listinfo[τη διεπαφή web του Mailman]. [[etiquette]] == Συμπεριφορά (Etiquette) στις Λίστες Η συμμετοχή στις λίστες ηλεκτρονικού ταχυδρομείου, όπως και η συμμετοχή σε οποιαδήποτε κοινότητα, απαιτεί μια κοινή βάση επικοινωνίας. Σας παρακαλούμε να κάνετε μόνο κατάλληλες δημοσιεύσεις, και να ακολουθείτε τους κοινούς κανόνες συμπεριφοράς. === Τι πρέπει να κάνω πριν από μια δημοσίευση; Διαβάζοντας αυτό το κείμενο, έχετε ήδη κάνει το πιο σημαντικό βήμα. Ωστόσο, αν είστε νέος στο FreeBSD, θα πρέπει πρώτα να εξοικειωθείτε με το λογισμικό και όλη την κοινωνική ιστορία που το περιβάλλει, διαβάζοντας τα διάφορα link:https://www.FreeBSD.org/docs/books/[άρθρα και βιβλία] τα οποία είναι διαθέσιμα. Ιδιαίτερο ενδιαφέρον έχουν extref:{faq}[Οι Συχνές Ερωτήσεις (FAQ) του FreeBSD], το extref:{handbook}[Εγχειρίδιο του FreeBSD] καθώς και τα άρθρα extref:{freebsd-questions-article}[Πως να χρησιμοποιείτε με επιτυχία τη λίστα ηλεκτρονικού ταχυδρομείου FreeBSD-questions], extref:{explaining-bsd}[Περιγραφή των Συστημάτων BSD], και extref:{new-users}[Για Χρήστες Νέους τόσο στο FreeBSD όσο και στο UNIX(R)]. Θεωρείται γενικά κακή συμπεριφορά να ρωτήσετε μια ερώτηση η οποία μπορεί να απαντηθεί από κάποιο από τα παραπάνω κείμενα. Αυτό δεν συμβαίνει επειδή οι εθελοντές που δουλεύουν σε αυτό το έργο είναι κακοί άνθρωποι, αλλά επειδή όταν έχουν απαντήσει την ίδια ερώτηση πολλές φορές, αρχίζει να τους ενοχλεί. Αυτό συμβαίνει ειδικά αν υπάρχει διαθέσιμη η απάντηση της ερώτησης. Να θυμάστε πάντα ότι σχεδόν όλη η δουλειά στο FreeBSD γίνεται από εθελοντές και τελικά είμαστε απλώς άνθρωποι. === Τι δημοσίευση μπορεί να θεωρηθεί ακατάλληλη; * Η δημοσίευση πρέπει να είναι σύμφωνη με τους κανονισμούς της λίστας. * Οι προσωπικές επιθέσεις είναι γενικά ανεπιθύμητες. Σαν καλοί διαδικτυακοί πολίτες, θα πρέπει να προσπαθούμε να κρατάμε υψηλά επίπεδα συμπεριφοράς. * Το spam δεν επιτρέπεται ποτέ. Γίνεται επεξεργασία στις λίστες για να απαγορευτούν οι δημοσιεύσεις σε όσους παραβαίνουν αυτό τον κανόνα. === Ποια θεωρείται σωστή συμπεριφορά στην αποστολή μηνυμάτων στις λίστες; * Παρακαλούμε να κάνετε αναδίπλωση των γραμμών κάθε 75 χαρακτήρες. Δεν χρησιμοποιούν όλοι GUI προγράμματα για να διαβάζουν το mail τους. * Παρακαλούμε σεβαστείτε το γεγονός ότι το εύρος ζώνης δεν είναι απεριόριστο. Δεν διαβάζει καθένας το email του μέσω συνδέσεων υψηλής ταχύτητας, έτσι αν το μήνυμα σας περιέχει κάτι σαν το περιεχόμενο του αρχείου [.filename]#config.log# ή ένα εκτεταμένο stack trace, σας παρακαλούμε να ανεβάσετε αυτές τις πληροφορίες σε κάποια δικτυακή τοποθεσία και να στείλετε ένα σύνδεσμο προς αυτές. Να θυμάστε επίσης ότι γίνεται αρχειοθέτηση αυτών των μηνυμάτων, έτσι αν στείλετε ένα τεράστιο μήνυμα θα μεγαλώσετε και το μέγεθος των αρχείων, ακόμα και όταν αυτές οι πληροφορίες δεν θα είναι πια χρήσιμες. * Μορφοποιήστε το μήνυμα σας ώστε να είναι ευανάγνωστο και σας παρακαλούμε ΜΗ ΦΩΝΑΖΕΤΕ!!!. Μην υποτιμάτε το αποτέλεσμα που θα έχει ένα φτωχά μορφοποιημένο μήνυμα, και αυτό δεν συμβαίνει μόνο στις λίστες του FreeBSD. Το μήνυμα σας είναι το μόνο που σας γνωστοποιεί στους υπόλοιπους ανθρώπους, και αν είναι άσχημα μορφοποιημένο, γεμάτο θαυμαστικά, θα αφήσει στους άλλους άσχημη εντύπωση για εσάς. * Χρησιμοποιήστε την κατάλληλη γλώσσα για τη λίστα ταχυδρομείου που πρόκειται να στείλετε μήνυμα. Μπορείτε να δείτε link:https://www.FreeBSD.org/community/mailinglists/[εδώ] τις λίστες που υπάρχουν σε γλώσσες εκτός της Αγγλικής. + Όσο αφορά τις Αγγλικές λίστες, αντιλαμβανόμαστε ότι για πολλούς η Αγγλική δεν είναι η μητρική τους γλώσσα και δείχνουμε κατανόηση. Θεωρείται κακή συμπεριφορά να κατακρίνετε όσους δεν έχουν τα Αγγλικά ως μητρική γλώσσα για λάθη γραμματικής ή ορθογραφίας. Το FreeBSD έχει μια πολύ καλή παράδοση σε αυτό το θέμα, σας παρακαλούμε να μας βοηθήσετε να τη διατηρήσουμε. * Παρακαλούμε χρησιμοποιήστε ένα πρόγραμμα αποστολής ταχυδρομείου (MUA) που να ακολουθεί σωστά τα πρότυπα. Πολλά από τα άσχημα μορφοποιημένα μηνύματα προέρχονται από http://www.lemis.com/email.html[κακής ποιότητας ή κακορυθμισμένα προγράμματα ταχυδρομείου]. Τα παρακάτω προγράμματα είναι γνωστό ότι στέλνουν προβληματικά μηνύματα, χωρίς εσείς να το γνωρίζετε: ** cc:Mail ** exmh ** Microsoft(R) Exchange ** Microsoft(R) Internet Mail ** Microsoft(R) Outlook(R) ** Netscape(R) (παλιότερες εκδόσεις) + Όπως μπορείτε να δείτε, πολλά από τα προβληματικά προγράμματα προέρχονται από τον κόσμο της Microsoft. Αν είναι δυνατόν χρησιμοποιήστε ένα πρόγραμμα που να προέρχεται από το UNIX(R). Αν πρέπει να χρησιμοποιήσετε ένα πρόγραμμα σε περιβάλλον Microsoft, φροντίστε να είναι ρυθμισμένο σωστά. Προσπαθήστε να μην χρησιμοποιήσετε MIME: αρκετός κόσμος χρησιμοποιεί προγράμματα ταχυδρομείου που δεν τα πάνε πολύ καλά με το MIME. * Βεβαιωθείτε ότι η ώρα και η ζώνη ώρας στον υπολογιστή σας είναι σωστά ρυθμισμένα. Αυτό μπορεί να φαίνεται κάπως ανόητο, ειδικά καθώς το μήνυμα σας θα φτάσει έτσι και αλλιώς, αλλά αρκετοί άνθρωποι σε αυτές τις λίστες λαμβάνουν εκατοντάδες μηνύματα κάθε μέρα. Συχνά τα ταξινομούν κατά θέμα και ημερομηνία, έτσι αν το μήνυμα σας έρθει μετά την πρώτη απάντηση θα θεωρήσουν ότι το έχασαν και δεν θα ασχοληθούν να το ψάξουν. * Πολλές φορές οι πληροφορίες που πρέπει να παρέχετε περιέχουν την έξοδο προγραμμάτων όπως το man:dmesg[8], ή τα μηνύματα που εμφανίζονται στην κονσόλα, τα οποία συνήθως γράφονται στο [.filename]#/var/log/messages#. Μην προσπαθήσετε να αντιγράψετε αυτές τις πληροφορίες πληκτρολογώντας τις ξανά: όχι μόνο είναι βασανιστικό, αλλά είναι σχεδόν σίγουρο ότι θα κάνετε κάποιο λάθος. Για να στείλετε τα περιεχόμενα κάποιου αρχείου καταγραφής, είτε αντιγράψτε το αρχείο και χρησιμοποιήστε κάποιο συντάκτη κειμένου για να κόψετε τα κομμάτια που σας ενδιαφέρουν, ή κάντε αποκοπή και επικόλληση μέσα στο μήνυμα σας. Για την έξοδο προγραμμάτων όπως το `dmesg`, χρησιμοποιήστε ανακατεύθυνση της εξόδου σε ένα αρχείο και στείλτε αυτό. Για παράδειγμα: + [source,shell] .... % dmesg > /tmp/dmesg.out .... + Το παραπάνω θα ανακατευθύνει τις πληροφορίες στο αρχείο [.filename]#/tmp/dmesg.out#. * Όταν χρησιμοποιείτε αποκοπή και επικόλληση να έχετε υπόψη σας ότι αυτές οι λειτουργίες μπορεί να καταστρέψουν το νόημα των μηνυμάτων. Αυτό συμβαίνει ιδιαίτερα όταν στέλνετε αρχεία όπως τα [.filename]#Makefiles#, όπου το `tab` είναι σημαντικός χαρακτήρας. Πρόκειται για πολύ κοινό και ενοχλητικό πρόβλημα ειδικά σε μηνύματα που απευθύνονται στη link:https://www.FreeBSD.org/support/gnats[Βάση Δεδομένων Προβλημάτων GNATS]. Τα [.filename]#Makefiles# όπου τα tabs έχουν αλλάξει είτε σε κενά ή στον ενοχλητικό χαρακτήρα `=3B` δημιουργούν πολλά ενοχλητικά προβλήματα στους committers. === Τι πρέπει να έχω υπόψη μου όσο αφορά τη συμπεριφορά στη λίστα όταν απαντάω σε κάποιο υπάρχον μήνυμα; * Παρακαλούμε να συμπεριλάβετε το σχετικό κείμενο από το αρχικό κείμενο. Περιορίστε το στο ελάχιστο, αλλά μη το παρακάνετε. Θα πρέπει κάποιος που δεν έχει δει το αρχικό μήνυμα να μπορεί να καταλάβει σε τι αναφέρεται η συζήτηση. + Αυτό είναι ιδιαίτερα σημαντικό σε μηνύματα του τύπου ""Ναι και σε μένα συμβαίνει το ίδιο"", όπου το αρχικό μήνυμα μπορεί να ήταν αρκετές δεκάδες ή εκατοντάδες γραμμές. * Χρησιμοποιήστε κάποια τεχνική με την οποία να γίνεται δυνατή η αναγνώριση του κειμένου που ανήκει στο αρχικό μήνυμα και του κειμένου που προσθέσατε. Μια συνηθισμένη σύμβαση είναι να χρησιμοποιείται το ""`> `"" μπροστά από το αρχικό μήνυμα. Είναι επίσης καλή ιδέα να αφήνετε κενό διάστημα μετά το ""`> `"" και κενές γραμμές ανάμεσα στο δικό σας και το αρχικό, ώστε το τελικό αποτέλεσμα να είναι πιο ευανάγνωστο. * Να βεβαιώνεστε πάντα ότι οι αναφορές στον αρχικό συγγραφέα του μηνύματος είναι σωστές. Συχνά οι άνθρωποι προσβάλλονται αν τους εμφανίζετε να έχουν γράψει λέξεις ενώ αυτό δεν συμβαίνει. * Παρακαλούμε μην κάνετε `top post`. Αυτό σημαίνει να μην ξεκινάτε την απάντηση σας πάνω από το κείμενο του μηνύματος στο οποίο απαντάτε. + ** Απ: Γιατί αντιστρέφει τη λογική ροή της συζήτησης. ** Ερ: Γιατί θεωρείται κακό το top posting; + (Ευχαριστούμε το Randy Bush για το ανέκδοτο.) [[recurring]] == Επαναλαμβανόμενα Θέματα στις Λίστες Ταχυδρομείου Η συμμετοχή στις λίστες ταχυδρομείου, όπως και η συμμετοχή σε κάθε κοινότητα, απαιτεί μια κοινή βάση επικοινωνίας. Πολλές από τις λίστες ταχυδρομείου προϋποθέτουν γνώση της ιστορίας του Project. Ειδικότερα, φαίνεται ότι κάποια θέματα προκύπτουν ξανά και ξανά στα νεώτερα μέλη της κοινότητας. Είναι ευθύνη του καθένα που συμμετέχει να φροντίζει ώστε τα μηνύματα του να μην εμπίπτουν σε κάποια από αυτές τις κατηγορίες. Με τον τρόπο αυτό, βοηθάτε τις λίστες ταχυδρομείου να μην ξεφεύγουν από το θέμα τους, και πιθανόν προφυλάσσετε και τον εαυτό σας από τυχόν λεκτικές επιθέσεις (flames). Η καλύτερη μέθοδος για να αποφύγετε το παραπάνω πρόβλημα είναι να εξοικειωθείτε με τα http://docs.FreeBSD.org/mail/[αρχεία των λιστών] για να μπορέσετε να καταλάβετε το ιστορικό της συζήτησης. Ιδιαίτερα χρήσιμη για αυτό το σκοπό θα σας φανεί και η link:https://www.FreeBSD.org/search/#mailinglists[λειτουργία αναζήτησης της λίστας]. (Αν η μέθοδος αυτή δεν φέρει το επιθυμητό αποτέλεσμα, συμπληρώστε την με μια αναζήτηση μέσω της μηχανής αναζήτησης που προτιμάτε). Όταν θα έχετε εξοικειωθεί με τα αρχεία της λίστας, όχι μόνο θα γνωρίζετε ποια θέματα έχουν συζητηθεί παλιότερα, αλλά και με ποιο τρόπο εξελίσσονται συνήθως οι συζητήσεις σε αυτή τη λίστα, ποιοι είναι οι συμμετέχοντες και σε ποιο κοινό απευθύνεται. Είναι πάντοτε καλό να γνωρίζετε εκ των προτέρων τα παραπάνω πριν στείλετε μήνυμα σε οποιαδήποτε λίστα (όχι μόνο του FreeBSD). Δεν υπάρχει αμφιβολία ότι τα αρχεία έχουν μεγάλη έκταση και μερικές ερωτήσεις φαίνονται να επαναλαμβάνονται πιο συχνά από άλλες, μερικές φορές σαν απαντήσεις όπου το θέμα που αναγράφεται στο μήνυμα δεν αντιπροσωπεύει πλέον το νέο περιεχόμενο. Ωστόσο πέφτει σε σας το βάρος να κάνετε όλη την εργασία που χρειάζεται ώστε να αποφύγετε αυτά τα επαναλαμβανόμενα θέματα. [[bikeshed]] == Τι είναι το ""Bikeshed""; Κυριολεκτικά το `bikeshed` είναι ένα μικρό εξωτερικό καταφύγιο όπου κάποιος μπορεί να φυλάξει το δίτροχο του (υπόστεγο ποδηλάτων). Στην ορολογία του FreeBSD ωστόσο, η λέξη αυτή χρησιμοποιείται για να αναφερόμαστε σε θέματα συζήτησης που είναι τόσο απλά ώστε (σχεδόν) καθένας να μπορεί να εκφέρει μια γνώμη για αυτά - και πολύ συχνά συμβαίνει ακριβώς αυτό. Η γέννηση αυτού του όρου εξηγείται με περισσότερη λεπτομέρεια σε extref:{faq}[αυτό το κείμενο, BIKESHED-PAINTING]. Θα πρέπει να κατανοείτε την έννοια αυτού του όρου πριν αρχίσετε να στέλνετε μηνύματα σε οποιαδήποτε λίστα του FreeBSD. Πιο γενικά, το bikeshed είναι ένα θέμα το οποίο τείνει να δημιουργεί περισσότερες παράπλευρες συζητήσεις και λεκτικούς διαξιφισμούς, αν δεν έχετε διαβάσει σχετικά με την προϊστορία του. Σας παρακαλούμε να μας βοηθήσετε να κρατήσουμε τις λίστες ταχυδρομείου όσο το δυνατόν πιο χρήσιμες γίνεται για τον περισσότερο κόσμο, προσπαθώντας να αποφύγετε τα bikesheds όποτε είναι δυνατόν. Ευχαριστούμε! [[acknowledgments]] == Ευχαριστίες `{grog}`:: Ο αρχικός συγγραφέας του περισσότερου υλικού που αφορά τους κανονισμούς των λιστών, που προέρχονται από το άρθρο extref:{freebsd-questions-article}[Πως να χρησιμοποιείτε με επιτυχία την λίστα ηλεκτρονικού ταχυδρομείου FreeBSD-questions]. `{linimon}`:: Δημιουργία του πρόχειρου αντίγραφου αυτού του FAQ. ",12292,True,3001.633607731472,median "[[netty-component]] = Netty Component :page-source: components/camel-netty/src/main/docs/netty-component.adoc *Since Camel 2.14* The Netty component in Camel is a socket communication component, based on the http://netty.io/[Netty] project version 4. + Netty is a NIO client server framework which enables quick and easy development of networkServerInitializerFactory applications such as protocol servers and clients. + Netty greatly simplifies and streamlines network programming such as TCP and UDP socket server. This camel component supports both producer and consumer endpoints. The Netty component has several options and allows fine-grained control of a number of TCP/UDP communication parameters (buffer sizes, keepAlives, tcpNoDelay, etc) and facilitates both In-Only and In-Out communication on a Camel route. Maven users will need to add the following dependency to their `pom.xml` for this component: [source,xml] ---- org.apache.camel camel-netty x.x.x ---- == URI format The URI scheme for a netty component is as follows [source,text] ---- netty:tcp://0.0.0.0:99999[?options] netty:udp://remotehost:99999/[?options] ---- This component supports producer and consumer endpoints for both TCP and UDP. You can append query options to the URI in the following format, `?option=value&option=value&...` == Options // component options: START The Netty component supports 6 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *maximumPoolSize* (advanced) | The thread pool size for the EventExecutorGroup if its in use. The default value is 16. | 16 | int | *configuration* (advanced) | To use the NettyConfiguration as configuration when creating endpoints. | | NettyConfiguration | *executorService* (advanced) | To use the given EventExecutorGroup. | | EventExecutorGroup | *useGlobalSslContext Parameters* (security) | Enable usage of global SSL context parameters. | false | boolean | *sslContextParameters* (security) | To configure security using SSLContextParameters | | SSLContextParameters | *basicPropertyBinding* (advanced) | Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean |=== // component options: END // endpoint options: START The Netty endpoint is configured using URI syntax: ---- netty:protocol:host:port ---- with the following path and query parameters: === Path Parameters (3 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *protocol* | *Required* The protocol to use which can be tcp or udp. | | String | *host* | *Required* The hostname. For the consumer the hostname is localhost or 0.0.0.0. For the producer the hostname is the remote host to connect to | | String | *port* | *Required* The host port number | | int |=== === Query Parameters (71 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *disconnect* (common) | Whether or not to disconnect(close) from Netty Channel right after use. Can be used for both consumer and producer. | false | boolean | *keepAlive* (common) | Setting to ensure socket is not closed due to inactivity | true | boolean | *reuseAddress* (common) | Setting to facilitate socket multiplexing | true | boolean | *reuseChannel* (common) | This option allows producers and consumers (in client mode) to reuse the same Netty Channel for the lifecycle of processing the Exchange. This is useful if you need to call a server multiple times in a Camel route and want to use the same network connection. When using this, the channel is not returned to the connection pool until the Exchange is done; or disconnected if the disconnect option is set to true. The reused Channel is stored on the Exchange as an exchange property with the key NettyConstants#NETTY_CHANNEL which allows you to obtain the channel during routing and use it as well. | false | boolean | *sync* (common) | Setting to set endpoint as one-way or request-response | true | boolean | *tcpNoDelay* (common) | Setting to improve TCP protocol performance | true | boolean | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *broadcast* (consumer) | Setting to choose Multicast over UDP | false | boolean | *clientMode* (consumer) | If the clientMode is true, netty consumer will connect the address as a TCP client. | false | boolean | *reconnect* (consumer) | Used only in clientMode in consumer, the consumer will attempt to reconnect on disconnection if this is enabled | true | boolean | *reconnectInterval* (consumer) | Used if reconnect and clientMode is enabled. The interval in milli seconds to attempt reconnection | 10000 | int | *backlog* (consumer) | Allows to configure a backlog for netty consumer (server). Note the backlog is just a best effort depending on the OS. Setting this option to a value such as 200, 500 or 1000, tells the TCP stack how long the accept queue can be If this option is not configured, then the backlog depends on OS setting. | | int | *bossCount* (consumer) | When netty works on nio mode, it uses default bossCount parameter from Netty, which is 1. User can use this operation to override the default bossCount from Netty | 1 | int | *bossGroup* (consumer) | Set the BossGroup which could be used for handling the new connection of the server side across the NettyEndpoint | | EventLoopGroup | *disconnectOnNoReply* (consumer) | If sync is enabled then this option dictates NettyConsumer if it should disconnect where there is no reply to send back. | true | boolean | *exceptionHandler* (consumer) | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | | ExceptionHandler | *exchangePattern* (consumer) | Sets the exchange pattern when the consumer creates an exchange. | | ExchangePattern | *nettyServerBootstrapFactory* (consumer) | To use a custom NettyServerBootstrapFactory | | NettyServerBootstrapFactory | *networkInterface* (consumer) | When using UDP then this option can be used to specify a network interface by its name, such as eth0 to join a multicast group. | | String | *noReplyLogLevel* (consumer) | If sync is enabled this option dictates NettyConsumer which logging level to use when logging a there is no reply to send back. | WARN | LoggingLevel | *serverClosedChannel ExceptionCaughtLogLevel* (consumer) | If the server (NettyConsumer) catches an java.nio.channels.ClosedChannelException then its logged using this logging level. This is used to avoid logging the closed channel exceptions, as clients can disconnect abruptly and then cause a flood of closed exceptions in the Netty server. | DEBUG | LoggingLevel | *serverExceptionCaughtLog Level* (consumer) | If the server (NettyConsumer) catches an exception then its logged using this logging level. | WARN | LoggingLevel | *serverInitializerFactory* (consumer) | To use a custom ServerInitializerFactory | | ServerInitializerFactory | *usingExecutorService* (consumer) | Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. | true | boolean | *connectTimeout* (producer) | Time to wait for a socket connection to be available. Value is in milliseconds. | 10000 | int | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *requestTimeout* (producer) | Allows to use a timeout for the Netty producer when calling a remote server. By default no timeout is in use. The value is in milli seconds, so eg 30000 is 30 seconds. The requestTimeout is using Netty's ReadTimeoutHandler to trigger the timeout. | | long | *clientInitializerFactory* (producer) | To use a custom ClientInitializerFactory | | ClientInitializerFactory | *correlationManager* (producer) | To use a custom correlation manager to manage how request and reply messages are mapped when using request/reply with the netty producer. This should only be used if you have a way to map requests together with replies such as if there is correlation ids in both the request and reply messages. This can be used if you want to multiplex concurrent messages on the same channel (aka connection) in netty. When doing this you must have a way to correlate the request and reply messages so you can store the right reply on the inflight Camel Exchange before its continued routed. We recommend extending the TimeoutCorrelationManagerSupport when you build custom correlation managers. This provides support for timeout and other complexities you otherwise would need to implement as well. See also the producerPoolEnabled option for more details. | | NettyCamelStateCorrelationManager | *lazyChannelCreation* (producer) | Channels can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. | true | boolean | *producerPoolEnabled* (producer) | Whether producer pool is enabled or not. Important: If you turn this off then a single shared connection is used for the producer, also if you are doing request/reply. That means there is a potential issue with interleaved responses if replies comes back out-of-order. Therefore you need to have a correlation id in both the request and reply messages so you can properly correlate the replies to the Camel callback that is responsible for continue processing the message in Camel. To do this you need to implement NettyCamelStateCorrelationManager as correlation manager and configure it via the correlationManager option. See also the correlationManager option for more details. | true | boolean | *producerPoolMaxActive* (producer) | Sets the cap on the number of objects that can be allocated by the pool (checked out to clients, or idle awaiting checkout) at a given time. Use a negative value for no limit. | -1 | int | *producerPoolMaxIdle* (producer) | Sets the cap on the number of idle instances in the pool. | 100 | int | *producerPoolMinEvictable Idle* (producer) | Sets the minimum amount of time (value in millis) an object may sit idle in the pool before it is eligible for eviction by the idle object evictor. | 300000 | long | *producerPoolMinIdle* (producer) | Sets the minimum number of instances allowed in the producer pool before the evictor thread (if active) spawns new objects. | | int | *udpConnectionlessSending* (producer) | This option supports connection less udp sending which is a real fire and forget. A connected udp send receive the PortUnreachableException if no one is listen on the receiving port. | false | boolean | *useByteBuf* (producer) | If the useByteBuf is true, netty producer will turn the message body into ByteBuf before sending it out. | false | boolean | *allowSerializedHeaders* (advanced) | Only used for TCP when transferExchange is true. When set to true, serializable objects in headers and properties will be added to the exchange. Otherwise Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *basicPropertyBinding* (advanced) | Whether the endpoint should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | boolean | *channelGroup* (advanced) | To use a explicit ChannelGroup. | | ChannelGroup | *nativeTransport* (advanced) | Whether to use native transport instead of NIO. Native transport takes advantage of the host operating system and is only supported on some platforms. You need to add the netty JAR for the host operating system you are using. See more details at: \\http://netty.io/wiki/native-transports.html | false | boolean | *options* (advanced) | Allows to configure additional netty options using option. as prefix. For example option.child.keepAlive=false to set the netty option child.keepAlive=false. See the Netty documentation for possible options that can be used. | | Map | *receiveBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during inbound communication. Size is bytes. | 65536 | int | *receiveBufferSizePredictor* (advanced) | Configures the buffer size predictor. See details at Jetty documentation and this mail thread. | | int | *sendBufferSize* (advanced) | The TCP/UDP buffer sizes to be used during outbound communication. Size is bytes. | 65536 | int | *synchronous* (advanced) | Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported). | false | boolean | *transferExchange* (advanced) | Only used for TCP. You can transfer the exchange over the wire instead of just the body. The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean | *udpByteArrayCodec* (advanced) | For UDP only. If enabled the using byte array codec instead of Java serialization protocol. | false | boolean | *workerCount* (advanced) | When netty works on nio mode, it uses default workerCount parameter from Netty, which is cpu_core_threads x 2. User can use this operation to override the default workerCount from Netty. | | int | *workerGroup* (advanced) | To use a explicit EventLoopGroup as the boss thread pool. For example to share a thread pool with multiple consumers or producers. By default each consumer or producer has their own worker pool with 2 x cpu count core threads. | | EventLoopGroup | *allowDefaultCodec* (codec) | The netty component installs a default codec if both, encoder/decoder is null and textline is false. Setting allowDefaultCodec to false prevents the netty component from installing a default codec as the first element in the filter chain. | true | boolean | *autoAppendDelimiter* (codec) | Whether or not to auto append missing end delimiter when sending using the textline codec. | true | boolean | *decoderMaxLineLength* (codec) | The max line length to use for the textline codec. | 1024 | int | *decoders* (codec) | A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *delimiter* (codec) | The delimiter to use for the textline codec. Possible values are LINE and NULL. | LINE | TextLineDelimiter | *encoders* (codec) | A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *encoding* (codec) | The encoding (a charset name) to use for the textline codec. If not provided, Camel will use the JVM default Charset. | | String | *textline* (codec) | Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; if not specified or the value is false, then Object Serialization is assumed over TCP. | false | boolean | *enabledProtocols* (security) | Which protocols to enable when using SSL | TLSv1,TLSv1.1,TLSv1.2 | String | *keyStoreFile* (security) | Client side certificate keystore to be used for encryption | | File | *keyStoreFormat* (security) | Keystore format to be used for payload encryption. Defaults to JKS if not set | | String | *keyStoreResource* (security) | Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String | *needClientAuth* (security) | Configures whether the server needs client authentication when using SSL. | false | boolean | *passphrase* (security) | Password setting to use in order to encrypt/decrypt payloads sent using SSH | | String | *securityProvider* (security) | Security provider to be used for payload encryption. Defaults to SunX509 if not set. | | String | *ssl* (security) | Setting to specify whether SSL encryption is applied to this endpoint | false | boolean | *sslClientCertHeaders* (security) | When enabled and in SSL mode, then the Netty consumer will enrich the Camel Message with headers having information about the client certificate such as subject name, issuer name, serial number, and the valid date range. | false | boolean | *sslContextParameters* (security) | To configure security using SSLContextParameters | | SSLContextParameters | *sslHandler* (security) | Reference to a class that could be used to return an SSL Handler | | SslHandler | *trustStoreFile* (security) | Server side certificate keystore to be used for encryption | | File | *trustStoreResource* (security) | Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | | String |=== // endpoint options: END // spring-boot-auto-configure options: START == Spring Boot Auto-Configuration When using Spring Boot make sure to use the following Maven dependency to have support for auto configuration: [source,xml] ---- org.apache.camel camel-netty-starter x.x.x ---- The component supports 78 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *camel.component.netty.basic-property-binding* | Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities | false | Boolean | *camel.component.netty.configuration.allow-default-codec* | The netty component installs a default codec if both, encoder/decoder is null and textline is false. Setting allowDefaultCodec to false prevents the netty component from installing a default codec as the first element in the filter chain. | true | Boolean | *camel.component.netty.configuration.allow-serialized-headers* | Only used for TCP when transferExchange is true. When set to true, serializable objects in headers and properties will be added to the exchange. Otherwise Camel will exclude any non-serializable objects and log it at WARN level. | false | Boolean | *camel.component.netty.configuration.auto-append-delimiter* | Whether or not to auto append missing end delimiter when sending using the textline codec. | true | Boolean | *camel.component.netty.configuration.backlog* | Allows to configure a backlog for netty consumer (server). Note the backlog is just a best effort depending on the OS. Setting this option to a value such as 200, 500 or 1000, tells the TCP stack how long the ""accept"" queue can be If this option is not configured, then the backlog depends on OS setting. | | Integer | *camel.component.netty.configuration.boss-count* | When netty works on nio mode, it uses default bossCount parameter from Netty, which is 1. User can use this operation to override the default bossCount from Netty | 1 | Integer | *camel.component.netty.configuration.boss-group* | Set the BossGroup which could be used for handling the new connection of the server side across the NettyEndpoint | | EventLoopGroup | *camel.component.netty.configuration.broadcast* | Setting to choose Multicast over UDP | false | Boolean | *camel.component.netty.configuration.channel-group* | To use a explicit ChannelGroup. | | ChannelGroup | *camel.component.netty.configuration.client-initializer-factory* | To use a custom ClientInitializerFactory | | ClientInitializerFactory | *camel.component.netty.configuration.client-mode* | If the clientMode is true, netty consumer will connect the address as a TCP client. | false | Boolean | *camel.component.netty.configuration.connect-timeout* | Time to wait for a socket connection to be available. Value is in milliseconds. | 10000 | Integer | *camel.component.netty.configuration.correlation-manager* | To use a custom correlation manager to manage how request and reply messages are mapped when using request/reply with the netty producer. This should only be used if you have a way to map requests together with replies such as if there is correlation ids in both the request and reply messages. This can be used if you want to multiplex concurrent messages on the same channel (aka connection) in netty. When doing this you must have a way to correlate the request and reply messages so you can store the right reply on the inflight Camel Exchange before its continued routed.

We recommend extending the {@link TimeoutCorrelationManagerSupport} when you build custom correlation managers. This provides support for timeout and other complexities you otherwise would need to implement as well.

See also the producerPoolEnabled option for more details. | | NettyCamelStateCorrelationManager | *camel.component.netty.configuration.decoder* | A custom ChannelHandler class that can be used to perform special marshalling of inbound payloads. | | ChannelHandler | *camel.component.netty.configuration.decoder-max-line-length* | The max line length to use for the textline codec. | 1024 | Integer | *camel.component.netty.configuration.decoders* | A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *camel.component.netty.configuration.delimiter* | The delimiter to use for the textline codec. Possible values are LINE and NULL. | | TextLineDelimiter | *camel.component.netty.configuration.disconnect* | Whether or not to disconnect(close) from Netty Channel right after use. Can be used for both consumer and producer. | false | Boolean | *camel.component.netty.configuration.disconnect-on-no-reply* | If sync is enabled then this option dictates NettyConsumer if it should disconnect where there is no reply to send back. | true | Boolean | *camel.component.netty.configuration.enabled-protocols* | Which protocols to enable when using SSL | TLSv1,TLSv1.1,TLSv1.2 | String | *camel.component.netty.configuration.encoder* | A custom ChannelHandler class that can be used to perform special marshalling of outbound payloads. | | ChannelHandler | *camel.component.netty.configuration.encoders* | A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. | | List | *camel.component.netty.configuration.encoding* | The encoding (a charset name) to use for the textline codec. If not provided, Camel will use the JVM default Charset. | | String | *camel.component.netty.configuration.host* | The hostname.

For the consumer the hostname is localhost or 0.0.0.0. For the producer the hostname is the remote host to connect to | | String | *camel.component.netty.configuration.keep-alive* | Setting to ensure socket is not closed due to inactivity | true | Boolean | *camel.component.netty.configuration.key-store-format* | Keystore format to be used for payload encryption. Defaults to ""JKS"" if not set | | String | *camel.component.netty.configuration.key-store-resource* | Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with ""classpath:"", ""file:"", or ""http:"" to load the resource from different systems. | | String | *camel.component.netty.configuration.lazy-channel-creation* | Channels can be lazily created to avoid exceptions, if the remote server is not up and running when the Camel producer is started. | true | Boolean | *camel.component.netty.configuration.native-transport* | Whether to use native transport instead of NIO. Native transport takes advantage of the host operating system and is only supported on some platforms. You need to add the netty JAR for the host operating system you are using. See more details at: \\http://netty.io/wiki/native-transports.html | false | Boolean | *camel.component.netty.configuration.need-client-auth* | Configures whether the server needs client authentication when using SSL. | false | Boolean | *camel.component.netty.configuration.netty-server-bootstrap-factory* | To use a custom NettyServerBootstrapFactory | | NettyServerBootstrapFactory | *camel.component.netty.configuration.network-interface* | When using UDP then this option can be used to specify a network interface by its name, such as eth0 to join a multicast group. | | String | *camel.component.netty.configuration.no-reply-log-level* | If sync is enabled this option dictates NettyConsumer which logging level to use when logging a there is no reply to send back. | | LoggingLevel | *camel.component.netty.configuration.options* | Allows to configure additional netty options using ""option."" as prefix. For example ""option.child.keepAlive=false"" to set the netty option ""child.keepAlive=false"". See the Netty documentation for possible options that can be used. | | Map | *camel.component.netty.configuration.passphrase* | Password setting to use in order to encrypt/decrypt payloads sent using SSH | | String | *camel.component.netty.configuration.port* | The host port number | | Integer | *camel.component.netty.configuration.producer-pool-enabled* | Whether producer pool is enabled or not. Important: If you turn this off then a single shared connection is used for the producer, also if you are doing request/reply. That means there is a potential issue with interleaved responses if replies comes back out-of-order. Therefore you need to have a correlation id in both the request and reply messages so you can properly correlate the replies to the Camel callback that is responsible for continue processing the message in Camel. To do this you need to implement {@link NettyCamelStateCorrelationManager} as correlation manager and configure it via the correlationManager option.

See also the correlationManager option for more details. | true | Boolean | *camel.component.netty.configuration.producer-pool-max-active* | Sets the cap on the number of objects that can be allocated by the pool (checked out to clients, or idle awaiting checkout) at a given time. Use a negative value for no limit. | -1 | Integer | *camel.component.netty.configuration.producer-pool-max-idle* | Sets the cap on the number of ""idle"" instances in the pool. | 100 | Integer | *camel.component.netty.configuration.producer-pool-min-evictable-idle* | Sets the minimum amount of time (value in millis) an object may sit idle in the pool before it is eligible for eviction by the idle object evictor. | 300000 | Long | *camel.component.netty.configuration.producer-pool-min-idle* | Sets the minimum number of instances allowed in the producer pool before the evictor thread (if active) spawns new objects. | | Integer | *camel.component.netty.configuration.protocol* | The protocol to use which can be tcp or udp. | | String | *camel.component.netty.configuration.receive-buffer-size* | The TCP/UDP buffer sizes to be used during inbound communication. Size is bytes. | 65536 | Integer | *camel.component.netty.configuration.receive-buffer-size-predictor* | Configures the buffer size predictor. See details at Jetty documentation and this mail thread. | | Integer | *camel.component.netty.configuration.reconnect* | Used only in clientMode in consumer, the consumer will attempt to reconnect on disconnection if this is enabled | true | Boolean | *camel.component.netty.configuration.reconnect-interval* | Used if reconnect and clientMode is enabled. The interval in milli seconds to attempt reconnection | 10000 | Integer | *camel.component.netty.configuration.request-timeout* | Allows to use a timeout for the Netty producer when calling a remote server. By default no timeout is in use. The value is in milli seconds, so eg 30000 is 30 seconds. The requestTimeout is using Netty's ReadTimeoutHandler to trigger the timeout. | | Long | *camel.component.netty.configuration.reuse-address* | Setting to facilitate socket multiplexing | true | Boolean | *camel.component.netty.configuration.reuse-channel* | This option allows producers and consumers (in client mode) to reuse the same Netty {@link Channel} for the lifecycle of processing the {@link Exchange}. This is useful if you need to call a server multiple times in a Camel route and want to use the same network connection. When using this, the channel is not returned to the connection pool until the {@link Exchange} is done; or disconnected if the disconnect option is set to true.

The reused {@link Channel} is stored on the {@link Exchange} as an exchange property with the key {@link NettyConstants#NETTY_CHANNEL} which allows you to obtain the channel during routing and use it as well. | false | Boolean | *camel.component.netty.configuration.security-provider* | Security provider to be used for payload encryption. Defaults to ""SunX509"" if not set. | | String | *camel.component.netty.configuration.send-buffer-size* | The TCP/UDP buffer sizes to be used during outbound communication. Size is bytes. | 65536 | Integer | *camel.component.netty.configuration.server-closed-channel-exception-caught-log-level* | If the server (NettyConsumer) catches an java.nio.channels.ClosedChannelException then its logged using this logging level. This is used to avoid logging the closed channel exceptions, as clients can disconnect abruptly and then cause a flood of closed exceptions in the Netty server. | | LoggingLevel | *camel.component.netty.configuration.server-exception-caught-log-level* | If the server (NettyConsumer) catches an exception then its logged using this logging level. | | LoggingLevel | *camel.component.netty.configuration.server-initializer-factory* | To use a custom ServerInitializerFactory | | ServerInitializerFactory | *camel.component.netty.configuration.ssl* | Setting to specify whether SSL encryption is applied to this endpoint | false | Boolean | *camel.component.netty.configuration.ssl-client-cert-headers* | When enabled and in SSL mode, then the Netty consumer will enrich the Camel Message with headers having information about the client certificate such as subject name, issuer name, serial number, and the valid date range. | false | Boolean | *camel.component.netty.configuration.ssl-context-parameters* | To configure security using SSLContextParameters | | SSLContextParameters | *camel.component.netty.configuration.ssl-handler* | Reference to a class that could be used to return an SSL Handler | | SslHandler | *camel.component.netty.configuration.sync* | Setting to set endpoint as one-way or request-response | true | Boolean | *camel.component.netty.configuration.tcp-no-delay* | Setting to improve TCP protocol performance | true | Boolean | *camel.component.netty.configuration.textline* | Only used for TCP. If no codec is specified, you can use this flag to indicate a text line based codec; if not specified or the value is false, then Object Serialization is assumed over TCP. | false | Boolean | *camel.component.netty.configuration.transfer-exchange* | Only used for TCP. You can transfer the exchange over the wire instead of just the body. The following fields are transferred: In body, Out body, fault body, In headers, Out headers, fault headers, exchange properties, exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. | false | Boolean | *camel.component.netty.configuration.trust-store-resource* | Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with ""classpath:"", ""file:"", or ""http:"" to load the resource from different systems. | | String | *camel.component.netty.configuration.udp-byte-array-codec* | For UDP only. If enabled the using byte array codec instead of Java serialization protocol. | false | Boolean | *camel.component.netty.configuration.udp-connectionless-sending* | This option supports connection less udp sending which is a real fire and forget. A connected udp send receive the PortUnreachableException if no one is listen on the receiving port. | false | Boolean | *camel.component.netty.configuration.use-byte-buf* | If the useByteBuf is true, netty producer will turn the message body into {@link ByteBuf} before sending it out. | false | Boolean | *camel.component.netty.configuration.using-executor-service* | Whether to use ordered thread pool, to ensure events are processed orderly on the same channel. | true | Boolean | *camel.component.netty.configuration.worker-count* | When netty works on nio mode, it uses default workerCount parameter from Netty, which is cpu_core_threads x 2. User can use this operation to override the default workerCount from Netty. | | Integer | *camel.component.netty.configuration.worker-group* | To use a explicit EventLoopGroup as the boss thread pool. For example to share a thread pool with multiple consumers or producers. By default each consumer or producer has their own worker pool with 2 x cpu count core threads. | | EventLoopGroup | *camel.component.netty.enabled* | Whether to enable auto configuration of the netty component. This is enabled by default. | | Boolean | *camel.component.netty.executor-service* | To use the given EventExecutorGroup. The option is a io.netty.util.concurrent.EventExecutorGroup type. | | String | *camel.component.netty.maximum-pool-size* | The thread pool size for the EventExecutorGroup if its in use. The default value is 16. | 16 | Integer | *camel.component.netty.ssl-context-parameters* | To configure security using SSLContextParameters. The option is a org.apache.camel.support.jsse.SSLContextParameters type. | | String | *camel.component.netty.use-global-ssl-context-parameters* | Enable usage of global SSL context parameters. | false | Boolean | *camel.component.netty.configuration.client-pipeline-factory* | *Deprecated* | | ClientInitializerFactory | *camel.component.netty.configuration.key-store-file* | *Deprecated* Client side certificate keystore to be used for encryption | | File | *camel.component.netty.configuration.server-pipeline-factory* | *Deprecated* | | ServerInitializerFactory | *camel.component.netty.configuration.trust-store-file* | *Deprecated* Server side certificate keystore to be used for encryption | | File |=== // spring-boot-auto-configure options: END == Registry based Options Codec Handlers and SSL Keystores can be enlisted in the Registry, such as in the Spring XML file. The values that could be passed in, are the following: [width=""100%"",cols=""10%,90%"",options=""header"",] |=== |Name |Description |`passphrase` |password setting to use in order to encrypt/decrypt payloads sent using SSH |`keyStoreFormat` |keystore format to be used for payload encryption. Defaults to ""JKS"" if not set |`securityProvider` |Security provider to be used for payload encryption. Defaults to ""SunX509"" if not set. |`keyStoreFile` |*deprecated:* Client side certificate keystore to be used for encryption |`trustStoreFile` |*deprecated:* Server side certificate keystore to be used for encryption |`keyStoreResource` |Client side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with `""classpath:""`, `""file:""`, or `""http:""` to load the resource from different systems. |`trustStoreResource` |Server side certificate keystore to be used for encryption. Is loaded by default from classpath, but you can prefix with `""classpath:""`, `""file:""`, or `""http:""` to load the resource from different systems. |`sslHandler` |Reference to a class that could be used to return an SSL Handler |`encoder` |A custom `ChannelHandler` class that can be used to perform special marshalling of outbound payloads. Must override io.netty.channel.ChannelInboundHandlerAdapter. |`encoders` |A list of encoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. |`decoder` |A custom `ChannelHandler` class that can be used to perform special marshalling of inbound payloads. Must override io.netty.channel.ChannelOutboundHandlerAdapter. |`decoders` |A list of decoders to be used. You can use a String which have values separated by comma, and have the values be looked up in the Registry. Just remember to prefix the value with # so Camel knows it should lookup. |=== NOTE: Read below about using non shareable encoders/decoders. === Using non shareable encoders or decoders If your encoders or decoders are not shareable (e.g. they don't have the @Shareable class annotation), then your encoder/decoder must implement the `org.apache.camel.component.netty.ChannelHandlerFactory` interface, and return a new instance in the `newChannelHandler` method. This is to ensure the encoder/decoder can safely be used. If this is not the case, then the Netty component will log a WARN when an endpoint is created. The Netty component offers a `org.apache.camel.component.netty.ChannelHandlerFactories` factory class, that has a number of commonly used methods. == Sending Messages to/from a Netty endpoint === Netty Producer In Producer mode, the component provides the ability to send payloads to a socket endpoint using either TCP or UDP protocols (with optional SSL support). The producer mode supports both one-way and request-response based operations. === Netty Consumer In Consumer mode, the component provides the ability to: * listen on a specified socket using either TCP or UDP protocols (with optional SSL support), * receive requests on the socket using text/xml, binary and serialized object based payloads and * send them along on a route as message exchanges. The consumer mode supports both one-way and request-response based operations. == Examples === A UDP Netty endpoint using Request-Reply and serialized object payload [source,java] ---- RouteBuilder builder = new RouteBuilder() { public void configure() { from(""netty:udp://0.0.0.0:5155?sync=true"") .process(new Processor() { public void process(Exchange exchange) throws Exception { Poetry poetry = (Poetry) exchange.getIn().getBody(); poetry.setPoet(""Dr. Sarojini Naidu""); exchange.getOut().setBody(poetry); } } } }; ---- === A TCP based Netty consumer endpoint using One-way communication [source,java] ---- RouteBuilder builder = new RouteBuilder() { public void configure() { from(""netty:tcp://0.0.0.0:5150"") .to(""mock:result""); } }; ---- === An SSL/TCP based Netty consumer endpoint using Request-Reply communication [[Netty-UsingtheJSSEConfigurationUtility]] Using the JSSE Configuration Utility The Netty component supports SSL/TLS configuration through the xref:manual::camel-configuration-utilities.adoc[Camel JSSE Configuration Utility]. This utility greatly decreases the amount of component specific code you need to write and is configurable at the endpoint and component levels. The following examples demonstrate how to use the utility with the Netty component. [[Netty-Programmaticconfigurationofthecomponent]] Programmatic configuration of the component [source,java] ---- KeyStoreParameters ksp = new KeyStoreParameters(); ksp.setResource(""/users/home/server/keystore.jks""); ksp.setPassword(""keystorePassword""); KeyManagersParameters kmp = new KeyManagersParameters(); kmp.setKeyStore(ksp); kmp.setKeyPassword(""keyPassword""); SSLContextParameters scp = new SSLContextParameters(); scp.setKeyManagers(kmp); NettyComponent nettyComponent = getContext().getComponent(""netty"", NettyComponent.class); nettyComponent.setSslContextParameters(scp); ---- [[Netty-SpringDSLbasedconfigurationofendpoint]] Spring DSL based configuration of endpoint [source,xml] ---- ... ... ... ... ---- [[Netty-UsingBasicSSL/TLSconfigurationontheJettyComponent]] Using Basic SSL/TLS configuration on the Jetty Component [source,java] ---- Registry registry = context.getRegistry(); registry.bind(""password"", ""changeit""); registry.bind(""ksf"", new File(""src/test/resources/keystore.jks"")); registry.bind(""tsf"", new File(""src/test/resources/keystore.jks"")); context.addRoutes(new RouteBuilder() { public void configure() { String netty_ssl_endpoint = ""netty:tcp://0.0.0.0:5150?sync=true&ssl=true&passphrase=#password"" + ""&keyStoreFile=#ksf&trustStoreFile=#tsf""; String return_string = ""When You Go Home, Tell Them Of Us And Say,"" + ""For Your Tomorrow, We Gave Our Today.""; from(netty_ssl_endpoint) .process(new Processor() { public void process(Exchange exchange) throws Exception { exchange.getOut().setBody(return_string); } } } }); ---- [[Netty-GettingaccesstoSSLSessionandtheclientcertificate]] Getting access to SSLSession and the client certificate You can get access to the `javax.net.ssl.SSLSession` if you eg need to get details about the client certificate. When `ssl=true` then the xref:netty-component.adoc[Netty] component will store the `SSLSession` as a header on the Camel Message as shown below: [source,java] ---- SSLSession session = exchange.getIn().getHeader(NettyConstants.NETTY_SSL_SESSION, SSLSession.class); // get the first certificate which is client certificate javax.security.cert.X509Certificate cert = session.getPeerCertificateChain()[0]; Principal principal = cert.getSubjectDN(); ---- Remember to set `needClientAuth=true` to authenticate the client, otherwise `SSLSession` cannot access information about the client certificate, and you may get an exception `javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated`. You may also get this exception if the client certificate is expired or not valid etc. TIP: The option `sslClientCertHeaders` can be set to `true` which then enriches the Camel Message with headers having details about the client certificate. For example the subject name is readily available in the header `CamelNettySSLClientCertSubjectName`. === Using Multiple Codecs In certain cases it may be necessary to add chains of encoders and decoders to the netty pipeline. To add multpile codecs to a camel netty endpoint the 'encoders' and 'decoders' uri parameters should be used. Like the 'encoder' and 'decoder' parameters they are used to supply references (lists of ChannelUpstreamHandlers and ChannelDownstreamHandlers) that should be added to the pipeline. Note that if encoders is specified then the encoder param will be ignored, similarly for decoders and the decoder param. NOTE: Read further above about using non shareable encoders/decoders. The lists of codecs need to be added to the Camel's registry so they can be resolved when the endpoint is created. [source,java] ---- ChannelHandlerFactory lengthDecoder = ChannelHandlerFactories.newLengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4); StringDecoder stringDecoder = new StringDecoder(); registry.bind(""length-decoder"", lengthDecoder); registry.bind(""string-decoder"", stringDecoder); LengthFieldPrepender lengthEncoder = new LengthFieldPrepender(4); StringEncoder stringEncoder = new StringEncoder(); registry.bind(""length-encoder"", lengthEncoder); registry.bind(""string-encoder"", stringEncoder); List decoders = new ArrayList(); decoders.add(lengthDecoder); decoders.add(stringDecoder); List encoders = new ArrayList(); encoders.add(lengthEncoder); encoders.add(stringEncoder); registry.bind(""encoders"", encoders); registry.bind(""decoders"", decoders); ---- Spring's native collections support can be used to specify the codec lists in an application context [source,xml] ---- ---- The bean names can then be used in netty endpoint definitions either as a comma separated list or contained in a List e.g. [source,java] ---- from(""direct:multiple-codec"").to(""netty:tcp://0.0.0.0:{{port}}?encoders=#encoders&sync=false""); from(""netty:tcp://0.0.0.0:{{port}}?decoders=#length-decoder,#string-decoder&sync=false"").to(""mock:multiple-codec""); ---- or via XML. [source,xml] ---- ---- == Closing Channel When Complete When acting as a server you sometimes want to close the channel when, for example, a client conversion is finished. + You can do this by simply setting the endpoint option `disconnect=true`. However you can also instruct Camel on a per message basis as follows. + To instruct Camel to close the channel, you should add a header with the key `CamelNettyCloseChannelWhenComplete` set to a boolean `true` value. + For instance, the example below will close the channel after it has written the bye message back to the client: [source,java] ---- from(""netty:tcp://0.0.0.0:8080"").process(new Processor() { public void process(Exchange exchange) throws Exception { String body = exchange.getIn().getBody(String.class); exchange.getOut().setBody(""Bye "" + body); // some condition which determines if we should close if (close) { exchange.getOut().setHeader(NettyConstants.NETTY_CLOSE_CHANNEL_WHEN_COMPLETE, true); } } }); ---- [[Netty-Addingcustomchannelpipelinefactoriestogaincompletecontroloveracreatedpipeline]] Adding custom channel pipeline factories to gain complete control over a created pipeline == Custom pipeline Custom channel pipelines provide complete control to the user over the handler/interceptor chain by inserting custom handler(s), encoder(s) & decoder(s) without having to specify them in the Netty Endpoint URL in a very simple way. In order to add a custom pipeline, a custom channel pipeline factory must be created and registered with the context via the context registry (Registry, or the camel-spring ApplicationContextRegistry etc). A custom pipeline factory must be constructed as follows * A Producer linked channel pipeline factory must extend the abstract class `ClientPipelineFactory`. * A Consumer linked channel pipeline factory must extend the abstract class `ServerInitializerFactory`. * The classes should override the initChannel() method in order to insert custom handler(s), encoder(s) and decoder(s). Not overriding the `initChannel()` method creates a pipeline with no handlers, encoders or decoders wired to the pipeline. The example below shows how ServerInitializerFactory factory may be created === Using custom pipeline factory [source,java] ---- public class SampleServerInitializerFactory extends ServerInitializerFactory { private int maxLineSize = 1024; protected void initChannel(Channel ch) throws Exception { ChannelPipeline channelPipeline = ch.pipeline(); channelPipeline.addLast(""encoder-SD"", new StringEncoder(CharsetUtil.UTF_8)); channelPipeline.addLast(""decoder-DELIM"", new DelimiterBasedFrameDecoder(maxLineSize, true, Delimiters.lineDelimiter())); channelPipeline.addLast(""decoder-SD"", new StringDecoder(CharsetUtil.UTF_8)); // here we add the default Camel ServerChannelHandler for the consumer, to allow Camel to route the message etc. channelPipeline.addLast(""handler"", new ServerChannelHandler(consumer)); } } ---- The custom channel pipeline factory can then be added to the registry and instantiated/utilized on a camel route in the following way [source,java] ---- Registry registry = camelContext.getRegistry(); ServerInitializerFactory factory = new TestServerInitializerFactory(); registry.bind(""spf"", factory); context.addRoutes(new RouteBuilder() { public void configure() { String netty_ssl_endpoint = ""netty:tcp://0.0.0.0:5150?serverInitializerFactory=#spf"" String return_string = ""When You Go Home, Tell Them Of Us And Say,"" + ""For Your Tomorrow, We Gave Our Today.""; from(netty_ssl_endpoint) .process(new Processor() { public void process(Exchange exchange) throws Exception { exchange.getOut().setBody(return_string); } } } }); ---- == Reusing Netty boss and worker thread pools Netty has two kind of thread pools: boss and worker. By default each Netty consumer and producer has their private thread pools. If you want to reuse these thread pools among multiple consumers or producers then the thread pools must be created and enlisted in the Registry. For example using Spring XML we can create a shared worker thread pool using the `NettyWorkerPoolBuilder` with 2 worker threads as shown below: [source,xml] ---- ---- TIP: For boss thread pool there is a `org.apache.camel.component.netty.NettyServerBossPoolBuilder` builder for Netty consumers, and a `org.apache.camel.component.netty.NettyClientBossPoolBuilder` for the Netty producers. Then in the Camel routes we can refer to this worker pools by configuring the `workerPool` option in the URI as shown below: [source,xml] ---- ... ---- And if we have another route we can refer to the shared worker pool: [source,xml] ---- ... ---- and so forth. == Multiplexing concurrent messages over a single connection with request/reply When using Netty for request/reply messaging via the netty producer then by default each message is sent via a non-shared connection (pooled). This ensures that replies are automatic being able to map to the correct request thread for further routing in Camel. In other words correlation between request/reply messages happens out-of-the-box because the replies comes back on the same connection that was used for sending the request; and this connection is not shared with others. When the response comes back, the connection is returned back to the connection pool, where it can be reused by others. However if you want to multiplex concurrent request/responses on a single shared connection, then you need to turn off the connection pooling by setting `producerPoolEnabled=false`. Now this means there is a potential issue with interleaved responses if replies comes back out-of-order. Therefore you need to have a correlation id in both the request and reply messages so you can properly correlate the replies to the Camel callback that is responsible for continue processing the message in Camel. To do this you need to implement `NettyCamelStateCorrelationManager` as correlation manager and configure it via the `correlationManager=#myManager` option. NOTE: We recommend extending the `TimeoutCorrelationManagerSupport` when you build custom correlation managers. This provides support for timeout and other complexities you otherwise would need to implement as well. You can find an example with the Apache Camel source code in the examples directory under the `camel-example-netty-custom-correlation` directory. ",12485,False,2313.5339388076677,median "[id=""baremetalhost-metal3-io-v1alpha1""] = BareMetalHost [metal3.io/v1alpha1] ifdef::product-title[] include::modules/common-attributes.adoc[] endif::[] toc::[] Description:: BareMetalHost is the Schema for the baremetalhosts API Type:: `object` == Specification [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `.apiVersion` | `string` | APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources | `.kind` | `string` | Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds | `.metadata` | xref:../objects/index.adoc#objectmeta_v2-meta-v1[`ObjectMeta_v2 meta/v1`] | Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata | `.spec` | `object` | BareMetalHostSpec defines the desired state of BareMetalHost | `.status` | `object` | BareMetalHostStatus defines the observed state of BareMetalHost |=== ..spec Description:: BareMetalHostSpec defines the desired state of BareMetalHost Type:: `object` Required:: - `online` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `bmc` | `object` | How do we connect to the BMC? | `bootMACAddress` | `string` | Which MAC address will PXE boot? This is optional for some types, but required for libvirt VMs driven by vbmc. | `bootMode` | `string` | Select the method of initializing the hardware during boot. Defaults to UEFI. | `consumerRef` | `object` | ConsumerRef can be used to store information about something that is using a host. When it is not empty, the host is considered ""in use"". | `description` | `string` | Description is a human-entered text used to help identify the host | `externallyProvisioned` | `boolean` | ExternallyProvisioned means something else is managing the image running on the host and the operator should only manage the power status and hardware inventory inspection. If the Image field is filled in, this field is ignored. | `hardwareProfile` | `string` | What is the name of the hardware profile for this host? It should only be necessary to set this when inspection cannot automatically determine the profile. | `image` | `object` | Image holds the details of the image to be provisioned. | `metaData` | `object` | MetaData holds the reference to the Secret containing host metadata (e.g. meta_data.json which is passed to Config Drive). | `networkData` | `object` | NetworkData holds the reference to the Secret containing network configuration (e.g content of network_data.json which is passed to Config Drive). | `online` | `boolean` | Should the server be online? | `rootDeviceHints` | `object` | Provide guidance about how to choose the device for the image being provisioned. | `taints` | `array` | Taints is the full, authoritative list of taints to apply to the corresponding Machine. This list will overwrite any modifications made to the Machine on an ongoing basis. | `taints[]` | `object` | The node this Taint is attached to has the ""effect"" on any pod that does not tolerate the Taint. | `userData` | `object` | UserData holds the reference to the Secret containing the user data to be passed to the host before it boots. |=== ..spec.bmc Description:: How do we connect to the BMC? Type:: `object` Required:: - `address` - `credentialsName` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `address` | `string` | Address holds the URL for accessing the controller on the network. | `credentialsName` | `string` | The name of the secret containing the BMC credentials (requires keys ""username"" and ""password""). | `disableCertificateVerification` | `boolean` | DisableCertificateVerification disables verification of server certificates when using HTTPS to connect to the BMC. This is required when the server certificate is self-signed, but is insecure because it allows a man-in-the-middle to intercept the connection. |=== ..spec.consumerRef Description:: ConsumerRef can be used to store information about something that is using a host. When it is not empty, the host is considered ""in use"". Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `apiVersion` | `string` | API version of the referent. | `fieldPath` | `string` | If referring to a piece of an object instead of an entire object, this string should contain a valid JSON/Go field access statement, such as desiredState.manifest.containers[2]. For example, if the object reference is to a container within a pod, this would take on a value like: ""spec.containers{name}"" (where ""name"" refers to the name of the container that triggered the event) or if no container name is specified ""spec.containers[2]"" (container with index 2 in this pod). This syntax is chosen only to have some well-defined way of referencing a part of an object. TODO: this design is not final and this field is subject to change in the future. | `kind` | `string` | Kind of the referent. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds | `name` | `string` | Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names | `namespace` | `string` | Namespace of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/ | `resourceVersion` | `string` | Specific resourceVersion to which this reference is made, if any. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency | `uid` | `string` | UID of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#uids |=== ..spec.image Description:: Image holds the details of the image to be provisioned. Type:: `object` Required:: - `checksum` - `url` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `checksum` | `string` | Checksum is the checksum for the image. | `checksumType` | `string` | ChecksumType is the checksum algorithm for the image. e.g md5, sha256, sha512 | `format` | `string` | DiskFormat contains the format of the image (raw, qcow2, ...) Needs to be set to raw for raw images streaming | `url` | `string` | URL is a location of an image to deploy. |=== ..spec.metaData Description:: MetaData holds the reference to the Secret containing host metadata (e.g. meta_data.json which is passed to Config Drive). Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `name` | `string` | Name is unique within a namespace to reference a secret resource. | `namespace` | `string` | Namespace defines the space within which the secret name must be unique. |=== ..spec.networkData Description:: NetworkData holds the reference to the Secret containing network configuration (e.g content of network_data.json which is passed to Config Drive). Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `name` | `string` | Name is unique within a namespace to reference a secret resource. | `namespace` | `string` | Namespace defines the space within which the secret name must be unique. |=== ..spec.rootDeviceHints Description:: Provide guidance about how to choose the device for the image being provisioned. Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `deviceName` | `string` | A Linux device name like ""/dev/vda"". The hint must match the actual value exactly. | `hctl` | `string` | A SCSI bus address like 0:0:0:0. The hint must match the actual value exactly. | `minSizeGigabytes` | `integer` | The minimum size of the device in Gigabytes. | `model` | `string` | A vendor-specific device identifier. The hint can be a substring of the actual value. | `rotational` | `boolean` | True if the device should use spinning media, false otherwise. | `serialNumber` | `string` | Device serial number. The hint must match the actual value exactly. | `vendor` | `string` | The name of the vendor or manufacturer of the device. The hint can be a substring of the actual value. | `wwn` | `string` | Unique storage identifier. The hint must match the actual value exactly. | `wwnVendorExtension` | `string` | Unique vendor storage identifier. The hint must match the actual value exactly. | `wwnWithExtension` | `string` | Unique storage identifier with the vendor extension appended. The hint must match the actual value exactly. |=== ..spec.taints Description:: Taints is the full, authoritative list of taints to apply to the corresponding Machine. This list will overwrite any modifications made to the Machine on an ongoing basis. Type:: `array` ..spec.taints[] Description:: The node this Taint is attached to has the ""effect"" on any pod that does not tolerate the Taint. Type:: `object` Required:: - `effect` - `key` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `effect` | `string` | Required. The effect of the taint on pods that do not tolerate the taint. Valid effects are NoSchedule, PreferNoSchedule and NoExecute. | `key` | `string` | Required. The taint key to be applied to a node. | `timeAdded` | `string` | TimeAdded represents the time at which the taint was added. It is only written for NoExecute taints. | `value` | `string` | Required. The taint value corresponding to the taint key. |=== ..spec.userData Description:: UserData holds the reference to the Secret containing the user data to be passed to the host before it boots. Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `name` | `string` | Name is unique within a namespace to reference a secret resource. | `namespace` | `string` | Namespace defines the space within which the secret name must be unique. |=== ..status Description:: BareMetalHostStatus defines the observed state of BareMetalHost Type:: `object` Required:: - `errorCount` - `errorMessage` - `hardwareProfile` - `operationHistory` - `operationalStatus` - `poweredOn` - `provisioning` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `errorCount` | `integer` | ErrorCount records how many times the host has encoutered an error since the last successful operation | `errorMessage` | `string` | the last error message reported by the provisioning subsystem | `errorType` | `string` | ErrorType indicates the type of failure encountered when the OperationalStatus is OperationalStatusError | `goodCredentials` | `object` | the last credentials we were able to validate as working | `hardware` | `object` | The hardware discovered to exist on the host. | `hardwareProfile` | `string` | The name of the profile matching the hardware details. | `lastUpdated` | `string` | LastUpdated identifies when this status was last observed. | `operationHistory` | `object` | OperationHistory holds information about operations performed on this host. | `operationalStatus` | `string` | OperationalStatus holds the status of the host | `poweredOn` | `boolean` | indicator for whether or not the host is powered on | `provisioning` | `object` | Information tracked by the provisioner. | `triedCredentials` | `object` | the last credentials we sent to the provisioning backend |=== ..status.goodCredentials Description:: the last credentials we were able to validate as working Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `credentials` | `object` | SecretReference represents a Secret Reference. It has enough information to retrieve secret in any namespace | `credentialsVersion` | `string` | |=== ..status.goodCredentials.credentials Description:: SecretReference represents a Secret Reference. It has enough information to retrieve secret in any namespace Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `name` | `string` | Name is unique within a namespace to reference a secret resource. | `namespace` | `string` | Namespace defines the space within which the secret name must be unique. |=== ..status.hardware Description:: The hardware discovered to exist on the host. Type:: `object` Required:: - `cpu` - `firmware` - `hostname` - `nics` - `ramMebibytes` - `storage` - `systemVendor` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `cpu` | `object` | CPU describes one processor on the host. | `firmware` | `object` | Firmware describes the firmware on the host. | `hostname` | `string` | | `nics` | `array` | | `nics[]` | `object` | NIC describes one network interface on the host. | `ramMebibytes` | `integer` | | `storage` | `array` | | `storage[]` | `object` | Storage describes one storage device (disk, SSD, etc.) on the host. | `systemVendor` | `object` | HardwareSystemVendor stores details about the whole hardware system. |=== ..status.hardware.cpu Description:: CPU describes one processor on the host. Type:: `object` Required:: - `arch` - `clockMegahertz` - `count` - `flags` - `model` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `arch` | `string` | | `clockMegahertz` | `number` | ClockSpeed is a clock speed in MHz | `count` | `integer` | | `flags` | `array (string)` | | `model` | `string` | |=== ..status.hardware.firmware Description:: Firmware describes the firmware on the host. Type:: `object` Required:: - `bios` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `bios` | `object` | The BIOS for this firmware |=== ..status.hardware.firmware.bios Description:: The BIOS for this firmware Type:: `object` Required:: - `date` - `vendor` - `version` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `date` | `string` | The release/build date for this BIOS | `vendor` | `string` | The vendor name for this BIOS | `version` | `string` | The version of the BIOS |=== ..status.hardware.nics Description:: Type:: `array` ..status.hardware.nics[] Description:: NIC describes one network interface on the host. Type:: `object` Required:: - `ip` - `mac` - `model` - `name` - `pxe` - `speedGbps` - `vlanId` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `ip` | `string` | The IP address of the device | `mac` | `string` | The device MAC addr | `model` | `string` | The name of the model, e.g. ""virt-io"" | `name` | `string` | The name of the NIC, e.g. ""nic-1"" | `pxe` | `boolean` | Whether the NIC is PXE Bootable | `speedGbps` | `integer` | The speed of the device | `vlanId` | `integer` | The untagged VLAN ID | `vlans` | `array` | The VLANs available | `vlans[]` | `object` | VLAN represents the name and ID of a VLAN |=== ..status.hardware.nics[].vlans Description:: The VLANs available Type:: `array` ..status.hardware.nics[].vlans[] Description:: VLAN represents the name and ID of a VLAN Type:: `object` Required:: - `id` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `id` | `integer` | VLANID is a 12-bit 802.1Q VLAN identifier | `name` | `string` | |=== ..status.hardware.storage Description:: Type:: `array` ..status.hardware.storage[] Description:: Storage describes one storage device (disk, SSD, etc.) on the host. Type:: `object` Required:: - `name` - `rotational` - `serialNumber` - `sizeBytes` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `hctl` | `string` | The SCSI location of the device | `model` | `string` | Hardware model | `name` | `string` | A name for the disk, e.g. ""disk 1 (boot)"" | `rotational` | `boolean` | Whether this disk represents rotational storage | `serialNumber` | `string` | The serial number of the device | `sizeBytes` | `integer` | The size of the disk in Bytes | `vendor` | `string` | The name of the vendor of the device | `wwn` | `string` | The WWN of the device | `wwnVendorExtension` | `string` | The WWN Vendor extension of the device | `wwnWithExtension` | `string` | The WWN with the extension |=== ..status.hardware.systemVendor Description:: HardwareSystemVendor stores details about the whole hardware system. Type:: `object` Required:: - `manufacturer` - `productName` - `serialNumber` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `manufacturer` | `string` | | `productName` | `string` | | `serialNumber` | `string` | |=== ..status.operationHistory Description:: OperationHistory holds information about operations performed on this host. Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `deprovision` | `object` | OperationMetric contains metadata about an operation (inspection, provisioning, etc.) used for tracking metrics. | `inspect` | `object` | OperationMetric contains metadata about an operation (inspection, provisioning, etc.) used for tracking metrics. | `provision` | `object` | OperationMetric contains metadata about an operation (inspection, provisioning, etc.) used for tracking metrics. | `register` | `object` | OperationMetric contains metadata about an operation (inspection, provisioning, etc.) used for tracking metrics. |=== ..status.operationHistory.deprovision Description:: OperationMetric contains metadata about an operation (inspection, provisioning, etc.) used for tracking metrics. Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `end` | `` | | `start` | `` | |=== ..status.operationHistory.inspect Description:: OperationMetric contains metadata about an operation (inspection, provisioning, etc.) used for tracking metrics. Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `end` | `` | | `start` | `` | |=== ..status.operationHistory.provision Description:: OperationMetric contains metadata about an operation (inspection, provisioning, etc.) used for tracking metrics. Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `end` | `` | | `start` | `` | |=== ..status.operationHistory.register Description:: OperationMetric contains metadata about an operation (inspection, provisioning, etc.) used for tracking metrics. Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `end` | `` | | `start` | `` | |=== ..status.provisioning Description:: Information tracked by the provisioner. Type:: `object` Required:: - `ID` - `state` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `ID` | `string` | The machine's UUID from the underlying provisioning tool | `bootMode` | `string` | BootMode indicates the boot mode used to provision the node | `image` | `object` | Image holds the details of the last image successfully provisioned to the host. | `rootDeviceHints` | `object` | The RootDevicehints set by the user | `state` | `string` | An indiciator for what the provisioner is doing with the host. |=== ..status.provisioning.image Description:: Image holds the details of the last image successfully provisioned to the host. Type:: `object` Required:: - `checksum` - `url` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `checksum` | `string` | Checksum is the checksum for the image. | `checksumType` | `string` | ChecksumType is the checksum algorithm for the image. e.g md5, sha256, sha512 | `format` | `string` | DiskFormat contains the format of the image (raw, qcow2, ...) Needs to be set to raw for raw images streaming | `url` | `string` | URL is a location of an image to deploy. |=== ..status.provisioning.rootDeviceHints Description:: The RootDevicehints set by the user Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `deviceName` | `string` | A Linux device name like ""/dev/vda"". The hint must match the actual value exactly. | `hctl` | `string` | A SCSI bus address like 0:0:0:0. The hint must match the actual value exactly. | `minSizeGigabytes` | `integer` | The minimum size of the device in Gigabytes. | `model` | `string` | A vendor-specific device identifier. The hint can be a substring of the actual value. | `rotational` | `boolean` | True if the device should use spinning media, false otherwise. | `serialNumber` | `string` | Device serial number. The hint must match the actual value exactly. | `vendor` | `string` | The name of the vendor or manufacturer of the device. The hint can be a substring of the actual value. | `wwn` | `string` | Unique storage identifier. The hint must match the actual value exactly. | `wwnVendorExtension` | `string` | Unique vendor storage identifier. The hint must match the actual value exactly. | `wwnWithExtension` | `string` | Unique storage identifier with the vendor extension appended. The hint must match the actual value exactly. |=== ..status.triedCredentials Description:: the last credentials we sent to the provisioning backend Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `credentials` | `object` | SecretReference represents a Secret Reference. It has enough information to retrieve secret in any namespace | `credentialsVersion` | `string` | |=== ..status.triedCredentials.credentials Description:: SecretReference represents a Secret Reference. It has enough information to retrieve secret in any namespace Type:: `object` [cols=""1,1,1"",options=""header""] |=== | Property | Type | Description | `name` | `string` | Name is unique within a namespace to reference a secret resource. | `namespace` | `string` | Namespace defines the space within which the secret name must be unique. |=== == API endpoints The following API endpoints are available: * `/apis/metal3.io/v1alpha1/baremetalhosts` - `GET`: list objects of kind BareMetalHost * `/apis/metal3.io/v1alpha1/namespaces/{namespace}/baremetalhosts` - `DELETE`: delete collection of BareMetalHost - `GET`: list objects of kind BareMetalHost - `POST`: create a BareMetalHost * `/apis/metal3.io/v1alpha1/namespaces/{namespace}/baremetalhosts/{name}` - `DELETE`: delete a BareMetalHost - `GET`: read the specified BareMetalHost - `PATCH`: partially update the specified BareMetalHost - `PUT`: replace the specified BareMetalHost * `/apis/metal3.io/v1alpha1/namespaces/{namespace}/baremetalhosts/{name}/status` - `GET`: read status of the specified BareMetalHost - `PATCH`: partially update status of the specified BareMetalHost - `PUT`: replace status of the specified BareMetalHost === /apis/metal3.io/v1alpha1/baremetalhosts .Global guery parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `allowWatchBookmarks` | `boolean` | allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. If the feature gate WatchBookmarks is not enabled in apiserver, this field is ignored. | `continue` | `string` | The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. | `fieldSelector` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. | `pretty` | `string` | If 'true', then the output is pretty printed. | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `resourceVersionMatch` | `string` | resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. | `watch` | `boolean` | Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== HTTP method:: `GET` Description:: list objects of kind BareMetalHost .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#baremetalhostlist-metal3-io-v1alpha1[`BareMetalHostList metal3.io/v1alpha1`] | 401 - Unauthorized | Empty |=== === /apis/metal3.io/v1alpha1/namespaces/{namespace}/baremetalhosts .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global guery parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `DELETE` Description:: delete collection of BareMetalHost .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `allowWatchBookmarks` | `boolean` | allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. If the feature gate WatchBookmarks is not enabled in apiserver, this field is ignored. | `continue` | `string` | The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. | `fieldSelector` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `resourceVersionMatch` | `string` | resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. | `watch` | `boolean` | Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#status_v2-meta-v1[`Status_v2 meta/v1`] | 401 - Unauthorized | Empty |=== HTTP method:: `GET` Description:: list objects of kind BareMetalHost .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `allowWatchBookmarks` | `boolean` | allowWatchBookmarks requests watch events with type "BOOKMARK". Servers that do not implement bookmarks may ignore this flag and bookmarks are sent at the server's discretion. Clients should not assume bookmarks are returned at any specific interval, nor may they assume the server will send any BOOKMARK event during a session. If this is not a watch, this field is ignored. If the feature gate WatchBookmarks is not enabled in apiserver, this field is ignored. | `continue` | `string` | The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the "next key". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. | `fieldSelector` | `string` | A selector to restrict the list of returned objects by their fields. Defaults to everything. | `labelSelector` | `string` | A selector to restrict the list of returned objects by their labels. Defaults to everything. | `limit` | `integer` | limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `resourceVersionMatch` | `string` | resourceVersionMatch determines how resourceVersion is applied to list calls. It is highly recommended that resourceVersionMatch be set for list calls where resourceVersion is set See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset | `timeoutSeconds` | `integer` | Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. | `watch` | `boolean` | Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#baremetalhostlist-metal3-io-v1alpha1[`BareMetalHostList metal3.io/v1alpha1`] | 401 - Unauthorized | Empty |=== HTTP method:: `POST` Description:: create a BareMetalHost .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../provisioning_apis/baremetalhost-metal3-io-v1alpha1.adoc#baremetalhost-metal3-io-v1alpha1[`BareMetalHost metal3.io/v1alpha1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../provisioning_apis/baremetalhost-metal3-io-v1alpha1.adoc#baremetalhost-metal3-io-v1alpha1[`BareMetalHost metal3.io/v1alpha1`] | 201 - Created | xref:../provisioning_apis/baremetalhost-metal3-io-v1alpha1.adoc#baremetalhost-metal3-io-v1alpha1[`BareMetalHost metal3.io/v1alpha1`] | 202 - Accepted | xref:../provisioning_apis/baremetalhost-metal3-io-v1alpha1.adoc#baremetalhost-metal3-io-v1alpha1[`BareMetalHost metal3.io/v1alpha1`] | 401 - Unauthorized | Empty |=== === /apis/metal3.io/v1alpha1/namespaces/{namespace}/baremetalhosts/{name} .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the BareMetalHost | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global guery parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `DELETE` Description:: delete a BareMetalHost .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `gracePeriodSeconds` | `integer` | The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. | `orphanDependents` | `boolean` | Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the "orphan" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. | `propagationPolicy` | `string` | Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#deleteoptions_v2-meta-v1[`DeleteOptions_v2 meta/v1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../objects/index.adoc#status_v2-meta-v1[`Status_v2 meta/v1`] | 202 - Accepted | xref:../objects/index.adoc#status_v2-meta-v1[`Status_v2 meta/v1`] | 401 - Unauthorized | Empty |=== HTTP method:: `GET` Description:: read the specified BareMetalHost .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../provisioning_apis/baremetalhost-metal3-io-v1alpha1.adoc#baremetalhost-metal3-io-v1alpha1[`BareMetalHost metal3.io/v1alpha1`] | 401 - Unauthorized | Empty |=== HTTP method:: `PATCH` Description:: partially update the specified BareMetalHost .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#patch-meta-v1[`Patch meta/v1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../provisioning_apis/baremetalhost-metal3-io-v1alpha1.adoc#baremetalhost-metal3-io-v1alpha1[`BareMetalHost metal3.io/v1alpha1`] | 401 - Unauthorized | Empty |=== HTTP method:: `PUT` Description:: replace the specified BareMetalHost .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../provisioning_apis/baremetalhost-metal3-io-v1alpha1.adoc#baremetalhost-metal3-io-v1alpha1[`BareMetalHost metal3.io/v1alpha1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../provisioning_apis/baremetalhost-metal3-io-v1alpha1.adoc#baremetalhost-metal3-io-v1alpha1[`BareMetalHost metal3.io/v1alpha1`] | 201 - Created | xref:../provisioning_apis/baremetalhost-metal3-io-v1alpha1.adoc#baremetalhost-metal3-io-v1alpha1[`BareMetalHost metal3.io/v1alpha1`] | 401 - Unauthorized | Empty |=== === /apis/metal3.io/v1alpha1/namespaces/{namespace}/baremetalhosts/{name}/status .Global path parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `name` | `string` | name of the BareMetalHost | `namespace` | `string` | object name and auth scope, such as for teams and projects |=== .Global guery parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `pretty` | `string` | If 'true', then the output is pretty printed. |=== HTTP method:: `GET` Description:: read status of the specified BareMetalHost .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `resourceVersion` | `string` | resourceVersion sets a constraint on what resource versions a request may be served from. See https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-versions for details. Defaults to unset |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../provisioning_apis/baremetalhost-metal3-io-v1alpha1.adoc#baremetalhost-metal3-io-v1alpha1[`BareMetalHost metal3.io/v1alpha1`] | 401 - Unauthorized | Empty |=== HTTP method:: `PATCH` Description:: partially update status of the specified BareMetalHost .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../objects/index.adoc#patch-meta-v1[`Patch meta/v1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../provisioning_apis/baremetalhost-metal3-io-v1alpha1.adoc#baremetalhost-metal3-io-v1alpha1[`BareMetalHost metal3.io/v1alpha1`] | 401 - Unauthorized | Empty |=== HTTP method:: `PUT` Description:: replace status of the specified BareMetalHost .Query parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `dryRun` | `string` | When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed | `fieldManager` | `string` | fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint. |=== .Body parameters [cols=""1,1,2"",options=""header""] |=== | Parameter | Type | Description | `body` | xref:../provisioning_apis/baremetalhost-metal3-io-v1alpha1.adoc#baremetalhost-metal3-io-v1alpha1[`BareMetalHost metal3.io/v1alpha1`] | |=== .HTTP responses [cols=""1,1"",options=""header""] |=== | HTTP code | Reponse body | 200 - OK | xref:../provisioning_apis/baremetalhost-metal3-io-v1alpha1.adoc#baremetalhost-metal3-io-v1alpha1[`BareMetalHost metal3.io/v1alpha1`] | 201 - Created | xref:../provisioning_apis/baremetalhost-metal3-io-v1alpha1.adoc#baremetalhost-metal3-io-v1alpha1[`BareMetalHost metal3.io/v1alpha1`] | 401 - Unauthorized | Empty |=== ",12281,False,2422.97595568637,median "[#ch08-methods] :imagesdir: chapters/08-methods/images :programsdir: chapters/08-methods/programs == Methods [quote, William Shakespeare] ____ Polonius (Aside): Though this be madness, yet there is method in `'t. ____ === Problem: Three card poker Gambling has held a fascination for humankind since its invention. As long as there have been mathematicians, they have studied the underlying mechanisms of probability and statistics that drive games of chance. A classic game of both statistics and strategy is poker. The problem we want to solve is programming one of the many variations of poker, called three card poker. Instead of bluffing, a player competes only with the house according to fixed rules without any room for psychology. A player is dealt three cards. If the player's hand contains a pair or better, he or she wins a payoff greater than or equal to the money bet. If the player does not have a pair or better, he or she loses the money bet. Below is a table giving one possible set of payoffs for each possible hand. [.center%autowidth%header,cols=""^,^,^,^,^""] |=================== |Hand |Payoff | |Hand | Payoff |Straight Flush |40| |Flush |2 |Three of a Kind |30| |Pair |1 |Straight |6| |Nothing |0 |=================== If you're unfamiliar with poker rules or card games in general, here's a quick explanation of the various hands. A traditional English or American deck of cards is made up of 52 cards, organized into four suits: spades, hearts, diamonds, and clubs. In each suit, there are 13 ranks: two, three, four, five, six, seven, eight, nine, ten, jack, queen, king, and ace. In three card poker, a straight is when the three cards can be arranged so that their ranks (ignoring suit) are in order. For example, a hand consisting of a Four of Diamonds, a Five of Spades, and a Six of Clubs would constitute a straight. An ace can serve as either the highest rank card (coming after a king) or the lowest rank card (coming before a two) and can help form a straight in either role (but not both at the same time). A flush is when all three cards have the same suit. For example, a Three of Hearts, a Seven of Hearts, and a Jack of Hearts would constitute a flush in three card poker. A straight flush, the highest hand, is made up of cards that form both a straight (by rank ordering) and a flush (by uniformity of suit). A three of a kind occurs when all three cards have the same rank, and a pair occurs when two of the cards have the same rank. When none of these conditions hold, the hand has no special designation in three card poker, and the bet is lost. Your task is to write a program that serves as a computerized version of the game. You must create a deck of 52 cards, thoroughly randomize them to simulate shuffling, and select the first three cards as a hand. You must then determine the highest designation that applies to the hand of cards and the corresponding winnings (if any). Any reasonable solution to this problem uses arrays, discussed in the previous chapter. Using only that knowledge, you should be able to create a three card poker game. However, the focus of this chapter is _methods_, which can be used to break the solution to a problem into logical pieces. By dividing the solution in this way, we'll be able to solve the three card poker problem in a relatively short, elegant, and easy to read way. === Concepts: Dividing work into segments You should notice that the solutions to problems we've been working on have become increasingly complex as the book progresses. This progression is partly because we want to solve more interesting problems with more complex solutions but also because we've introduced additional Java tools that make solving these harder problems possible. Surprisingly, the tools we introduce in this chapter do not allow you to solve a problem you couldn't solve before. Instead, the tools in this chapter and in the next make solving a problem easier and less susceptible to errors. A relatively long, complicated list of Java statements was necessary to solve problems like the statistics program or Conway's Game of Life. Instead of solving those problems as a single monolithic segment of code, we can break our solutions into units called _static methods_. ==== Reasons for `static` methods A static method is a short, named segment of code that's been packaged up so that it can be _called_ from other parts of the program. Whenever the task performed by this method is needed, the execution of the program jumps to the code in the method, does the work it's supposed to, and then returns to whatever it was doing before. The reasons for using static methods can be boiled down to three essentials: Modularity::: Very little software is written by individuals. Commercial software can have tens or even hundreds of developers involved in designing, implementing, testing, and maintaining code. When the code's divided into individual methods, those methods can be written and tested by different people with minimal interference. It's much harder to work together on one giant block of code. Readability::: Methods are *named* segments of code. When a method is called, its name is used. If a meaningful name is chosen, the line in the code that calls the method helps document the code by explaining what's happening. For example, if a method called `sort()` is used, a reader instantly understands that something's being sorted. If, instead of a separate `sort()` method, the code that does sorting was pasted into the same location, a reader might have to devote a few moments to understanding the meaning of those lines of code, particularly without comments. Reusability::: The fact that a method can be called from anywhere in the code makes it reusable. To use the `sort()` example again, we might have to sort several different arrays in one program. Without methods, we'd have to keep copying and pasting code over and over again. With methods, the total amount of source code can be smaller. In fact, if you find yourself copying and pasting code, it's often an indication that a method would be useful. + {empty} + This idea of reusability stretches beyond individual programs. A static method can be called from an entirely different program. If you create a method that's really useful, you're free to use it in other programs you write. By doing so, you only have to makes changes in one place if you discover errors or want to increase its functionality. ==== Parallel to mathematical functions We've been discussing the usefulness of static methods without saying exactly what they are. One way to get insight into methods is by acknowledging their similarity to functions from mathematics. In procedural (non-object oriented) languages like C, the equivalents of static methods are usually referred to as functions. Like functions in mathematics, a static method takes some number of inputs (possibly as few as zero) and usually produces some output. You've already used several static methods from the `Math` class, such as `Math.sqrt()`. Consider the following function. //[stem] //++++ //f(x) = \\sqrt{x} //++++ [.text-center] image::root.svg[scaledwidth=15%,pdfwidth=15%,width=15%] This function mirrors the code inside of `Math.sqrt()`. In math, when you apply _f_(_x_) to a specific value, you might write _y_ = _f_(5). In Java, you might type the following. [source,java] ---- double y = Math.sqrt(5); ---- In the statement _f_(5), the placeholder variable _x_ takes on the value 5. In the same way, some variable inside of `Math.sqrt()` takes on the value `5` when the method is called. It's important to understand this similarity between methods and mathematical functions because the designers of many programming languages have been directly influenced by the older notation. However, there are many differences between the two concepts as well. Mathematical functions can take more than one input, and so can Java methods. Java methods can also take no input, while the central idea of a mathematical function is to map some input value(s) to some output value. Java methods do not necessarily even have output values. They may just *do* something. ==== Control flow We have discussed selection statements such as `if` and `switch` as well as three different looping structures, `for`, `while`, and `do`-`while`. Each of these Java language features is used for control flow. The selection statements allow your program to choose which code to execute. The loops allow your code to repeatedly execute certain code. Methods also affect control flow. When a method is called, the execution of the program jumps into the method, does all the work it needs to there, and then returns to the code that called it. Recall the very simple example from above. [source,java] ---- double y = Math.sqrt(5); ---- The JVM has allocated a variable of type `double` and is preparing to assign a value to it. Suddenly, the execution of the JVM jumps into the code inside of the `Math.sqrt()` method. It takes some non-trivial amount of work to compute the square root of a number. After that computation is finished, the flow of execution returns to the assignment that has been waiting all that time. Just like a mathematical function, we can treat the method call `Math.sqrt(5)` as if it were ""`magically`"" replaced by a `double` approximating the square root of 5. === Syntax: Methods By now, you should have a good feel for the concepts behind calling and even creating static methods and are probably getting impatient to use them. However, we haven't yet described all the details of Java method syntax. First, we'll describe how you can create your own static methods, then we'll discuss the finer points of calling static methods, and finally we'll explain how _class variables_ can be used from many different methods. ==== Defining methods A very simple method that the `Math` class provides is the `Math.max()` method. This method selects the larger of the two values provided as input. [source,java] ---- int maximum = Math.max(5, 10); ---- In this case, the value stored into `maximum` is `10`. Despite its simplicity, we demonstrated how useful this method could be in our solution to Conway's Game of Life from <>. If we wanted to write this method ourselves, the code would be as follows. [source,java] ---- public static int max(int a, int b) { if(a >= b) return a; else return b; } ---- Even in such a small method, there's a lot of syntax to worry about. The first line of this method is called the _method header_. The `public` keyword in this header is used to denote that any code, even code from a different class, can call this method. We discuss restricting access to methods and variables more in the later part of this chapter. For now, assume that every method is `public`. The keyword `static` indicates that this method is static. Although we have used the term _static method_ many times, we have not yet defined it. A static method is linked to a whole class, not to a specific object of that class–that is, a static method can be called without referencing an object of the class. Again, we discuss the finer points of objects and classes in the next chapter. For now, all methods are `static`. The third keyword in the method header is the familiar `int`, giving the return type of the method. Wherever this method is called, it can be treated like an `int` value, because that's what it gives back. In this case, the return type is obvious: The maximum of two `int` values must also be an `int` value. Any type can be used as a return value including all the primitive types and any reference or array types. The only limitation is that a method can only return a single item, but since that item can be an array, this limitation is usually not important. It's also possible for a method to return nothing. In that case, the keyword `void` is used for the return type. Next in the method header is the identifier `max`, which is the name of the method. Any legal identifier that you can use for a variable name is valid for a method name as well. It's important to pick a name that's readable and gives a reader a clear idea about what the method does. A common convention is to name a method using a verb phrase, indicating the operation that is being done by that method (e.g., `computeTax`). Like variable names, the Java standard is to use camel notation, starting with a lowercase letter and capitalizing the first letter of each new word in the name. After the name of the method is the list of _parameters_, separated by commas. In this case, each parameter has the `int` type. You're free to name your parameters whatever you want, though they should be meaningful. You can have as few as zero parameters, but there's an upper limit imposed by the JVM, usually 255. The body of the method follows the header of the method, surrounded by braces (`{ }`). Unlike `if` statements and loops, the braces for methods are *required*. Inside the body of a method, the usual rules for Java control flow apply. Each line is executed one by one unless there are selection statements or loops. Calling methods inside of methods is also allowed. In the `max()` method, we use an `if`-`else` construction to find the larger of `a` and `b`. A `return` statement immediately stops execution of the method, transfers execution back to the calling code, and gives back the value that comes after it. In this case, the value of `a` is returned if it is equal or larger, and the value of `b` is returned otherwise. Because a `return` statement immediately jumps out of a method, we could have written the method with one fewer line of code. [source,java] ---- public static int max(int a, int b) { if(a >= b) return a; return b; } ---- The only way that the line `return b;` can be reached is if `a` had not already been returned. Beginner programmers sometimes ask what to do if `a` and `b` are equal. In our code it's clear that the value of `a` will be returned, but it hardly matters: two equal `int` values are indistinguishable from each other. Some students imagine handling this special case by printing an error message, but that approach is seldom useful. When trying to find the larger of two numbers in programming, it's usually the value we want, not information about which one is actually larger. ===== The `main()` method If some of this syntax seems eerily familiar, remember that you've been coding static methods since your very first Java program. The `main()` method is just another static method, special only because the JVM chooses to start execution there. Let's look at the `main()` method from a standard Hello, World! program. [source,java] ---- public static void main(String[] args) { System.out.println(""Hello, world!""); return; } ---- Just like the `max()` method, the header for `main()` starts with `public static`. Then, the return type for `main()` is `void` because the JVM is not expecting to get any answer back. The `main()` method has a single parameter, an array `String` values. In this program, we do not use the `args` parameter, but it is available. For the `main()` method, this declaration is fine, because `main()` has to be uniform across all programs. However, when designing your own methods, you should not include unnecessary parameters. The final executable line in this `main()` method is a `return` statement. Because `main()` has a `void` return type, the `return` statement has no value to return. For `void` methods, a `return` statement is optional. You can use it to leave a method early if desired. For a value-returning method, execution *must* reach a `return` statement with a valid value no matter what the input of the method is. If Java finds a way that execution could reach the end of a value returning method without reaching a `return` statement, it causes a compiler error. ===== Overloaded methods Since this declaration is in another class, it's fine to create a `max()` method even though there's already one in the `Math` class. However, it's possible to create more than one method with the same name even in the same class, provided that their _signatures_ are not the same. Two methods have the same _signature_ if they have the same name and parameter types. [source,java] ---- public static int max(int a, int b, int c) { return max(max(a, b), c); } ---- In this example, we've created yet another `max()` method, but this one takes three parameters instead of two. This method even calls the two parameter version of `max()`. Creating more than one method with the same name is called _overloading_ those methods. Overloading methods is useful because it allows you to use the same method name for similar functionality, even when there are some underlying differences in the implementation. For example, the `Math` class provides four different, overloaded versions of the `max()` method, specialized for `int`, `long`, `float`, and `double` values, respectively. There are limitations on creating overloaded methods, of course. The compiler must be able to determine which method you intend to use. Thus, the signatures have to vary by type or number of parameters. A different return type is not enough. ==== Calling methods After a method has been defined, it must be called before it does anything. You have plenty of experience calling static methods like `Math.sqrt()` and `Math.max()`. An example of the appropriate syntax was given earlier. [source,java] ---- int maximum = Math.max(5, 10); ---- Formally, the call starts with the name of the class (`Math`), followed by a dot, followed by the name of the method (`max`), followed by the list of _arguments_ inside parentheses. These arguments are the values you want to _pass_ into the method. Some books use the term _formal parameters_ to describe the variables defined in the method signature and _actual parameters_ to describe the values passed into the methods, but we stick with the simpler terms parameters and arguments. Of course, the number of arguments must match the number of parameters defined by the method, and the types must match as well. Java performs automatic casting when no precision is lost. Thus, you can always supply an `int` argument for a `double` parameter but not the reverse. Arguments can be literal values, variables, or even other method calls that return the appropriate type. Using the `max()` method defined before, we could rewrite our simple example without a class name. [source,java] ---- int maximum = max(5, 10); ---- Whenever you call a static method from code that's inside the same class, you can leave out the class name. ===== Binding Many new programmers are confused about the relationship between arguments and parameters. The process of supplying an argument to be used as a parameter is called _binding_. Through binding, a value or variable from the calling code is given a new name inside of a method. Consider the following method. [source,java] ---- public static int add(int a, int b) { return a + b; } ---- This absurdly short method adds two numbers together and returns the result, approximating the functionality of the `+` operator. We could call the method in the following context. [source,java] ---- int x = 3; int y = 5; int z = add(x, y); ---- Inside the method, the value of `x` is bound to the variable `a`, and the value of `y` is bound to the variable `b`. The `add()` method has its own _scope_. Scope means the area where a variable name is visible (or meaningful). Thus, `x` and `y` do not exist inside of the `add()` method, only the variables `a` and `b` do. Since methods have their own scope, variables in one method can have the same names as variables in another method without the compiler (or the programmer!) becoming confused. Consider the following example. [source,java] ---- int a = 3; int b = 5; int c = add(b, a); ---- Here the variables `a` and `b` exist in both the calling code and inside the method, but the names are independent. The value of `a` in the calling code happens to be bound to a variable called `b` inside the method, but the JVM has no confusion about which `a` is which. Herein lies the value of methods: They are largely independent of whatever else is going on in the code, allowing the programmer to focus on a small, manageable task. Another important feature of Java is that the process of binding variables is _pass by value_, meaning that only the *value* of the argument is bound to the parameter. Whenever a method is called, the method creates a new variable for each parameter and copies the value of its argument into it. In practice, this approach means that a method cannot directly change the value of an argument. Consider the following method. [source,java] ---- public static void increment(int counter) { counter++; } ---- This method takes the value of its argument and copies it into the new variable `counter`. Then, it increments `counter`, but the original argument is unchanged. Thus, the following fragment is an infinite loop. [source,java] ---- int i = 0; while(i < 100) increment(i); ---- The value of `i` remains fixed at `0` for the entire program. The copy of `i` bound to `counter` increases to `1` every time `increment()` is called, but `i` remains unaffected. This is not to say that a method cannot affect the variables outside of itself. The primary way that it can do so is by using `return` statements. We can rewrite `increment()` to achieve this effect. [source,java] ---- public static int increment(int counter) { return counter + 1; } ---- Then, we need to adjust the loop so that it stores the returned value instead of dropping it on the floor. [source,java] ---- int i = 0; while(i < 100) i = increment(i); ---- A second way that methods can affect the values of outside variables is more indirect. In Java, every argument is passed by value, even arrays and objects. Practically, this means that, if a reference to an array is passed into a method, you cannot change which array it is pointing at. Since references are not values but names pointing at particular locations in memory, you can directly change the contents of that memory with a method, even if you can't change which locations are being referenced. For example, the following method does *not* reverse the order of an array. [source,java] ---- public static void badReverseArray(int[] array) { int[] temp = new int[array.length]; for(int i = 0; i < array.length; i++) temp[i] = array[array.length - i - 1]; array = temp; } ---- Although this code does store a reversed version of `array` in `temp`, the last line of the method is meaningless: The array passed into the method still points to the original location in memory. We can rewrite the method to do the reversal _in place_, meaning that the values of the array are shuffled around, but the array still occupies the same memory locations. [source,java] ---- public static void goodReverseArray(int[] array) { int temp; for(int i = 0; i < array.length / 2; i++) { temp = array[i]; array[i] = array[array.length - i - 1]; array[array.length - i - 1] = temp; } } ---- In this version of the method, we swap the first element of the array with the last, the second with the second to last, and so on. We only go up to the halfway point of the array, otherwise we would undo the reversal process. The values of the array are reversed, but they still occupy the same chunk of memory. It's possible to write a correct method more in the style of `badReverseArray()` which creates a temporary array, copies the original values into it, and then copies them back to the original array in reverse order, but it's less efficient to create the extra array and perform two copies. ==== Class variables According to the rules we've given so far, the only legal variables in the scope of a static method are the parameters and any other _local_ variables declared inside the method. However, it's possible to create a variable that exists outside of static methods yet is visible inside all of them. These kinds of variables are called _class variables_ (or sometimes _static fields_ or _global variables_). These variables persist *between* method calls. The syntax for creating such a variable is to declare it outside of all methods (but inside the class) with the keyword `static` and an access modifier such as `public` or `private`. For example, the following class includes a method called `record()` that increases the class variable `counter` every time it's called. .Keeps track of the number of times the `record()` method is called. [source, java] [[BookkeeperProgram]] ---- include::{programsdir}/Bookkeeper.java[] ---- When run, this program calls the `record()` method some random number of times, and the variable `counter` keeps track of the number. Because `counter` is static, it's accessible to both the `main()` and `record()` methods. Many programmers frown on the use of class variables precisely because they're visible to many different methods. The idea of a method is to isolate pieces of code so that the complexity of a program can be divided into simple units. In the case of a public class variable, even code in other classes can modify its value. If many different pieces of code can modify a variable, it may be difficult to keep that variable from being changed in unexpected ways. For example, if another method used the `counter` variable to record the number of times it was called, the final value of `counter` would be the sum of the number of times the two methods were called. There might be some reason to keep track of such information, but it would be impossible to reconstruct what fraction of the value in `counter` came from one method and what fraction came from the other. Class variables have their uses, but they should generally be avoided. The chief exception to this rule is constants. Since a constant never changes, a class variable is a great place to store it, making the value available to all code. An example you've already used is `Math.PI`. As with static methods, a static field from another class can be accessed by using the class name, then a dot, and then the name of the static field. Again, when the code using the field is in the same class, the class name can be dropped. A class constant is declared like a class variable, but with the addition of the `final` keyword. [[gravitationalAttractionExample]] .Gravitational attraction ==== The following class allows a user to compute the one-dimensional force due to gravity. This force _F_ is given by the following equation. //[stem] //**** //F = \\frac{Gm_1m_2}{r^2} //**** [.text-center] image::gravitation.svg[scaledwidth=15%,pdfwidth=15%,width=15%] In this equation, _m_~1~ is the mass of one object, _m_~2~ is the mass of another, _r_ is the distance between their centers, and _G_ is the gravitational constant, 6.673 × 10^-11^ N⋅m^2^⋅kg^-2^. .Calculates the attraction due to gravity between two masses. [source, java] [[GravityProgram]] ---- include::{programsdir}/Gravity.java[] ---- ==== Use named constants whenever they increase readability. You can use the `public` modifier if you want all classes to have access to your constant (`Gravity.G` is a good example). You can use the `private` modifier if you want the constant to be accessible only inside your class, if it has no use outside, or if it contains secret information. === Examples: Defining methods Any large problem should be broken down into methods. Because the technique is useful in so many circumstances, it's difficult to give a set of examples that covers all cases. Instead, our examples are short, easy to understand methods, focusing on Euclidean distance, testing for palindromes, and converting a `String` representation of an `int` to an `int`. .Euclidean distance ==== The Euclidean distance between two points is the length of a straight line connecting them. It plays an important role in 3D graphics and games and is the basis for many other practical applications involving spatial relationships. Given two points in 3D space (_x_~1~, _y_~1~, _z_~1~) and (_x_~2~, _y_~2~, _z_~2~), we can compute the Euclidean distance between them with the following equation. //[stem] //**** //d = \\sqrt{(x_1 - x_2)^2 + (y_1 - y_2)^2 + (z_1 - z_2)^2} //**** [.text-center] image::distance.svg[scaledwidth=55%,pdfwidth=55%,width=55%] The method below applies this equation directly. [source,java] ---- public static double distance(double x1, double y1, double z1, double x2, double y2, double z2) { double x = x1 - x2; double y = y1 - y2; double z = z1 - z2; return Math.sqrt(x*x + y*y + z*z); } ---- This equation is a good candidate for a static method since it might be necessary to do this calculation many times and it does not depend on any other variables or program state. ==== [[palindromeTestingExample]] .Palindrome testing ==== A palindrome is a word or phrase (or even a number) that's the same spelled forward and backward. ""`Racecar,`"" ""`Madam, I'm Adam,`"" and ""`Satan, oscillate my metallic sonatas`"" are examples in English. Typically, spaces and punctuation are ignored. We're going to write a function that, given a `String`, returns `true` if it's a palindrome and `false` otherwise. To simplify the problem, we're *not* going to ignore spaces and punctuation. Thus, with our method, ""`racecar`"" counts as a palindrome, but neither of the other two examples would. [source,java] ---- public static boolean isPalindrome(String text) { //<.> text = text.toLowerCase(); //<.> for(int i = 0; i < text.length() / 2; i++) //<.> if(text.charAt(i) != text.charAt(text.length() - i - 1)) //<.> return false; return true; } ---- <.> Because our method returns `true` or `false`, its return type must be `boolean`. Many methods that return a `boolean` value have a name starting with `is`, like our method. <.> The first line of the body of our method changes `text` to lowercase. The `String` method `toLowerCase()` creates a lowercase copy of the `String` it's called on, in this case `text`. Then, we point the reference variable `text` at that new, lowercase `String`. On the outside of this function, the `String` passed in does not change because the reference `text` is passed by value. <.> The loop iterates through the first half of `text`, comparing it to the second half. This loop reflects the asymmetry of these kinds of tests: You can't be sure that `text` is a palindrome until you've checked the entire thing, but you immediately know that it's not if even a single pair of characters doesn't match. <.> If the test in that `if` statement ever shows that the two `char` values aren't equal, the `return false` statement jumps out of the method without completing the loop. ==== **** <> **** [[parsingANumberExample]] .Parsing a number ==== When you read in a number using an object of the `Scanner` class, it converts (or _parses_) the text entered by the user into the appropriate type. For example, the `nextDouble()` method reads in some text and convert it into a `double`. When you use a `JOptionPane` method to read in input, it comes in as a `String`. If you want to use that data as a `double`, you must convert it using the `Double.parseDouble()` static method. Some Java programmer had to write this method. We're going to recreate a similar method to convert the `String` representation of a floating-point number into a `double`. Our simple method ignores scientific notation. [source,java] ---- public static double parseDouble(String value) { int i = 0; boolean negative = false; double temp = 0.0; double fraction = 10.0; if(value.charAt(i) == '-') { //<.> negative = true; i++; } else if(value.charAt(i) == '+') i++; while(i < value.length() && value.charAt(i) != '.') { //<.> temp *= 10.0; temp += value.charAt(i) - '0'; i++; } i++; //move past decimal point (if there) <.> while(i < value.length()) { //<.> temp += (value.charAt(i) - '0') / fraction; fraction *= 10.0; i++; } if(negative) //<.> temp = -temp; return temp; } ---- <.> After declaring a few variables, this method first checks index `0` in the input `String` `value` to see if it is a `'-'` or a `'+'`. If it is a `'-'`, it sets `negative` to `true` and moves on. If it is a `'+'`, it simply moves on. <.> Then, the method loops through `value` until it reaches the end or reaches a decimal point. As it iterates, it multiplies the current value of `temp` by `10.0` and adds in the next digit from `value` (after subtracting `'0'` so that the range is is from 0 to 9). This repetitive multiplication by `10.0` accounts for the increasing powers of 10 in the base 10 number system. Since `temp` starts with a value of `0.0`, the first multiplication has no effect, as intended. <.> After the first `while` loop, the index `i` is incremented once, to skip the decimal point, if there is one. If there is no decimal point, the loop must have exited because the end of `value` had been reached. <.> The second `while` loop runs to the end of `value`, this time adding in each digit value divided by `fraction`, which is increased by a factor of `10.0` each time. Doing so allows us to add smaller and smaller fractional digits to the total. <.> We set `temp` to its opposite if the flag `negative` was set earlier and finally return `temp`. Note that the real `Double.parseDouble()` method not only accepts `String` values in scientific notation but also does a great deal of error checking. Our code either crashes or gives inaccurate results on an empty `String`, a `String` containing non-numerical characters, or a `String` with more than one decimal point. Furthermore, this code does not use the best approach for minimizing floating-point precision errors. ==== **** <> **** === Solution: Three card poker Here we present our solution to the three card poker problem. We explain each method individually. [source, java] ---- include::{programsdir}/ThreeCardPoker.java[lines=1..11] ---- <.> Before our `main()` method begins, we declare a number of class constants. Two constant arrays of `String` values provide us with an easy way to represent suits and ranks. <.> The remaining six `int` constants are used to allocate a winning payoff to each possible outcome. Note that these constants can be declared anywhere inside the class, provided that they're outside of methods. However, it's typical (and good style) to declare them at the top of the class. [source, java] ---- include::{programsdir}/ThreeCardPoker.java[lines=13..29] ---- <.> In the `main()` method, an array representing a deck of 52 cards is created first, followed by an array representing the 3 cards to be dealt. <.> The deck is filled sequentially and then shuffled with a method. <.> Next, the first 3 cards of the deck are copied into the array representing the hand of cards. <.> The score of the hand is determined, and then the hand is printed out. We print the hand after determining the score because the hand is sorted in the process of determining the score, making the output easier to read. <.> Finally, we print the appropriate output, depending on the score. [source, java] ---- include::{programsdir}/ThreeCardPoker.java[lines=31..39] ---- This method shuffles the deck. Its approach is to swap the first element in the array of cards with one of the elements that follow, chosen randomly. Then, it swaps the second element in the array with any of the elements that follow it, and so on. If `Math.random()` truly gives us a uniformly generated random number in the range [0,1), the final shuffled deck should be any one of the 52! possible decks with equal probability. [source, java] ---- include::{programsdir}/ThreeCardPoker.java[lines=41..48] ---- <.> The first of these methods prints out a human readable version of each card in an array (instead of 0 - 51). It does so using the second and third methods as helper methods. <.> Method `getRank()` computes the rank of a card from its number. <.> Method `getSuit()` computes the suit of a card from its number. The indexes obtained from these methods are used to index into the `RANKS` and `SUITS` arrays. In the C language, calling the equivalent of a method from a method defined earlier requires a special declaration step called _prototyping_ before both methods. Java does not have this complication, and the `getRank()` and `getSuit()` methods compile and function perfectly if they are written above `print()` or below it inside the class definition. [source, java] ---- include::{programsdir}/ThreeCardPoker.java[lines=50..63] ---- This method computes the score by first sorting the hand and then testing progressively worse outcomes, starting with the best, a straight flush. As it moves down the list of outcomes, it calls appropriate methods to determine if a hand has a certain characteristic. [source, java] ---- include::{programsdir}/ThreeCardPoker.java[lines=65..77] ---- This code is an implementation of selection sort packaged into a method. Note that this method *does* change the values inside of the array `hand` even though it cannot change the array that `hand` points to. The array itself is passed by value, but its contents are effectively passed by reference. [source, java] ---- include::{programsdir}/ThreeCardPoker.java[lines=79..100] ---- <.> The code in `hasPair()` works by checking to see if the first and second or second and third cards have the same rank. An extra condition would be required if the cards weren't sorted. <.> The code in `hasThree()` checks to see if all the ranks are the same. <.> The code in `hasFlush()` is the same as `hasThree()` except that it checks for suit instead of rank. <.> Finally, `hasStraight()` checks to see if the ranks come one after the other, with an extra case to deal with the possibility of the ace counting as low. This test only works because the cards were sorted previously. These four methods would be similar but more complex for five- or seven-card poker hands. === Concurrency: Methods In Java, it's impossible to have concurrency without methods. Methods are the way we break a large program into manageable pieces but are also part of the syntax that Java uses to create threads of execution. Each thread of execution is associated with a `Thread` object; however, creating the object is not enough to start a new thread of execution running. Only when the `start()` method is called on the `Thread` object does the new thread start running. Hopefully, you've begun to visualize the execution of Java programs as an arrow that sits next to each line of code as it's executed. This arrow can jump to a choice and skip over other code using `if` and `switch` statements. Using loops, the arrow can jump backward and repeatedly execute code it's just executed. As we discussed in this chapter, the arrow can jump into a method, execute the code in that method, and then return to its caller, going back right to where it left off before the call. When the `start()` method is called on a `Thread` object, however, the arrow returns to the caller, but it also splits itself into a second arrow that then executes the corresponding `run()` method and any other methods it calls. Note that we're talking about a method called on a `Thread` object, not a static method called on the class as a whole. Calling `start()` is an instance method, which we discuss in <>. Unlike the static methods in this chapter, an instance method is tied to a particular object, but most of what you've learned about methods still applies. Methods are supposed to make programming easier by breaking programs into chunks small enough to think about. One of the only real dangers of methods is using class variables, as mentioned in <>. This problem becomes worse with multiple threads. With a single thread, two or more different methods can all affect the same class variable, perhaps in conflicting ways. With multiple threads, even the *same* method can interfere with itself. .LCG without thread safety ==== A linear congruential generator (LCG) allows you to create a sequence of pseudorandom numbers using the equation _x_~i~ = (_ax_~_i_-1~ + _b_) mod _m_, deriving the next number from the previous one, and so on. .Implements an LCG similar to one sometimes used in the function `rand()` used in the C language. [source, java] [[UnsafeRandomProgram]] ---- include::{programsdir}/UnsafeRandom.java[] ---- The `UnsafeRandom` program listed above always generates the same sequence of pseudorandom numbers, which can be useful for debugging a program. However, if two or more threads call `nextInt()`, they'll probably get different sequences. One thread will pick up some of the numbers, and the other will pick up the missing numbers in between. If each thread wants to generate the same sequence of numbers, the method should be rewritten so that it takes in the *previous* number in the sequence. In that way, there's no shared state. Remember that using a (non-final) class variable should be avoided whenever possible. .Implements the same LCG safely by requiring the caller to supply the previous random number. [source, java] [[SafeRandomProgram]] ---- include::{programsdir}/SafeRandom.java[] ---- ==== .Unpredictable methods ==== By forcing each thread to carry its own state, we fixed the previous problem. In <> we'll talk about the much nastier problem of two threads executing a method at exactly the same time. When that happens, very curious effects are possible. Consider the following program. .The `print()` method always prints `""Even""` when run with a single thread but can sometimes print `""Odd""` if called repeatedly with multiple threads. [source, java] [[AlwaysEvenProgram]] ---- include::{programsdir}/AlwaysEven.java[] ---- <.> With a single thread running, `value` always goes up to an even number before printing. <.> Afterward, it increments to the next odd number. If two or more threads call the `print()` method, `value` could be changed by one right before the other executes the `if` statements. ==== === Exercises *Conceptual Problems* . Describe three advantages of dividing long segments of code into static methods. . Can you think of any disadvantages of dividing code into methods? Are there situations in which using a method is unwise? . If you wanted to declare a static method that would compute the mean, median, and standard deviation of an input array of `double` values, how would you return those three answers? . Consider the following method definition. + [source,java] ---- public static void twice(int i) { i = 2 * i; } ---- + How many times does the following loop run, and why? + [source,java] ---- int x = 2; while(x < 128) twice(x); ---- . Consider the following signatures of two overloaded methods. + [source,java] ---- public static int magic(int rabbit, double hat) public static int magic(double wand, int spell) ---- + Which method would be invoked by the following call? + [source,java] ---- int x = magic(3, 16); ---- + What about the following? + [source,java] ---- int y = magic(3.2, 16.4); ---- + Use a compiler to check your answers. . The following class generates a sequence of even numbers. Each time the `next()` method is called, the next even number in the sequence is returned. What's the design problem with using a static field to keep track of the next value in the sequence? + [source,java] ---- public class EvenNumbers { private static int counter = 0; public static int next() { counter += 2; return counter; } } ---- *Programming Practice* . Write a static method called `cube()` that takes a single `double` value as a parameter and returns its value cubed. Do not use the `Math.pow()` method. . Implement a static method that takes a single `int` value as a parameter and prints its digits in reverse. For example, if `103` was passed into this method, it would print `301` to the screen. + You can find out what digit is in the ones place of a number by taking its remainder modulus 10. Then, you can remove the digit in the ones place by dividing by 10. Do not convert the `int` value into a `String`. . Write a static method that takes an array of `int` values as a parameter and returns `true` if the array is in ascending order and `false` otherwise. Compare each element of the array to the next element of the array. If the current element is ever larger than the next element, the array is not sorted in ascending order. Note that you can only be sure that the array is in ascending order after you have checked all neighboring pairs. . Write a static method that finds the ⌊log~2~ _n_⌋ of an integer _n_. Note that if log~2~ _n_ = _x_, it's also true that _n_ = 2^_x_^. In other words, the log~2~ operator tells you what power of 2 a number is. One way to define the log~2~ _n_ is the number of times you have to divide _n_ by 2 to get 1. Use this definition to make a loop that finds the value without using any calls to the `Math` library. + Here are some examples of the return values your method should give for various input values of _n_. + [.center%autowidth%header,cols=""5*^""] |============================= |_n_ |Return Value | |_n_ |Return Value |1 |0 | |16 |4 |2 |1 | |100 |6 |4 |2 | |512 |9 |8 |3 | |1000 |9 |10 |3 | |1024 |10 |============================= . [[palindromeExercise]] Write a method that tests palindromes like the method from <> but also ignores punctuation and spaces. Thus, `""A man, a plan, a canal: Panama""` should be counted as a palindrome by this new method. . [[scientificNotationExercise]] Add to the `parseDouble()` method from <> so that it can also handle numbers in standard Java scientific notation, such as `7.239e-14`. Note that the `e` can be uppercase or lowercase, and the exponent can begin with a minus sign (`-`), a plus sign (`+`), or neither. . Re-implement the solution from <> so that it uses a GUI constructed with `JOptionPane` to display the hand and the winnings. . Five card poker is a much more common version of poker than the three card version we discussed in <>. Using static methods, implement a two-player game of poker in which the deck is shuffled and then dealt into two hands of five cards each. Then, state which player's hand wins. With five cards, determining which hand wins is a more complicated process. The rankings of the various possible hands from best to worst are as follows. Straight Flush::: All five cards belong to the same suit and have ranks in sequential order (with either ace high or low). If two people both have straight flushes, the higher ranked one wins. If they both have the same ranks, it is a tie. Four of a Kind::: Four of the five cards have the same rank. If two people have four of a kind, the higher rank set of four wins. Full House::: Three of the five cards have the same rank and the other two share another rank. If two people have a full house, the higher ranked set of three wins. Flush::: All five cards have the same suit. If two people have flushes, the one with the highest card wins. If the highest card is a tie, the next highest is the tie breaker, and so on. If the two flushes have exactly the same ranks, the two flushes tie. Straight::: All five cards have ranks in sequential order (with either ace high or low). If two people both have straight, the higher ranked one wins. If they both have the same ranks, it is a tie. Three of a Kind::: Three of the cards have the same rank. If two people have three of a kind, the higher ranked set of three wins. Two Pair::: A pair of cards have the same rank and another pair of cards share another rank. If two people both have two pairs, the higher ranked pair is a tiebreaker. If the higher ranked pair is the same, the lower ranked pair is a tiebreaker. If the lower ranked pair is the same, the final unpaired card is the tiebreaker. If all the ranks of both hands match, it is a tie. Pair::: A pair of cards has the same rank. If two people have pairs, the rank of the pair is a tiebreaker. If the pairs have the same rank, the remaining cards in each hand are tiebreakers, in descending rank order. High Card::: If none of the other cases hold, the high card determines the value of the hand. If two people have the same highest card, the remaining cards in each hand are used as tiebreakers, in descending rank order. *Experiments* . In terms of time, there's a small overhead associated with calling a method and returning a value, but it's very hard to measure. Write a program with two `int` variables, `a` and `b`, where `a` starts with a value of `1` and `b` starts with a value of `2`. Run a `for` loop 100,000,000 times. On each iteration first increase the value of `a` by the value of `b` and then increase the value of `b` by `a`. Time this loop with `System.nanoTime()`, and then print out the time taken and the value of `a`. The value of `a` is not important, but the compiler will optimize away the math done with `a` and `b` unless we output the value. We recommend that you run this program repeatedly to get a sense of the average running time. + Now, instead of using the `+` operator to add `a` and `b`, use the following method. + [source,java] ---- public static int add(int a, int b) { return a + b; } ---- + Again, run your program repeatedly with this modification. What's the difference in running time between the version that uses a method and the version that does addition directly? + Depending on your JVM, it's quite possible that there's almost no difference. The JVM does a lot of optimizations including _inlining_, which replaces a call to a short method with the actual code inside the method.",12131,False,1897.1194469517563,median "/* * * Copyright (c) 2020 Project CHIP Authors * * 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. */ /* * Copyright (c) 2016-2019, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * Provides Bluez dbus implementatioon for BLE */ #include #include #include #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE #include #include #include #include #include #include ""CHIPBluezHelper.h"" #include using namespace ::nl; namespace chip { namespace DeviceLayer { namespace Internal { static int sBluezFD[2]; static GMainLoop * sBluezMainLoop = nullptr; static pthread_t sBluezThread; static BluezConnection * GetBluezConnectionViaDevice(BluezEndpoint * apEndpoint); static gboolean BluezAdvertisingRelease(BluezLEAdvertisement1 * aAdv, GDBusMethodInvocation * aInvocation, gpointer apClosure) { bool isSuccess = false; BluezEndpoint * endpoint = static_cast(apClosure); VerifyOrExit(endpoint != nullptr, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); VerifyOrExit(aAdv != nullptr, ChipLogProgress(DeviceLayer, ""BluezLEAdvertisement1 is NULL in %s"", __func__)); ChipLogProgress(DeviceLayer, ""Release adv object in %s"", __func__); g_dbus_object_manager_server_unexport(endpoint->mpRoot, endpoint->mpAdvPath); endpoint->mIsAdvertising = false; isSuccess = true; exit: return isSuccess ? TRUE : FALSE; } static BluezLEAdvertisement1 * BluezAdvertisingCreate(BluezEndpoint * apEndpoint) { BluezLEAdvertisement1 * adv = nullptr; BluezObjectSkeleton * object; GVariant * serviceData; gchar * localName; GVariantBuilder serviceDataBuilder; GVariantBuilder serviceUUIDsBuilder; char * debugStr; const gchar * array[1]; VerifyOrExit(apEndpoint != nullptr, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); if (apEndpoint->mpAdvPath == nullptr) apEndpoint->mpAdvPath = g_strdup_printf(""%s/advertising"", apEndpoint->mpRootPath); array[0] = g_strdup_printf(""%s"", apEndpoint->mpAdvertisingUUID); ChipLogProgress(DeviceLayer, ""Create adv object at %s"", apEndpoint->mpAdvPath); object = bluez_object_skeleton_new(apEndpoint->mpAdvPath); adv = bluez_leadvertisement1_skeleton_new(); g_variant_builder_init(&serviceDataBuilder, G_VARIANT_TYPE(""a{sv}"")); g_variant_builder_init(&serviceUUIDsBuilder, G_VARIANT_TYPE(""as"")); g_variant_builder_add( &serviceDataBuilder, ""{sv}"", apEndpoint->mpAdvertisingUUID, g_variant_new_fixed_array(G_VARIANT_TYPE_BYTE, apEndpoint->mpChipServiceData, sizeof(CHIPServiceData), sizeof(uint8_t))); g_variant_builder_add(&serviceUUIDsBuilder, ""s"", apEndpoint->mpAdvertisingUUID); if (apEndpoint->mpAdapterName != nullptr) localName = g_strdup_printf(""%s"", apEndpoint->mpAdapterName); else localName = g_strdup_printf(""%s%04x"", CHIP_DEVICE_CONFIG_BLE_DEVICE_NAME_PREFIX, getpid() & 0xffff); serviceData = g_variant_builder_end(&serviceDataBuilder); debugStr = g_variant_print(serviceData, TRUE); ChipLogProgress(DeviceLayer, ""SET service data to %s"", debugStr); g_free(debugStr); bluez_leadvertisement1_set_type_(adv, (apEndpoint->mType & BLUEZ_ADV_TYPE_CONNECTABLE) ? ""peripheral"" : ""broadcast""); // empty manufacturer data // empty solicit UUIDs bluez_leadvertisement1_set_service_data(adv, serviceData); // empty data bluez_leadvertisement1_set_discoverable(adv, (apEndpoint->mType & BLUEZ_ADV_TYPE_SCANNABLE) ? TRUE : FALSE); // advertising name corresponding to the PID and object path, for debug purposes bluez_leadvertisement1_set_local_name(adv, localName); bluez_leadvertisement1_set_service_uuids(adv, array); // 0xffff means no appearance bluez_leadvertisement1_set_appearance(adv, 0xffff); bluez_leadvertisement1_set_duration(adv, apEndpoint->mDuration); // empty duration, we don't have a clear notion what it would mean to timeslice between toble and anyone else bluez_leadvertisement1_set_timeout(adv, 0); // empty secondary channel for now bluez_object_skeleton_set_leadvertisement1(object, adv); g_signal_connect(adv, ""handle-release"", G_CALLBACK(BluezAdvertisingRelease), apEndpoint); g_dbus_object_manager_server_export(apEndpoint->mpRoot, G_DBUS_OBJECT_SKELETON(object)); g_object_unref(object); BLEManagerImpl::NotifyBLEPeripheralAdvConfiguredComplete(true, nullptr); exit: return adv; } static void BluezAdvStartDone(GObject * aObject, GAsyncResult * aResult, gpointer apClosure) { BluezLEAdvertisingManager1 * advMgr = BLUEZ_LEADVERTISING_MANAGER1(aObject); GError * error = nullptr; BluezEndpoint * endpoint = static_cast(apClosure); gboolean success = FALSE; VerifyOrExit(endpoint != nullptr, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); success = bluez_leadvertising_manager1_call_register_advertisement_finish(advMgr, aResult, &error); if (success == FALSE) { g_dbus_object_manager_server_unexport(endpoint->mpRoot, endpoint->mpAdvPath); } VerifyOrExit(success == TRUE, ChipLogProgress(DeviceLayer, ""FAIL: RegisterAdvertisement : %s"", error->message)); endpoint->mIsAdvertising = true; ChipLogProgress(DeviceLayer, ""RegisterAdvertisement complete""); exit: BLEManagerImpl::NotifyBLEPeripheralAdvStopComplete(success == TRUE ? true : false, nullptr); if (error != nullptr) g_error_free(error); } static void BluezAdvStopDone(GObject * aObject, GAsyncResult * aResult, gpointer apClosure) { BluezLEAdvertisingManager1 * advMgr = BLUEZ_LEADVERTISING_MANAGER1(aObject); BluezEndpoint * endpoint = static_cast(apClosure); GError * error = nullptr; gboolean success = FALSE; VerifyOrExit(endpoint != nullptr, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); success = bluez_leadvertising_manager1_call_unregister_advertisement_finish(advMgr, aResult, &error); if (success == FALSE) { g_dbus_object_manager_server_unexport(endpoint->mpRoot, endpoint->mpAdvPath); } else { endpoint->mIsAdvertising = false; } VerifyOrExit(success == TRUE, ChipLogProgress(DeviceLayer, ""FAIL: UnregisterAdvertisement : %s"", error->message)); ChipLogProgress(DeviceLayer, ""UnregisterAdvertisement complete""); exit: BLEManagerImpl::NotifyBLEPeripheralAdvStopComplete(success == TRUE ? true : false, nullptr); if (error != nullptr) g_error_free(error); } static gboolean BluezAdvSetup(void * apClosure) { BluezEndpoint * endpoint = static_cast(apClosure); BluezLEAdvertisement1 * adv; VerifyOrExit(endpoint != nullptr, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); VerifyOrExit(endpoint->mIsAdvertising == FALSE, ChipLogProgress(DeviceLayer, ""FAIL: Advertising already enabled in %s"", __func__)); VerifyOrExit(endpoint->mpAdapter != nullptr, ChipLogProgress(DeviceLayer, ""FAIL: NULL endpoint->mpAdapter in %s"", __func__)); adv = BluezAdvertisingCreate(endpoint); VerifyOrExit(adv != nullptr, ChipLogProgress(DeviceLayer, ""FAIL: NULL adv in %s"", __func__)); exit: return G_SOURCE_REMOVE; } static gboolean BluezAdvStart(void * apClosure) { GDBusObject * adapter; BluezLEAdvertisingManager1 * advMgr = nullptr; GVariantBuilder optionsBuilder; GVariant * options; BluezEndpoint * endpoint = static_cast(apClosure); VerifyOrExit(endpoint != nullptr, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); VerifyOrExit(!endpoint->mIsAdvertising, ChipLogProgress(DeviceLayer, ""FAIL: Advertising has already been enabled in %s"", __func__)); VerifyOrExit(endpoint->mpAdapter != nullptr, ChipLogProgress(DeviceLayer, ""FAIL: NULL endpoint->mpAdapter in %s"", __func__)); adapter = g_dbus_interface_get_object(G_DBUS_INTERFACE(endpoint->mpAdapter)); VerifyOrExit(adapter != nullptr, ChipLogProgress(DeviceLayer, ""FAIL: NULL adapter in %s"", __func__)); advMgr = bluez_object_get_leadvertising_manager1(BLUEZ_OBJECT(adapter)); VerifyOrExit(advMgr != nullptr, ChipLogProgress(DeviceLayer, ""FAIL: NULL advMgr in %s"", __func__)); g_variant_builder_init(&optionsBuilder, G_VARIANT_TYPE(""a{sv}"")); options = g_variant_builder_end(&optionsBuilder); bluez_leadvertising_manager1_call_register_advertisement(advMgr, endpoint->mpAdvPath, options, nullptr, BluezAdvStartDone, apClosure); exit: return G_SOURCE_REMOVE; } static gboolean BluezAdvStop(void * apClosure) { GDBusObject * adapter; BluezEndpoint * endpoint = static_cast(apClosure); BluezLEAdvertisingManager1 * advMgr = nullptr; VerifyOrExit(endpoint != nullptr, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); VerifyOrExit(endpoint->mIsAdvertising, ChipLogProgress(DeviceLayer, ""FAIL: Advertising has already been disabled in %s"", __func__)); VerifyOrExit(endpoint->mpAdapter != nullptr, ChipLogProgress(DeviceLayer, ""FAIL: NULL endpoint->mpAdapter in %s"", __func__)); adapter = g_dbus_interface_get_object(G_DBUS_INTERFACE(endpoint->mpAdapter)); VerifyOrExit(adapter != nullptr, ChipLogProgress(DeviceLayer, ""FAIL: NULL adapter in %s"", __func__)); advMgr = bluez_object_get_leadvertising_manager1(BLUEZ_OBJECT(adapter)); VerifyOrExit(advMgr != nullptr, ChipLogProgress(DeviceLayer, ""FAIL: NULL advMgr in %s"", __func__)); bluez_leadvertising_manager1_call_unregister_advertisement(advMgr, endpoint->mpAdvPath, nullptr, BluezAdvStopDone, apClosure); exit: return G_SOURCE_REMOVE; } static gboolean BluezCharacteristicReadValue(BluezGattCharacteristic1 * aChar, GDBusMethodInvocation * aInvocation, GVariant * aOptions) { GVariant * val; ChipLogProgress(DeviceLayer, ""Received BluezCharacteristicReadValue""); val = (GVariant *) bluez_gatt_characteristic1_get_value(aChar); bluez_gatt_characteristic1_complete_read_value(aChar, aInvocation, val); return TRUE; } #if CHIP_BLUEZ_CHAR_WRITE_VALUE static gboolean BluezCharacteristicWriteValue(BluezGattCharacteristic1 * aChar, GDBusMethodInvocation * aInvocation, GVariant * aValue, GVariant * aOptions, gpointer apClosure) { const uint8_t * tmpBuf; uint8_t * buf; size_t len; bool isSuccess = false; BluezConnection * conn = NULL; BluezEndpoint * endpoint = static_cast(apClosure); VerifyOrExit(endpoint != NULL, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); VerifyOrExit(aValue != NULL, ChipLogProgress(DeviceLayer, ""aValue is NULL in %s"", __func__)); conn = GetBluezConnectionViaDevice(endpoint); VerifyOrExit(conn != NULL, g_dbus_method_invocation_return_dbus_error(aInvocation, ""org.bluez.Error.Failed"", ""No CHIP Bluez connection"")); bluez_gatt_characteristic1_set_value(aChar, g_variant_ref(aValue)); tmpBuf = (uint8_t *) (g_variant_get_fixed_array(aValue, &len, sizeof(uint8_t))); buf = (uint8_t *) (g_memdup(tmpBuf, len)); BLEManagerImpl::HandleRXCharWrite(conn, buf, len); bluez_gatt_characteristic1_complete_write_value(aChar, aInvocation); isSuccess = true; exit: return isSuccess ? TRUE : FALSE; } #endif static gboolean BluezCharacteristicWriteValueError(BluezGattCharacteristic1 * aChar, GDBusMethodInvocation * aInvocation, GVariant * aValue, GVariant * aOptions, gpointer apClosure) { ChipLogProgress(DeviceLayer, ""BluezCharacteristicWriteValueError""); g_dbus_method_invocation_return_dbus_error(aInvocation, ""org.bluez.Error.NotSupported"", ""Write for characteristic is unsupported""); return TRUE; } static gboolean BluezCharacteristicWriteFD(GIOChannel * aChannel, GIOCondition aCond, gpointer apClosure) { GVariant * newVal; gchar * buf; ssize_t len; int fd; bool isSuccess = false; BluezConnection * conn = static_cast(apClosure); VerifyOrExit(conn != nullptr, ChipLogProgress(DeviceLayer, ""No CHIP Bluez connection in %s"", __func__)); VerifyOrExit(!(aCond & G_IO_HUP), ChipLogProgress(DeviceLayer, ""INFO: socket disconnected in %s"", __func__)); VerifyOrExit(!(aCond & (G_IO_ERR | G_IO_NVAL)), ChipLogProgress(DeviceLayer, ""INFO: socket error in %s"", __func__)); VerifyOrExit(aCond == G_IO_IN, ChipLogProgress(DeviceLayer, ""FAIL: error in %s"", __func__)); ChipLogProgress(DeviceLayer, ""c1 %s mtu, %d"", __func__, conn->mMtu); buf = (gchar *) (g_malloc(conn->mMtu)); fd = g_io_channel_unix_get_fd(aChannel); len = read(fd, buf, conn->mMtu); VerifyOrExit(len > 0, ChipLogProgress(DeviceLayer, ""FAIL: short read in %s (%d)"", __func__, len)); newVal = g_variant_new_fixed_array(G_VARIANT_TYPE_BYTE, buf, len, sizeof(uint8_t)); bluez_gatt_characteristic1_set_value(conn->mpC1, newVal); BLEManagerImpl::HandleRXCharWrite(conn, (uint8_t *) (buf), len); isSuccess = true; exit: return isSuccess ? TRUE : FALSE; } static void Bluez_gatt_characteristic1_complete_acquire_write_with_fd(GDBusMethodInvocation * invocation, int fd, guint16 mtu) { GUnixFDList * fd_list = g_unix_fd_list_new(); int index; index = g_unix_fd_list_append(fd_list, fd, nullptr); g_dbus_method_invocation_return_value_with_unix_fd_list(invocation, g_variant_new(""(@hq)"", g_variant_new_handle(index), mtu), fd_list); } static gboolean bluezCharacteristicDestroyFD(GIOChannel * aChannel, GIOCondition aCond, gpointer apClosure) { return G_SOURCE_REMOVE; } static gboolean BluezCharacteristicAcquireWrite(BluezGattCharacteristic1 * aChar, GDBusMethodInvocation * aInvocation, GVariant * aOptions, gpointer apClosure) { int fds[2] = { -1, -1 }; GIOChannel * channel; char * errStr; GVariantDict options; bool isSuccess = false; BluezConnection * conn = nullptr; BluezEndpoint * endpoint = static_cast(apClosure); VerifyOrExit(endpoint != nullptr, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); conn = GetBluezConnectionViaDevice(endpoint); VerifyOrExit(conn != nullptr, g_dbus_method_invocation_return_dbus_error(aInvocation, ""org.bluez.Error.Failed"", ""No Chipoble connection"")); ChipLogProgress(DeviceLayer, ""BluezCharacteristicAcquireWrite is called, conn: %p"", conn); if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_NONBLOCK | SOCK_CLOEXEC, 0, fds) < 0) { errStr = strerror(errno); ChipLogProgress(DeviceLayer, ""FAIL: socketpair: %s in %s"", errStr, __func__); g_dbus_method_invocation_return_dbus_error(aInvocation, ""org.bluez.Error.Failed"", ""FD creation failed""); SuccessOrExit(false); } g_variant_dict_init(&options, aOptions); if (g_variant_dict_contains(&options, ""mtu"") == TRUE) { GVariant * v = g_variant_dict_lookup_value(&options, ""mtu"", G_VARIANT_TYPE_UINT16); conn->mMtu = g_variant_get_uint16(v); } else { ChipLogProgress(DeviceLayer, ""FAIL: no MTU in options in %s"", __func__); g_dbus_method_invocation_return_dbus_error(aInvocation, ""org.bluez.Error.InvalidArguments"", ""MTU negotiation failed""); SuccessOrExit(false); } channel = g_io_channel_unix_new(fds[0]); g_io_channel_set_encoding(channel, nullptr, nullptr); g_io_channel_set_close_on_unref(channel, TRUE); g_io_channel_set_buffered(channel, FALSE); conn->mC1Channel.mpChannel = channel; conn->mC1Channel.mWatch = g_io_add_watch(channel, (GIOCondition)(G_IO_HUP | G_IO_IN | G_IO_ERR | G_IO_NVAL), BluezCharacteristicWriteFD, conn); bluez_gatt_characteristic1_set_write_acquired(aChar, TRUE); Bluez_gatt_characteristic1_complete_acquire_write_with_fd(aInvocation, fds[1], conn->mMtu); close(fds[1]); isSuccess = true; exit: return isSuccess ? TRUE : FALSE; } static gboolean BluezCharacteristicAcquireWriteError(BluezGattCharacteristic1 * aChar, GDBusMethodInvocation * aInvocation, GVariant * aOptions) { ChipLogProgress(DeviceLayer, ""BluezCharacteristicAcquireWriteError is called""); g_dbus_method_invocation_return_dbus_error(aInvocation, ""org.bluez.Error.NotSupported"", ""AcquireWrite for characteristic is unsupported""); return TRUE; } static gboolean BluezCharacteristicAcquireNotify(BluezGattCharacteristic1 * aChar, GDBusMethodInvocation * aInvocation, GVariant * aOptions, gpointer apClosure) { int fds[2] = { -1, -1 }; GIOChannel * channel; char * errStr; GVariantDict options; BluezConnection * conn = nullptr; bool isSuccess = false; BluezEndpoint * endpoint = static_cast(apClosure); VerifyOrExit(endpoint != nullptr, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); conn = GetBluezConnectionViaDevice(endpoint); VerifyOrExit(conn != nullptr, g_dbus_method_invocation_return_dbus_error(aInvocation, ""org.bluez.Error.Failed"", ""No Chipoble connection"")); g_variant_dict_init(&options, aOptions); if ((g_variant_dict_contains(&options, ""mtu"") == TRUE)) { GVariant * v = g_variant_dict_lookup_value(&options, ""mtu"", G_VARIANT_TYPE_UINT16); conn->mMtu = g_variant_get_uint16(v); } if (bluez_gatt_characteristic1_get_notifying(aChar)) { g_dbus_method_invocation_return_dbus_error(aInvocation, ""org.bluez.Error.NotPermitted"", ""Already notifying""); } if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_NONBLOCK | SOCK_CLOEXEC, 0, fds) < 0) { errStr = strerror(errno); ChipLogProgress(DeviceLayer, ""FAIL: socketpair: %s in %s"", errStr, __func__); g_dbus_method_invocation_return_dbus_error(aInvocation, ""org.bluez.Error.Failed"", ""FD creation failed""); SuccessOrExit(false); } channel = g_io_channel_unix_new(fds[0]); g_io_channel_set_encoding(channel, nullptr, nullptr); g_io_channel_set_close_on_unref(channel, TRUE); g_io_channel_set_buffered(channel, FALSE); conn->mC2Channel.mpChannel = channel; conn->mC2Channel.mWatch = g_io_add_watch_full(channel, G_PRIORITY_DEFAULT_IDLE, (GIOCondition)(G_IO_HUP | G_IO_ERR | G_IO_NVAL), bluezCharacteristicDestroyFD, conn, nullptr); bluez_gatt_characteristic1_set_notify_acquired(aChar, TRUE); // same reply as for AcquireWrite Bluez_gatt_characteristic1_complete_acquire_write_with_fd(aInvocation, fds[1], conn->mMtu); close(fds[1]); conn->mIsNotify = true; BLEManagerImpl::HandleTXCharCCCDWrite((void *) conn); isSuccess = true; exit: return isSuccess ? TRUE : FALSE; } static gboolean BluezCharacteristicAcquireNotifyError(BluezGattCharacteristic1 * aChar, GDBusMethodInvocation * aInvocation, GVariant * aOptions) { ChipLogProgress(DeviceLayer, ""TRACE: AcquireNotify is called""); g_dbus_method_invocation_return_dbus_error(aInvocation, ""org.bluez.Error.NotSupported"", ""AcquireNotify for characteristic is unsupported""); return TRUE; } static gboolean BluezCharacteristicStartNotify(BluezGattCharacteristic1 * aChar, GDBusMethodInvocation * aInvocation, gpointer apClosure) { bool isSuccess = false; BluezConnection * conn = nullptr; BluezEndpoint * endpoint = static_cast(apClosure); VerifyOrExit(endpoint != nullptr, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); conn = GetBluezConnectionViaDevice(endpoint); VerifyOrExit(conn != nullptr, g_dbus_method_invocation_return_dbus_error(aInvocation, ""org.bluez.Error.Failed"", ""No Chipoble connection"")); if (bluez_gatt_characteristic1_get_notifying(aChar) == TRUE) { g_dbus_method_invocation_return_dbus_error(aInvocation, ""org.bluez.Error.Failed"", ""Characteristic is already subscribed""); } else { bluez_gatt_characteristic1_complete_start_notify(aChar, aInvocation); bluez_gatt_characteristic1_set_notifying(aChar, TRUE); conn->mIsNotify = true; BLEManagerImpl::HandleTXCharCCCDWrite(conn); } isSuccess = true; exit: return isSuccess ? TRUE : FALSE; } static gboolean BluezCharacteristicStartNotifyError(BluezGattCharacteristic1 * aChar, GDBusMethodInvocation * aInvocation) { g_dbus_method_invocation_return_dbus_error(aInvocation, ""org.bluez.Error.NotSupported"", ""Subscribing to characteristic is unsupported""); return TRUE; } static gboolean BluezCharacteristicStopNotify(BluezGattCharacteristic1 * aChar, GDBusMethodInvocation * aInvocation, gpointer apClosure) { bool isSuccess = false; BluezConnection * conn = nullptr; BluezEndpoint * endpoint = static_cast(apClosure); VerifyOrExit(endpoint != nullptr, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); conn = GetBluezConnectionViaDevice(endpoint); VerifyOrExit(conn != nullptr, g_dbus_method_invocation_return_dbus_error(aInvocation, ""org.bluez.Error.Failed"", ""No Chipoble connection"")); if (bluez_gatt_characteristic1_get_notifying(aChar) == FALSE) { g_dbus_method_invocation_return_dbus_error(aInvocation, ""org.bluez.Error.Failed"", ""Characteristic is already unsubscribed""); } else { bluez_gatt_characteristic1_complete_start_notify(aChar, aInvocation); bluez_gatt_characteristic1_set_notifying(aChar, FALSE); } conn->mIsNotify = false; isSuccess = true; exit: return isSuccess ? TRUE : FALSE; } static gboolean BluezCharacteristicConfirm(BluezGattCharacteristic1 * aChar, GDBusMethodInvocation * aInvocation, gpointer apClosure) { BluezEndpoint * endpoint = (BluezEndpoint *) apClosure; BluezConnection * conn = GetBluezConnectionViaDevice(endpoint); ChipLogDetail(Ble, ""Indication confirmation, %p"", conn); BLEManagerImpl::HandleTXComplete(conn); return TRUE; } static gboolean BluezCharacteristicStopNotifyError(BluezGattCharacteristic1 * aChar, GDBusMethodInvocation * aInvocation) { g_dbus_method_invocation_return_dbus_error(aInvocation, ""org.bluez.Error.Failed"", ""Unsubscribing from characteristic is unsupported""); return TRUE; } static gboolean BluezCharacteristicConfirmError(BluezGattCharacteristic1 * aChar, GDBusMethodInvocation * aInvocation) { g_dbus_method_invocation_return_dbus_error(aInvocation, ""org.bluez.Error.Failed"", ""Confirm from characteristic is unsupported""); return TRUE; } // both arguments allocated, and non-null static void BluezStringAddressToCHIPAddress(const char * aAddressString, BluezAddress * apAddress) { size_t i, j = 0; for (i = 0; i < BLUEZ_ADDRESS_SIZE; i++) { apAddress->mAddress[i] = (CHAR_TO_BLUEZ(aAddressString[j]) << 4) + CHAR_TO_BLUEZ(aAddressString[j + 1]); j += 2; if (aAddressString[j] == ':') j++; } } static gboolean BluezIsDeviceOnAdapter(BluezDevice1 * aDevice, BluezAdapter1 * aAdapter) { return strcmp(bluez_device1_get_adapter(aDevice), g_dbus_proxy_get_object_path(G_DBUS_PROXY(aAdapter))) == 0 ? TRUE : FALSE; } static gboolean BluezIsServiceOnDevice(BluezGattService1 * aService, BluezDevice1 * aDevice) { return strcmp(bluez_gatt_service1_get_device(aService), g_dbus_proxy_get_object_path(G_DBUS_PROXY(aDevice))) == 0 ? TRUE : FALSE; } static gboolean BluezIsCharOnService(BluezGattCharacteristic1 * aChar, BluezGattService1 * aService) { ChipLogProgress(DeviceLayer, ""Char1 %s"", bluez_gatt_characteristic1_get_service(aChar)); ChipLogProgress(DeviceLayer, ""Char1 %s"", g_dbus_proxy_get_object_path(G_DBUS_PROXY(aService))); return strcmp(bluez_gatt_characteristic1_get_service(aChar), g_dbus_proxy_get_object_path(G_DBUS_PROXY(aService))) == 0 ? TRUE : FALSE; } static uint16_t BluezUUIDStringToShortServiceID(const char * aService) { uint32_t shortService = 0; size_t i; // check that the service is a short UUID if (strncasecmp(CHIP_BLE_BASE_SERVICE_UUID_STRING, aService + CHIP_BLE_SERVICE_PREFIX_LENGTH, sizeof(CHIP_BLE_BASE_SERVICE_UUID_STRING)) == 0) { for (i = 0; i < 4; i++) { shortService = (shortService << 8) | (CHAR_TO_BLUEZ(aService[2 * i]) << 4) | CHAR_TO_BLUEZ(aService[2 * i + 1]); } ChipLogProgress(DeviceLayer, ""TRACE: full service UUID: %s, short service %08x"", aService, shortService); if (shortService > UINT16_MAX) { shortService = 0; } } return (uint16_t) shortService; } static void BluezConnectionInit(BluezConnection * apConn) { // populate the service and the characteristics GList * objects = nullptr; GList * l; BluezEndpoint * endpoint = nullptr; VerifyOrExit(apConn != nullptr, ChipLogProgress(DeviceLayer, ""Bluez connection is NULL in %s"", __func__)); endpoint = apConn->mpEndpoint; VerifyOrExit(endpoint != nullptr, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); if (!endpoint->mIsCentral) { apConn->mpService = BLUEZ_GATT_SERVICE1(g_object_ref(apConn->mpEndpoint->mpService)); apConn->mpC1 = BLUEZ_GATT_CHARACTERISTIC1(g_object_ref(endpoint->mpC1)); apConn->mpC2 = BLUEZ_GATT_CHARACTERISTIC1(g_object_ref(endpoint->mpC2)); } else { objects = g_dbus_object_manager_get_objects(endpoint->mpObjMgr); for (l = objects; l != nullptr; l = l->next) { BluezObject * object = BLUEZ_OBJECT(l->data); BluezGattService1 * service = bluez_object_get_gatt_service1(object); if (service != nullptr) { if ((BluezIsServiceOnDevice(service, apConn->mpDevice)) == TRUE && (strcmp(bluez_gatt_service1_get_uuid(service), CHIP_BLE_UUID_SERVICE_STRING) == 0)) { apConn->mpService = service; break; } g_object_unref(service); } } VerifyOrExit(apConn->mpService != nullptr, ChipLogProgress(DeviceLayer, ""FAIL: NULL service in %s"", __func__)); for (l = objects; l != nullptr; l = l->next) { BluezObject * object = BLUEZ_OBJECT(l->data); BluezGattCharacteristic1 * char1 = bluez_object_get_gatt_characteristic1(object); if (char1 != nullptr) { if ((BluezIsCharOnService(char1, apConn->mpService) == TRUE) && (strcmp(bluez_gatt_characteristic1_get_uuid(char1), CHIP_PLAT_BLE_UUID_C1_STRING) == 0)) { apConn->mpC1 = char1; } else if ((BluezIsCharOnService(char1, apConn->mpService) == TRUE) && (strcmp(bluez_gatt_characteristic1_get_uuid(char1), CHIP_PLAT_BLE_UUID_C2_STRING) == 0)) { apConn->mpC2 = char1; } else { g_object_unref(char1); } if ((apConn->mpC1 != nullptr) && (apConn->mpC2 != nullptr)) { break; } } } VerifyOrExit(apConn->mpC1 != nullptr, ChipLogProgress(DeviceLayer, ""FAIL: NULL C1 in %s"", __func__)); VerifyOrExit(apConn->mpC2 != nullptr, ChipLogProgress(DeviceLayer, ""FAIL: NULL C2 in %s"", __func__)); } exit: if (objects != nullptr) g_list_free_full(objects, g_object_unref); } static gboolean BluezConnectionInitIdle(gpointer user_data) { BluezConnection * conn = (BluezConnection *) user_data; ChipLogProgress(DeviceLayer, ""%s"", __func__); BluezConnectionInit(conn); return FALSE; } static void BluezOTConnectionDestroy(BluezConnection * aConn) { if (aConn) { if (aConn->mpDevice) g_object_unref(aConn->mpDevice); if (aConn->mpService) g_object_unref(aConn->mpService); if (aConn->mpC1) g_object_unref(aConn->mpC1); if (aConn->mpC2) g_object_unref(aConn->mpC2); if (aConn->mpPeerAddress) g_free(aConn->mpPeerAddress); if (aConn->mC1Channel.mWatch > 0) g_source_remove(aConn->mC1Channel.mWatch); if (aConn->mC1Channel.mpChannel) g_io_channel_unref(aConn->mC1Channel.mpChannel); if (aConn->mC2Channel.mWatch > 0) g_source_remove(aConn->mC2Channel.mWatch); if (aConn->mC2Channel.mpChannel) g_io_channel_unref(aConn->mC2Channel.mpChannel); g_free(aConn); } } static BluezGattCharacteristic1 * BluezCharacteristicCreate(BluezGattService1 * aService, const char * aCharName, const char * aUUID, GDBusObjectManagerServer * aRoot) { char * servicePath = g_strdup(g_dbus_object_get_object_path(g_dbus_interface_get_object(G_DBUS_INTERFACE(aService)))); char * charPath = g_strdup_printf(""%s/%s"", servicePath, aCharName); BluezObjectSkeleton * object; BluezGattCharacteristic1 * characteristic; ChipLogProgress(DeviceLayer, ""Create characteristic object at %s"", charPath); object = bluez_object_skeleton_new(charPath); characteristic = bluez_gatt_characteristic1_skeleton_new(); bluez_gatt_characteristic1_set_uuid(characteristic, aUUID); bluez_gatt_characteristic1_set_service(characteristic, servicePath); bluez_object_skeleton_set_gatt_characteristic1(object, characteristic); g_dbus_object_manager_server_export(aRoot, G_DBUS_OBJECT_SKELETON(object)); g_object_unref(object); return characteristic; } static void BluezPeripheralRegisterAppDone(GObject * aObject, GAsyncResult * aResult, gpointer apClosure) { GError * error = nullptr; BluezGattManager1 * gattMgr = BLUEZ_GATT_MANAGER1(aObject); gboolean success = bluez_gatt_manager1_call_register_application_finish(gattMgr, aResult, &error); VerifyOrExit(success == TRUE, ChipLogProgress(DeviceLayer, ""FAIL: RegisterApplication : %s"", error->message)); BLEManagerImpl::NotifyBLEPeripheralRegisterAppComplete(true, nullptr); ChipLogProgress(DeviceLayer, ""BluezPeripheralRegisterAppDone done""); exit: if (error != nullptr) { BLEManagerImpl::NotifyBLEPeripheralRegisterAppComplete(false, nullptr); g_error_free(error); } return; } gboolean BluezPeripheralRegisterApp(void * apClosure) { GDBusObject * adapter; BluezGattManager1 * gattMgr; GVariantBuilder optionsBuilder; GVariant * options; BluezEndpoint * endpoint = (BluezEndpoint *) apClosure; VerifyOrExit(endpoint->mpAdapter != nullptr, ChipLogProgress(DeviceLayer, ""FAIL: NULL endpoint->mpAdapter in %s"", __func__)); adapter = g_dbus_interface_get_object(G_DBUS_INTERFACE(endpoint->mpAdapter)); VerifyOrExit(adapter != nullptr, ChipLogProgress(DeviceLayer, ""FAIL: NULL adapter in %s"", __func__)); gattMgr = bluez_object_get_gatt_manager1(BLUEZ_OBJECT(adapter)); VerifyOrExit(gattMgr != nullptr, ChipLogProgress(DeviceLayer, ""FAIL: NULL gattMgr in %s"", __func__)); g_variant_builder_init(&optionsBuilder, G_VARIANT_TYPE(""a{sv}"")); options = g_variant_builder_end(&optionsBuilder); bluez_gatt_manager1_call_register_application(gattMgr, endpoint->mpRootPath, options, nullptr, BluezPeripheralRegisterAppDone, nullptr); exit: return G_SOURCE_REMOVE; } /*********************************************************************** * GATT Characteristic object ***********************************************************************/ static void BluezHandleAdvertisementFromDevice(BluezDevice1 * aDevice) { const char * address = bluez_device1_get_address(aDevice); GVariant * serviceData = bluez_device1_get_service_data(aDevice); GVariant * entry; GVariantIter iter; BluezAddress * src; const uint8_t * tmpBuf; uint8_t * buf; size_t len, dataLen; size_t i, j; uint16_t serviceId; char * debugStr; // service data is optional and may not be present SuccessOrExit(serviceData != nullptr); src = g_new0(BluezAddress, 1); BluezStringAddressToCHIPAddress(address, src); debugStr = g_variant_print(serviceData, TRUE); ChipLogProgress(DeviceLayer, ""TRACE: Device %s Service data: %s"", address, debugStr); g_free(debugStr); // advertising flags ChipLogProgress(DeviceLayer, ""TRACE: Device %s Advertising flags: %s"", address, bluez_device1_get_advertising_flags(aDevice)); g_variant_iter_init(&iter, serviceData); len = 0; while ((entry = g_variant_iter_next_value(&iter)) != nullptr) { GVariant * key = g_variant_get_child_value(entry, 0); GVariant * val = g_variant_get_child_value(entry, 1); GVariant * rawVal = g_variant_get_variant(val); serviceId = BluezUUIDStringToShortServiceID(g_variant_get_string(key, &dataLen)); if (serviceId != 0) { len += 1 + sizeof(uint8_t) + sizeof(serviceId) + g_variant_n_children(rawVal); } } if (len != 0) { // we only parsed services, add 3 bytes for flags len = len + 3; buf = (uint8_t *) g_malloc(len); i = 0; buf[i++] = 2; // length of flags buf[i++] = BLUEZ_ADV_TYPE_FLAGS; buf[i++] = BLUEZ_ADV_FLAGS_LE_DISCOVERABLE | BLUEZ_ADV_FLAGS_EDR_UNSUPPORTED; g_variant_iter_init(&iter, serviceData); while ((entry = g_variant_iter_next_value(&iter)) != nullptr) { GVariant * key = g_variant_get_child_value(entry, 0); GVariant * val = g_variant_get_child_value(entry, 1); GVariant * rawVal = g_variant_get_variant(val); serviceId = BluezUUIDStringToShortServiceID(g_variant_get_string(key, &dataLen)); if (serviceId != 0) { buf[i++] = g_variant_n_children(rawVal) + 2 + 1; buf[i++] = BLUEZ_ADV_TYPE_SERVICE_DATA; buf[i++] = serviceId & 0xff; buf[i++] = (serviceId >> 8) & 0xff; tmpBuf = (const uint8_t *) g_variant_get_fixed_array(rawVal, &dataLen, sizeof(uint8_t)); for (j = 0; j < dataLen; j++) { buf[i++] = tmpBuf[j]; } } } } exit: return; } static void BluezSignalInterfacePropertiesChanged(GDBusObjectManagerClient * aManager, GDBusObjectProxy * aObject, GDBusProxy * aInterface, GVariant * aChangedProperties, const gchar * const * aInvalidatedProps, gpointer apClosure) { BluezEndpoint * endpoint = (BluezEndpoint *) apClosure; VerifyOrExit(endpoint != nullptr, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); VerifyOrExit(endpoint->mpAdapter != nullptr, ChipLogProgress(DeviceLayer, ""FAIL: NULL endpoint->mpAdapter in %s"", __func__)); if (strcmp(g_dbus_proxy_get_interface_name(aInterface), DEVICE_INTERFACE) == 0) { BluezDevice1 * device = BLUEZ_DEVICE1(aInterface); GVariantIter iter; GVariant * value; char * key; if (BluezIsDeviceOnAdapter(device, endpoint->mpAdapter)) { BluezConnection * conn = (BluezConnection *) g_hash_table_lookup(endpoint->mpConnMap, g_dbus_proxy_get_object_path(aInterface)); g_variant_iter_init(&iter, aChangedProperties); while (g_variant_iter_next(&iter, ""{&sv}"", &key, &value)) { if (strcmp(key, ""Connected"") == 0) { gboolean connected; connected = g_variant_get_boolean(value); if (connected) { ChipLogProgress(DeviceLayer, ""Bluez coonnected""); // for a central, the connection has been already allocated. For a peripheral, it has not. // todo do we need this ? we could handle all connection the same wa... if (endpoint->mIsCentral) SuccessOrExit(conn != nullptr); if (!endpoint->mIsCentral) { VerifyOrExit(conn == nullptr, ChipLogProgress(DeviceLayer, ""FAIL: connection already tracked: conn: %x device: %s"", conn, g_dbus_proxy_get_object_path(aInterface))); conn = g_new0(BluezConnection, 1); conn->mpPeerAddress = g_strdup(bluez_device1_get_address(device)); conn->mpDevice = (BluezDevice1 *) g_object_ref(device); conn->mpEndpoint = endpoint; BluezConnectionInit(conn); endpoint->mpPeerDevicePath = g_strdup(g_dbus_proxy_get_object_path(aInterface)); ChipLogProgress(DeviceLayer, ""coonnected, insert, conn:%p, c1:%p, c2:%p and %s"", conn, conn->mpC1, conn->mpC2, endpoint->mpPeerDevicePath); g_hash_table_insert(endpoint->mpConnMap, endpoint->mpPeerDevicePath, conn); } // for central, we do not call BluezConnectionInit until the services have been resolved BLEManagerImpl::CHIPoBluez_NewConnection(endpoint); } else { ChipLogProgress(DeviceLayer, ""Bluez disconnected""); BLEManagerImpl::CHIPoBluez_ConnectionClosed(endpoint); BluezOTConnectionDestroy(conn); g_hash_table_remove(endpoint->mpConnMap, g_dbus_proxy_get_object_path(aInterface)); } } else if (strcmp(key, ""ServicesResolved"") == 0) { gboolean resolved; resolved = g_variant_get_boolean(value); if (endpoint->mIsCentral && conn != nullptr && resolved == TRUE) { /* delay to idle, this is to workaround race in handling * of interface-added and properites-changed signals * it looks like we cannot specify order of those * handlers and currently implementation assumes * that interfaces-added is called first. * * TODO figure out if we can avoid this */ g_idle_add(BluezConnectionInitIdle, conn); } } else if (strcmp(key, ""RSSI"") == 0) { /* when discovery starts we will get this one device is * found even if device object was already present */ if (endpoint->mIsCentral) { BluezHandleAdvertisementFromDevice(device); } } g_variant_unref(value); } } } exit: return; } static void BluezHandleNewDevice(BluezDevice1 * device, BluezEndpoint * apEndpoint) { VerifyOrExit(apEndpoint != nullptr, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); if (apEndpoint->mIsCentral) { BluezHandleAdvertisementFromDevice(device); } else { BluezConnection * conn; SuccessOrExit(bluez_device1_get_connected(device)); conn = (BluezConnection *) g_hash_table_lookup(apEndpoint->mpConnMap, g_dbus_proxy_get_object_path(G_DBUS_PROXY(device))); VerifyOrExit(conn == nullptr, ChipLogProgress(DeviceLayer, ""FAIL: connection already tracked: conn: %x new device: %s"", conn, g_dbus_proxy_get_object_path(G_DBUS_PROXY(device)))); conn = g_new0(BluezConnection, 1); conn->mpPeerAddress = g_strdup(bluez_device1_get_address(device)); conn->mpDevice = (BluezDevice1 *) g_object_ref(device); conn->mpEndpoint = apEndpoint; BluezConnectionInit(conn); g_hash_table_insert(apEndpoint->mpConnMap, g_strdup(g_dbus_proxy_get_object_path(G_DBUS_PROXY(device))), conn); } exit: return; } static void BluezSignalOnObjectAdded(GDBusObjectManager * aManager, GDBusObject * aObject, gpointer apClosure) { // TODO: right now we do not handle addition/removal of adapters // Primary focus here is to handle addition of a device BluezObject * o = BLUEZ_OBJECT(aObject); BluezDevice1 * device = bluez_object_get_device1(o); BluezEndpoint * endpoint = (BluezEndpoint *) apClosure; if (device != nullptr) { if (BluezIsDeviceOnAdapter(device, endpoint->mpAdapter) == TRUE) { BluezHandleNewDevice(device, endpoint); } g_object_unref(device); } } static void BluezSignalOnObjectRemoved(GDBusObjectManager * aManager, GDBusObject * aObject, gpointer apClosure) { // TODO: for Device1, lookup connection, and call otPlatTobleHandleDisconnected // for Adapter1: unclear, crash if this pertains to our adapter? at least null out the endpoint->mpAdapter. // for Characteristic1, or GattService -- handle here via calling otPlatTobleHandleDisconnected, or ignore. } static BluezGattService1 * BluezServiceCreate(gpointer apClosure) { BluezObjectSkeleton * object; BluezGattService1 * service; BluezEndpoint * endpoint = (BluezEndpoint *) apClosure; endpoint->mpServicePath = g_strdup_printf(""%s/service"", endpoint->mpRootPath); ChipLogProgress(DeviceLayer, ""CREATE service object at %s"", endpoint->mpServicePath); object = bluez_object_skeleton_new(endpoint->mpServicePath); service = bluez_gatt_service1_skeleton_new(); bluez_gatt_service1_set_uuid(service, ""0xFEAF""); // device is only valid for remote services bluez_gatt_service1_set_primary(service, TRUE); // includes -- unclear whether required. Might be filled in later bluez_object_skeleton_set_gatt_service1(object, service); g_dbus_object_manager_server_export(endpoint->mpRoot, G_DBUS_OBJECT_SKELETON(object)); g_object_unref(object); return service; } static void bluezObjectsSetup(BluezEndpoint * apEndpoint) { GList * objects = nullptr; GList * l; char * expectedPath = nullptr; VerifyOrExit(apEndpoint != nullptr, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); expectedPath = g_strdup_printf(""%s/hci%d"", BLUEZ_PATH, apEndpoint->mNodeId); objects = g_dbus_object_manager_get_objects(apEndpoint->mpObjMgr); for (l = objects; l != nullptr && apEndpoint->mpAdapter == nullptr; l = l->next) { BluezObject * object = BLUEZ_OBJECT(l->data); GList * interfaces; GList * ll; interfaces = g_dbus_object_get_interfaces(G_DBUS_OBJECT(object)); for (ll = interfaces; ll != nullptr; ll = ll->next) { if (BLUEZ_IS_ADAPTER1(ll->data)) { // we found the adapter BluezAdapter1 * adapter = BLUEZ_ADAPTER1(ll->data); char * addr = (char *) bluez_adapter1_get_address(adapter); if (apEndpoint->mpAdapterAddr == nullptr) // no adapter address provided, bind to the hci indicated by nodeid { if (strcmp(g_dbus_proxy_get_object_path(G_DBUS_PROXY(adapter)), expectedPath) == 0) { apEndpoint->mpAdapter = (BluezAdapter1 *) g_object_ref(adapter); } } else { if (strcmp(apEndpoint->mpAdapterAddr, addr) == 0) { apEndpoint->mpAdapter = (BluezAdapter1 *) g_object_ref(adapter); } } } } g_list_free_full(interfaces, g_object_unref); } VerifyOrExit(apEndpoint->mpAdapter != nullptr, ChipLogProgress(DeviceLayer, ""FAIL: NULL apEndpoint->mpAdapter in %s"", __func__)); bluez_adapter1_set_powered(apEndpoint->mpAdapter, TRUE); // with BLE we are discoverable only when advertising so this can be // set once on init bluez_adapter1_set_discoverable_timeout(apEndpoint->mpAdapter, 0); bluez_adapter1_set_discoverable(apEndpoint->mpAdapter, TRUE); exit: g_list_free_full(objects, g_object_unref); g_free(expectedPath); } static BluezConnection * GetBluezConnectionViaDevice(BluezEndpoint * apEndpoint) { BluezConnection * retval = (BluezConnection *) g_hash_table_lookup(apEndpoint->mpConnMap, apEndpoint->mpPeerDevicePath); // ChipLogProgress(DeviceLayer, ""acquire connection object %p in (%s)"", retval, __func__); return retval; } #if CHIP_BLUEZ_CENTRAL_SUPPORT static BluezConnection * BluezCharacteristicGetBluezConnection(BluezGattCharacteristic1 * aChar, GVariant * aOptions, BluezEndpoint * apEndpoint) { BluezConnection * retval = NULL; const gchar * path = NULL; GVariantDict options; GVariant * v; VerifyOrExit(apEndpoint != NULL, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); VerifyOrExit(apEndpoint->mIsCentral, ); /* TODO Unfortunately StartNotify/StopNotify doesn't provide info about * peer device in call params so we need look this up ourselves. */ if (aOptions == NULL) { GList * objects; GList * l; GList * ll; objects = g_dbus_object_manager_get_objects(apEndpoint->mpObjMgr); for (l = objects; l != NULL; l = l->next) { BluezDevice1 * device = bluez_object_get_device1(BLUEZ_OBJECT(l->data)); if (device != NULL) { if (BluezIsDeviceOnAdapter(device, apEndpoint->mpAdapter)) { for (ll = objects; ll != NULL; ll = ll->next) { BluezGattService1 * service = bluez_object_get_gatt_service1(BLUEZ_OBJECT(ll->data)); if (service != NULL) { if (BluezIsServiceOnDevice(service, device)) { if (BluezIsCharOnService(aChar, service)) { retval = (BluezConnection *) g_hash_table_lookup( apEndpoint->mpConnMap, g_dbus_proxy_get_object_path(G_DBUS_PROXY(device))); } } g_object_unref(service); if (retval != NULL) break; } } } g_object_unref(device); if (retval != NULL) break; } } g_list_free_full(objects, g_object_unref); } else { g_variant_dict_init(&options, aOptions); v = g_variant_dict_lookup_value(&options, ""device"", G_VARIANT_TYPE_OBJECT_PATH); VerifyOrExit(v != NULL, ChipLogProgress(DeviceLayer, ""FAIL: No device option in dictionary (%s)"", __func__)); path = g_variant_get_string(v, NULL); retval = (BluezConnection *) g_hash_table_lookup(apEndpoint->mpConnMap, path); } exit: return retval; } #endif // CHIP_BLUEZ_CENTRAL_SUPPORT void EndpointCleanup(BluezEndpoint * apEndpoint) { if (apEndpoint != nullptr) { if (apEndpoint->mpOwningName != nullptr) { g_free(apEndpoint->mpOwningName); apEndpoint->mpOwningName = nullptr; } if (apEndpoint->mpAdapterName != nullptr) { g_free(apEndpoint->mpAdapterName); apEndpoint->mpAdapterName = nullptr; } if (apEndpoint->mpAdapterAddr != nullptr) { g_free(apEndpoint->mpAdapterAddr); apEndpoint->mpAdapterAddr = nullptr; } if (apEndpoint->mpRootPath != nullptr) { g_free(apEndpoint->mpRootPath); apEndpoint->mpRootPath = nullptr; } if (apEndpoint->mpAdvPath != nullptr) { g_free(apEndpoint->mpAdvPath); apEndpoint->mpAdvPath = nullptr; } if (apEndpoint->mpServicePath != nullptr) { g_free(apEndpoint->mpServicePath); apEndpoint->mpServicePath = nullptr; } if (apEndpoint->mpConnMap != nullptr) { g_hash_table_destroy(apEndpoint->mpConnMap); apEndpoint->mpConnMap = nullptr; } if (apEndpoint->mpAdvertisingUUID != nullptr) { g_free(apEndpoint->mpAdvertisingUUID); apEndpoint->mpAdvertisingUUID = nullptr; } if (apEndpoint->mpChipServiceData != nullptr) { g_free(apEndpoint->mpChipServiceData); apEndpoint->mpChipServiceData = nullptr; } if (apEndpoint->mpPeerDevicePath != nullptr) { g_free(apEndpoint->mpPeerDevicePath); apEndpoint->mpPeerDevicePath = nullptr; } g_free(apEndpoint); } } void BluezObjectsCleanup(BluezEndpoint * apEndpoint) { g_object_unref(apEndpoint->mpAdapter); EndpointCleanup(apEndpoint); } static void BluezPeripheralObjectsSetup(gpointer apClosure) { static const char * const c1_flags[] = { ""write"", nullptr }; static const char * const c2_flags[] = { ""read"", ""indicate"", nullptr }; BluezEndpoint * endpoint = (BluezEndpoint *) apClosure; VerifyOrExit(endpoint != nullptr, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); endpoint->mpService = BluezServiceCreate(apClosure); // C1 characteristic endpoint->mpC1 = BluezCharacteristicCreate(endpoint->mpService, g_strdup(""c1""), g_strdup(CHIP_PLAT_BLE_UUID_C1_STRING), endpoint->mpRoot); bluez_gatt_characteristic1_set_flags(endpoint->mpC1, c1_flags); g_signal_connect(endpoint->mpC1, ""handle-read-value"", G_CALLBACK(BluezCharacteristicReadValue), apClosure); g_signal_connect(endpoint->mpC1, ""handle-write-value"", G_CALLBACK(BluezCharacteristicWriteValueError), NULL); g_signal_connect(endpoint->mpC1, ""handle-acquire-write"", G_CALLBACK(BluezCharacteristicAcquireWrite), apClosure); g_signal_connect(endpoint->mpC1, ""handle-acquire-notify"", G_CALLBACK(BluezCharacteristicAcquireNotifyError), NULL); g_signal_connect(endpoint->mpC1, ""handle-start-notify"", G_CALLBACK(BluezCharacteristicStartNotifyError), NULL); g_signal_connect(endpoint->mpC1, ""handle-stop-notify"", G_CALLBACK(BluezCharacteristicStopNotifyError), NULL); g_signal_connect(endpoint->mpC1, ""handle-confirm"", G_CALLBACK(BluezCharacteristicConfirmError), NULL); endpoint->mpC2 = BluezCharacteristicCreate(endpoint->mpService, g_strdup(""c2""), g_strdup(CHIP_PLAT_BLE_UUID_C2_STRING), endpoint->mpRoot); bluez_gatt_characteristic1_set_flags(endpoint->mpC2, c2_flags); g_signal_connect(endpoint->mpC2, ""handle-read-value"", G_CALLBACK(BluezCharacteristicReadValue), apClosure); g_signal_connect(endpoint->mpC2, ""handle-write-value"", G_CALLBACK(BluezCharacteristicWriteValueError), NULL); g_signal_connect(endpoint->mpC2, ""handle-acquire-write"", G_CALLBACK(BluezCharacteristicAcquireWriteError), NULL); g_signal_connect(endpoint->mpC2, ""handle-acquire-notify"", G_CALLBACK(BluezCharacteristicAcquireNotify), apClosure); g_signal_connect(endpoint->mpC2, ""handle-start-notify"", G_CALLBACK(BluezCharacteristicStartNotify), apClosure); g_signal_connect(endpoint->mpC2, ""handle-stop-notify"", G_CALLBACK(BluezCharacteristicStopNotify), apClosure); g_signal_connect(endpoint->mpC2, ""handle-confirm"", G_CALLBACK(BluezCharacteristicConfirm), apClosure); ChipLogProgress(DeviceLayer, ""CHIP BTP C1 %s"", bluez_gatt_characteristic1_get_service(endpoint->mpC1)); ChipLogProgress(DeviceLayer, ""CHIP BTP C2 %s"", bluez_gatt_characteristic1_get_service(endpoint->mpC2)); exit: return; } static void BluezOnBusAcquired(GDBusConnection * aConn, const gchar * aName, gpointer apClosure) { BluezEndpoint * endpoint = (BluezEndpoint *) apClosure; VerifyOrExit(endpoint != nullptr, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); ChipLogProgress(DeviceLayer, ""TRACE: Bus acquired for name %s"", aName); endpoint->mpRootPath = g_strdup_printf(""/chipoble/%04x"", getpid() & 0xffff); endpoint->mpRoot = g_dbus_object_manager_server_new(endpoint->mpRootPath); g_dbus_object_manager_server_set_connection(endpoint->mpRoot, aConn); BluezPeripheralObjectsSetup(apClosure); exit: return; } #if CHIP_BLUEZ_NAME_MONITOR static void BluezOnNameAcquired(GDBusConnection * aConn, const gchar * aName, gpointer apClosure) { ChipLogProgress(DeviceLayer, ""TRACE: Owning name: Acquired %s"", aName); } static void BluezOnNameLost(GDBusConnection * aConn, const gchar * aName, gpointer apClosure) { ChipLogProgress(DeviceLayer, ""TRACE: Owning name: lost %s"", aName); } #endif static void * BluezMainLoop(void * apClosure) { GDBusObjectManager * manager; GError * error = nullptr; GDBusConnection * conn = nullptr; BluezEndpoint * endpoint = (BluezEndpoint *) apClosure; VerifyOrExit(endpoint != nullptr, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); conn = g_bus_get_sync(G_BUS_TYPE_SYSTEM, nullptr, &error); VerifyOrExit(conn != nullptr, ChipLogProgress(DeviceLayer, ""FAIL: get bus sync in %s, error: %s"", __func__, error->message)); if (endpoint->mpAdapterName != nullptr) endpoint->mpOwningName = g_strdup_printf(""%s"", endpoint->mpAdapterName); else endpoint->mpOwningName = g_strdup_printf(""C-%04x"", getpid() & 0xffff); BluezOnBusAcquired(conn, endpoint->mpOwningName, apClosure); manager = g_dbus_object_manager_client_new_sync( conn, G_DBUS_OBJECT_MANAGER_CLIENT_FLAGS_NONE, BLUEZ_INTERFACE, ""/"", bluez_object_manager_client_get_proxy_type, nullptr /* unused user data in the Proxy Type Func */, nullptr /*destroy notify */, nullptr /* cancellable */, &error); VerifyOrExit(manager != nullptr, ChipLogProgress(DeviceLayer, ""FAIL: Error getting object manager client: %s"", error->message)); endpoint->mpObjMgr = manager; bluezObjectsSetup(endpoint); #if 0 // reenable if we want to handle the bluetoothd restart g_signal_connect (manager, ""notify::name-owner"", G_CALLBACK (on_notify_name_owner), NULL); #endif g_signal_connect(manager, ""object-added"", G_CALLBACK(BluezSignalOnObjectAdded), apClosure); g_signal_connect(manager, ""object-removed"", G_CALLBACK(BluezSignalOnObjectRemoved), apClosure); g_signal_connect(manager, ""interface-proxy-properties-changed"", G_CALLBACK(BluezSignalInterfacePropertiesChanged), apClosure); ChipLogProgress(DeviceLayer, ""TRACE: Bluez mainloop starting %s"", __func__); g_main_loop_run(sBluezMainLoop); ChipLogProgress(DeviceLayer, ""TRACE: Bluez mainloop stopping %s"", __func__); BluezObjectsCleanup(endpoint); exit: if (error != nullptr) g_error_free(error); return nullptr; } bool BluezRunOnBluezThread(int (*aCallback)(void *), void * apClosure) { GMainContext * context = nullptr; const char * msg = nullptr; VerifyOrExit(sBluezMainLoop != nullptr, msg = ""FAIL: NULL sBluezMainLoop""); VerifyOrExit(g_main_loop_is_running(sBluezMainLoop), msg = ""FAIL: sBluezMainLoop not running""); context = g_main_loop_get_context(sBluezMainLoop); VerifyOrExit(context != nullptr, msg = ""FAIL: NULL main context""); g_main_context_invoke(context, aCallback, apClosure); exit: if (msg != nullptr) { ChipLogProgress(DeviceLayer, ""%s in %s"", msg, __func__); } return msg == nullptr; } static gboolean BluezC2Indicate(void * apClosure) { ConnectionDataBundle * closure = nullptr; BluezConnection * conn = nullptr; GError * error = nullptr; GIOStatus status; const char * buf; size_t len, written; closure = static_cast(apClosure); VerifyOrExit(closure != nullptr, ChipLogProgress(DeviceLayer, ""ConnectionDataBundle is NULL in %s"", __func__)); conn = closure->mpConn; VerifyOrExit(conn != nullptr, ChipLogProgress(DeviceLayer, ""BluezConnection is NULL in %s"", __func__)); VerifyOrExit(conn->mpC2 != nullptr, ChipLogProgress(DeviceLayer, ""FAIL: C2 Indicate: %s"", ""NULL C2"")); if (bluez_gatt_characteristic1_get_notify_acquired(conn->mpC2) == TRUE) { buf = (char *) g_variant_get_fixed_array(closure->mpVal, &len, sizeof(uint8_t)); status = g_io_channel_write_chars(conn->mC2Channel.mpChannel, buf, len, &written, &error); g_variant_unref(closure->mpVal); closure->mpVal = nullptr; VerifyOrExit(status == G_IO_STATUS_NORMAL, ChipLogProgress(DeviceLayer, ""FAIL: C2 Indicate: %s"", error->message)); } else { bluez_gatt_characteristic1_set_value(conn->mpC2, closure->mpVal); closure->mpVal = nullptr; } exit: if (closure != nullptr) { if (closure->mpVal) { g_variant_unref(closure->mpVal); } g_free(closure); } if (error != nullptr) g_error_free(error); return G_SOURCE_REMOVE; } bool SendBluezIndication(void * apConn, chip::System::PacketBuffer * apBuf) { ConnectionDataBundle * closure; const char * msg = nullptr; bool success = false; uint8_t * buffer = nullptr; size_t len = 0; VerifyOrExit(apBuf != nullptr, ChipLogProgress(DeviceLayer, ""apBuf is NULL in %s"", __func__)); buffer = apBuf->Start(); len = apBuf->DataLength(); closure = g_new(ConnectionDataBundle, 1); closure->mpConn = static_cast(apConn); closure->mpVal = g_variant_new_fixed_array(G_VARIANT_TYPE_BYTE, buffer, len * sizeof(uint8_t), sizeof(uint8_t)); success = BluezRunOnBluezThread(BluezC2Indicate, closure); exit: if (nullptr != msg) { ChipLogError(Ble, msg); } if (nullptr != apBuf) { chip::System::PacketBuffer::Free(apBuf); } return success; } static gboolean BluezDisconnect(void * apClosure) { BluezConnection * conn = static_cast(apClosure); GError * error = nullptr; gboolean success; VerifyOrExit(conn != nullptr, ChipLogProgress(DeviceLayer, ""conn is NULL in %s"", __func__)); VerifyOrExit(conn->mpDevice != nullptr, ChipLogProgress(DeviceLayer, ""FAIL: Disconnect: %s"", ""NULL Device"")); ChipLogProgress(DeviceLayer, ""%s peer=%s"", __func__, bluez_device1_get_address(conn->mpDevice)); success = bluez_device1_call_disconnect_sync(conn->mpDevice, nullptr, &error); VerifyOrExit(success == TRUE, ChipLogProgress(DeviceLayer, ""FAIL: Disconnect: %s"", error->message)); exit: if (error != nullptr) g_error_free(error); return G_SOURCE_REMOVE; } static int CloseBleconnectionCB(void * apAppState) { BluezDisconnect(apAppState); return G_SOURCE_REMOVE; } bool CloseBluezConnection(void * apAppState) { return BluezRunOnBluezThread(CloseBleconnectionCB, apAppState); } CHIP_ERROR StartBluezAdv(void * apAppState) { CHIP_ERROR err = CHIP_NO_ERROR; if (!BluezRunOnBluezThread(BluezAdvStart, apAppState)) { err = CHIP_ERROR_INCORRECT_STATE; ChipLogError(Ble, ""Failed to schedule BluezAdvStart() on CHIPoBluez thread""); } return err; } CHIP_ERROR StopBluezAdv(void * apAppState) { CHIP_ERROR err = CHIP_NO_ERROR; if (!BluezRunOnBluezThread(BluezAdvStop, apAppState)) { err = CHIP_ERROR_INCORRECT_STATE; ChipLogError(Ble, ""Failed to schedule BluezAdvStop() on CHIPoBluez thread""); } return err; } CHIP_ERROR BluezAdvertisementSetup(void * apAppState) { CHIP_ERROR err = CHIP_NO_ERROR; if (!BluezRunOnBluezThread(BluezAdvSetup, apAppState)) { err = CHIP_ERROR_INCORRECT_STATE; ChipLogError(Ble, ""Failed to schedule BluezAdvertisementSetup() on CHIPoBluez thread""); } return err; } CHIP_ERROR BluezGattsAppRegister(void * apAppState) { CHIP_ERROR err = CHIP_NO_ERROR; if (!BluezRunOnBluezThread(BluezPeripheralRegisterApp, apAppState)) { err = CHIP_ERROR_INCORRECT_STATE; ChipLogError(Ble, ""Failed to schedule BluezPeripheralRegisterApp() on CHIPoBluez thread""); } return err; } CHIP_ERROR ConfigureBluezAdv(BLEAdvConfig & aBleAdvConfig, BluezEndpoint * apEndpoint) { const char * msg = nullptr; CHIP_ERROR err = CHIP_NO_ERROR; VerifyOrExit(aBleAdvConfig.mpBleName != nullptr, msg = ""FAIL: BLE name is NULL""); VerifyOrExit(aBleAdvConfig.mpAdvertisingUUID != nullptr, msg = ""FAIL: BLE mpAdvertisingUUID is NULL in %s""); apEndpoint->mpAdapterName = g_strdup(aBleAdvConfig.mpBleName); apEndpoint->mpAdvertisingUUID = g_strdup(aBleAdvConfig.mpAdvertisingUUID); apEndpoint->mNodeId = aBleAdvConfig.mNodeId; apEndpoint->mType = aBleAdvConfig.mType; apEndpoint->mDuration = aBleAdvConfig.mDuration; apEndpoint->mpChipServiceData = static_cast(g_malloc(sizeof(CHIPServiceData) + 1)); apEndpoint->mpChipServiceData->mDataBlock0Len = sizeof(CHIPIdInfo) + 1; apEndpoint->mpChipServiceData->mDataBlock0Type = 1; apEndpoint->mpChipServiceData->mIdInfo.mMajor = aBleAdvConfig.mMajor; apEndpoint->mpChipServiceData->mIdInfo.mMinor = aBleAdvConfig.mMinor; apEndpoint->mpChipServiceData->mIdInfo.mVendorId = aBleAdvConfig.mVendorId; apEndpoint->mpChipServiceData->mIdInfo.mProductId = aBleAdvConfig.mProductId; apEndpoint->mpChipServiceData->mIdInfo.mDeviceId = aBleAdvConfig.mDeviceId; apEndpoint->mpChipServiceData->mIdInfo.mPairingStatus = aBleAdvConfig.mPairingStatus; apEndpoint->mDuration = aBleAdvConfig.mDuration; exit: if (nullptr != msg) { ChipLogProgress(DeviceLayer, ""%s in %s"", msg, __func__); err = CHIP_ERROR_INCORRECT_STATE; if (apEndpoint->mpChipServiceData != nullptr) { g_free(apEndpoint->mpChipServiceData); apEndpoint->mpChipServiceData = nullptr; } } return err; } CHIP_ERROR InitBluezBleLayer(bool aIsCentral, char * apBleAddr, BLEAdvConfig & aBleAdvConfig, void *& apEndpoint) { CHIP_ERROR err = CHIP_NO_ERROR; bool retval = false; int pthreadErr = 0; int tmpErrno; BluezEndpoint * endpoint = nullptr; VerifyOrExit(pipe2(sBluezFD, O_DIRECT) == 0, ChipLogProgress(DeviceLayer, ""FAIL: open pipe in %s"", __func__)); // initialize server endpoint endpoint = g_new0(BluezEndpoint, 1); VerifyOrExit(endpoint != nullptr, ChipLogProgress(DeviceLayer, ""FAIL: memory allocation in %s"", __func__)); if (apBleAddr != nullptr) endpoint->mpAdapterAddr = g_strdup(apBleAddr); else endpoint->mpAdapterAddr = nullptr; endpoint->mpConnMap = g_hash_table_new(g_str_hash, g_str_equal); endpoint->mIsCentral = aIsCentral; err = ConfigureBluezAdv(aBleAdvConfig, endpoint); SuccessOrExit(err); sBluezMainLoop = g_main_loop_new(nullptr, FALSE); VerifyOrExit(sBluezMainLoop != nullptr, ChipLogProgress(DeviceLayer, ""FAIL: memory alloc in %s"", __func__)); pthreadErr = pthread_create(&sBluezThread, nullptr, BluezMainLoop, endpoint); tmpErrno = errno; VerifyOrExit(pthreadErr == 0, ChipLogProgress(DeviceLayer, ""FAIL: pthread_create (%s) in %s"", strerror(tmpErrno), __func__)); sleep(1); retval = TRUE; exit: if (retval) { apEndpoint = endpoint; ChipLogProgress(DeviceLayer, ""PlatformBlueZInit init success""); } else { EndpointCleanup(endpoint); } return err; } } // namespace Internal } // namespace DeviceLayer } // namespace chip #endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE ",16169,True,3067.3686010546808,median "////////////////////////////////////////// Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. ////////////////////////////////////////// = Object orientation :jls: https://docs.oracle.com/javase/specs/jls/se14/html/ :javabeans: https://download.oracle.com/otndocs/jcp/7224-javabeans-1.01-fr-spec-oth-JSpec/ This chapter covers the object orientation of the Groovy programming language. == Types === Primitive types Groovy supports the same primitive types as those defined by the {jls}[Java Language Specification]: * integral types: `byte` (8 bit), `short` (16 bit), `int` (32 bit) and `long` (64 bit) * floating-point types: `float` (32 bit) and `double` (64 bit) * `boolean` type (exactly `true` or `false`) * `char` type (16 bit, usable as a numeric type, representing an UTF-16 code) While Groovy declares and stores primitive fields and variables as primitives, because it uses Objects for everything, it autowraps references to primitives. Just like Java, the wrappers it uses are [cols=""1,1"" options=""header""] .primitive wrappers |==== | Primitive type | Wrapper class | boolean | Boolean | char | Character | short | Short | int | Integer | long | Long | float | Float | double | Double |==== Here's an example using `int` [source,groovy] ---- include::../test/PrimitiveTest.groovy[tags=primitive_references,indent=0] ---- Now you may be concerned that this means every time you use a mathematical operator on a reference to a primitive that you'll incur the cost of unboxing and reboxing the primitive. But this is not the case, as Groovy will compile your operators into their link:core-operators.html#_operator-overloading[method equivalents] and uses those instead. Additionally, Groovy will automatically unbox to a primitive when calling a Java method that takes a primitive parameter and automatically box primitive method return values from Java. However, be aware there are some link:core-differences-java.html#_primitives_and_wrappers[differences] from Java's method resolution. === Class Groovy classes are very similar to Java classes, and are compatible with Java ones at JVM level. They may have methods, fields and properties (think JavaBeans properties but with less boilerplate). Classes and class members can have the same modifiers (public, protected, private, static, etc) as in Java with some minor differences at the source level which are explained shortly. The key differences between Groovy classes and their Java counterparts are: * Classes or methods with no visibility modifier are automatically public (a special annotation can be used to achieve package private visibility). * Fields with no visibility modifier are turned into properties automatically, which results in less verbose code, since explicit getter and setter methods aren't needed. More on this aspect will be covered in the <>. * Classes do not need to have the same base name as their source file definitions but it is highly recommended in most scenarios (see also the next point about scripts). * One source file may contain one or more classes (but if a file contains any code not in a class, it is considered a script). Scripts are just classes with some special conventions and will have the same name as their source file (so don't include a class definition within a script having the same name as the script source file). The following code presents an example class. [source,groovy] ---- include::../test/ClassTest.groovy[tags=class_definition,indent=0] ---- <1> class beginning, with the name `Person` <2> string field and property named `name` <3> method definition ==== Normal class Normal classes refer to classes which are top level and concrete. This means they can be instantiated without restrictions from any other classes or scripts. This way, they can only be public (even though the `public` keyword may be suppressed). Classes are instantiated by calling their constructors, using the `new` keyword, as in the following snippet. [source,groovy] ---- include::../test/ClassTest.groovy[tags=class_instantiation,indent=0] ---- ==== Inner class Inner classes are defined within another classes. The enclosing class can use the inner class as usual. On the other side, a inner class can access members of its enclosing class, even if they are private. Classes other than the enclosing class are not allowed to access inner classes. Here is an example: [source,groovy] ---- include::../test/ClassTest.groovy[tags=inner_class,indent=0] ---- <1> the inner class is instantiated and its method gets called <2> inner class definition, inside its enclosing class <3> even being private, a field of the enclosing class is accessed by the inner class There are some reasons for using inner classes: * They increase encapsulation by hiding the inner class from other classes, which do not need to know about it. This also leads to cleaner packages and workspaces. * They provide a good organization, by grouping classes that are used by only one class. * They lead to more maintainable codes, since inner classes are near the classes that use them. It is common for an inner class to be an implementation of some interface whose method(s) are needed by the outer class. The code below illustrates this typical usage pattern, here being used with threads. [source,groovy] ---- include::../test/ClassTest.groovy[tags=inner_class2,indent=0] ---- Note that the class `Inner2` is defined only to provide an implementation of the method `run` to class `Outer2`. Anonymous inner classes help to eliminate verbosity in this case. That topic is covered shortly. Groovy 3+ also supports Java syntax for non-static inner class instantiation, for example: [source,groovy] -------------------------------------- include::../test/ClassTest.groovy[tags=inner_instantiation,indent=0] -------------------------------------- ===== Anonymous inner class The earlier example of an inner class (`Inner2`) can be simplified with an anonymous inner class. The same functionality can be achieved with the following code: [source,groovy] ---- include::../test/ClassTest.groovy[tags=anonymous_inner_class,indent=0] ---- <1> comparing with the last example of previous section, the `new Inner2()` was replaced by `new Runnable()` along with all its implementation <2> the method `start` is invoked normally Thus, there was no need to define a new class to be used just once. ==== Abstract class Abstract classes represent generic concepts, thus, they cannot be instantiated, being created to be subclassed. Their members include fields/properties and abstract or concrete methods. Abstract methods do not have implementation, and must be implemented by concrete subclasses. [source,groovy] ---- include::../test/ClassTest.groovy[tags=abstract_class,indent=0] ---- <1> abstract classes must be declared with `abstract` keyword <2> abstract methods must also be declared with `abstract` keyword Abstract classes are commonly compared to interfaces. There are at least two important differences of choosing one or another. First, while abstract classes may contain fields/properties and concrete methods, interfaces may contain only abstract methods (method signatures). Moreover, one class can implement several interfaces, whereas it can extend just one class, abstract or not. === Inheritance Inheritance in Groovy resembles inheritance in Java. It provides a mechanism for a child class (or subclass) to reuse code or properties from a parent (or super class). Classes related through inheritance form an inheritance hierarchy. Common behavior and members are pushed up the hierarchy to reduce duplication. Specializations occur in child classes. Different forms of inheritance are supported: * _implementation_ inheritance where code (methods, fields or properties) from a <> or from one or more <<_traits,traits>> is reused by a child class * _contract_ inheritance where a class promises to provide particular abstract methods defined in a <>, or defined in one or more <<_traits,traits>> or <<_interface,interfaces>>. === Interface An interface defines a contract that a class needs to conform to. An interface only defines a list of methods that need to be implemented, but does not define the method's implementation. [source,groovy] ---- include::../test/ClassTest.groovy[tags=interface_def_1,indent=0] ---- <1> an interface needs to be declared using the `interface` keyword <2> an interface only defines method signatures Methods of an interface are always *public*. It is an error to use `protected` or `private` methods in interfaces: [source,groovy] ---- include::../test/ClassTest.groovy[tags=protected_forbidden,indent=0] ---- <1> Using `protected` is a compile-time error A class _implements_ an interface if it defines the interface in its `implements` list or if any of its superclasses does: [source,groovy] ---- include::../test/ClassTest.groovy[tags=class_implements,indent=0] ---- <1> The `SystemGreeter` declares the `Greeter` interface using the `implements` keyword <2> Then implements the required `greet` method <3> Any instance of `SystemGreeter` is also an instance of the `Greeter` interface An interface can extend another interface: [source,groovy] ---- include::../test/ClassTest.groovy[tags=extended_interface,indent=0] ---- <1> the `ExtendedGreeter` interface extends the `Greeter` interface using the `extends` keyword It is worth noting that for a class to be an instance of an interface, it has to be explicit. For example, the following class defines the `greet` method as it is declared in the `Greeter` interface, but does not declare `Greeter` in its interfaces: [source,groovy] ---- include::../test/ClassTest.groovy[tags=no_structural_interface,indent=0] ---- In other words, Groovy does not define structural typing. It is however possible to make an instance of an object implement an interface at runtime, using the `as` coercion operator: [source,groovy] ---- include::../test/ClassTest.groovy[tags=interface_coercion,indent=0] ---- <1> create an instance of `DefaultGreeter` that does not implement the interface <2> coerce the instance into a `Greeter` at runtime <3> the coerced instance implements the `Greeter` interface You can see that there are two distinct objects: one is the source object, a `DefaultGreeter` instance, which does not implement the interface. The other is an instance of `Greeter` that delegates to the coerced object. TIP: Groovy interfaces do not support default implementation like Java 8 interfaces. If you are looking for something similar (but not equal), <<_traits,traits>> are close to interfaces, but allow default implementation as well as other important features described in this manual. [[superclass]] === Superclass Parent classes share visible fields, properties or methods with child classes. A child class may have at most one parent class. The `extends` keyword is used immediately prior to giving the superclass type. === Constructors Constructors are special methods used to initialize an object with a specific state. As with normal methods, it is possible for a class to declare more than one constructor, so long as each constructor has a unique type signature. If an object doesn't require any parameters during construction, it may use a _no-arg_ constructor. If no constructors are supplied, an empty no-arg constructor will be provided by the Groovy compiler. Groovy supports two invocation styles: * _positional parameters_ are used in a similar to how you would use Java constructors * _named parameters_ allow you to specify parameter names when invoking the constructor. ==== Positional parameters To create an object by using positional parameters, the respective class needs to declare one or more constructors. In the case of multiple constructors, each must have a unique type signature. The constructors can also added to the class using the gapi:groovy.transform.TupleConstructor[] annotation. Typically, once at least one constructor is declared, the class can only be instantiated by having one of its constructors called. It is worth noting that, in this case, you can't normally create the class with named parameters. Groovy does support named parameters so long as the class contains a no-arg constructor or provides a constructor which takes a `Map` argument as the first (and potentially only) argument - see the next section for details. There are three forms of using a declared constructor. The first one is the normal Java way, with the `new` keyword. The others rely on coercion of lists into the desired types. In this case, it is possible to coerce with the `as` keyword and by statically typing the variable. [source,groovy] ---- include::../test/ClassTest.groovy[tags=constructor_positional_parameters,indent=0] ---- <1> Constructor declaration <2> Constructor invocation, classic Java way <3> Constructor usage, using coercion with `as` keyword <4> Constructor usage, using coercion in assignment ==== Named parameters If no (or a no-arg) constructor is declared, it is possible to create objects by passing parameters in the form of a map (property/value pairs). This can be in handy in cases where one wants to allow several combinations of parameters. Otherwise, by using traditional positional parameters it would be necessary to declare all possible constructors. Having a constructor where the first (and perhaps only) argument is a `Map` argument is also supported - such a constructor may also be added using the gapi:groovy.transform.MapConstructor[] annotation. [source,groovy] ---- include::../test/ClassTest.groovy[tags=constructor_named_parameters,indent=0] ---- <1> No constructor declared <2> No parameters given in the instantiation <3> `name` parameter given in the instantiation <4> `age` parameter given in the instantiation <5> `name` and `age` parameters given in the instantiation It is important to highlight, however, that this approach gives more power to the constructor caller, while imposing an increased responsibility on the caller to get the names and value types correct. Thus, if greater control is desired, declaring constructors using positional parameters might be preferred. Notes: * While the example above supplied no constructor, you can also supply a no-arg constructor or a constructor where the first argument is a `Map`, most typically it's the only argument. * When no (or a no-arg) constructor is declared, Groovy replaces the named constructor call by a call to the no-arg constructor followed by calls to the setter for each supplied named property. * When the first argument is a Map, Groovy combines all named parameters into a Map (regardless of ordering) and supplies the map as the first parameter. This can be a good approach if your properties are declared as `final` (since they will be set in the constructor rather than after the fact with setters). * You can support both named and positional construction by supply both positional constructors as well as a no-arg or Map constructor. * You can support hybrid construction by having a constructor where the first argument is a Map but there are also additional positional parameters. Use this style with caution. === Methods Groovy methods are quite similar to other languages. Some peculiarities will be shown in the next subsections. ==== Method definition A method is defined with a return type or with the `def` keyword, to make the return type untyped. A method can also receive any number of arguments, which may not have their types explicitly declared. Java modifiers can be used normally, and if no visibility modifier is provided, the method is public. Methods in Groovy always return some value. If no `return` statement is provided, the value evaluated in the last line executed will be returned. For instance, note that none of the following methods uses the `return` keyword. [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=method_definition ,indent=0] ---- <1> Method with no return type declared and no parameter <2> Method with explicit return type and no parameter <3> Method with a parameter with no type defined <4> Static method with a String parameter ==== Named parameters Like constructors, normal methods can also be called with named parameters. To support this notation, a convention is used where the first argument to the method is a `Map`. In the method body, the parameter values can be accessed as in normal maps (`map.key`). If the method has just a single Map argument, all supplied parameters must be named. [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=named_arguments ,indent=0] ---- ===== Mixing named and positional parameters Named parameters can be mixed with positional parameters. The same convention applies, in this case, in addition to the `Map` argument as the first argument, the method in question will have additional positional arguments as needed. Supplied positional parameters when calling the method must be in order. The named parameters can be in any position. They are grouped into the map and supplied as the first parameter automatically. [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=named_arguments_with_additional_arguments ,indent=0] ---- <1> Method call with additional `number` argument of `Integer` type <2> Method call with changed order of arguments If we don't have the Map as the first argument, then a Map must be supplied for that argument instead of named parameters. Failure to do so will lead to `groovy.lang.MissingMethodException`: [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=failed_named_arguments_with_additional_arguments ,indent=0] ---- <1> Method call throws `groovy.lang.MissingMethodException: No signature of method: foo() is applicable for argument types: (LinkedHashMap, Integer) values: [[name:Marie, age:1], 23]`, because the named argument `Map` parameter is not defined as the first argument Above exception can be avoided if we replace named arguments with an explicit `Map` argument: [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=explicit_named_arguments_with_additional_arguments ,indent=0] ---- <1> Explicit `Map` argument in place of named arguments makes invocation valid TIP: Although Groovy allows you to mix named and positional parameters, it can lead to unnecessary confusion. Mix named and positional arguments with caution. ==== Default arguments Default arguments make parameters optional. If the argument is not supplied, the method assumes a default value. [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=default_arguments ,indent=0] ---- Note that no mandatory parameter can be defined after a default parameter is present, only other default parameters. ==== Varargs Groovy supports methods with a variable number of arguments. They are defined like this: `def foo(p1, ..., pn, T... args)`. Here `foo` supports `n` arguments by default, but also an unspecified number of further arguments exceeding `n`. [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=varargs_example,indent=0] ---- This example defines a method `foo`, that can take any number of arguments, including no arguments at all. `args.length` will return the number of arguments given. Groovy allows `T[]` as a alternative notation to `T...`. That means any method with an array as last parameter is seen by Groovy as a method that can take a variable number of arguments. [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=varargs_array_notation,indent=0] ---- If a method with varargs is called with `null` as the vararg parameter, then the argument will be `null` and not an array of length one with `null` as the only element. [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=varargs_null_parameter,indent=0] ---- If a varargs method is called with an array as an argument, then the argument will be that array instead of an array of length one containing the given array as the only element. [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=varargs_array_parameter,indent=0] ---- Another important point are varargs in combination with method overloading. In case of method overloading Groovy will select the most specific method. For example if a method `foo` takes a varargs argument of type `T` and another method `foo` also takes one argument of type `T`, the second method is preferred. [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=varargs_method_overloading,indent=0] ---- ==== Method selection algorithm Dynamic Groovy supports https://en.wikipedia.org/wiki/Multiple_dispatch[multiple dispatch] (aka multimethods). When calling a method, the actual method invoked is determined dynamically based on the run-time type of methods arguments. First the method name and number of arguments will be considered (including allowance for varargs), and then the type of each argument. Consider the following method definitions: [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=multi_methods,indent=0] ---- Perhaps as expected, calling `method` with `String` and `Integer` parameters, invokes our third method definition. [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=call_single_method,indent=0] ---- Of more interest here is when the types are not known at compile time. Perhaps the arguments are declared to be of type `Object` (a list of such objects in our case). Java would determine that the `method(Object, Object)` variant would be selected in all cases (unless casts were used) but as can be seen in the following example, Groovy uses the runtime type and will invoke each of our methods once (and normally, no casting is needed): [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=call_multi_methods,indent=0] ---- For each of the first two of our three method invocations an exact match of argument types was found. For the third invocation, an exact match of `method(Integer, Integer)` wasn't found but `method(Object, Object)` is still valid and will be selected. Method selection then is about finding the _closest fit_ from valid method candidates which have compatible parameter types. So, `method(Object, Object)` is also valid for the first two invocations but is not as close a match as the variants where types exactly match. To determine the closest fit, the runtime has a notion of the _distance_ an actual argument type is away from the declared parameter type and tries to minimise the total distance across all parameters. The following table illustrates some factors which affect the distance calculation. [cols=""1,1"" options=""header""] |==== | Aspect | Example | Directly implemented interfaces match more closely than ones from further up the inheritance hierarchy. a| Given these interface and method definitions: [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=multi_method_distance_interfaces,indent=0] ---- The directly implemented interface will match: [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=multi_method_distance_interfaces_usage,indent=0] ---- | An Object array is preferred over an Object. a| [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=object_array_over_object,indent=0] ---- | Non-vararg variants are favored over vararg variants. a| [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=non_varargs_over_vararg,indent=0] ---- | If two vararg variants are applicable, the one which uses the minimum number of vararg arguments is preferred. a| [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=minimal_varargs,indent=0] ---- | Interfaces are preferred over super classes. a| [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=multi_method_distance_interface_over_super,indent=0] ---- | For a primitive argument type, a declared parameter type which is the same or slightly larger is preferred. a| [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=primitive_larger_over_smaller,indent=0] ---- |==== In the case where two variants have exactly the same distance, this is deemed ambiguous and will cause a runtime exception: [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=multi_method_ambiguous,indent=0] ---- Casting can be used to select the desired method: [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=multi_method_ambiguous_cast,indent=0] ---- ==== Exception declaration Groovy automatically allows you to treat checked exceptions like unchecked exceptions. This means that you don't need to declare any checked exceptions that a method may throw as shown in the following example which can throw a `FileNotFoundException` if the file isn't found: [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=idiomatic_method_declaration,indent=0] ---- Nor will you be required to surround the call to the `badRead` method in the previous example within a try/catch block - though you are free to do so if you wish. If you wish to declare any exceptions that your code might throw (checked or otherwise) you are free to do so. Adding exceptions won't change how the code is used from any other Groovy code but can be seen as documentation for the human reader of your code. The exceptions will become part of the method declaration in the bytecode, so if your code might be called from Java, it might be useful to include them. Using an explicit checked exception declaration is illustrated in the following example: [source,groovy] ---- include::../test/objectorientation/MethodsTest.groovy[tags=checked_method_declaration,indent=0] ---- === Fields and Properties [[fields]] ==== Fields A field is a member of a class or a trait which has: * a mandatory _access modifier_ (`public`, `protected`, or `private`) * one or more optional _modifiers_ (`static`, `final`, `synchronized`) * an optional _type_ * a mandatory _name_ [source,groovy] ---- include::../test/ClassTest.groovy[tags=field_declaration,indent=0] ---- <1> a `private` field named `id`, of type `int` <2> a `protected` field named `description`, of type `String` <3> a `public static final` field named _DEBUG_ of type `boolean` A field may be initialized directly at declaration: [source,groovy] ---- include::../test/ClassTest.groovy[tags=field_initialization,indent=0] ---- <1> the private field `id` is initialized with `IDGenerator.next()` It is possible to omit the type declaration of a field. This is however considered a bad practice and in general it is a good idea to use strong typing for fields: [source,groovy] ---- include::../test/ClassTest.groovy[tags=typing_fields,indent=0] ---- <1> the field `mapping` doesn't declare a type <2> the field `mapping` has a strong type The difference between the two is important if you want to use optional type checking later. It is also important as a way to document the class design. However, in some cases like scripting or if you want to rely on duck typing it may be useful to omit the type. [[properties]] ==== Properties A property is an externally visible feature of a class. Rather than just using a public field to represent such features (which provides a more limited abstraction and would restrict refactoring possibilities), the typical approach in Java is to follow the conventions outlined in the {javabeans}[JavaBeans Specification], i.e. represent the property using a combination of a private backing field and getters/setters. Groovy follows these same conventions but provides a simpler way to define the property. You can define a property with: * an *absent* access modifier (no `public`, `protected` or `private`) * one or more optional _modifiers_ (`static`, `final`, `synchronized`) * an optional _type_ * a mandatory _name_ Groovy will then generate the getters/setters appropriately. For example: [source,groovy] ---- include::../test/ClassTest.groovy[tags=properties_definition,indent=0] ---- <1> creates a backing `private String name` field, a `getName` and a `setName` method <2> creates a backing `private int age` field, a `getAge` and a `setAge` method If a property is declared `final`, no setter is generated: [source,groovy] ---- include::../test/ClassTest.groovy[tags=readonly_property,indent=0] ---- <1> defines a read-only property of type `String` <2> defines a read-only property of type `int` <3> assigns the `name` parameter to the `name` field <4> assigns the `age` parameter to the `age` field Properties are accessed by name and will call the getter or setter transparently, unless the code is in the class which defines the property: [source,groovy] ---- include::../test/ClassTest.groovy[tags=property_access,indent=0] ---- <1> `this.name` will directly access the field because the property is accessed from within the class that defines it <2> similarily a read access is done directly on the `name` field <3> write access to the property is done outside of the `Person` class so it will implicitly call `setName` <4> read access to the property is done outside of the `Person` class so it will implicitly call `getName` <5> this will call the `name` method on `Person` which performs a direct access to the field <6> this will call the `title` method on `Person` which performs a direct read access to the field It is worth noting that this behavior of accessing the backing field directly is done in order to prevent a stack overflow when using the property access syntax within a class that defines the property. It is possible to list the properties of a class thanks to the meta `properties` field of an instance: [source,groovy] ---- include::../test/ClassTest.groovy[tags=properties_meta,indent=0] ---- By convention, Groovy will recognize properties even if there is no backing field provided there are getters or setters that follow the Java Beans specification. For example: [source,groovy] ---- include::../test/ClassTest.groovy[tags=pseudo_properties,indent=0] ---- <1> writing `p.name` is allowed because there is a pseudo-property `name` <2> reading `p.age` is allowed because there is a pseudo-readonly property `age` <3> writing `p.groovy` is allowed because there is a pseudo-writeonly property `groovy` This syntactic sugar is at the core of many DSLs written in Groovy. ===== Property naming conventions It is generally recommended that the first two letters of a property name are lowercase and for multi-word properties that camel case is used. In those cases, generated getters and setters will have a name formed by capitalizing the property name and adding a `get` or `set` prefix (or optionally ""is"" for a boolean getter). So, `getLength` would be a getter for a `length` property and `setFirstName` a setter for a `firstName` property. `isEmpty` might be the getter method name for a property named `empty`. [NOTE] ==== Property names starting with a capital letter would have getters/setters with just the prefix added. So, the property `Foo` is allowed even though it isn't following the recommended naming conventions. For this property, the accessor methods would be `setFoo` and `getFoo`. A consequence of this is that you aren't allowed to have both a `foo` and a `Foo` property, since they would have the same named accessor methods. ==== The JavaBeans specification makes a special case for properties which typically might be acronyms. If the first two letters of a property name are uppercase, no capitalization is performed (or more importantly, no decapitalization is done if generating the property name from the accessor method name). So, `getURL` would be the getter for a `URL` property. [NOTE] ==== Because of the special ""acronym handling"" property naming logic in the JavaBeans specification, the conversion to and from a property name are non-symmetrical. This leads to some strange edge cases. Groovy adopts a naming convention that avoids one ambiguity that might seem a little strange but was popular at the time of Groovy's design and has remained (so far) for historical reasons. Groovy looks at the second letter of a property name. If that is a capital, the property is deemed to be one of the acronym style properties and no capitalization is done, otherwise normal capitalization is done. Although we _never_ recommend it, it does allow you to have what might seem like ""duplicate named"" properties, e.g. you can have `aProp` and `AProp`, or `pNAME` and `PNAME`. The getters would be `getaProp` and `getAProp`, and `getpNAME` and `getPNAME` respectively. ==== ===== Modifiers on a property We have already seen that properties are defined by omitting the visibility modifier. In general, any other modifiers, e.g. `transient` would be copied across to the field. Two special cases are worth noting: * `final`, which we saw earlier is for read-only properties, is copied onto the backing field but also causes no setter to be defined * `static` is copied onto the backing field but also causes the accessor methods to be static If you wish to have a modifier like `final` also carried over to the accessor methods, you can write your properties long hand or consider using a <>. ===== Annotations on a property Annotations, including those associated with AST transforms, are copied on to the backing field for the property. This allows AST transforms which are applicable to fields to be applied to properties, e.g.: [source,groovy] ---- include::../test/ClassTest.groovy[tags=annotated_properties,indent=0] ---- <1> Confirms no eager initialization <2> Normal property access <3> Confirms initialization upon property access [[split-properties]] ===== Split property definition with an explicit backing field Groovy's property syntax is a convenient shorthand when your class design follows certain conventions which align with common JavaBean practice. If your class doesn't exactly fit these conventions, you can certainly write the getter, setter and backing field long hand like you would in Java. However, Groovy does provide a split definition capability which still provides a shortened syntax while allowing slight adjustments to the conventions. For a split definition, you write a field and a property with the same name and type. Only one of the field or property may have an initial value. For split properties, annotations on the field remain on the backing field for the property. Annotations on the property part of the definition are copied onto the getter and setter methods. This mechanism allows a number of common variations that property users may wish to use if the standard property definition doesn't exactly fit their needs. For example, if the backing field should be `protected` rather than `private`: [source,groovy] ---- class HasPropertyWithProtectedField { protected String name // <1> String name // <2> } ---- <1> Protected backing field for name property instead of normal private one <2> Declare name property Or, the same example but with a package-private backing field: [source,groovy] ---- class HasPropertyWithPackagePrivateField { String name // <1> @PackageScope String name // <2> } ---- <1> Declare name property <2> Package-private backing field for name property instead of normal private one As a final example, we may wish to apply method-related AST transforms, or in general, any annotation to the setters/getters, e.g. to have the accessors be synchronized: [source,groovy] ---- class HasPropertyWithSynchronizedAccessorMethods { private String name // <1> @Synchronized String name // <2> } ---- <1> Backing field for name property <2> Declare name property with annotation for setter/getter ===== Explicit accessor methods The automatic generation of accessor methods doesn't occur if there is an explicit definition of the getter or setter in the class. This allows you to modify the normal behavior of such a getter or setter if needed. Inherited accessor methods aren't normally considered but if an inherited accessor method is marked final, that will also cause no generation of an additional accessor method to honor the `final` requirement of no subclassing of such methods. === Annotation [[ann-definition]] ==== Annotation definition An annotation is a kind of special interface dedicated at annotating elements of the code. An annotation is a type which superinterface is the jdk:java.lang.annotation.Annotation[Annotation] interface. Annotations are declared in a very similar way to interfaces, using the `@interface` keyword: [source,groovy] ---- include::../test/ClassTest.groovy[tags=define_annotation,indent=0] ---- An annotation may define members in the form of methods without bodies and an optional default value. The possible member types are limited to: * primitive types * jdk:java.lang.String[Strings] * jdk:java.lang.Class[Classes] * an jdk:java.lang.Enum[enumeration] * another jdk:java.lang.annotation.Annotation[annotation type] * or any array of the above For example: [source,groovy] ---- include::../test/ClassTest.groovy[tags=ann_member_string,indent=0] include::../test/ClassTest.groovy[tags=ann_member_string_default,indent=0] include::../test/ClassTest.groovy[tags=ann_member_int,indent=0] include::../test/ClassTest.groovy[tags=ann_member_class,indent=0] include::../test/ClassTest.groovy[tags=ann_member_annotation,indent=0] include::../test/ClassTest.groovy[tags=ann_member_enum,indent=0] ---- <1> an annotation defining a `value` member of type `String` <2> an annotation defining a `value` member of type `String` with a default value of `something` <3> an annotation defining a `step` member of type the primitive type `int` <4> an annotation defining a `appliesTo` member of type `Class` <5> an annotation defining a `value` member which type is an array of another annotation type <6> an annotation defining a `dayOfWeek` member which type is the enumeration type `DayOfWeek` Unlike in the Java language, in Groovy, an annotation can be used to alter the semantics of the language. It is especially true of AST transformations which will generate code based on annotations. [[ann-placement]] ==== Annotation placement An annotation can be applied on various elements of the code: [source,groovy] ---- include::../test/ClassTest.groovy[tags=apply_annotation_1,indent=0] ---- <1> `@SomeAnnotation` applies to the `someMethod` method <2> `@SomeAnnotation` applies to the `SomeClass` class <3> `@SomeAnnotation` applies to the `var` variable In order to limit the scope where an annotation can be applied, it is necessary to declare it on the annotation definition, using the jdk:java.lang.annotation.Target[Target] annotation. For example, here is how you would declare that an annotation can be applied to a class or a method: [source,groovy] ---- include::../test/ClassTest.groovy[tags=ann_target,indent=0] ---- <1> the `@Target` annotation is meant to annotate an annotation with a scope. <2> `@SomeAnnotation` will therefore only be allowed on `TYPE` or `METHOD` The list of possible targets is available in the jdk:java.lang.annotation.ElementType[ElementType enumeration]. WARNING: Groovy does not support the jdk:java.lang.annotation.ElementType#TYPE_PARAMETER[TYPE_PARAMETER] and jdk:java.lang.annotation.ElementType#TYPE_PARAMETER[TYPE_USE] element types which were introduced in Java 8. ==== Annotation member values When an annotation is used, it is required to set at least all members that do not have a default value. For example: [source,groovy] ---- include::../test/ClassTest.groovy[tags=annotation_value_set,indent=0] ---- However it is possible to omit `value=` in the declaration of the value of an annotation if the member `value` is the only one being set: [source,groovy] ---- include::../test/ClassTest.groovy[tags=annotation_value_set_option,indent=0] ---- <1> we can omit the `statusCode` because it has a default value, but `value` needs to be set <2> since `value` is the only mandatory member without a default, we can omit `value=` <3> if both `value` and `statusCode` need to be set, it is required to use `value=` for the default `value` member ==== Retention policy The visibility of an annotation depends on its retention policy. The retention policy of an annotation is set using the jdk:java.lang.annotation.Retention[Retention] annotation: [source,groovy] ---- include::../test/ClassTest.groovy[tags=ann_retention,indent=0] ---- <1> the `@Retention` annotation annotates the `@SomeAnnotation` annotation <2> so `@SomeAnnotation` will have a `SOURCE` retention The list of possible retention targets and description is available in the jdk:java.lang.annotation.RetentionPolicy[RetentionPolicy] enumeration. The choice usually depends on whether you want an annotation to be visible at compile time or runtime. ==== Closure annotation parameters An interesting feature of annotations in Groovy is that you can use a closure as an annotation value. Therefore annotations may be used with a wide variety of expressions and still have IDE support. For example, imagine a framework where you want to execute some methods based on environmental constraints like the JDK version or the OS. One could write the following code: [source,groovy] ---- include::../test/ClassTest.groovy[tags=closure_ann_example,indent=0] ---- For the `@OnlyIf` annotation to accept a `Closure` as an argument, you only have to declare the `value` as a `Class`: [source,groovy] ---- include::../test/ClassTest.groovy[tags=closure_ann_def,indent=0] ---- To complete the example, let's write a sample runner that would use that information: [source,groovy] ---- include::../test/ClassTest.groovy[tags=closure_ann_runner,indent=0] ---- <1> create a new instance of the class passed as an argument (the task class) <2> emulate an environment which is JDK 6 and not Windows <3> iterate on all declared methods of the task class <4> if the method is public and takes no-argument <5> try to find the `@OnlyIf` annotation <6> if it is found get the `value` and create a new `Closure` out of it <7> set the `delegate` of the closure to our environment variable <8> call the closure, which is the annotation closure. It will return a `boolean` <9> if it is `true`, call the method <10> if the method is not annotated with `@OnlyIf`, execute the method anyway <11> after that, return the task object Then the runner can be used this way: [source,groovy] ---- include::../test/ClassTest.groovy[tags=closure_ann_runner_exec,indent=0] ---- ==== Meta-annotations ===== Declaring meta-annotations Meta-annotations, also known as annotation aliases are annotations that are replaced at compile time by other annotations (one meta-annotation is an alias for one or more annotations). Meta-annotations can be used to reduce the size of code involving multiple annotations. Let’s start with a simple example. Imagine you have the `@Service` and `@Transactional` annotations and that you want to annotate a class with both: [source,groovy] ---- include::../test/ClassTest.groovy[tags=transactionalservice_class,indent=0] ---- Given the multiplication of annotations that you could add to the same class, a meta-annotation could help by reducing the two annotations with a single one having the very same semantics. For example, we might want to write this instead: [source,groovy] ---- include::../test/ClassTest.groovy[tags=transactionalservice_class2,indent=0] ---- <1> `@TransactionalService` is a meta-annotation A meta-annotation is declared as a regular annotation but annotated with `@AnnotationCollector` and the list of annotations it is collecting. In our case, the `@TransactionalService` annotation can be written: [source,groovy] ---- include::../test/ClassTest.groovy[tags=metaann_ts,indent=0] ---- <1> annotate the meta-annotation with `@Service` <2> annotate the meta-annotation with `@Transactional` <3> annotate the meta-annotation with `@AnnotationCollector` [[meta-ann-behavior]] ===== Behavior of meta-annotations Groovy supports both _precompiled_ and _source form_ meta-annotations. This means that your meta-annotation _may_ be precompiled, or you can have it in the same source tree as the one you are currently compiling. INFO: Meta-annotations are a Groovy-only feature. There is no chance for you to annotate a Java class with a meta-annotation and hope it will do the same as in Groovy. Likewise, you cannot write a meta-annotation in Java: both the meta-annotation definition *and* usage have to be Groovy code. But you can happily collect Java annotations and Groovy annotations within your meta-annotation. When the Groovy compiler encounters a class annotated with a meta-annotation, it *replaces* it with the collected annotations. So, in our previous example, it will replace `@TransactionalService` with `@Transactional` and `@Service`: [source,groovy] ---- include::../test/ClassTest.groovy[tags=annotations_expanded,indent=0] ---- The conversion from a meta-annotation to the collected annotations is performed during the _semantic analysis_ compilation phase.  In addition to replacing the alias with the collected annotations, a meta-annotation is capable of processing them, including arguments. [[meta-ann-members]] ===== Meta-annotation parameters Meta-annotations can collect annotations which have parameters. To illustrate this, we will imagine two annotations, each of them accepting one argument: [source,groovy] ---- include::../test/ClassTest.groovy[tags=collected_ann_explosive,indent=0] ---- And suppose that you want create a meta-annotation named `@Explosive`: [source,groovy] ---- include::../test/ClassTest.groovy[tags=collected_ann_explosive,indent=0] include::../test/ClassTest.groovy[tags=collector_ann_explosive,indent=0] ---- By default, when the annotations are replaced, they will get the annotation parameter values *as they were defined in the alias*. More interesting, the meta-annotation supports overriding specific values: [source,groovy] ---- include::../test/ClassTest.groovy[tags=example_bomb,indent=0] ---- <1> the `after` value provided as a parameter to `@Explosive` overrides the one defined in the `@Timeout` annotation If two annotations define the same parameter name, the default processor will copy the annotation value to all annotations that accept this parameter: [source,groovy] ---- include::../test/ClassTest.groovy[tags=collector_ann_same_values,indent=0] ---- <1> the `@Foo` annotation defines the `value` member of type `String` <2> the `@Bar` annotation also defines the `value` member of type `String` <3> the `@FooBar` meta-annotation aggregates `@Foo` and `@Bar` <4> class `Bob` is annotated with `@Foo` and `@Bar` <5> the value of the `@Foo` annotation on `Bob` is `a` <6> while the value of the `@Bar` annotation on `Bob` is `b` <7> class `Joe` is annotated with `@FooBar` <8> then the value of the `@Foo` annotation on `Joe` is `a` <9> and the value of the `@Bar` annotation on `Joe` is also `a` In the second case, the meta-annotation value was copied in both `@Foo` and `@Bar` annotations. WARNING: It is a compile time error if the collected annotations define the same members with incompatible types. For example if on the previous example `@Foo` defined a value of type `String` but `@Bar` defined a value of type `int`. It is however possible to customize the behavior of meta-annotations and describe how collected annotations are expanded. We'll look at how to do that shortly but first there is an advanced processing option to cover. [[handling_duplicate_annotations]] ===== Handling duplicate annotations The `@AnnotationCollector` annotation supports a `mode` parameter which can be used to alter how the default processor handles annotation replacement in the presence of duplicate annotations. INFO: Custom processors (discussed next) may or may not support this parameter. As an example, suppose you create a meta-annotation containing the `@ToString` annotation and then place your meta-annotation on a class that already has an explicit `@ToString` annotation. Should this be an error? Should both annotations be applied? Does one take priority over the other? There is no correct answer. In some scenarios it might be quite appropriate for any of these answers to be correct. So, rather than trying to preempt one correct way to handle the duplicate annotation issue, Groovy let's you write your own custom meta-annotation processors (covered next) and let's you write whatever checking logic you like within AST transforms - which are a frequent target for aggregating. Having said that, by simply setting the `mode`, a number of commonly expected scenarios are handled automatically for you within any extra coding. The behavior of the `mode` parameter is determined by the `AnnotationCollectorMode` enum value chosen and is summarized in the following table. |================================ | Mode | Description | DUPLICATE | Annotations from the annotation collection will always be inserted. After all transforms have been run, it will be an error if multiple annotations (excluding those with SOURCE retention) exist. | PREFER_COLLECTOR | Annotations from the collector will be added and any existing annotations with the same name will be removed. | PREFER_COLLECTOR_MERGED | Annotations from the collector will be added and any existing annotations with the same name will be removed but any new parameters found within existing annotations will be merged into the added annotation. | PREFER_EXPLICIT | Annotations from the collector will be ignored if any existing annotations with the same name are found. | PREFER_EXPLICIT_MERGED | Annotations from the collector will be ignored if any existing annotations with the same name are found but any new parameters on the collector annotation will be added to existing annotations. |================================ [[meta-ann-processor]] ===== Custom annotation processors A custom annotation processor will let you choose how to expand a meta-annotation into collected annotations. The behaviour of the meta-annotation is, in this case, totally up to you. To do this, you must: * create a meta-annotation processor, extending gapi:org.codehaus.groovy.transform.AnnotationCollectorTransform[AnnotationCollectorTransform] * declare the processor to be used in the meta-annotation declaration To illustrate this, we are going to explore how the meta-annotation `@CompileDynamic` is implemented. `@CompileDynamic` is a meta-annotation that expands itself to `@CompileStatic(TypeCheckingMode.SKIP)`. The problem is that the default meta annotation processor doesn’t support enums and the annotation value `TypeCheckingMode.SKIP` is one. The naive implementation here would not work: [source,groovy] ---- include::../test/ClassTest.groovy[tags=compiledynamic_naive,indent=0] ---- Instead, we will define it like this: [source,groovy] ---- include::../test/ClassTest.groovy[tags=compiledynamic_def_fixed,indent=0] ---- The first thing you may notice is that our interface is no longer annotated with `@CompileStatic`. The reason for this is that we rely on the `processor` parameter instead, that references a class which will *generate* the annotation. Here is how the custom processor is implemented: [source,groovy] .CompileDynamicProcessor.groovy ---- include::../test/ClassTest.groovy[tags=compiledynamic_processor,indent=0] ---- <1> our custom processor is written in Groovy, and for better compilation performance, we use static compilation <2> the custom processor has to extend gapi:org.codehaus.groovy.transform.AnnotationCollectorTransform[AnnotationCollectorTransform] <3> create a class node representing the `@CompileStatic` annotation type <4> create a class node representing the `TypeCheckingMode` enum type <5> `collector` is the `@AnnotationCollector` node found in the meta-annotation. Usually unused. <6> `aliasAnnotationUsage` is the meta-annotation being expanded, here it is `@CompileDynamic` <7> `aliasAnnotated` is the node being annotated with the meta-annotation <8> `sourceUnit` is the `SourceUnit` being compiled <9> we create a new annotation node for `@CompileStatic` <10> we create an expression equivalent to `TypeCheckingMode.SKIP` <11> we add that expression to the annotation node, which is now `@CompileStatic(TypeCheckingMode.SKIP)` <12> return the generated annotation In the example, the `visit` method is the only method which has to be overridden. It is meant to return a list of annotation nodes that will be added to the node annotated with the meta-annotation. In this example, we return a single one corresponding to `@CompileStatic(TypeCheckingMode.SKIP)`. [[generics]] === Generics (TBD) include::_traits.adoc[leveloffset=+1] include::_sealed.adoc[leveloffset=+1] ",12191,False,2080.186865155141,median "CLASS zcl_abapgit_object_srvd DEFINITION PUBLIC INHERITING FROM zcl_abapgit_objects_super FINAL. PUBLIC SECTION. INTERFACES zif_abapgit_object. METHODS: constructor IMPORTING is_item TYPE zif_abapgit_definitions=>ty_item iv_language TYPE spras RAISING zcx_abapgit_exception. PROTECTED SECTION. PRIVATE SECTION. DATA mv_service_definition_key TYPE seu_objkey . DATA mr_service_definition TYPE REF TO data . CONSTANTS mc_source_file TYPE string VALUE 'srvdsrv' ##NO_TEXT. CONSTANTS mc_xml_parent_name TYPE string VALUE 'SRVD' ##NO_TEXT. DATA mo_object_operator TYPE REF TO object . METHODS clear_fields CHANGING !cs_metadata TYPE any . METHODS clear_field IMPORTING !iv_fieldname TYPE csequence CHANGING !cs_metadata TYPE any . METHODS get_object_data IMPORTING !io_xml TYPE REF TO zif_abapgit_xml_input RETURNING VALUE(ro_object_data) TYPE REF TO if_wb_object_data_model RAISING zcx_abapgit_exception . METHODS get_wb_object_operator RETURNING VALUE(ro_object_operator) TYPE REF TO object RAISING zcx_abapgit_exception . METHODS merge_object_data IMPORTING !io_object_data TYPE REF TO object RETURNING VALUE(ro_object_data_merged) TYPE REF TO if_wb_object_data_model RAISING zcx_abapgit_exception . METHODS is_delete_tadir RETURNING VALUE(rv_delete_tadir) TYPE abap_bool . ENDCLASS. CLASS zcl_abapgit_object_srvd IMPLEMENTATION. METHOD clear_field. FIELD-SYMBOLS: TYPE data. ASSIGN COMPONENT iv_fieldname OF STRUCTURE cs_metadata TO . IF sy-subrc = 0. CLEAR: . ENDIF. ENDMETHOD. METHOD clear_fields. clear_field( EXPORTING iv_fieldname = 'VERSION' CHANGING cs_metadata = cs_metadata ). clear_field( EXPORTING iv_fieldname = 'CREATED_AT' CHANGING cs_metadata = cs_metadata ). clear_field( EXPORTING iv_fieldname = 'CREATED_BY' CHANGING cs_metadata = cs_metadata ). clear_field( EXPORTING iv_fieldname = 'CHANGED_AT' CHANGING cs_metadata = cs_metadata ). clear_field( EXPORTING iv_fieldname = 'CHANGED_BY' CHANGING cs_metadata = cs_metadata ). clear_field( EXPORTING iv_fieldname = 'RESPONSIBLE' CHANGING cs_metadata = cs_metadata ). clear_field( EXPORTING iv_fieldname = 'PACKAGE_REF' CHANGING cs_metadata = cs_metadata ). clear_field( EXPORTING iv_fieldname = 'MASTER_SYSTEM' CHANGING cs_metadata = cs_metadata ). clear_field( EXPORTING iv_fieldname = 'DT_UUID' CHANGING cs_metadata = cs_metadata ). clear_field( EXPORTING iv_fieldname = 'ABAP_LANGUAGE_VERSION' CHANGING cs_metadata = cs_metadata ). clear_field( EXPORTING iv_fieldname = 'ABAP_LANGU_VERSION' CHANGING cs_metadata = cs_metadata ). clear_field( EXPORTING iv_fieldname = 'LINKS' CHANGING cs_metadata = cs_metadata ). ENDMETHOD. METHOD constructor. super->constructor( is_item = is_item iv_language = iv_language ). mv_service_definition_key = ms_item-obj_name. TRY. CREATE DATA mr_service_definition TYPE ('CL_SRVD_WB_OBJECT_DATA=>TY_SRVD_OBJECT_DATA'). CATCH cx_sy_create_error. zcx_abapgit_exception=>raise( |SRVD not supported by your NW release| ). ENDTRY. ENDMETHOD. METHOD get_object_data. DATA: lr_metadata TYPE REF TO data, lr_data TYPE REF TO data. FIELD-SYMBOLS: TYPE any, TYPE any, TYPE any, TYPE any. CREATE DATA lr_data TYPE ('CL_SRVD_WB_OBJECT_DATA=>TY_SRVD_OBJECT_DATA'). ASSIGN lr_data->* TO . ASSERT sy-subrc = 0. ASSIGN COMPONENT 'METADATA' OF STRUCTURE TO . ASSERT sy-subrc = 0. CREATE DATA lr_metadata TYPE ('CL_SRVD_WB_OBJECT_DATA=>TY_METADATA_EXTENDED'). ASSIGN lr_metadata->* TO . ASSERT sy-subrc = 0. io_xml->read( EXPORTING iv_name = mc_xml_parent_name CHANGING cg_data = ). = . ASSIGN COMPONENT 'CONTENT-SOURCE' OF STRUCTURE TO . ASSERT sy-subrc = 0. = zif_abapgit_object~mo_files->read_string( mc_source_file ). IF IS INITIAL. = zif_abapgit_object~mo_files->read_string( 'assrvd' ). ENDIF. CREATE OBJECT ro_object_data TYPE ('CL_SRVD_WB_OBJECT_DATA'). ro_object_data->set_data( p_data = ). ENDMETHOD. METHOD get_wb_object_operator. DATA: ls_object_type TYPE wbobjtype, lx_error TYPE REF TO cx_root. IF mo_object_operator IS BOUND. ro_object_operator = mo_object_operator. ENDIF. ls_object_type-objtype_tr = 'SRVD'. ls_object_type-subtype_wb = 'SRV'. TRY. CALL METHOD ('CL_WB_OBJECT_OPERATOR')=>('CREATE_INSTANCE') EXPORTING object_type = ls_object_type object_key = mv_service_definition_key RECEIVING result = mo_object_operator. CATCH cx_root INTO lx_error. zcx_abapgit_exception=>raise_with_text( lx_error ). ENDTRY. ro_object_operator = mo_object_operator. ENDMETHOD. METHOD is_delete_tadir. rv_delete_tadir = abap_true. ENDMETHOD. METHOD merge_object_data. DATA: lo_object_data TYPE REF TO object, lo_object_data_old TYPE REF TO if_wb_object_data_model, lr_new TYPE REF TO data, lr_old TYPE REF TO data, lo_wb_object_operator TYPE REF TO object. FIELD-SYMBOLS: TYPE any, TYPE any, TYPE any, TYPE any. CREATE OBJECT lo_object_data TYPE ('CL_SRVD_WB_OBJECT_DATA'). lo_object_data = io_object_data. CREATE DATA lr_new TYPE ('CL_SRVD_WB_OBJECT_DATA=>TY_SRVD_OBJECT_DATA'). ASSIGN lr_new->* TO . ASSERT sy-subrc = 0. CREATE DATA lr_old TYPE ('CL_SRVD_WB_OBJECT_DATA=>TY_SRVD_OBJECT_DATA'). ASSIGN lr_old->* TO . ASSERT sy-subrc = 0. CALL METHOD lo_object_data->('IF_WB_OBJECT_DATA_MODEL~GET_DATA') EXPORTING p_metadata_only = abap_false p_data_selection = 'AL' IMPORTING p_data = . lo_wb_object_operator = get_wb_object_operator( ). CALL METHOD lo_wb_object_operator->('IF_WB_OBJECT_OPERATOR~READ') EXPORTING data_selection = 'AL' "" if_wb_object_data_selection_co=>c_all_data IMPORTING eo_object_data = lo_object_data_old. CALL METHOD lo_object_data_old->('GET_DATA') EXPORTING p_metadata_only = abap_false p_data_selection = 'AL' "" if_wb_object_data_selection_co=>c_all_data IMPORTING p_data = . ASSIGN COMPONENT 'METADATA-DESCRIPTION' OF STRUCTURE TO . ASSIGN COMPONENT 'METADATA-DESCRIPTION' OF STRUCTURE TO . = . ASSIGN COMPONENT 'CONTENT-SOURCE' OF STRUCTURE TO . ASSIGN COMPONENT 'CONTENT-SOURCE' OF STRUCTURE TO . = . CREATE OBJECT ro_object_data_merged TYPE ('CL_SRVD_WB_OBJECT_DATA'). CALL METHOD ro_object_data_merged->('SET_DATA') EXPORTING p_data = . ENDMETHOD. METHOD zif_abapgit_object~changed_by. DATA: li_object_data_model TYPE REF TO if_wb_object_data_model, li_wb_object_operator TYPE REF TO object, lx_error TYPE REF TO cx_root. li_wb_object_operator = get_wb_object_operator( ). TRY. CALL METHOD li_wb_object_operator->('IF_WB_OBJECT_OPERATOR~READ') IMPORTING eo_object_data = li_object_data_model. rv_user = li_object_data_model->get_changed_by( ). CATCH cx_root INTO lx_error. zcx_abapgit_exception=>raise_with_text( lx_error ). ENDTRY. ENDMETHOD. METHOD zif_abapgit_object~delete. DATA: lx_error TYPE REF TO cx_root, li_wb_object_operator TYPE REF TO object. li_wb_object_operator = get_wb_object_operator( ). TRY. CALL METHOD li_wb_object_operator->('IF_WB_OBJECT_OPERATOR~DELETE') EXPORTING transport_request = iv_transport. CATCH cx_root INTO lx_error. zcx_abapgit_exception=>raise_with_text( lx_error ). ENDTRY. ENDMETHOD. METHOD zif_abapgit_object~deserialize. DATA: lo_object_data TYPE REF TO if_wb_object_data_model, lx_error TYPE REF TO cx_root, lo_wb_object_operator TYPE REF TO object, lo_merged_data_all TYPE REF TO if_wb_object_data_model, lo_merged_data_prop TYPE REF TO if_wb_object_data_model, lo_merged_data_cont TYPE REF TO if_wb_object_data_model, lr_wbobjtype TYPE REF TO data, lr_category TYPE REF TO data. FIELD-SYMBOLS: TYPE any, TYPE any, TYPE any. TRY. lo_object_data = get_object_data( io_xml ). lo_wb_object_operator = get_wb_object_operator( ). CREATE DATA lr_wbobjtype TYPE ('WBOBJTYPE'). ASSIGN lr_wbobjtype->* TO . ASSIGN COMPONENT 'OBJTYPE_TR' OF STRUCTURE TO . = 'SRVD'. ASSIGN COMPONENT 'SUBTYPE_WB' OF STRUCTURE TO . = 'SRV'. CREATE DATA lr_category TYPE ('WBADT_RESOURCE_CATEGORY'). ASSIGN lr_category->* TO . CALL METHOD ('CL_BLUE_WB_UTILITY')=>('GET_RESOURCE_CATEGORY') EXPORTING is_object_type = RECEIVING result = . lo_wb_object_operator = get_wb_object_operator( ). tadir_insert( iv_package ). IF zif_abapgit_object~exists( ) = abap_false. CASE . WHEN '1'. ""if_wb_adt_plugin_resource_co=>co_sfs_res_category_atomic. CALL METHOD lo_wb_object_operator->('IF_WB_OBJECT_OPERATOR~CREATE') EXPORTING io_object_data = lo_object_data data_selection = 'AL' ""if_wb_object_data_selection_co=>c_all_data version = 'I' ""swbm_version_inactive package = iv_package transport_request = iv_transport. WHEN '2'. ""if_wb_adt_plugin_resource_co=>co_sfs_res_category_compound_s. CALL METHOD lo_wb_object_operator->('IF_WB_OBJECT_OPERATOR~CREATE') EXPORTING io_object_data = lo_object_data data_selection = 'P' ""if_wb_object_data_selection_co=>c_properties version = 'I' ""swbm_version_inactive package = iv_package transport_request = iv_transport. CALL METHOD lo_wb_object_operator->('IF_WB_OBJECT_OPERATOR~UPDATE') EXPORTING io_object_data = lo_object_data data_selection = 'D' ""if_wb_object_data_selection_co=>c_data_content version = 'I' ""swbm_version_inactive transport_request = iv_transport. WHEN OTHERS. zcx_abapgit_exception=>raise( |Category '{ }' not supported| ). ENDCASE. ELSE. CASE . WHEN '1'. ""if_wb_adt_plugin_resource_co=>co_sfs_res_category_atomic. lo_merged_data_all = merge_object_data( lo_object_data ). CALL METHOD lo_wb_object_operator->('IF_WB_OBJECT_OPERATOR~UPDATE') EXPORTING io_object_data = lo_merged_data_all data_selection = 'AL' ""if_wb_object_data_selection_co=>c_all_data version = 'I' ""swbm_version_inactive transport_request = iv_transport. WHEN '2'. ""if_wb_adt_plugin_resource_co=>co_sfs_res_category_compound_s. lo_merged_data_prop = merge_object_data( lo_object_data ). lo_merged_data_cont = merge_object_data( lo_object_data ). CALL METHOD lo_wb_object_operator->('IF_WB_OBJECT_OPERATOR~UPDATE') EXPORTING io_object_data = lo_merged_data_prop data_selection = 'P' ""if_wb_object_data_selection_co=>c_properties version = 'I' ""swbm_version_inactive transport_request = iv_transport. CALL METHOD lo_wb_object_operator->('IF_WB_OBJECT_OPERATOR~UPDATE') EXPORTING io_object_data = lo_merged_data_cont data_selection = 'D' ""if_wb_object_data_selection_co=>c_data_content version = 'I' ""swbm_version_inactive transport_request = iv_transport. WHEN OTHERS. zcx_abapgit_exception=>raise( |Category '{ }' not supported| ). ENDCASE. ENDIF. corr_insert( iv_package ). CATCH cx_root INTO lx_error. zcx_abapgit_exception=>raise_with_text( lx_error ). ENDTRY. zcl_abapgit_objects_activation=>add_item( ms_item ). ENDMETHOD. METHOD zif_abapgit_object~exists. DATA lo_object_data TYPE REF TO if_wb_object_data_model. DATA lo_wb_object_operator TYPE REF TO object. TRY. lo_wb_object_operator = get_wb_object_operator( ). CALL METHOD lo_wb_object_operator->('IF_WB_OBJECT_OPERATOR~READ') EXPORTING data_selection = 'P' IMPORTING eo_object_data = lo_object_data. rv_bool = boolc( lo_object_data IS NOT INITIAL AND lo_object_data->get_object_key( ) IS NOT INITIAL ). CATCH cx_root. rv_bool = abap_false. ENDTRY. ENDMETHOD. METHOD zif_abapgit_object~get_comparator. RETURN. ENDMETHOD. METHOD zif_abapgit_object~get_deserialize_steps. APPEND zif_abapgit_object=>gc_step_id-abap TO rt_steps. ENDMETHOD. METHOD zif_abapgit_object~get_metadata. rs_metadata = get_metadata( ). rs_metadata-delete_tadir = is_delete_tadir( ). ENDMETHOD. METHOD zif_abapgit_object~is_active. rv_active = is_active( ). ENDMETHOD. METHOD zif_abapgit_object~is_locked. rv_is_locked = exists_a_lock_entry_for( iv_lock_object = 'ESWB_EO' iv_argument = |{ ms_item-obj_type }{ ms_item-obj_name }| ). ENDMETHOD. METHOD zif_abapgit_object~jump. "" Covered by ZCL_ABAPGIT_OBJECTS=>JUMP ENDMETHOD. METHOD zif_abapgit_object~serialize. DATA: li_object_data_model TYPE REF TO if_wb_object_data_model, li_wb_object_operator TYPE REF TO object, lx_error TYPE REF TO cx_root, lv_source TYPE string. FIELD-SYMBOLS: TYPE any, TYPE any, TYPE string. ASSIGN mr_service_definition->* TO . ASSERT sy-subrc = 0. TRY. li_wb_object_operator = get_wb_object_operator( ). CALL METHOD li_wb_object_operator->('IF_WB_OBJECT_OPERATOR~READ') EXPORTING version = 'A' data_selection = 'AL' IMPORTING ""data = eo_object_data = li_object_data_model. CALL METHOD li_object_data_model->('GET_DATA') IMPORTING p_data = . ASSIGN COMPONENT 'METADATA' OF STRUCTURE TO . ASSERT sy-subrc = 0. clear_fields( CHANGING cs_metadata = ). ASSIGN COMPONENT 'CONTENT-SOURCE' OF STRUCTURE TO . ASSERT sy-subrc = 0. lv_source = . io_xml->add( iv_name = mc_xml_parent_name ig_data = ). zif_abapgit_object~mo_files->add_string( iv_ext = mc_source_file iv_string = lv_source ). CATCH cx_root INTO lx_error. zcx_abapgit_exception=>raise_with_text( lx_error ). ENDTRY. ENDMETHOD. ENDCLASS. ",4139,False,951.5163396055544,median "CLASS zcl_abapgit_objects DEFINITION PUBLIC CREATE PUBLIC . PUBLIC SECTION. TYPES: ty_types_tt TYPE SORTED TABLE OF tadir-object WITH UNIQUE KEY table_line . TYPES: BEGIN OF ty_serialization, files TYPE zif_abapgit_definitions=>ty_files_tt, item TYPE zif_abapgit_definitions=>ty_item, END OF ty_serialization . CLASS-METHODS serialize IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item !iv_language TYPE spras !iv_main_language_only TYPE abap_bool DEFAULT abap_false !it_translation_langs TYPE zif_abapgit_definitions=>ty_languages OPTIONAL RETURNING VALUE(rs_files_and_item) TYPE ty_serialization RAISING zcx_abapgit_exception . CLASS-METHODS deserialize IMPORTING !io_repo TYPE REF TO zcl_abapgit_repo !is_checks TYPE zif_abapgit_definitions=>ty_deserialize_checks !ii_log TYPE REF TO zif_abapgit_log RETURNING VALUE(rt_accessed_files) TYPE zif_abapgit_definitions=>ty_file_signatures_tt RAISING zcx_abapgit_exception . CLASS-METHODS deserialize_checks IMPORTING !io_repo TYPE REF TO zcl_abapgit_repo RETURNING VALUE(rs_checks) TYPE zif_abapgit_definitions=>ty_deserialize_checks RAISING zcx_abapgit_exception . CLASS-METHODS delete IMPORTING !it_tadir TYPE zif_abapgit_definitions=>ty_tadir_tt !is_checks TYPE zif_abapgit_definitions=>ty_delete_checks OPTIONAL !ii_log TYPE REF TO zif_abapgit_log OPTIONAL RAISING zcx_abapgit_exception . CLASS-METHODS jump IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item !iv_line_number TYPE i OPTIONAL !iv_sub_obj_name TYPE zif_abapgit_definitions=>ty_item-obj_name OPTIONAL !iv_sub_obj_type TYPE zif_abapgit_definitions=>ty_item-obj_type OPTIONAL RAISING zcx_abapgit_exception . CLASS-METHODS changed_by IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item RETURNING VALUE(rv_user) TYPE syuname . CLASS-METHODS is_supported IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item !iv_native_only TYPE abap_bool DEFAULT abap_false RETURNING VALUE(rv_bool) TYPE abap_bool . CLASS-METHODS is_type_supported IMPORTING !iv_obj_type TYPE zif_abapgit_definitions=>ty_item-obj_type RETURNING VALUE(rv_bool) TYPE abap_bool . CLASS-METHODS exists IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item RETURNING VALUE(rv_bool) TYPE abap_bool . CLASS-METHODS supported_list RETURNING VALUE(rt_types) TYPE ty_types_tt . CLASS-METHODS is_active IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item RETURNING VALUE(rv_active) TYPE abap_bool RAISING zcx_abapgit_exception . PROTECTED SECTION. PRIVATE SECTION. TYPES: BEGIN OF ty_supported_types, obj_type TYPE tadir-object, supported TYPE abap_bool, END OF ty_supported_types. TYPES: ty_supported_types_tt TYPE SORTED TABLE OF ty_supported_types WITH UNIQUE KEY obj_type. TYPES: BEGIN OF ty_obj_serializer_item, item TYPE zif_abapgit_definitions=>ty_item, metadata TYPE zif_abapgit_definitions=>ty_metadata, END OF ty_obj_serializer_item . TYPES: ty_obj_serializer_map TYPE SORTED TABLE OF ty_obj_serializer_item WITH UNIQUE KEY item . CLASS-DATA gt_obj_serializer_map TYPE ty_obj_serializer_map . CLASS-DATA gt_supported_obj_types TYPE ty_supported_types_tt . CLASS-DATA gv_supported_obj_types_loaded TYPE abap_bool . CLASS-METHODS check_duplicates IMPORTING !it_files TYPE zif_abapgit_definitions=>ty_files_tt RAISING zcx_abapgit_exception . CLASS-METHODS class_name IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item RETURNING VALUE(rv_class_name) TYPE string . CLASS-METHODS update_package_tree IMPORTING !iv_package TYPE devclass . CLASS-METHODS delete_object IMPORTING !iv_package TYPE devclass !is_item TYPE zif_abapgit_definitions=>ty_item !iv_transport TYPE trkorr RAISING zcx_abapgit_exception . CLASS-METHODS compare_remote_to_local IMPORTING !ii_object TYPE REF TO zif_abapgit_object !it_remote TYPE zif_abapgit_definitions=>ty_files_tt !is_result TYPE zif_abapgit_definitions=>ty_result !ii_log TYPE REF TO zif_abapgit_log RAISING zcx_abapgit_exception . CLASS-METHODS deserialize_objects IMPORTING !is_step TYPE zif_abapgit_objects=>ty_step_data !ii_log TYPE REF TO zif_abapgit_log !iv_transport TYPE trkorr CHANGING !ct_files TYPE zif_abapgit_definitions=>ty_file_signatures_tt RAISING zcx_abapgit_exception . CLASS-METHODS check_objects_locked IMPORTING !iv_language TYPE spras !it_items TYPE zif_abapgit_definitions=>ty_items_tt RAISING zcx_abapgit_exception . CLASS-METHODS create_object IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item !iv_language TYPE spras !is_metadata TYPE zif_abapgit_definitions=>ty_metadata OPTIONAL !iv_native_only TYPE abap_bool DEFAULT abap_false RETURNING VALUE(ri_obj) TYPE REF TO zif_abapgit_object RAISING zcx_abapgit_exception . CLASS-METHODS map_tadir_to_items IMPORTING !it_tadir TYPE zif_abapgit_definitions=>ty_tadir_tt RETURNING VALUE(rt_items) TYPE zif_abapgit_definitions=>ty_items_tt . CLASS-METHODS map_results_to_items IMPORTING !it_results TYPE zif_abapgit_definitions=>ty_results_tt RETURNING VALUE(rt_items) TYPE zif_abapgit_definitions=>ty_items_tt . CLASS-METHODS get_deserialize_steps RETURNING VALUE(rt_steps) TYPE zif_abapgit_objects=>ty_step_data_tt . CLASS-METHODS check_main_package IMPORTING !iv_package TYPE devclass !iv_obj_type TYPE tadir-object RAISING zcx_abapgit_exception . CLASS-METHODS change_package_assignments IMPORTING !is_item TYPE zif_abapgit_definitions=>ty_item !ii_log TYPE REF TO zif_abapgit_log . ENDCLASS. CLASS zcl_abapgit_objects IMPLEMENTATION. METHOD changed_by. DATA: li_obj TYPE REF TO zif_abapgit_object. "" For unsupported objects, return empty string IF is_type_supported( is_item-obj_type ) = abap_false. RETURN. ENDIF. TRY. li_obj = create_object( is_item = is_item iv_language = zif_abapgit_definitions=>c_english ). rv_user = li_obj->changed_by( ). CATCH zcx_abapgit_exception ##NO_HANDLER. "" Ignore errors ENDTRY. IF rv_user IS INITIAL. "" Eg. "".abapgit.xml"" file rv_user = zcl_abapgit_objects_super=>c_user_unknown. ENDIF. ENDMETHOD. METHOD change_package_assignments. CALL FUNCTION 'TR_TADIR_INTERFACE' EXPORTING wi_tadir_pgmid = 'R3TR' wi_tadir_object = is_item-obj_type wi_tadir_obj_name = is_item-obj_name wi_tadir_devclass = is_item-devclass wi_test_modus = abap_false EXCEPTIONS OTHERS = 1. IF sy-subrc = 0. ii_log->add_success( iv_msg = |Object { is_item-obj_name } assigned to package { is_item-devclass }| is_item = is_item ). ELSE. ii_log->add_error( iv_msg = |Package change of object { is_item-obj_name } failed| is_item = is_item ). ENDIF. ENDMETHOD. METHOD check_duplicates. DATA: lt_files TYPE zif_abapgit_definitions=>ty_files_tt, lv_path TYPE string, lv_filename TYPE string, lt_duplicates TYPE STANDARD TABLE OF string WITH DEFAULT KEY, lv_duplicates LIKE LINE OF lt_duplicates, lv_all_duplicates TYPE string. FIELD-SYMBOLS: LIKE LINE OF it_files. lt_files = it_files. SORT lt_files BY path ASCENDING filename ASCENDING. LOOP AT lt_files ASSIGNING . IF lv_path = -path AND lv_filename = -filename. CONCATENATE -path -filename INTO lv_duplicates. APPEND lv_duplicates TO lt_duplicates. ENDIF. lv_path = -path. lv_filename = -filename. ENDLOOP. IF lt_duplicates IS NOT INITIAL. CONCATENATE LINES OF lt_duplicates INTO lv_all_duplicates SEPARATED BY `, `. zcx_abapgit_exception=>raise( |Duplicates: { lv_all_duplicates }| ). ENDIF. ENDMETHOD. METHOD check_main_package. "" check package restrictions, closed package, descriptive or "" functional package cl_pak_object_types=>check_object_type( EXPORTING i_working_mode = 'I' i_package_name = iv_package i_pgmid = 'R3TR' i_object_type = iv_obj_type EXCEPTIONS wrong_object_type = 1 package_not_extensible = 2 package_not_loaded = 3 OTHERS = 4 ). CASE sy-subrc. WHEN 0. RETURN. WHEN 2. zcx_abapgit_exception=>raise( |Object type { iv_obj_type } not allowed for package { iv_package }| ). WHEN OTHERS. zcx_abapgit_exception=>raise_t100( ). ENDCASE. ENDMETHOD. METHOD check_objects_locked. DATA: li_obj TYPE REF TO zif_abapgit_object. FIELD-SYMBOLS: LIKE LINE OF it_items. LOOP AT it_items ASSIGNING . "" You should remember that we ignore not supported objects here, "" because otherwise the process aborts which is not desired IF is_type_supported( -obj_type ) = abap_false. CONTINUE. ENDIF. li_obj = create_object( is_item = iv_language = iv_language ). IF li_obj->is_locked( ) = abap_true. zcx_abapgit_exception=>raise( |Object { -obj_type } { -obj_name } | && |is locked. Action not possible.| ). ENDIF. ENDLOOP. ENDMETHOD. METHOD class_name. CONCATENATE 'ZCL_ABAPGIT_OBJECT_' is_item-obj_type INTO rv_class_name. ENDMETHOD. METHOD compare_remote_to_local. * this method is used for comparing local with remote objects * before pull, this is useful eg. when overwriting a TABL object. * only the main XML file is used for comparison DATA: ls_remote_file TYPE zif_abapgit_definitions=>ty_file, li_remote_version TYPE REF TO zif_abapgit_xml_input, lv_count TYPE i, ls_result TYPE zif_abapgit_comparator=>ty_result, lv_answer TYPE string, li_comparator TYPE REF TO zif_abapgit_comparator, ls_item TYPE zif_abapgit_definitions=>ty_item. FIND ALL OCCURRENCES OF '.' IN is_result-filename MATCH COUNT lv_count. IF is_result-filename CS '.XML' AND lv_count = 2. IF ii_object->exists( ) = abap_false. RETURN. ENDIF. READ TABLE it_remote WITH KEY file COMPONENTS filename = is_result-filename INTO ls_remote_file. IF sy-subrc <> 0. ""if file does not exist in remote, we don't need to validate RETURN. ENDIF. li_comparator = ii_object->get_comparator( ). IF NOT li_comparator IS BOUND. RETURN. ENDIF. CREATE OBJECT li_remote_version TYPE zcl_abapgit_xml_input EXPORTING iv_xml = zcl_abapgit_convert=>xstring_to_string_utf8( ls_remote_file-data ) iv_filename = ls_remote_file-filename. ls_result = li_comparator->compare( ii_remote = li_remote_version ii_log = ii_log ). IF ls_result-text IS INITIAL. RETURN. ENDIF. ""log comparison result ls_item-obj_type = is_result-obj_type. ls_item-obj_name = is_result-obj_name. ii_log->add_warning( iv_msg = ls_result-text is_item = ls_item ). ""continue or abort? IF zcl_abapgit_ui_factory=>get_frontend_services( )->gui_is_available( ) = abap_true. lv_answer = zcl_abapgit_ui_factory=>get_popups( )->popup_to_confirm( iv_titlebar = 'Warning' iv_text_question = ls_result-text iv_text_button_1 = 'Pull Anyway' iv_icon_button_1 = 'ICON_OKAY' iv_text_button_2 = 'Cancel' iv_icon_button_2 = 'ICON_CANCEL' iv_default_button = '2' iv_display_cancel_button = abap_false ). IF lv_answer = '2'. zcx_abapgit_exception=>raise( |Deserialization for object { is_result-obj_name } | & |(type { is_result-obj_type }) aborted by user| ). ENDIF. ELSE. zcx_abapgit_exception=>raise( |Deserialization for object { is_result-obj_name } | & |(type { is_result-obj_type }) aborted, user descision required| ). ENDIF. ENDIF. ENDMETHOD. METHOD create_object. DATA: lv_message TYPE string, lv_class_name TYPE string, ls_obj_serializer_map LIKE LINE OF gt_obj_serializer_map. READ TABLE gt_obj_serializer_map INTO ls_obj_serializer_map WITH KEY item = is_item. IF sy-subrc = 0. lv_class_name = ls_obj_serializer_map-metadata-class. ELSEIF is_metadata IS NOT INITIAL. * Metadata is provided only on deserialization * Once this has been triggered, the same deserializer shall be used * for subsequent processes. * Thus, buffer the metadata afterwards ls_obj_serializer_map-item = is_item. ls_obj_serializer_map-metadata = is_metadata. INSERT ls_obj_serializer_map INTO TABLE gt_obj_serializer_map. lv_class_name = is_metadata-class. ELSE. lv_class_name = class_name( is_item ). ENDIF. REPLACE FIRST OCCURRENCE OF 'LCL' IN lv_class_name WITH 'ZCL_ABAPGIT'. TRY. CREATE OBJECT ri_obj TYPE (lv_class_name) EXPORTING is_item = is_item iv_language = iv_language. CATCH cx_sy_create_object_error. lv_message = |Object type { is_item-obj_type } is not supported by this system|. IF iv_native_only = abap_false. TRY. "" 2nd step, try looking for plugins CREATE OBJECT ri_obj TYPE zcl_abapgit_objects_bridge EXPORTING is_item = is_item. CATCH cx_sy_create_object_error. zcx_abapgit_exception=>raise( lv_message ). ENDTRY. ELSE. "" No native support? -> fail zcx_abapgit_exception=>raise( lv_message ). ENDIF. ENDTRY. ENDMETHOD. METHOD delete. DATA: ls_item TYPE zif_abapgit_definitions=>ty_item, li_progress TYPE REF TO zif_abapgit_progress, lt_tadir LIKE it_tadir, lt_deleted LIKE it_tadir, lt_items TYPE zif_abapgit_definitions=>ty_items_tt, lx_error TYPE REF TO zcx_abapgit_exception, lv_count TYPE i. FIELD-SYMBOLS: LIKE LINE OF it_tadir. lt_tadir = it_tadir. IF is_checks-transport-required = abap_true. zcl_abapgit_default_transport=>get_instance( )->set( is_checks-transport-transport ). ENDIF. TRY. zcl_abapgit_dependencies=>resolve( CHANGING ct_tadir = lt_tadir ). li_progress = zcl_abapgit_progress=>get_instance( lines( lt_tadir ) ). lt_items = map_tadir_to_items( lt_tadir ). check_objects_locked( iv_language = zif_abapgit_definitions=>c_english it_items = lt_items ). CATCH zcx_abapgit_exception INTO lx_error. zcl_abapgit_default_transport=>get_instance( )->reset( ). RAISE EXCEPTION lx_error. ENDTRY. lv_count = 1. DO. CLEAR lt_deleted. LOOP AT lt_tadir ASSIGNING . li_progress->show( iv_current = lv_count iv_text = |Delete { -obj_name }| ). CLEAR ls_item. ls_item-obj_type = -object. ls_item-obj_name = -obj_name. TRY. delete_object( iv_package = -devclass is_item = ls_item iv_transport = is_checks-transport-transport ). INSERT INTO TABLE lt_deleted. DELETE lt_tadir. lv_count = lv_count + 1. "" make sure to save object deletions COMMIT WORK. CATCH zcx_abapgit_exception INTO lx_error. IF ii_log IS BOUND. ii_log->add_exception( ix_exc = lx_error is_item = ls_item ). ii_log->add_error( iv_msg = |Deletion of object { ls_item-obj_name } failed| is_item = ls_item ). ENDIF. ENDTRY. ENDLOOP. "" Exit if done or nothing else was deleted IF lines( lt_tadir ) = 0 OR lines( lt_deleted ) = 0. EXIT. ENDIF. ENDDO. zcl_abapgit_default_transport=>get_instance( )->reset( ). IF lx_error IS BOUND AND lines( lt_tadir ) > 0. zcx_abapgit_exception=>raise( 'Error during uninstall. Check the log.' ). ENDIF. li_progress->off( ). ENDMETHOD. METHOD delete_object. DATA: li_obj TYPE REF TO zif_abapgit_object. "" Nothing to do for unsupported objects IF is_type_supported( is_item-obj_type ) = abap_false. RETURN. ENDIF. li_obj = create_object( is_item = is_item iv_language = zif_abapgit_definitions=>c_english ). li_obj->delete( iv_package = iv_package iv_transport = iv_transport ). IF li_obj->get_metadata( )-delete_tadir = abap_true. CALL FUNCTION 'TR_TADIR_INTERFACE' EXPORTING wi_delete_tadir_entry = abap_true wi_tadir_pgmid = 'R3TR' wi_tadir_object = is_item-obj_type wi_tadir_obj_name = is_item-obj_name wi_test_modus = abap_false EXCEPTIONS OTHERS = 1 ##FM_SUBRC_OK. "" We deliberately ignore the subrc, because throwing an exception would "" break the deletion of lots of object types. On the other hand we have "" to catch the exceptions because otherwise messages would directly be issued "" by the function module and change the control flow. Thus breaking the "" deletion of TOBJ and other object types. "" TODO: This is not very clean and has to be improved in the future. See PR 2741. ENDIF. ENDMETHOD. METHOD deserialize. DATA: ls_item TYPE zif_abapgit_definitions=>ty_item, li_obj TYPE REF TO zif_abapgit_object, lt_remote TYPE zif_abapgit_definitions=>ty_files_tt, lv_package TYPE devclass, lo_files TYPE REF TO zcl_abapgit_objects_files, ls_metadata TYPE zif_abapgit_definitions=>ty_metadata, lo_xml TYPE REF TO zif_abapgit_xml_input, lt_results TYPE zif_abapgit_definitions=>ty_results_tt, li_progress TYPE REF TO zif_abapgit_progress, lv_path TYPE string, lt_items TYPE zif_abapgit_definitions=>ty_items_tt, lt_steps_id TYPE zif_abapgit_definitions=>ty_deserialization_step_tt, lt_steps TYPE zif_abapgit_objects=>ty_step_data_tt, lx_exc TYPE REF TO zcx_abapgit_exception. DATA: lo_folder_logic TYPE REF TO zcl_abapgit_folder_logic. FIELD-SYMBOLS: TYPE zif_abapgit_definitions=>ty_result, TYPE LINE OF zif_abapgit_definitions=>ty_deserialization_step_tt, TYPE LINE OF zif_abapgit_objects=>ty_step_data_tt, TYPE LINE OF zif_abapgit_objects=>ty_deserialization_tt. lt_steps = get_deserialize_steps( ). lv_package = io_repo->get_package( ). IF is_checks-transport-required = abap_true. zcl_abapgit_default_transport=>get_instance( )->set( is_checks-transport-transport ). ENDIF. zcl_abapgit_objects_activation=>clear( ). lt_remote = io_repo->get_files_remote( ). lt_results = zcl_abapgit_file_deserialize=>get_results( io_repo = io_repo ii_log = ii_log ). zcl_abapgit_objects_check=>checks_adjust( EXPORTING io_repo = io_repo is_checks = is_checks CHANGING ct_results = lt_results ). li_progress = zcl_abapgit_progress=>get_instance( lines( lt_results ) ). lt_items = map_results_to_items( lt_results ). check_objects_locked( iv_language = io_repo->get_dot_abapgit( )->get_main_language( ) it_items = lt_items ). ii_log->add_success( |Prepare Deserialize| ). lo_folder_logic = zcl_abapgit_folder_logic=>get_instance( ). LOOP AT lt_results ASSIGNING . li_progress->show( iv_current = sy-tabix iv_text = |Prepare Deserialize: { -obj_type } { -obj_name }| ). CLEAR ls_item. ls_item-obj_type = -obj_type. ls_item-obj_name = -obj_name. ""error handling & logging added TRY. "" If package does not exist yet, it will be created with this call lv_package = lo_folder_logic->path_to_package( iv_top = io_repo->get_package( ) io_dot = io_repo->get_dot_abapgit( ) iv_path = -path ). check_main_package( iv_package = lv_package iv_obj_type = ls_item-obj_type ). IF ls_item-obj_type = 'DEVC'. "" Packages have the same filename across different folders. The path needs to be supplied "" to find the correct file. lv_path = -path. ENDIF. ls_item-devclass = lv_package. IF -packmove = abap_true. "" Move object to new package change_package_assignments( is_item = ls_item ii_log = ii_log ). "" No other changes required CONTINUE. ENDIF. "" Create or update object CREATE OBJECT lo_files EXPORTING is_item = ls_item iv_path = lv_path. lo_files->set_files( lt_remote ). IF lo_files->is_json_metadata( ) = abap_false. ""analyze XML in order to instantiate the proper serializer lo_xml = lo_files->read_xml( ). ls_metadata = lo_xml->get_metadata( ). ELSE. "" there's no XML and metadata for JSON format CLEAR: lo_xml, ls_metadata. ENDIF. li_obj = create_object( is_item = ls_item iv_language = io_repo->get_dot_abapgit( )->get_main_language( ) is_metadata = ls_metadata ). compare_remote_to_local( ii_object = li_obj it_remote = lt_remote is_result = ii_log = ii_log ). li_obj->mo_files = lo_files. ""get required steps for deserialize the object lt_steps_id = li_obj->get_deserialize_steps( ). LOOP AT lt_steps_id ASSIGNING . READ TABLE lt_steps WITH KEY step_id = ASSIGNING . ASSERT sy-subrc = 0. IF = zif_abapgit_object=>gc_step_id-ddic AND zcl_abapgit_objects_activation=>is_ddic_type( ls_item-obj_type ) = abap_false. "" DDIC only for DDIC objects zcx_abapgit_exception=>raise( |Step { } is only for DDIC objects| ). ENDIF. APPEND INITIAL LINE TO -objects ASSIGNING . -item = ls_item. -obj = li_obj. -xml = lo_xml. -package = lv_package. ENDLOOP. CLEAR: lv_path, lv_package. CATCH zcx_abapgit_exception INTO lx_exc. ii_log->add_exception( ix_exc = lx_exc is_item = ls_item ). ii_log->add_error( iv_msg = |Import of object { ls_item-obj_name } failed| is_item = ls_item ). ""object should not be part of any deserialization step CONTINUE. ENDTRY. ENDLOOP. li_progress->off( ). ""run deserialize for all steps and it's objects SORT lt_steps BY order. LOOP AT lt_steps ASSIGNING . deserialize_objects( EXPORTING is_step = ii_log = ii_log iv_transport = is_checks-transport-transport CHANGING ct_files = rt_accessed_files ). ENDLOOP. update_package_tree( io_repo->get_package( ) ). SORT rt_accessed_files BY path ASCENDING filename ASCENDING. DELETE ADJACENT DUPLICATES FROM rt_accessed_files. "" Just in case zcl_abapgit_default_transport=>get_instance( )->reset( ). ENDMETHOD. METHOD deserialize_checks. rs_checks = zcl_abapgit_objects_check=>deserialize_checks( io_repo ). ENDMETHOD. METHOD deserialize_objects. DATA: li_progress TYPE REF TO zif_abapgit_progress, li_exit TYPE REF TO zif_abapgit_exit, lx_exc TYPE REF TO zcx_abapgit_exception. FIELD-SYMBOLS: LIKE LINE OF is_step-objects. zcl_abapgit_objects_activation=>clear( ). ii_log->add_success( |Step { is_step-order } - { is_step-descr }| ). li_progress = zcl_abapgit_progress=>get_instance( lines( is_step-objects ) ). LOOP AT is_step-objects ASSIGNING . li_progress->show( iv_current = sy-tabix iv_text = |Step { is_step-order } - { is_step-descr }:| && | { -item-obj_type } { -item-obj_name }| ). TRY. -obj->deserialize( iv_package = -package io_xml = -xml iv_step = is_step-step_id ii_log = ii_log iv_transport = iv_transport ). APPEND LINES OF -obj->mo_files->get_accessed_files( ) TO ct_files. ii_log->add_success( iv_msg = |Object { -item-obj_name } imported| is_item = -item ). CATCH zcx_abapgit_exception INTO lx_exc. ii_log->add_exception( ix_exc = lx_exc is_item = -item ). ii_log->add_error( iv_msg = |Import of object { -item-obj_name } failed| is_item = -item ). ENDTRY. ENDLOOP. li_progress->show( iv_current = lines( is_step-objects ) iv_text = |Step { is_step-order } - Activating Objects| ). CASE is_step-step_id. WHEN zif_abapgit_object=>gc_step_id-ddic. zcl_abapgit_objects_activation=>activate( iv_ddic = abap_true ii_log = ii_log ). WHEN zif_abapgit_object=>gc_step_id-abap. zcl_abapgit_objects_activation=>activate( iv_ddic = abap_false ii_log = ii_log ). WHEN zif_abapgit_object=>gc_step_id-late. "" late can have both DDIC (like TABL with REF TO) and non-DDIC objects zcl_abapgit_objects_activation=>activate( iv_ddic = abap_true ii_log = ii_log ). zcl_abapgit_objects_activation=>activate( iv_ddic = abap_false ii_log = ii_log ). ENDCASE. li_progress->off( ). * Call postprocessing li_exit = zcl_abapgit_exit=>get_instance( ). li_exit->deserialize_postprocess( is_step = is_step ii_log = ii_log ). ENDMETHOD. METHOD exists. DATA: li_obj TYPE REF TO zif_abapgit_object. "" Might be called for objects without tadir entry IF is_item IS INITIAL. RETURN. ENDIF. "" For unsupported objects, assume object exists IF is_type_supported( is_item-obj_type ) = abap_false. rv_bool = abap_true. RETURN. ENDIF. TRY. li_obj = create_object( is_item = is_item iv_language = zif_abapgit_definitions=>c_english ). rv_bool = li_obj->exists( ). CATCH zcx_abapgit_exception. "" Ignore errors and assume the object exists rv_bool = abap_true. ENDTRY. ENDMETHOD. METHOD get_deserialize_steps. FIELD-SYMBOLS: TYPE LINE OF zif_abapgit_objects=>ty_step_data_tt. APPEND INITIAL LINE TO rt_steps ASSIGNING . -step_id = zif_abapgit_object=>gc_step_id-ddic. -descr = 'Deserialize DDIC Objects'. -syntax_check = abap_false. -order = 1. APPEND INITIAL LINE TO rt_steps ASSIGNING . -step_id = zif_abapgit_object=>gc_step_id-abap. -descr = 'Deserialize non-DDIC Objects'. -syntax_check = abap_false. -order = 2. APPEND INITIAL LINE TO rt_steps ASSIGNING . -step_id = zif_abapgit_object=>gc_step_id-late. -descr = 'Post-process Objects'. -syntax_check = abap_true. -order = 3. ENDMETHOD. METHOD is_active. DATA: li_obj TYPE REF TO zif_abapgit_object. "" For unsupported objects, assume active state IF is_type_supported( is_item-obj_type ) = abap_false. rv_active = abap_true. RETURN. ENDIF. TRY. li_obj = create_object( is_item = is_item iv_language = zif_abapgit_definitions=>c_english ). rv_active = li_obj->is_active( ). CATCH cx_sy_dyn_call_illegal_method cx_sy_ref_is_initial zcx_abapgit_exception. "" Ignore errors and assume active state rv_active = abap_true. ENDTRY. ENDMETHOD. METHOD is_supported. TRY. create_object( is_item = is_item iv_language = zif_abapgit_definitions=>c_english iv_native_only = iv_native_only ). rv_bool = abap_true. CATCH zcx_abapgit_exception. rv_bool = abap_false. ENDTRY. ENDMETHOD. METHOD is_type_supported. DATA: ls_item TYPE zif_abapgit_definitions=>ty_item, ls_supported_obj_type TYPE ty_supported_types. FIELD-SYMBOLS TYPE ty_supported_types. IF iv_obj_type IS INITIAL. "" empty object type should never exist RETURN. ENDIF. READ TABLE gt_supported_obj_types ASSIGNING WITH KEY obj_type = iv_obj_type. IF sy-subrc <> 0. ls_item-obj_type = iv_obj_type. ls_supported_obj_type-obj_type = iv_obj_type. ls_supported_obj_type-supported = is_supported( ls_item ). INSERT ls_supported_obj_type INTO TABLE gt_supported_obj_types. rv_bool = ls_supported_obj_type-supported. RETURN. ENDIF. rv_bool = -supported. ENDMETHOD. METHOD jump. DATA: li_obj TYPE REF TO zif_abapgit_object, lv_exit TYPE abap_bool. "" Nothing to do for unsupported objects IF is_type_supported( is_item-obj_type ) = abap_false. zcx_abapgit_exception=>raise( |Object type { is_item-obj_type } is not supported by this system| ). ENDIF. "" Nothing to do if object does not exist li_obj = create_object( is_item = is_item iv_language = zif_abapgit_definitions=>c_english ). IF li_obj->exists( ) = abap_false. zcx_abapgit_exception=>raise( |Object { is_item-obj_type } { is_item-obj_name } doesn't exist| ). ENDIF. "" First priority object-specific handler lv_exit = li_obj->jump( ). IF lv_exit = abap_false. "" Open object in new window with generic jumper lv_exit = zcl_abapgit_ui_factory=>get_gui_jumper( )->jump( is_item = is_item iv_sub_obj_name = iv_sub_obj_name iv_sub_obj_type = iv_sub_obj_type iv_line_number = iv_line_number ). ENDIF. IF lv_exit = abap_false. zcx_abapgit_exception=>raise( |Jump to { is_item-obj_type } { is_item-obj_name } not possible| ). ENDIF. ENDMETHOD. METHOD map_results_to_items. DATA: ls_item LIKE LINE OF rt_items. FIELD-SYMBOLS: TYPE zif_abapgit_definitions=>ty_result. LOOP AT it_results ASSIGNING . ls_item-devclass = -package. ls_item-obj_type = -obj_type. ls_item-obj_name = -obj_name. INSERT ls_item INTO TABLE rt_items. ENDLOOP. ENDMETHOD. METHOD map_tadir_to_items. DATA: ls_item LIKE LINE OF rt_items. FIELD-SYMBOLS: TYPE zif_abapgit_definitions=>ty_tadir. LOOP AT it_tadir ASSIGNING . ls_item-devclass = -devclass. ls_item-obj_type = -object. ls_item-obj_name = -obj_name. INSERT ls_item INTO TABLE rt_items. ENDLOOP. ENDMETHOD. METHOD serialize. DATA: li_obj TYPE REF TO zif_abapgit_object, lx_error TYPE REF TO zcx_abapgit_exception, li_xml TYPE REF TO zif_abapgit_xml_output, lo_files TYPE REF TO zcl_abapgit_objects_files, ls_i18n_params TYPE zif_abapgit_definitions=>ty_i18n_params. FIELD-SYMBOLS: LIKE LINE OF rs_files_and_item-files. rs_files_and_item-item = is_item. IF is_type_supported( rs_files_and_item-item-obj_type ) = abap_false. zcx_abapgit_exception=>raise( |Object type ignored, not supported: { rs_files_and_item-item-obj_type }-{ rs_files_and_item-item-obj_name }| ). ENDIF. CREATE OBJECT lo_files EXPORTING is_item = rs_files_and_item-item. li_obj = create_object( is_item = rs_files_and_item-item iv_language = iv_language ). li_obj->mo_files = lo_files. CREATE OBJECT li_xml TYPE zcl_abapgit_xml_output. ls_i18n_params-main_language = iv_language. ls_i18n_params-main_language_only = iv_main_language_only. ls_i18n_params-translation_languages = it_translation_langs. li_xml->i18n_params( ls_i18n_params ). TRY. li_obj->serialize( li_xml ). CATCH zcx_abapgit_exception INTO lx_error. rs_files_and_item-item-inactive = boolc( li_obj->is_active( ) = abap_false ). RAISE EXCEPTION lx_error. ENDTRY. IF lo_files->is_json_metadata( ) = abap_false. lo_files->add_xml( ii_xml = li_xml is_metadata = li_obj->get_metadata( ) ). ENDIF. rs_files_and_item-files = lo_files->get_files( ). check_duplicates( rs_files_and_item-files ). rs_files_and_item-item-inactive = boolc( li_obj->is_active( ) = abap_false ). LOOP AT rs_files_and_item-files ASSIGNING . -sha1 = zcl_abapgit_hash=>sha1_blob( -data ). ENDLOOP. ENDMETHOD. METHOD supported_list. DATA: lt_objects TYPE STANDARD TABLE OF ko100, ls_item TYPE zif_abapgit_definitions=>ty_item, ls_supported_obj_type TYPE ty_supported_types. FIELD-SYMBOLS LIKE LINE OF lt_objects. FIELD-SYMBOLS TYPE ty_supported_types. IF gv_supported_obj_types_loaded = abap_true. LOOP AT gt_supported_obj_types ASSIGNING WHERE supported = abap_true. INSERT -obj_type INTO TABLE rt_types. ENDLOOP. RETURN. ENDIF. "" delete content because it might be filled already by method IS_TYPE_SUPPORTED CLEAR gt_supported_obj_types. CALL FUNCTION 'TR_OBJECT_TABLE' TABLES wt_object_text = lt_objects EXCEPTIONS OTHERS = 1 ##FM_SUBRC_OK. LOOP AT lt_objects ASSIGNING WHERE pgmid = 'R3TR'. ls_item-obj_type = -object. ls_supported_obj_type-obj_type = -object. ls_supported_obj_type-supported = is_supported( ls_item ). INSERT ls_supported_obj_type INTO TABLE gt_supported_obj_types. IF ls_supported_obj_type-supported = abap_true. INSERT ls_supported_obj_type-obj_type INTO TABLE rt_types. ENDIF. ENDLOOP. gv_supported_obj_types_loaded = abap_true. ENDMETHOD. METHOD update_package_tree. DATA: lt_packages TYPE zif_abapgit_sap_package=>ty_devclass_tt, lv_package LIKE LINE OF lt_packages, lv_tree TYPE dirtree-tname. lt_packages = zcl_abapgit_factory=>get_sap_package( iv_package )->list_subpackages( ). APPEND iv_package TO lt_packages. LOOP AT lt_packages INTO lv_package. * update package tree for SE80 lv_tree = 'EU_' && lv_package. CALL FUNCTION 'WB_TREE_ACTUALIZE' EXPORTING tree_name = lv_tree without_crossreference = abap_true with_tcode_index = abap_true. ENDLOOP. ENDMETHOD. ENDCLASS. ",9351,False,2167.110285866693,median "The 1.8 release of Groovy comes with many new features that greatly enhance * the dynamic expressiveness of Groovy, specifically for defining DSLs * runtime performance * concurrent and parallel execution * design by contract * functional programming style * first-class JSON support * compile-time meta programming * and more helpers and library additions These features have undergone the Groovy developer process with formal descriptions, discussion, and voting (GEP - Groovy Enhancement Proposal) for core parts and less formal developer discussions and JIRA voting for additional parts. Our goal has stayed the same, though: to give the Java developer a tool that makes him more productive, allows him to achieve his goals faster and with a smaller margin of error, and extend the scalability of the Java platform from full-blown enterprise projects to everyday ""getting things done"" tasks. [[Groovy18releasenotes-CommandchainsfornicerDomain-SpecificLanguages]] == Command chains for nicer Domain-Specific Languages Thanks to its flexible syntax and its compile-time and runtime metaprogramming capabilities, Groovy is well known for its Domain-Specific Language capabilities. However, we felt that we could improve upon the syntax further by removing additional punctuation symbols when users chain method calls. This allows DSL implementors to develop command descriptions that read almost like natural sentences. Before Groovy 1.8, we could omit parentheses around the arguments of a method call for top-level statements. But we couldn’t chain method calls. The new `command chain` feature allows us to chain such parentheses-free method calls, requiring neither parentheses around arguments, nor dots between the chained calls. The general idea is that a call like `a b c d` will actually be equivalent to `a(b).c(d)`. This also works with multiple arguments, closure arguments, and even named arguments. Furthermore, such command chains can also appear on the right-hand side of assignments. Let’s have a look at some examples supported by this new syntax: [source,groovy] --------------------------------------------------------------------------------------------------------------- turn left then right // equivalent to: turn(left).then(right) take 2.pills of chloroquinine after 6.hours // equivalent to: take(2.pills).of(chloroquinine).after(6.hours) paint wall with red, green and yellow // equivalent to: paint(wall).with(red, green).and(yellow) // with named parameters too check that: margarita tastes good // equivalent to: check(that: margarita).tastes(good) // with closures as parameters given { } when { } then { } // equivalent to: given({}).when({}).then({}) --------------------------------------------------------------------------------------------------------------- It is also possible to use methods in the chain which take no arguments, but in that case, the parentheses are needed: [source,groovy] ------------------------------------------------------------------------------------------------- select all unique() from names // equivalent to: select(all).unique().from(names) ------------------------------------------------------------------------------------------------- If your command chain contains an odd number of elements, the chain will be composed of method / arguments, and will finish by a final property access: [source,groovy] ------------------------------------------------------------------------------------- take 3 cookies // equivalent to: take(3).cookies // and also this: take(3).getCookies() ------------------------------------------------------------------------------------- This new command chain approach opens up interesting possibilities in terms of the much wider range of DSLs which can now be written in Groovy. This new feature has been developed thanks to the Google Summer of Code program, where our student, Lidia, helped us modify the Groovy Antlr grammar to extend top-level statements to accept that command chain syntax. The above examples illustrate using a command chain based DSL but not how to create one. You will be able to find some http://groovyconsole.appspot.com/tag/gep3[further examples] of `command chains` on the Groovy Web Console but to illustrate creating such a DSL, we will show just a couple of examples - first using maps and Closures: [source,groovy] ------------------------------------------------------------------------------------------------------ show = { println it } square_root = { Math.sqrt(it) } def please(action) { [the: { what -> [of: { n -> action(what(n)) }] }] } please show the square_root of 100 // equivalent to: please(show).the(square_root).of(100) // ==> 10.0 ------------------------------------------------------------------------------------------------------ Or if you prefer Japanese and a metaprogramming style (see http://d.hatena.ne.jp/uehaj/20100919/1284906117[here] for more details): [source,groovy] ---------------------------------------------------------- // Japanese DSL using GEP3 rules Object.metaClass.を = Object.metaClass.の = { clos -> clos(delegate) } まず = { it } 表示する = { println it } 平方根 = { Math.sqrt(it) } まず 100 の 平方根 を 表示する // First, show the square root of 100 // => 10.0 ---------------------------------------------------------- As a second example, consider how you might write a DSL for simplifying one of your existing APIs. Maybe you need to put this code in front of customers, business analysts or testers who might be not hard-core Java developers. We’ll use the `Splitter` from the Google http://code.google.com/p/guava-libraries/[Guava libraries] project as it already has a nice Fluent API. Here is how we might use it out of the box: [source,groovy] ---------------------------------------------------------------------------------------------------------------- @Grab('com.google.guava:guava:r09') import com.google.common.base.* def result = Splitter.on(',').trimResults(CharMatcher.is('_' as char)).split(""_a ,_b_ ,c__"").iterator().toList() assert result == ['a ', 'b_ ', 'c'] ---------------------------------------------------------------------------------------------------------------- It reads fairly well for a Java developer but if that is not your target audience or you have many such statements to write, it could be considered a little verbose. Again, there are many options for writing a DSL. We’ll keep it simple with Maps and Closures. We’ll first write a helper method: [source,groovy] ------------------------------------------------------------------------------------------------------ def split(string) { [on: { sep -> [trimming: { trimChar -> Splitter.on(sep).trimResults(CharMatcher.is(trimChar as char)).split(string).iterator().toList() }] }] } ------------------------------------------------------------------------------------------------------ now instead of this line from our original example: [source,groovy] ---------------------------------------------------------------------------------------------------------------- def result = Splitter.on(',').trimResults(CharMatcher.is('_' as char)).split(""_a ,_b_ ,c__"").iterator().toList() ---------------------------------------------------------------------------------------------------------------- we can write this: [source,groovy] ----------------------------------------------------- def result = split ""_a ,_b_ ,c__"" on ',' trimming '_' ----------------------------------------------------- [[Groovy18releasenotes-Performanceimprovements]] == Performance improvements Groovy’s flexible metaprogramming model involves numerous decision points when making method calls or accessing properties to determine whether any metaprogamming hooks are being utilized. During complex expression calculations, such decision points involved identical checks being executed numerous times. Recent performance improvements allow some of these checks to be bypassed during an expression calculation once certain initial assumptions have been checked. Basically if certain preconditions hold, some streamlining can take place. Groovy 1.8.0 contains two main streams of optimization work: * There are several optimizations for basic operations on integers like plus, minus, multiply, increment, decrement and comparisons. This version doesn’t support the mixed usage of different types. If an expression contains different types, then it falls back to the classical way of performing the operation, i.e. no streamlining occurs. * There is also an optimization for direct method calls. Such a method call is done directly if it is done on `this` and if the argument types are a direct match with the parameter types of the method we may call. Since this is an operation that does not behave too well with a method call logic based on runtime types we select only methods where the primitive types match, the parameter types are final or for methods that take no arguments. Currently methods with a variable parameter list are not matched in general, unless a fitting array is used for the method call. Those two areas of optimization are only the beginning of further similar improvements. Upcoming versions of the Groovy 1.8.x branch will see more optimizations coming. In particular, primitive types other than integers should be expected to be supported shortly. [[Groovy18releasenotes-GParsbundledwithintheGroovydistribution]] == GPars bundled within the Groovy distribution The http://gpars.codehaus.org[GPars] project offers developers new intuitive and safe ways to handle Java or Groovy tasks concurrently, asynchronously, and distributed by utilizing the power of the Java platform and the flexibility of the Groovy language. Groovy 1.8 now bundles GPars 0.11 in the libraries of the Groovy installation, so that you can leverage all the features of the library for + Fork/Join, Map/Filter/Reduce, DataFlow, Actors, Agents, and more with all the Groovy goodness. To learn more about GPars, head over to the http://gpars.codehaus.org/[GPars website], read the http://gpars.org/guide/index.html[detailed online user guide], or check out chapter 17 of http://www.manning.com/koenig2[Groovy in Action, 2nd Edition (MEAP)]. [[Groovy18releasenotes-Closureenhancements]] == Closure enhancements Closures are a central and essential piece of the Groovy programming language and are used in various ways throughout the Groovy APIs. In Groovy 1.8, we introduce the ability to use closures as annotation parameters. Closures are also a key part of what gives Groovy its functional flavor. [[Groovy18releasenotes-Closureannotationparameters]] === Closure annotation parameters In Java, there’s a limited set of types you can use as annotation parameters (String, primitives, annotations, classes, and arrays of these). But in Groovy 1.8, we’re going further and let you use closures as annotation parameters – which are actually transformed into a class parameter for compatibility reasons. [source,groovy] ------------------------------------------------ import java.lang.annotation.* @Retention(RetentionPolicy.RUNTIME) @interface Invariant { Class value() // will hold a closure class } @Invariant({ number >= 0 }) class Distance { float number String unit } def d = new Distance(number: 10, unit: ""meters"") def anno = Distance.getAnnotation(Invariant) def check = anno.value().newInstance(d, d) assert check(d) ------------------------------------------------ Closure annotation parameters open up some interesting possibilities for framework authors! As an example, the https://github.com/andresteingress/gcontracts/wiki/[GContracts] project, which brings the `Design by Contract` paradigm to Groovy makes heavy use of annotation parameters to allow preconditions, postconditions and invariants to be declared. [[Groovy18releasenotes-Closurefunctionalflavors]] === Closure functional flavors [[Groovy18releasenotes-Closurecomposition]] ==== Closure composition If you recall your math lessons, function composition may be a concept you’re familiar with. And in turn, *Closure composition* is about that: the ability to compose Closures together to form a new Closure which chains the call of those Closures. Here’s an example of composition in action: [source,groovy] --------------------------------------------- def plus2  = { it + 2 } def times3 = { it * 3 } def times3plus2 = plus2 << times3 assert times3plus2(3) == 11 assert times3plus2(4) == plus2(times3(4)) def plus2times3 = times3 << plus2 assert plus2times3(3) == 15 assert plus2times3(5) == times3(plus2(5)) // reverse composition assert times3plus2(3) == (times3 >> plus2)(3) --------------------------------------------- To see more examples of Closure composition and reverse composition, please have a look at our http://svn.codehaus.org/groovy/trunk/groovy/groovy-core/src/test/groovy/ClosureComposeTest.groovy[test case]. [[Groovy18releasenotes-Closuretrampoline]] ==== Closure trampoline When writing recursive algorithms, you may be getting the infamous stack overflow exceptions, as the stack starts to have a too high depth of recursive calls. An approach that helps in those situations is by using Closures and their new http://en.wikipedia.org/wiki/Tail_call#Through_trampolining[trampoline] capability. Closures are wrapped in a `TrampolineClosure`. Upon calling, a trampolined Closure will call the original Closure waiting for its result. If the outcome of the call is another instance of a `TrampolineClosure`, created perhaps as a result to a call to the `trampoline()` method, the Closure will again be invoked. This repetitive invocation of returned trampolined Closures instances will continue until a value other than a trampolined Closure is returned. That value will become the final result of the trampoline. That way, calls are made serially, rather than filling the stack. Here’s an example of the use of `trampoline()` to implement the factorial function: [source,groovy] ------------------------------------------------------------------ def factorial factorial = { int n, def accu = 1G -> if (n < 2) return accu factorial.trampoline(n - 1, n * accu) } factorial = factorial.trampoline() assert factorial(1) == 1 assert factorial(3) == 1 * 2 * 3 assert factorial(1000) == 402387260... // plus another 2560 digits ------------------------------------------------------------------ [[Groovy18releasenotes-Closurememoization]] ==== Closure memoization Another improvement to Closures is the ability to http://en.wikipedia.org/wiki/Memoization[memoize] the outcome of previous (ideally side-effect free) invocations of your Closures. The return values for a given set of Closure parameter values are kept in a cache, for those memoized Closures. That way, if you have an expensive computation to make that takes seconds, you can put the return value in cache, so that the next execution with the same parameter will return the same result – again, we assume results of an invocation are the same given the same set of parameter values. There are three forms of memoize functions: * the standard `memoize()` which caches all the invocations * `memoizeAtMost(max)` call which caches a maximum number of invocations * `memoizeAtLeast(min)` call which keeps at least a certain number of invocation results * and `memoizeBetween(min, max)` which keeps a range results (between a minimum and a maximum) Let’s illustrate that: [source,groovy] -------------------------------------------------- def plus = { a, b -> sleep 1000; a + b }.memoize() assert plus(1, 2) == 3 // after 1000ms assert plus(1, 2) == 3 // return immediately assert plus(2, 2) == 4 // after 1000ms assert plus(2, 2) == 4 // return immediately   // other forms: // at least 10 invocations cached def plusAtLeast = { ... }.memoizeAtLeast(10) // at most 10 invocations cached def plusAtMost = { ... }.memoizeAtMost(10) // between 10 and 20 invocations cached def plusAtLeast = { ... }.memoizeBetween(10, 20) -------------------------------------------------- [[Groovy18releasenotes-Curryingimprovements]] === Currying improvements Currying improvements have also been backported to recent releases of Groovy 1.7, but it’s worth outlining here for reference. Currying used to be done only from left to right, but it’s also possible to do it from right to left, or from a given index, as the following examples demonstrate: [source,groovy] ------------------------------------------ // right currying def divide = { a, b -> a / b } def halver = divide.rcurry(2) assert halver(8) == 4   // currying n-th parameter def joinWithSeparator = { one, sep, two -> one + sep + two } def joinWithComma = joinWithSeparator.ncurry(1, ', ') assert joinWithComma('a', 'b') == 'a, b' ------------------------------------------ [[Groovy18releasenotes-NativeJSONsupport]] == Native JSON support With the ubiquity of JSON as an interchange format for our applications, it is natural that Groovy added support for JSON, in a similar fashion as the support Groovy’s always had with XML. So Groovy 1.8 introduces a JSON builder and parser. [[Groovy18releasenotes-ReadingJSON]] === Reading JSON A `JsonSlurper` class allows you to parse JSON payloads, and access the nested Map and List data structures representing that content. JSON objects and arrays are indeed simply represented as Maps and Lists, giving you access to all the GPath expression benefits (subscript/property notation, find/findAll/each/inject/groupBy/etc.). Here’s an example showing how to find all the recent commit messages on the Grails project: [source,groovy] -------------------------------------------------------------------------------------------------- import groovy.json.* def payload = new URL(""http://github.com/api/v2/json/commits/list/grails/grails-core/master"").text def slurper = new JsonSlurper() def doc = slurper.parseText(payload) doc.commits.message.each { println it } -------------------------------------------------------------------------------------------------- If you want to see some more examples of the usage of the JSON parser, you can have a look at the http://svn.codehaus.org/groovy/branches/GROOVY_1_8_X/src/test/groovy/json/JsonSlurperTest.groovy[JsonSlurper tests] in our code base. [[Groovy18releasenotes-JSONbuilder]] === JSON builder Parsing JSON data structures is one thing, but we should also be able to produce JSON content just like we create markup with the `MarkupBuilder`. The following example: [source,groovy] ---------------------------- import groovy.json.* def json = new JsonBuilder() json.person { name ""Guillaume"" age 33 pets ""Hector"", ""Felix"" } println json.toString() ---------------------------- Will create the JSON output: [source,groovy] ------------------------------------------------------------------ {""person"":{""name"":""Guillaume"",""age"":33,""pets"":[""Hector"",""Felix""]}} ------------------------------------------------------------------ You can find some more usages of the JSON builder in our http://svn.codehaus.org/groovy/branches/GROOVY_1_8_X/src/test/groovy/json/JsonBuilderTest.groovy[JsonBuilder tests]. [[Groovy18releasenotes-PrettyprintingJSONcontent]] === Pretty printing JSON content When given a JSON data structure, you may wish to pretty-print it, so that you can more easily inspect it, with a more friendly layout. So for instance, if you want to pretty print the result of the previous example, you could do: [source,groovy] -------------------------------------------------------------------------------------------------------------------- import groovy.json.* println JsonOutput.prettyPrint('''{""person"":{""name"":""Guillaume"",""age"":33,""pets"":[""Hector"",""Felix""]}}''')​​​​​​​​​​​​ -------------------------------------------------------------------------------------------------------------------- Which would result in the following pretty-printed output: [source,groovy] ---------------------------- { ""person"": { ""name"": ""Guillaume"", ""age"": 33, ""pets"": [ ""Hector"", ""Felix"" ] } } ---------------------------- [[Groovy18releasenotes-NewASTTransformations]] == New AST Transformations The Groovy compiler reads the source code, builds an Abstract Syntax Tree (AST) from it, and then puts the AST into bytecode. With AST transformations, the programmer can hook into this process. A general description of this process, an exhaustive description of all available transformations, and a guide of how to write you own ones can be found for example in http://www.manning.com/koenig2[Groovy in Action, 2nd Edition (MEAP)], chapter 9. Below is a list of all new transformations that come with Groovy 1.8. They save you from writing repetitive code and help avoiding common errors. [[Groovy18releasenotes-Log]] === @Log You can annotate your classes with the @Log transformation to automatically inject a logger in your Groovy classes, under the `log` property. Four kind of loggers are actually available: * `@Log` for java.util.logging * `@Commons` for Commons-Logging * `@Log4j` for Log4J * `@Slf4j` for SLF4J Here’s a sample usage of the @Log transformation: [source,groovy] ---------------------------------- import groovy.util.logging.* @Log class Car { Car() { log.info 'Car constructed' } } def c = new Car() ---------------------------------- You can change the name of the logger by specifying a different name, for instance with `@Log('myLoggerName')`. Another particularity of these logger AST transformations is that they take care of wrapping and safe-guarding logger calls with the usual `isSomeLevelEnabled()` calls. So when you write `log.info 'Car constructed'`, the generated code is actually equivalent to: [source,groovy] --------------------------------- if (log.isLoggable(Level.INFO)) { log.info 'Car constructed' } --------------------------------- [[Groovy18releasenotes-Field]] === @Field When defining variables in a script, those variables are actually local to the script’s run method, so they are not accessible from other methods of the script. A usual approach to that problem has been to store variables in the binding, by not def’ining those variables and by just assigning them a value. Fortunately, the `@Field` transformation provides a better alternative: by annotating your variables in your script with this annotation, the annotated variable will become a private field of the script class. More concretely, you’ll be able to do as follows: [source,groovy] --------------------------- @Field List awe = [1, 2, 3] def awesum() { awe.sum() } assert awesum() == 6 --------------------------- [[Groovy18releasenotes-PackageScopeenhancements]] === @PackageScope enhancements The @PackageScope annotation can be placed on classes, methods or fields and is used for turning off Groovy’s visibility conventions and reverting back to Java conventions. This ability is usually only needed when using 3rd party libraries which rely on the package scope visibility. When adding the `@PackageScope` annotation to a field, Groovy will assign package scope access to the field rather than automatically treating it as a property (and adding setters/getters). Annotating a class or method with `@PackageScope` will cause Groovy to revert to Java’s convention of leaving the class/method as package scoped rather than automatically promoting it to public scope. The class variant can also take one or more parameters to allow nested setting of visibility of attributes within the class - see the Javadoc for more details. Recent releases of Groovy 1.7 have had a more limited version of this annotation. [[Groovy18releasenotes-AutoClone]] === @AutoClone The `@AutoClone` annotation is placed on classes which you want to be `Cloneable`. The annotation instructs the compiler to execute an AST transformation which adds a public `clone()` method and adds `Cloneable` to the classes implements list of interfaces. Because the JVM doesn’t have a one-size-fits-all cloning strategy, several customizations exist for the cloning implementation: * By default, the `clone()` method will call `super.clone()` before calling `clone()` on each `Cloneable` property of the class. Example usage: [source,groovy] --------------------------------- import groovy.transform.AutoClone @AutoClone class Person { String first, last List favItems Date since } --------------------------------- Which will create a class of the following form: [source,groovy] ------------------------------------------------------------- class Person implements Cloneable { ... public Object clone() throws CloneNotSupportedException { Object result = super.clone() result.favItems = favItems.clone() result.since = since.clone() return result } ... } ------------------------------------------------------------- * Another popular cloning strategy is known as the copy constructor pattern. If any of your fields are `final` and `Cloneable` you should set `style=COPY_CONSTRUCTOR` which will then use the copy constructor pattern. * As a final alternative, if your class already implements the `Serializable` or `Externalizable` interface, you might like to set `style=SERIALIZATION` which will then use serialization to do the cloning. See the Javadoc for `AutoClone` for further details. [[Groovy18releasenotes-AutoExternalizable]] === @AutoExternalizable The `@AutoExternalizable` class annotation is used to assist in the creation of `Externalizable` classes. The annotation instructs the compiler to execute an AST transformation which adds `writeExternal()` and `readExternal()` methods to a class and adds `Externalizable` to the interfaces which the class implements. The `writeExternal()` method writes each property (or field) for the class while the `readExternal()` method will read each one back in the same order. Properties or fields marked as `transient` are ignored. Example usage: [source,groovy] ------------------------- import groovy.transform.* @AutoExternalize class Person { String first, last List favItems Date since } ------------------------- Which will create a class of the following form: [source,groovy] ------------------------------------------------------------- class Person implements Externalizable { ... void writeExternal(ObjectOutput out) throws IOException { out.writeObject(first) out.writeObject(last) out.writeObject(favItems) out.writeObject(since) } void readExternal(ObjectInput oin) { first = oin.readObject() last = oin.readObject() favItems = oin.readObject() since = oin.readObject() } ... } ------------------------------------------------------------- [[Groovy18releasenotes-Controllingtheexecutionofyourcode]] === Controlling the execution of your code When integrating user-provided Groovy scripts and classes in your Java application, you may be worried about code that would eat all your CPU with infinite loops, or that call methods like `System.exit(0)` (for the latter, check the section on compiler customizers, and particularly the `SecureASTCustomizer`). It would be interesting to have a wait to control the execution of that Groovy code, to be able to interrupt its execution when the thread is interrupted, when a certain duration has elapsed, or when a certain condition is met (lack of resources, etc). Groovy 1.8 introduces three transformations for those purposes, as we shall see in the following sections. By default, the three transformations add some checks in at the beginning of each method body, and each closure body, to check whether a condition of interruption is met or not. Note that those transformations are local (triggered by an annotation). If you want to apply them transparently, so that the annotation doesn’t show up, I encourage you to have a look at the `ASTTransformationCustomizer` explained at the end of this article. Cédric Champeau, our most recent Groovy committer, who implemented those features, has a http://www.jroller.com/melix/entry/upcoming_groovy_goodness_automatic_thread[very nice blog post] covering those code interruption transformations. [[Groovy18releasenotes-ThreadInterrupt]] ==== @ThreadInterrupt You don’t need to write checks in your scripts for whether the current thread of execution has been interrupted or not, by default, the transformation will add those checks for you for scripts and classes, at the beginning of each method body and closure body: [source,groovy] --------------------------------------- @ThreadInterrupt import groovy.transform.ThreadInterrupt while (true) { // eat lots of CPU } --------------------------------------- You can specify a `checkOnMethodStart` annotation parameter (defaults to true) to customize where checks are added by the transformation (adds an interrupt check by default as the first statement of a method body). And you can also specify the `applyToAllClasses` annotation parameter (default to true) if you want to specify whether only the current class or script should have this interruption logic applied or not. [[Groovy18releasenotes-TimedInterrupt]] ==== @TimedInterrupt With `@TimedInterrupt`, you can interrupt the script after a certain amount of time: [source,groovy] -------------------------------------- @TimedInterrupt(10) import groovy.transform.TimedInterrupt while (true) { // eat lots of CPU } -------------------------------------- In addition to the previous annotation parameters we mentioned for `@ThreadInterrupt`, you should specify `value`, the amount of time to wait, and `unit` (defaulting to `TimeUnit.SECONDS`) to specify the unit of time to be used. [[Groovy18releasenotes-ConditionalInterrupt]] ==== @ConditionalInterrupt An example of `@ConditionalInterrupt` which leverages the closure annotation parameter feature, and the `@Field` transformation as well: [source,groovy] -------------------------------------------- @ConditionalInterrupt({ counter++ > 2 }) import groovy.transform.ConditionalInterrupt import groovy.transform.Field @Field int counter = 0 100.times { println 'executing script method...' } -------------------------------------------- You can imagine defining any kind of condition: on counters, on resource availability, on resource usage, and more. [[Groovy18releasenotes-ToString]] === @ToString Provides your classes with a default `toString()` method which prints out the values of the class’ properties (and optionally the property names and optionally fields). A basic example is here: [source,groovy] ----------------------------------------- import groovy.transform.ToString @ToString class Person { String name int age } println new Person(name: 'Pete', age: 15) // => Person(Pete, 15) ----------------------------------------- And here’s another example using a few more options: [source,groovy] ---------------------------------------------------- @ToString(includeNames = true, includeFields = true) class Coord { int x, y private z = 0 } println new Coord(x:20, y:5) // => Coord(x:20, y:5, z:0) ---------------------------------------------------- [[Groovy18releasenotes-EqualsAndHashCode]] === @EqualsAndHashCode Provides your classes with `equals()` and `hashCode()` methods based on the values of the class’ properties (and optionally fields and optionally super class values for `equals()` and `hashCode()`). [source,groovy] ----------------------------------------- import groovy.transform.EqualsAndHashCode @EqualsAndHashCode class Coord { int x, y } def c1 = new Coord(x:20, y:5) def c2 = new Coord(x:20, y:5) assert c1 == c2 assert c1.hashCode() == c2.hashCode() ----------------------------------------- [[Groovy18releasenotes-TupleConstructor]] === @TupleConstructor Provides a tuple (ordered) constructor. For POGOs (plain old Groovy objects), this will be in addition to Groovy’s default `named-arg` constructor. [source,groovy] --------------------------------------------------------- import groovy.transform.TupleConstructor @TupleConstructor class Person { String name int age } def p1 = new Person(name: 'Pete', age: 15) // map-based def p2 = new Person('Pete', 15) // tuple-based assert p1.name == p2.name assert p1.age == p2.age --------------------------------------------------------- [[Groovy18releasenotes-Canonical]] === @Canonical Allows you to combine `@ToString`, `@EqualsAndHashCode` and `@TupleConstructor`. For those familiar with Groovy’s `@Immutable` transform, this provides similar features but for mutable objects. [source,groovy] -------------------------------------------- import groovy.transform.Canonical @Canonical class Person { String name int age } def p1 = new Person(name: 'Pete', age: 15) def p2 = new Person('Paul', 15) p2.name = 'Pete' println ""${p1.equals(p2)} $p1 $p2"" // => true Person(Pete, 15) Person(Pete, 15) -------------------------------------------- By default, `@Canonical` gives you vanilla versions for each of the combined annotations. If you want to use any of the special features that the individual annotations give you, simply include the individual annotation as well. [source,groovy] ----------------------------------------- import groovy.transform.* @Canonical @ToString(includeNames = true) class Person { String name int age } def p = new Person(name: 'Pete', age: 15) println p // => Person(name:Pete, age:15) ----------------------------------------- You will find a great http://prystash.blogspot.com/2011/04/groovy-18-playing-with-new-canonical.html[write-up on @Canonical, @ToString, @EqualsAndHashCode and @TupleConstructor] on John Prystash’s weblog. [[Groovy18releasenotes-InheritConstructors]] === @InheritConstructors Sometimes, when you want to subclass certain classes, you also need to override all the constructors of the parent, even if only to call the super constructor. Such a case happens for instance when you define your own exceptions, you want your exceptions to also have the constructors taking messages and throwable as parameters. But instead of writing this kind of boilerplate code each time for your exceptions: [source,groovy] -------------------------------------------------------------- class CustomException extends Exception { CustomException() { super() } CustomException(String msg) { super(msg) } CustomException(String msg, Throwable t) { super(msg, t) } CustomException(Throwable t) { super(t) } } -------------------------------------------------------------- Simply use the @InheritConstructors transformation which takes care of overriding the base constructors for you: [source,groovy] ------------------------------------------ import groovy.transform.* @InheritConstructors class CustomException extends Exception {} ------------------------------------------ [[Groovy18releasenotes-WithReadLockandWithWriteLock]] === @WithReadLock and @WithWriteLock Those two transformations, combined together, simplify the usage of `java.util.concurrent.locks.ReentrantReadWriteLock`, are safer to use than the `synchronized` keyword, and improve upon the `@Synchronized` transformation with a more granular locking. More concretely, with an example, the following: [source,groovy] ------------------------------------------------------------ import groovy.transform.* class ResourceProvider { private final Map data = new HashMap<>() @WithReadLock String getResource(String key) { return data.get(key) } @WithWriteLock void refresh() { //reload the resources into memory } } ------------------------------------------------------------ Will generate code as follows: [source,groovy] ----------------------------------------------------------------------------- import java.util.concurrent.locks.ReentrantReadWriteLock import java.util.concurrent.locks.ReadWriteLock class ResourceProvider { private final ReadWriteLock $reentrantlock = new ReentrantReadWriteLock() private final Map data = new HashMap() String getResource(String key) { $reentrantlock.readLock().lock() try { return data.get(key) } finally { $reentrantlock.readLock().unlock() } } void refresh() throws Exception { $reentrantlock.writeLock().lock() try { //reload the resources into memory } finally { $reentrantlock.writeLock().unlock() } } } ----------------------------------------------------------------------------- [[Groovy18releasenotes-ListenerList]] === @ListenerList If you annotate a Collection type field with @ListenerList, it generates everything that is needed to follow the bean event pattern. This is kind of an EventType independent version of what @Bindable is for PropertyChangeEvents. This example shows the most basic usage of the @ListenerList annotation. The easiest way to use this annotation is to annotate a field of type List and give the List a generic type. In this example we use a List of type MyListener. MyListener is a one method interface that takes a MyEvent as a parameter. The following code is some sample source code showing the simplest scenario. [source,groovy] ----------------------------------------- interface MyListener { void eventOccurred(MyEvent event) } class MyEvent { def source String message MyEvent(def source, String message) { this.source = source this.message = message } } class MyBeanClass { @ListenerList List listeners } ----------------------------------------- * + addMyListener(MyListener) : void - This method is created based on the generic type of your annotated List field. The name and parameter type is are based on the List field’s generic parameter. * + removeMyListener(MyListener) : void- This method is created based on the generic type of your annotated List field. The name and parameter type is are based on the List field’s generic parameter. * + getMyListeners() : MyListener[] - This method is created based on the generic type of your annotated List field.The name is the plural form of the List field’s generic parameter, and the return type is an array of the generic parameter. * + fireEventOccurred(MyEvent) : void - This method is created based on the type that the List’s generic type points to. In this case, MyListener is a one method interface with an eventOccurred(MyEvent) method. The method name is fire[MethodName of the interface] and the parameter is the parameter list from the interface. A fireX method will be generated for each public method in the target class, including overloaded methods.  [[Groovy18releasenotes-AlignmentswithJDK7]] == Alignments with JDK 7 Groovy 1.9 will be the version which will align as much as possible with the upcoming JDK 7, so beyond those aspects already covered in Groovy (like strings in switch and others), most of those `Project Coin` proposals will be in 1.9, except the `diamond operator` which was added in 1.8, as explained in the following paragraph. [[Groovy18releasenotes-Diamondoperator]] === Diamond operator Java 7 will introduce the `diamond` operator in generics type information, so that you can avoid the usual repetition of the parameterized types. Groovy decided to adopt the notation before JDK 7 is actually released. So instead of writing: [source,groovy] -------------------------------------------------------- List> list1 = new ArrayList>() -------------------------------------------------------- You can _omit_ the parameterized types and just use the pointy brackets, which now look like a diamond: [source,groovy] -------------------------------------------- List> list1 = new ArrayList<>() -------------------------------------------- [[Groovy18releasenotes-NewDGMmethods]] == New DGM methods * count Closure variants [source,groovy] --------------------------------------------- def isEven = { it % 2 == 0 } assert [2,4,2,1,3,5,2,4,3].count(isEven) == 5 --------------------------------------------- * countBy [source,groovy] ---------------------------------------------------------------------- assert [0:2, 1:3] == [1,2,3,4,5].countBy{ it % 2 } assert [(true):2, (false):4] == 'Groovy'.toList().countBy{ it == 'o' } ---------------------------------------------------------------------- * plus variants specifying a starting index [source,groovy] ------------------------------------------------------- assert [10, 20].plus(1, 'a', 'b') == [10, 'a', 'b', 20] ------------------------------------------------------- * equals for Sets and Maps now do flexible numeric comparisons (on values for Maps) [source,groovy] ---------------------------------------- assert [1L, 2.0] as Set == [1, 2] as Set assert [a:2, b:3] == [a:2L, b:3.0] ---------------------------------------- * toSet for primitive arrays, Strings and Collections [source,groovy] ----------------------------------------------------------- assert [1, 2, 2, 2, 3].toSet() == [1, 2, 3] as Set assert 'groovy'.toSet() == ['v', 'g', 'r', 'o', 'y'] as Set ----------------------------------------------------------- * min / max methods for maps taking closures + (also available in Groovy 1.7) [source,groovy] ---------------------------------------------- def map = [a: 1, bbb: 4, cc: 5, dddd: 2] assert map.max { it.key.size() }.key == 'dddd' assert map.min { it.value }.value == 1 ---------------------------------------------- * map withDefault\\{} + Oftentimes, when using a map, for example for counting the frequency of words in a document, you need to check that a certain key exists, before doing something with the associating value (like incrementing it). Nothing really complex, but we could improve upon that with a new method, called `withDefault`. So instead of writing code like below: [source,groovy] --------------------------------------------------- def words = ""one two two three three three"".split() def freq = [:] words.each { if (it in freq) freq[it] += 1 else freq[it] = 1 } --------------------------------------------------- Thanks to the new method (also backported to 1.7), you can write the example as follows: [source,groovy] --------------------------------------------------- def words = ""one two two three three three"".split() def freq = [:].withDefault { k -> 0 } words.each { freq[it] += 1 } --------------------------------------------------- [[Groovy18releasenotes-Miscellaneous]] == Miscellaneous [[Groovy18releasenotes-Slashystrings]] === Slashy strings Slashy strings are now multi-line: [source,groovy] ----------------------------------- def poem = / to be or not to be / assert poem.readLines().size() == 4 ----------------------------------- This is particularly useful for multi-line regexs when using the regex free-spacing comment style (though you would still need to escape slashes): [source,groovy] ------------------------------------------------------------------------------------------- // match yyyy-mm-dd from this or previous century def dateRegex = /(?x) # enable whitespace and comments ((?:19|20)\\d\\d) # year (group 1) (non-capture alternation for century) - # seperator (0[1-9]|1[012]) # month (group 2) - # seperator (0[1-9]|[12][0-9]|3[01]) # day (group 3) / assert '04/04/1988' == '1988-04-04'.find(dateRegex) { all, y, m, d -> [d, m, y].join('/') } ------------------------------------------------------------------------------------------- [[Groovy18releasenotes-Dollarslashystrings]] === Dollar slashy strings A new string notation has been introduced: the `dollar slashy` string. This is a multi-line GString similar to the slashy string, but with slightly different escaping rules. You are no longer required to escape slash (with a preceding backslash) but you can use `$$' to escape a `$' or `$/' to escape a slash if needed. Here’s an example of its usage: [source,groovy] ------------------------ def name = ""Guillaume"" def date = ""April, 21st"" def dollarSlashy = $/ Hello $name, today we're ${date} $ dollar-sign $$ dollar-sign \\ backslash / slash $/ slash /$ println dollarSlashy ------------------------ This form of string is typically used when you wish to embed content that may naturally contains slashes or backslashes and you don’t want to have to rework the content to include all of the necessary escaping. Some examples are shown below: * Embedded XML fragments with backslashes: [source,groovy] ------------------------------------------- def tic = 'tic' def xml = $/ $tic\\tac /$ assert ""\\n\\ntic\\\\tac\\n\\n"" == xml ------------------------------------------- Better than a normal (now multi-line) slashy string where you would have to escape the slashes or a triple quote (``'''``) GString where you would have to escape the backslashes. * Or windows pathnames containing a slash at the end: [source,groovy] ---------------------- def dir = $/C:\\temp\\/$ ---------------------- Previously, triple quote (`'''`) GString required extra escaping, and the above sequence was illegal for a normal slashy string. Now, ugly workarounds are not needed. * Embedding multi-line regexs when using the regex free-spacing comment style (particularly ones which contain slashes): [source,groovy] ------------------------------------------------------------------------------------------- // match yyyy-mm-dd from current or previous century def dateRegex = $/(?x) # enable whitespace and comments ((?:19|20)\\d\\d) # year (group 1) (non-capture alternation for century) [- /.] # seperator (0[1-9]|1[012]) # month (group 2) [- /.] # seperator (0[1-9]|[12][0-9]|3[01]) # day (group 3) /$ assert '04/04/1988' == '1988-04-04'.find(dateRegex) { all, y, m, d -> [d, m, y].join('/') } assert '10-08-1989' == '1989/08/10'.find(dateRegex) { all, y, m, d -> [d, m, y].join('-') } ------------------------------------------------------------------------------------------- So, you can cut and paste most PERL regex examples without further escaping. * Or Strings which are themselves Groovy code fragments containing slashes: [source,groovy] ----------------------------------- def alphabet = ('a'..'z').join('') def code = $/ def normal = '\\b\\t\\n\\r' def slashy = /\\b\\t\\n\\r/ assert '$alphabet'.size() == 26 assert normal.size() == 4 assert slashy.size() == 8 /$ println code Eval.me(code) ----------------------------------- Again allowing you to cut and paste many slashy string Groovy examples and have them embedded within dollar slashy strings without further escaping. [[Groovy18releasenotes-Compilationcustomizers]] === Compilation customizers The compilation of Groovy code can be configured through the `CompilerConfiguration` class, for example for setting the encoding of your sources, the base script class, the recompilation parameters, etc). `CompilerConfiguration` now has a new option for setting _compilation customizers_ (belonging to the `org.codehaus.groovy.control.customizers` package). Those customizers allow to customize the compilation process in three ways: * adding default imports with the `ImportCustomizer`: so you don’t have to always add the same imports all over again * securing your scripts and classes with the `SecureASTCustomizer`: by allowing/disallowing certain classes, or special AST nodes (Abstract Syntax Tree), filtering imports, you can secure your scripts to avoid malicious code or code that would go beyond the limits of what the code should be allowed to do. * applying AST transformations with the `ASTTransformationCustomizer`: lets you apply transformations to all the class nodes of your compilation unit. For example, if you want to apply the @Log transformation to all the classes and scripts, you could do: [source,groovy] ----------------------------------------------------------------------------- import org.codehaus.groovy.control.CompilerConfiguration import org.codehaus.groovy.control.customizers.* import groovy.util.logging.Log def configuration = new CompilerConfiguration() configuration.addCompilationCustomizers(new ASTTransformationCustomizer(Log)) def shell = new GroovyShell(configuration) shell.evaluate("""""" class Car { Car() { log.info 'Car constructed' } } log.info 'Constructing a car' def c = new Car() """""") ----------------------------------------------------------------------------- This will log the two messages, the one from the script, and the one from the Car class constructor, through java.util.logging. No need to apply the @Log transformation manually to both the script and the class: the transformation is applied to all class nodes transparently. This mechanism can also be used for adding global transformations, just for the classes and scripts that you compile, instead of those global transformations being applied to all scripts and classes globally. If you want to add some default imports (single import, static import, star import, star static imports, and also aliased imports and static imports), you can use the import customizer as follows: [source,groovy] -------------------------------------------------------- import org.codehaus.groovy.control.CompilerConfiguration import org.codehaus.groovy.control.customizers.* def configuration = new CompilerConfiguration() def custo = new ImportCustomizer() custo.addStaticStar(Math.name) configuration.addCompilationCustomizers(custo) def shell = new GroovyShell(configuration) shell.evaluate("""""" cos PI/3 """""") -------------------------------------------------------- When you want to evaluate Math expressions, you don’t need anymore to use the `import static java.lang.Math.*` star static import to import all the Math constants and static functions. [[Groovy18releasenotes-GStringtoEnumcoercion]] === (G)String to Enum coercion Given a String or a GString, you can coerce it to Enum values bearing the same name, as the sample below presents: [source,groovy] ----------------------------- enum Color { red, green, blue } // coercion with as def r = ""red"" as Color // implicit coercion Color b = ""blue"" // with GStrings too def g = ""${'green'}"" as Color ----------------------------- [[Groovy18releasenotes-MapssupportisCase]] === Maps support isCase() Maps now support `isCase()`, so you can use maps in your switch/case statements, for instance: [source,groovy] ---------------------------------------------- def m = [a: 1, b: 2] def val = 'a' switch (val) { case m: ""key in map""; break // equivalent to // case { val in m }: ... default: ""not in map"" } ---------------------------------------------- [[Groovy18releasenotes-GrapeGrabImprovements]] === Grape/Grab Improvements [[Groovy18releasenotes-ShorternotationforGrabResolver]] ==== Shorter notation for @GrabResolver When you need to specify a special grab resolver, for when the artifacts you need are not stored in Maven central, you could use: [source,groovy] ---------------------------------------------------------------------- @GrabResolver(name = 'restlet.org', root = 'http://maven.restlet.org') @Grab('org.restlet:org.restlet:2.0.6') import org.restlet.Restlet ---------------------------------------------------------------------- Groovy 1.8 adds a shorter syntax as well: [source,groovy] ----------------------------------------- @GrabResolver('http://maven.restlet.org') @Grab('org.restlet:org.restlet:2.0.6') import org.restlet.Restlet ----------------------------------------- [[Groovy18releasenotes-CompactformforoptionalGrabattributes]] ==== Compact form for optional Grab attributes The `@Grab` annotation has numerous options. For example, to download the Apache commons-io library (where you wanted to set the `transitive` and `force` attributes - not strictly needed for this example but see the Grab or Ivy documentation for details on what those attributes do) you could use a grab statement similar to below: [source,groovy] --------------------------------------------------------------------------------------------- @Grab(group='commons-io', module='commons-io', version='2.0.1', transitive=false, force=true) --------------------------------------------------------------------------------------------- The compact form for grab which allows the artifact information to be represented as a string now supports specifying additional attributes. As an example, the following script will download the commons-io jar and the corresponding javadoc jar before using one of the commons-io methods. [source,groovy] ---------------------------------------------------------------- @Grab('commons-io:commons-io:2.0.1;transitive=false;force=true') @Grab('commons-io:commons-io:2.0.1;classifier=javadoc') import static org.apache.commons.io.FileSystemUtils.* assert freeSpaceKb() > 0 ---------------------------------------------------------------- [[Groovy18releasenotes-Sqlimprovements]] === Sql improvements The `eachRow` and `rows` methods in the `groovy.sql.Sql` class now support paging. Here’s an example: [source,groovy] --------------------------------------------------- sql.eachRow('select * from PROJECT', 2, 2) { row -> println ""${row.name.padRight(10)} ($row.url)"" } --------------------------------------------------- Which will start at the second row and return a maximum of 2 rows. Here’s an example result from a database containing numerous projects with their URLs: ---------------------------------------- Grails (http://grails.org) Griffon (http://griffon.codehaus.org) ---------------------------------------- [[Groovy18releasenotes-StoringASTnodemetadata]] === Storing AST node metadata When developing AST transformations, and particularly when using a visitor to navigate the AST nodes, it is sometimes tricky to keep track of information as you visit the tree, or if a combination of transforms need to be sharing some context. The `ASTNode` base class features 4 methods to store node metadata: * `public Object getNodeMetaData(Object key)` * `public void copyNodeMetaData(ASTNode other)` * `public void setNodeMetaData(Object key, Object value)` * `public void removeNodeMetaData(Object key)` [[Groovy18releasenotes-AbilitytocustomizetheGroovyDoctemplates]] === Ability to customize the GroovyDoc templates GroovyDoc uses hard-coded templates to create the JavaDoc for your Groovy classes. Three templates are used: top-level templates, a package-level template, a class template. If you want to customize these templates, you can subclass the `Groovydoc` Ant task and override the `getDocTemplates()`, `getPackageTemplates()`, and `getClassTemplates()` methods pointing at your own templates. Then you can use your custom GroovyDoc Ant task in lieu of Groovy’s original one. ",12216,False,2115.851445875785,median "/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include ""SampleCode.h"" #include ""SkBitmap.h"" #include ""SkCanvas.h"" #include ""SkGeometry.h"" #include ""SkIntersections.h"" #include ""SkOpEdgeBuilder.h"" // #include ""SkPathOpsSimplifyAA.h"" // #include ""SkPathStroker.h"" #include ""SkView.h"" #if 0 void SkStrokeSegment::dump() const { SkDebugf(""{{{%1.9g,%1.9g}, {%1.9g,%1.9g}"", fPts[0].fX, fPts[0].fY, fPts[1].fX, fPts[1].fY); if (SkPath::kQuad_Verb == fVerb) { SkDebugf("", {%1.9g,%1.9g}"", fPts[2].fX, fPts[2].fY); } SkDebugf(""}}""); #ifdef SK_DEBUG SkDebugf("" id=%d"", fDebugID); #endif SkDebugf(""\\n""); } void SkStrokeSegment::dumpAll() const { const SkStrokeSegment* segment = this; while (segment) { segment->dump(); segment = segment->fNext; } } void SkStrokeTriple::dump() const { SkDebugf(""{{{%1.9g,%1.9g}, {%1.9g,%1.9g}"", fPts[0].fX, fPts[0].fY, fPts[1].fX, fPts[1].fY); if (SkPath::kQuad_Verb <= fVerb) { SkDebugf("", {%1.9g,%1.9g}"", fPts[2].fX, fPts[2].fY); } if (SkPath::kCubic_Verb == fVerb) { SkDebugf("", {%1.9g,%1.9g}"", fPts[3].fX, fPts[3].fY); } else if (SkPath::kConic_Verb == fVerb) { SkDebugf("", %1.9g"", weight()); } SkDebugf(""}}""); #ifdef SK_DEBUG SkDebugf("" triple id=%d"", fDebugID); #endif SkDebugf(""\\ninner:\\n""); fInner->dumpAll(); SkDebugf(""outer:\\n""); fOuter->dumpAll(); SkDebugf(""join:\\n""); fJoin->dumpAll(); } void SkStrokeTriple::dumpAll() const { const SkStrokeTriple* triple = this; while (triple) { triple->dump(); triple = triple->fNext; } } void SkStrokeContour::dump() const { #ifdef SK_DEBUG SkDebugf(""id=%d "", fDebugID); #endif SkDebugf(""head:\\n""); fHead->dumpAll(); SkDebugf(""head cap:\\n""); fHeadCap->dumpAll(); SkDebugf(""tail cap:\\n""); fTailCap->dumpAll(); } void SkStrokeContour::dumpAll() const { const SkStrokeContour* contour = this; while (contour) { contour->dump(); contour = contour->fNext; } } #endif SkScalar gCurveDistance = 10; #if 0 // unused static SkPath::Verb get_path_verb(int index, const SkPath& path) { if (index < 0) { return SkPath::kMove_Verb; } SkPoint pts[4]; SkPath::Verb verb; SkPath::Iter iter(path, true); int counter = -1; while ((verb = iter.next(pts)) != SkPath::kDone_Verb) { if (++counter < index) { continue; } return verb; } SkASSERT(0); return SkPath::kMove_Verb; } #endif static SkScalar get_path_weight(int index, const SkPath& path) { SkPoint pts[4]; SkPath::Verb verb; SkPath::Iter iter(path, true); int counter = -1; while ((verb = iter.next(pts)) != SkPath::kDone_Verb) { if (++counter < index) { continue; } return verb == SkPath::kConic_Verb ? iter.conicWeight() : 1; } SkASSERT(0); return 0; } static void set_path_pt(int index, const SkPoint& pt, SkPath* path) { SkPath result; SkPoint pts[4]; SkPath::Verb verb; SkPath::RawIter iter(*path); int startIndex = 0; int endIndex = 0; while ((verb = iter.next(pts)) != SkPath::kDone_Verb) { switch (verb) { case SkPath::kMove_Verb: endIndex += 1; break; case SkPath::kLine_Verb: endIndex += 1; break; case SkPath::kQuad_Verb: case SkPath::kConic_Verb: endIndex += 2; break; case SkPath::kCubic_Verb: endIndex += 3; break; case SkPath::kClose_Verb: break; case SkPath::kDone_Verb: break; default: SkASSERT(0); } if (startIndex <= index && index < endIndex) { pts[index - startIndex] = pt; index = -1; } switch (verb) { case SkPath::kMove_Verb: result.moveTo(pts[0]); break; case SkPath::kLine_Verb: result.lineTo(pts[1]); startIndex += 1; break; case SkPath::kQuad_Verb: result.quadTo(pts[1], pts[2]); startIndex += 2; break; case SkPath::kConic_Verb: result.conicTo(pts[1], pts[2], iter.conicWeight()); startIndex += 2; break; case SkPath::kCubic_Verb: result.cubicTo(pts[1], pts[2], pts[3]); startIndex += 3; break; case SkPath::kClose_Verb: result.close(); startIndex += 1; break; case SkPath::kDone_Verb: break; default: SkASSERT(0); } } #if 0 SkDebugf(""\\n\\noriginal\\n""); path->dump(); SkDebugf(""\\nedited\\n""); result.dump(); #endif *path = result; } static void add_path_segment(int index, SkPath* path) { SkPath result; SkPoint pts[4]; SkPoint firstPt = { 0, 0 }; // init to avoid warning SkPoint lastPt = { 0, 0 }; // init to avoid warning SkPath::Verb verb; SkPath::RawIter iter(*path); int counter = -1; while ((verb = iter.next(pts)) != SkPath::kDone_Verb) { SkScalar weight SK_INIT_TO_AVOID_WARNING; if (++counter == index) { switch (verb) { case SkPath::kLine_Verb: result.lineTo((pts[0].fX + pts[1].fX) / 2, (pts[0].fY + pts[1].fY) / 2); break; case SkPath::kQuad_Verb: { SkPoint chop[5]; SkChopQuadAtHalf(pts, chop); result.quadTo(chop[1], chop[2]); pts[1] = chop[3]; } break; case SkPath::kConic_Verb: { SkConic chop[2]; SkConic conic; conic.set(pts, iter.conicWeight()); if (!conic.chopAt(0.5f, chop)) { return; } result.conicTo(chop[0].fPts[1], chop[0].fPts[2], chop[0].fW); pts[1] = chop[1].fPts[1]; weight = chop[1].fW; } break; case SkPath::kCubic_Verb: { SkPoint chop[7]; SkChopCubicAtHalf(pts, chop); result.cubicTo(chop[1], chop[2], chop[3]); pts[1] = chop[4]; pts[2] = chop[5]; } break; case SkPath::kClose_Verb: { result.lineTo((lastPt.fX + firstPt.fX) / 2, (lastPt.fY + firstPt.fY) / 2); } break; default: SkASSERT(0); } } else if (verb == SkPath::kConic_Verb) { weight = iter.conicWeight(); } switch (verb) { case SkPath::kMove_Verb: result.moveTo(firstPt = pts[0]); break; case SkPath::kLine_Verb: result.lineTo(lastPt = pts[1]); break; case SkPath::kQuad_Verb: result.quadTo(pts[1], lastPt = pts[2]); break; case SkPath::kConic_Verb: result.conicTo(pts[1], lastPt = pts[2], weight); break; case SkPath::kCubic_Verb: result.cubicTo(pts[1], pts[2], lastPt = pts[3]); break; case SkPath::kClose_Verb: result.close(); break; case SkPath::kDone_Verb: break; default: SkASSERT(0); } } *path = result; } static void delete_path_segment(int index, SkPath* path) { SkPath result; SkPoint pts[4]; SkPath::Verb verb; SkPath::RawIter iter(*path); int counter = -1; while ((verb = iter.next(pts)) != SkPath::kDone_Verb) { if (++counter == index) { continue; } switch (verb) { case SkPath::kMove_Verb: result.moveTo(pts[0]); break; case SkPath::kLine_Verb: result.lineTo(pts[1]); break; case SkPath::kQuad_Verb: result.quadTo(pts[1], pts[2]); break; case SkPath::kConic_Verb: result.conicTo(pts[1], pts[2], iter.conicWeight()); break; case SkPath::kCubic_Verb: result.cubicTo(pts[1], pts[2], pts[3]); break; case SkPath::kClose_Verb: result.close(); break; case SkPath::kDone_Verb: break; default: SkASSERT(0); } } *path = result; } static void set_path_weight(int index, SkScalar w, SkPath* path) { SkPath result; SkPoint pts[4]; SkPath::Verb verb; SkPath::Iter iter(*path, true); int counter = -1; while ((verb = iter.next(pts)) != SkPath::kDone_Verb) { ++counter; switch (verb) { case SkPath::kMove_Verb: result.moveTo(pts[0]); break; case SkPath::kLine_Verb: result.lineTo(pts[1]); break; case SkPath::kQuad_Verb: result.quadTo(pts[1], pts[2]); break; case SkPath::kConic_Verb: result.conicTo(pts[1], pts[2], counter == index ? w : iter.conicWeight()); break; case SkPath::kCubic_Verb: result.cubicTo(pts[1], pts[2], pts[3]); break; case SkPath::kClose_Verb: result.close(); break; case SkPath::kDone_Verb: break; default: SkASSERT(0); } } *path = result; } static void set_path_verb(int index, SkPath::Verb v, SkPath* path, SkScalar w) { SkASSERT(SkPath::kLine_Verb <= v && v <= SkPath::kCubic_Verb); SkPath result; SkPoint pts[4]; SkPath::Verb verb; SkPath::Iter iter(*path, true); int counter = -1; while ((verb = iter.next(pts)) != SkPath::kDone_Verb) { SkScalar weight = verb == SkPath::kConic_Verb ? iter.conicWeight() : 1; if (++counter == index && v != verb) { SkASSERT(SkPath::kLine_Verb <= verb && verb <= SkPath::kCubic_Verb); switch (verb) { case SkPath::kLine_Verb: switch (v) { case SkPath::kConic_Verb: weight = w; case SkPath::kQuad_Verb: pts[2] = pts[1]; pts[1].fX = (pts[0].fX + pts[2].fX) / 2; pts[1].fY = (pts[0].fY + pts[2].fY) / 2; break; case SkPath::kCubic_Verb: pts[3] = pts[1]; pts[1].fX = (pts[0].fX * 2 + pts[3].fX) / 3; pts[1].fY = (pts[0].fY * 2 + pts[3].fY) / 3; pts[2].fX = (pts[0].fX + pts[3].fX * 2) / 3; pts[2].fY = (pts[0].fY + pts[3].fY * 2) / 3; break; default: SkASSERT(0); break; } break; case SkPath::kQuad_Verb: case SkPath::kConic_Verb: switch (v) { case SkPath::kLine_Verb: pts[1] = pts[2]; break; case SkPath::kConic_Verb: weight = w; case SkPath::kQuad_Verb: break; case SkPath::kCubic_Verb: { SkDQuad dQuad; dQuad.set(pts); SkDCubic dCubic = dQuad.debugToCubic(); pts[3] = pts[2]; pts[1] = dCubic[1].asSkPoint(); pts[2] = dCubic[2].asSkPoint(); } break; default: SkASSERT(0); break; } break; case SkPath::kCubic_Verb: switch (v) { case SkPath::kLine_Verb: pts[1] = pts[3]; break; case SkPath::kConic_Verb: weight = w; case SkPath::kQuad_Verb: { SkDCubic dCubic; dCubic.set(pts); SkDQuad dQuad = dCubic.toQuad(); pts[1] = dQuad[1].asSkPoint(); pts[2] = pts[3]; } break; default: SkASSERT(0); break; } break; default: SkASSERT(0); break; } verb = v; } switch (verb) { case SkPath::kMove_Verb: result.moveTo(pts[0]); break; case SkPath::kLine_Verb: result.lineTo(pts[1]); break; case SkPath::kQuad_Verb: result.quadTo(pts[1], pts[2]); break; case SkPath::kConic_Verb: result.conicTo(pts[1], pts[2], weight); break; case SkPath::kCubic_Verb: result.cubicTo(pts[1], pts[2], pts[3]); break; case SkPath::kClose_Verb: result.close(); break; default: SkASSERT(0); break; } } *path = result; } static void add_to_map(SkScalar coverage, int x, int y, uint8_t* distanceMap, int w, int h) { int byteCoverage = (int) (coverage * 256); if (byteCoverage < 0) { byteCoverage = 0; } else if (byteCoverage > 255) { byteCoverage = 255; } SkASSERT(x < w); SkASSERT(y < h); distanceMap[y * w + x] = SkTMax(distanceMap[y * w + x], (uint8_t) byteCoverage); } static void filter_coverage(const uint8_t* map, int len, uint8_t min, uint8_t max, uint8_t* filter) { for (int index = 0; index < len; ++index) { uint8_t in = map[index]; filter[index] = in < min ? 0 : max < in ? 0 : in; } } static void construct_path(SkPath& path) { path.reset(); path.moveTo(442, 101.5f); path.quadTo(413.5f, 691, 772, 514); path.lineTo(346, 721.5f); path.lineTo(154, 209); path.lineTo(442, 101.5f); path.close(); } struct ButtonPaints { static const int kMaxStateCount = 3; SkPaint fDisabled; SkPaint fStates[kMaxStateCount]; SkPaint fLabel; ButtonPaints() { fStates[0].setAntiAlias(true); fStates[0].setStyle(SkPaint::kStroke_Style); fStates[0].setColor(0xFF3F0000); fStates[1] = fStates[0]; fStates[1].setStrokeWidth(3); fStates[2] = fStates[1]; fStates[2].setColor(0xFFcf0000); fLabel.setAntiAlias(true); fLabel.setTextSize(25.0f); fLabel.setTextAlign(SkPaint::kCenter_Align); fLabel.setStyle(SkPaint::kFill_Style); } }; struct Button { SkRect fBounds; int fStateCount; int fState; char fLabel; bool fVisible; Button(char label) { fStateCount = 2; fState = 0; fLabel = label; fVisible = false; } Button(char label, int stateCount) { SkASSERT(stateCount <= ButtonPaints::kMaxStateCount); fStateCount = stateCount; fState = 0; fLabel = label; fVisible = false; } bool contains(const SkRect& rect) { return fVisible && fBounds.contains(rect); } bool enabled() { return SkToBool(fState); } void draw(SkCanvas* canvas, const ButtonPaints& paints) { if (!fVisible) { return; } canvas->drawRect(fBounds, paints.fStates[fState]); canvas->drawText(&fLabel, 1, fBounds.centerX(), fBounds.fBottom - 5, paints.fLabel); } void toggle() { if (++fState == fStateCount) { fState = 0; } } void setEnabled(bool enabled) { fState = (int) enabled; } }; struct ControlPaints { SkPaint fOutline; SkPaint fIndicator; SkPaint fFill; SkPaint fLabel; SkPaint fValue; ControlPaints() { fOutline.setAntiAlias(true); fOutline.setStyle(SkPaint::kStroke_Style); fIndicator = fOutline; fIndicator.setColor(SK_ColorRED); fFill.setAntiAlias(true); fFill.setColor(0x7fff0000); fLabel.setAntiAlias(true); fLabel.setTextSize(13.0f); fValue.setAntiAlias(true); fValue.setTextSize(11.0f); } }; struct UniControl { SkString fName; SkRect fBounds; SkScalar fMin; SkScalar fMax; SkScalar fValLo; SkScalar fYLo; bool fVisible; UniControl(const char* name, SkScalar min, SkScalar max) { fName = name; fValLo = fMin = min; fMax = max; fVisible = false; } virtual ~UniControl() {} bool contains(const SkRect& rect) { return fVisible && fBounds.contains(rect); } virtual void draw(SkCanvas* canvas, const ControlPaints& paints) { if (!fVisible) { return; } canvas->drawRect(fBounds, paints.fOutline); fYLo = fBounds.fTop + (fValLo - fMin) * fBounds.height() / (fMax - fMin); canvas->drawLine(fBounds.fLeft - 5, fYLo, fBounds.fRight + 5, fYLo, paints.fIndicator); SkString label; label.printf(""%0.3g"", fValLo); canvas->drawString(label, fBounds.fLeft + 5, fYLo - 5, paints.fValue); canvas->drawString(fName, fBounds.fLeft, fBounds.bottom() + 11, paints.fLabel); } }; struct BiControl : public UniControl { SkScalar fValHi; BiControl(const char* name, SkScalar min, SkScalar max) : UniControl(name, min, max) , fValHi(fMax) { } virtual ~BiControl() {} virtual void draw(SkCanvas* canvas, const ControlPaints& paints) { UniControl::draw(canvas, paints); if (!fVisible || fValHi == fValLo) { return; } SkScalar yPos = fBounds.fTop + (fValHi - fMin) * fBounds.height() / (fMax - fMin); canvas->drawLine(fBounds.fLeft - 5, yPos, fBounds.fRight + 5, yPos, paints.fIndicator); SkString label; label.printf(""%0.3g"", fValHi); if (yPos < fYLo + 10) { yPos = fYLo + 10; } canvas->drawString(label, fBounds.fLeft + 5, yPos - 5, paints.fValue); SkRect fill = { fBounds.fLeft, fYLo, fBounds.fRight, yPos }; canvas->drawRect(fill, paints.fFill); } }; class MyClick : public SampleView::Click { public: enum ClickType { kInvalidType = -1, kPtType, kVerbType, kControlType, kPathType, } fType; enum ControlType { kInvalidControl = -1, kFirstControl, kFilterControl = kFirstControl, kResControl, kWeightControl, kWidthControl, kLastControl = kWidthControl, kFirstButton, kCubicButton = kFirstButton, kConicButton, kQuadButton, kLineButton, kLastVerbButton = kLineButton, kAddButton, kDeleteButton, kInOutButton, kFillButton, kSkeletonButton, kFilterButton, kBisectButton, kJoinButton, kLastButton = kJoinButton, kPathMove, } fControl; SkPath::Verb fVerb; SkScalar fWeight; MyClick(SkView* target, ClickType type, ControlType control) : Click(target) , fType(type) , fControl(control) , fVerb((SkPath::Verb) -1) , fWeight(1) { } MyClick(SkView* target, ClickType type, int index) : Click(target) , fType(type) , fControl((ControlType) index) , fVerb((SkPath::Verb) -1) , fWeight(1) { } MyClick(SkView* target, ClickType type, int index, SkPath::Verb verb, SkScalar weight) : Click(target) , fType(type) , fControl((ControlType) index) , fVerb(verb) , fWeight(weight) { } bool isButton() { return kFirstButton <= fControl && fControl <= kLastButton; } int ptHit() const { SkASSERT(fType == kPtType); return (int) fControl; } int verbHit() const { SkASSERT(fType == kVerbType); return (int) fControl; } }; enum { kControlCount = MyClick::kLastControl - MyClick::kFirstControl + 1, }; static struct ControlPair { UniControl* fControl; MyClick::ControlType fControlType; } kControlList[kControlCount]; enum { kButtonCount = MyClick::kLastButton - MyClick::kFirstButton + 1, kVerbCount = MyClick::kLastVerbButton - MyClick::kFirstButton + 1, }; static struct ButtonPair { Button* fButton; MyClick::ControlType fButtonType; } kButtonList[kButtonCount]; static void enable_verb_button(MyClick::ControlType type) { for (int index = 0; index < kButtonCount; ++index) { MyClick::ControlType testType = kButtonList[index].fButtonType; if (MyClick::kFirstButton <= testType && testType <= MyClick::kLastVerbButton) { Button* button = kButtonList[index].fButton; button->setEnabled(testType == type); } } } struct Stroke; struct Active { Active* fNext; Stroke* fParent; SkScalar fStart; SkScalar fEnd; void reset() { fNext = NULL; fStart = 0; fEnd = 1; } }; struct Stroke { SkPath fPath; Active fActive; bool fInner; void reset() { fPath.reset(); fActive.reset(); } }; struct PathUndo { SkPath fPath; PathUndo* fNext; }; class AAGeometryView : public SampleView { SkPaint fActivePaint; SkPaint fComplexPaint; SkPaint fCoveragePaint; SkPaint fLegendLeftPaint; SkPaint fLegendRightPaint; SkPaint fPointPaint; SkPaint fSkeletonPaint; SkPaint fLightSkeletonPaint; SkPath fPath; ControlPaints fControlPaints; UniControl fResControl; UniControl fWeightControl; UniControl fWidthControl; BiControl fFilterControl; ButtonPaints fButtonPaints; Button fCubicButton; Button fConicButton; Button fQuadButton; Button fLineButton; Button fAddButton; Button fDeleteButton; Button fFillButton; Button fSkeletonButton; Button fFilterButton; Button fBisectButton; Button fJoinButton; Button fInOutButton; SkTArray fStrokes; PathUndo* fUndo; int fActivePt; int fActiveVerb; bool fHandlePathMove; bool fShowLegend; bool fHideAll; const int kHitToleranace = 5; public: AAGeometryView() : fResControl(""error"", 0, 10) , fWeightControl(""weight"", 0, 5) , fWidthControl(""width"", FLT_EPSILON, 100) , fFilterControl(""filter"", 0, 255) , fCubicButton('C') , fConicButton('K') , fQuadButton('Q') , fLineButton('L') , fAddButton('+') , fDeleteButton('x') , fFillButton('p') , fSkeletonButton('s') , fFilterButton('f', 3) , fBisectButton('b') , fJoinButton('j') , fInOutButton('|') , fUndo(NULL) , fActivePt(-1) , fActiveVerb(-1) , fHandlePathMove(true) , fShowLegend(false) , fHideAll(false) { fCoveragePaint.setAntiAlias(true); fCoveragePaint.setColor(SK_ColorBLUE); SkPaint strokePaint; strokePaint.setAntiAlias(true); strokePaint.setStyle(SkPaint::kStroke_Style); fPointPaint = strokePaint; fPointPaint.setColor(0x99ee3300); fSkeletonPaint = strokePaint; fSkeletonPaint.setColor(SK_ColorRED); fLightSkeletonPaint = fSkeletonPaint; fLightSkeletonPaint.setColor(0xFFFF7f7f); fActivePaint = strokePaint; fActivePaint.setColor(0x99ee3300); fActivePaint.setStrokeWidth(5); fComplexPaint = fActivePaint; fComplexPaint.setColor(SK_ColorBLUE); fLegendLeftPaint.setAntiAlias(true); fLegendLeftPaint.setTextSize(13); fLegendRightPaint = fLegendLeftPaint; fLegendRightPaint.setTextAlign(SkPaint::kRight_Align); construct_path(fPath); fFillButton.fVisible = fSkeletonButton.fVisible = fFilterButton.fVisible = fBisectButton.fVisible = fJoinButton.fVisible = fInOutButton.fVisible = true; fSkeletonButton.setEnabled(true); fInOutButton.setEnabled(true); fJoinButton.setEnabled(true); fFilterControl.fValLo = 120; fFilterControl.fValHi = 141; fFilterControl.fVisible = fFilterButton.fState == 2; fResControl.fValLo = 5; fResControl.fVisible = true; fWidthControl.fValLo = 50; fWidthControl.fVisible = true; init_controlList(); init_buttonList(); } bool constructPath() { construct_path(fPath); this->inval(NULL); return true; } void savePath(Click::State state) { if (state != Click::kDown_State) { return; } if (fUndo && fUndo->fPath == fPath) { return; } PathUndo* undo = new PathUndo; undo->fPath = fPath; undo->fNext = fUndo; fUndo = undo; } bool undo() { if (!fUndo) { return false; } fPath = fUndo->fPath; validatePath(); PathUndo* next = fUndo->fNext; delete fUndo; fUndo = next; this->inval(NULL); return true; } void validatePath() { PathUndo* undo = fUndo; int match = 0; while (undo) { match += fPath == undo->fPath; undo = undo->fNext; } } void set_controlList(int index, UniControl* control, MyClick::ControlType type) { kControlList[index].fControl = control; kControlList[index].fControlType = type; } #define SET_CONTROL(Name) set_controlList(index++, &f##Name##Control, \\ MyClick::k##Name##Control) bool hideAll() { fHideAll ^= true; this->inval(NULL); return true; } void init_controlList() { int index = 0; SET_CONTROL(Width); SET_CONTROL(Res); SET_CONTROL(Filter); SET_CONTROL(Weight); } #undef SET_CONTROL void set_buttonList(int index, Button* button, MyClick::ControlType type) { kButtonList[index].fButton = button; kButtonList[index].fButtonType = type; } #define SET_BUTTON(Name) set_buttonList(index++, &f##Name##Button, \\ MyClick::k##Name##Button) void init_buttonList() { int index = 0; SET_BUTTON(Fill); SET_BUTTON(Skeleton); SET_BUTTON(Filter); SET_BUTTON(Bisect); SET_BUTTON(Join); SET_BUTTON(InOut); SET_BUTTON(Cubic); SET_BUTTON(Conic); SET_BUTTON(Quad); SET_BUTTON(Line); SET_BUTTON(Add); SET_BUTTON(Delete); } #undef SET_BUTTON // overrides from SkEventSink bool onQuery(SkEvent* evt) override; void onSizeChange() override { setControlButtonsPos(); this->INHERITED::onSizeChange(); } bool pathDump() { fPath.dump(); return true; } bool scaleDown() { SkMatrix matrix; SkRect bounds = fPath.getBounds(); matrix.setScale(1.f / 1.5f, 1.f / 1.5f, bounds.centerX(), bounds.centerY()); fPath.transform(matrix); validatePath(); this->inval(NULL); return true; } bool scaleToFit() { SkMatrix matrix; SkRect bounds = fPath.getBounds(); SkScalar scale = SkTMin(this->width() / bounds.width(), this->height() / bounds.height()) * 0.8f; matrix.setScale(scale, scale, bounds.centerX(), bounds.centerY()); fPath.transform(matrix); bounds = fPath.getBounds(); SkScalar offsetX = (this->width() - bounds.width()) / 2 - bounds.fLeft; SkScalar offsetY = (this->height() - bounds.height()) / 2 - bounds.fTop; fPath.offset(offsetX, offsetY); validatePath(); this->inval(NULL); return true; } bool scaleUp() { SkMatrix matrix; SkRect bounds = fPath.getBounds(); matrix.setScale(1.5f, 1.5f, bounds.centerX(), bounds.centerY()); fPath.transform(matrix); validatePath(); this->inval(NULL); return true; } void setControlButtonsPos() { SkScalar widthOffset = this->width() - 100; for (int index = 0; index < kControlCount; ++index) { if (kControlList[index].fControl->fVisible) { kControlList[index].fControl->fBounds.setXYWH(widthOffset, 30, 30, 400); widthOffset -= 50; } } SkScalar buttonOffset = 0; for (int index = 0; index < kButtonCount; ++index) { kButtonList[index].fButton->fBounds.setXYWH(this->width() - 50, buttonOffset += 50, 30, 30); } } bool showLegend() { fShowLegend ^= true; this->inval(NULL); return true; } void draw_bisect(SkCanvas* canvas, const SkVector& lastVector, const SkVector& vector, const SkPoint& pt) { SkVector lastV = lastVector; SkScalar lastLen = lastVector.length(); SkVector nextV = vector; SkScalar nextLen = vector.length(); if (lastLen < nextLen) { lastV.setLength(nextLen); } else { nextV.setLength(lastLen); } SkVector bisect = { (lastV.fX + nextV.fX) / 2, (lastV.fY + nextV.fY) / 2 }; bisect.setLength(fWidthControl.fValLo * 2); if (fBisectButton.enabled()) { canvas->drawLine(pt, pt + bisect, fSkeletonPaint); } lastV.setLength(fWidthControl.fValLo); if (fBisectButton.enabled()) { canvas->drawLine(pt, {pt.fX - lastV.fY, pt.fY + lastV.fX}, fSkeletonPaint); } nextV.setLength(fWidthControl.fValLo); if (fBisectButton.enabled()) { canvas->drawLine(pt, {pt.fX + nextV.fY, pt.fY - nextV.fX}, fSkeletonPaint); } if (fJoinButton.enabled()) { SkScalar r = fWidthControl.fValLo; SkRect oval = { pt.fX - r, pt.fY - r, pt.fX + r, pt.fY + r}; SkScalar startAngle = SkScalarATan2(lastV.fX, -lastV.fY) * 180.f / SK_ScalarPI; SkScalar endAngle = SkScalarATan2(-nextV.fX, nextV.fY) * 180.f / SK_ScalarPI; if (endAngle > startAngle) { canvas->drawArc(oval, startAngle, endAngle - startAngle, false, fSkeletonPaint); } else { canvas->drawArc(oval, startAngle, 360 - (startAngle - endAngle), false, fSkeletonPaint); } } } void draw_bisects(SkCanvas* canvas, bool activeOnly) { SkVector firstVector, lastVector, nextLast, vector; SkPoint pts[4]; SkPoint firstPt = { 0, 0 }; // init to avoid warning; SkPath::Verb verb; SkPath::Iter iter(fPath, true); bool foundFirst = false; int counter = -1; while ((verb = iter.next(pts)) != SkPath::kDone_Verb) { ++counter; if (activeOnly && counter != fActiveVerb && counter - 1 != fActiveVerb && counter + 1 != fActiveVerb && (fActiveVerb != 1 || counter != fPath.countVerbs())) { continue; } switch (verb) { case SkPath::kLine_Verb: nextLast = pts[0] - pts[1]; vector = pts[1] - pts[0]; break; case SkPath::kQuad_Verb: { nextLast = pts[1] - pts[2]; if (SkScalarNearlyZero(nextLast.length())) { nextLast = pts[0] - pts[2]; } vector = pts[1] - pts[0]; if (SkScalarNearlyZero(vector.length())) { vector = pts[2] - pts[0]; } if (!fBisectButton.enabled()) { break; } SkScalar t = SkFindQuadMaxCurvature(pts); if (0 < t && t < 1) { SkPoint maxPt = SkEvalQuadAt(pts, t); SkVector tangent = SkEvalQuadTangentAt(pts, t); tangent.setLength(fWidthControl.fValLo * 2); canvas->drawLine(maxPt, {maxPt.fX + tangent.fY, maxPt.fY - tangent.fX}, fSkeletonPaint); } } break; case SkPath::kConic_Verb: nextLast = pts[1] - pts[2]; if (SkScalarNearlyZero(nextLast.length())) { nextLast = pts[0] - pts[2]; } vector = pts[1] - pts[0]; if (SkScalarNearlyZero(vector.length())) { vector = pts[2] - pts[0]; } if (!fBisectButton.enabled()) { break; } // FIXME : need max curvature or equivalent here break; case SkPath::kCubic_Verb: { nextLast = pts[2] - pts[3]; if (SkScalarNearlyZero(nextLast.length())) { nextLast = pts[1] - pts[3]; if (SkScalarNearlyZero(nextLast.length())) { nextLast = pts[0] - pts[3]; } } vector = pts[0] - pts[1]; if (SkScalarNearlyZero(vector.length())) { vector = pts[0] - pts[2]; if (SkScalarNearlyZero(vector.length())) { vector = pts[0] - pts[3]; } } if (!fBisectButton.enabled()) { break; } SkScalar tMax[2]; int tMaxCount = SkFindCubicMaxCurvature(pts, tMax); for (int tIndex = 0; tIndex < tMaxCount; ++tIndex) { if (0 >= tMax[tIndex] || tMax[tIndex] >= 1) { continue; } SkPoint maxPt; SkVector tangent; SkEvalCubicAt(pts, tMax[tIndex], &maxPt, &tangent, NULL); tangent.setLength(fWidthControl.fValLo * 2); canvas->drawLine(maxPt, {maxPt.fX + tangent.fY, maxPt.fY - tangent.fX}, fSkeletonPaint); } } break; case SkPath::kClose_Verb: if (foundFirst) { draw_bisect(canvas, lastVector, firstVector, firstPt); foundFirst = false; } break; default: break; } if (SkPath::kLine_Verb <= verb && verb <= SkPath::kCubic_Verb) { if (!foundFirst) { firstPt = pts[0]; firstVector = vector; foundFirst = true; } else { draw_bisect(canvas, lastVector, vector, pts[0]); } lastVector = nextLast; } } } void draw_legend(SkCanvas* canvas); void draw_segment(SkCanvas* canvas) { SkPoint pts[4]; SkPath::Verb verb; SkPath::Iter iter(fPath, true); int counter = -1; while ((verb = iter.next(pts)) != SkPath::kDone_Verb) { if (++counter < fActiveVerb) { continue; } switch (verb) { case SkPath::kLine_Verb: canvas->drawPoints(SkCanvas::kLines_PointMode, 2, pts, fActivePaint); draw_points(canvas, pts, 2); break; case SkPath::kQuad_Verb: { SkPath qPath; qPath.moveTo(pts[0]); qPath.quadTo(pts[1], pts[2]); canvas->drawPath(qPath, fActivePaint); draw_points(canvas, pts, 3); } break; case SkPath::kConic_Verb: { SkPath conicPath; conicPath.moveTo(pts[0]); conicPath.conicTo(pts[1], pts[2], iter.conicWeight()); canvas->drawPath(conicPath, fActivePaint); draw_points(canvas, pts, 3); } break; case SkPath::kCubic_Verb: { SkScalar loopT[3]; int complex = SkDCubic::ComplexBreak(pts, loopT); SkPath cPath; cPath.moveTo(pts[0]); cPath.cubicTo(pts[1], pts[2], pts[3]); canvas->drawPath(cPath, complex ? fComplexPaint : fActivePaint); draw_points(canvas, pts, 4); } break; default: break; } return; } } void draw_points(SkCanvas* canvas, SkPoint* points, int count) { for (int index = 0; index < count; ++index) { canvas->drawCircle(points[index].fX, points[index].fY, 10, fPointPaint); } } int hittest_verb(SkPoint pt, SkPath::Verb* verbPtr, SkScalar* weight) { SkIntersections i; SkDLine hHit = {{{pt.fX - kHitToleranace, pt.fY }, {pt.fX + kHitToleranace, pt.fY}}}; SkDLine vHit = {{{pt.fX, pt.fY - kHitToleranace }, {pt.fX, pt.fY + kHitToleranace}}}; SkPoint pts[4]; SkPath::Verb verb; SkPath::Iter iter(fPath, true); int counter = -1; while ((verb = iter.next(pts)) != SkPath::kDone_Verb) { ++counter; switch (verb) { case SkPath::kLine_Verb: { SkDLine line; line.set(pts); if (i.intersect(line, hHit) || i.intersect(line, vHit)) { *verbPtr = verb; *weight = 1; return counter; } } break; case SkPath::kQuad_Verb: { SkDQuad quad; quad.set(pts); if (i.intersect(quad, hHit) || i.intersect(quad, vHit)) { *verbPtr = verb; *weight = 1; return counter; } } break; case SkPath::kConic_Verb: { SkDConic conic; SkScalar w = iter.conicWeight(); conic.set(pts, w); if (i.intersect(conic, hHit) || i.intersect(conic, vHit)) { *verbPtr = verb; *weight = w; return counter; } } break; case SkPath::kCubic_Verb: { SkDCubic cubic; cubic.set(pts); if (i.intersect(cubic, hHit) || i.intersect(cubic, vHit)) { *verbPtr = verb; *weight = 1; return counter; } } break; default: break; } } return -1; } SkScalar pt_to_line(SkPoint s, SkPoint e, int x, int y) { SkScalar radius = fWidthControl.fValLo; SkVector adjOpp = e - s; SkScalar lenSq = adjOpp.lengthSqd(); SkPoint rotated = { (y - s.fY) * adjOpp.fY + (x - s.fX) * adjOpp.fX, (y - s.fY) * adjOpp.fX - (x - s.fX) * adjOpp.fY, }; if (rotated.fX < 0 || rotated.fX > lenSq) { return -radius; } rotated.fY /= SkScalarSqrt(lenSq); return SkTMax(-radius, SkTMin(radius, rotated.fY)); } // given a line, compute the interior and exterior gradient coverage bool coverage(SkPoint s, SkPoint e, uint8_t* distanceMap, int w, int h) { SkScalar radius = fWidthControl.fValLo; int minX = SkTMax(0, (int) (SkTMin(s.fX, e.fX) - radius)); int minY = SkTMax(0, (int) (SkTMin(s.fY, e.fY) - radius)); int maxX = SkTMin(w, (int) (SkTMax(s.fX, e.fX) + radius) + 1); int maxY = SkTMin(h, (int) (SkTMax(s.fY, e.fY) + radius) + 1); for (int y = minY; y < maxY; ++y) { for (int x = minX; x < maxX; ++x) { SkScalar ptToLineDist = pt_to_line(s, e, x, y); if (ptToLineDist > -radius && ptToLineDist < radius) { SkScalar coverage = ptToLineDist / radius; add_to_map(1 - SkScalarAbs(coverage), x, y, distanceMap, w, h); } SkVector ptToS = { x - s.fX, y - s.fY }; SkScalar dist = ptToS.length(); if (dist < radius) { SkScalar coverage = dist / radius; add_to_map(1 - SkScalarAbs(coverage), x, y, distanceMap, w, h); } SkVector ptToE = { x - e.fX, y - e.fY }; dist = ptToE.length(); if (dist < radius) { SkScalar coverage = dist / radius; add_to_map(1 - SkScalarAbs(coverage), x, y, distanceMap, w, h); } } } return true; } void quad_coverage(SkPoint pts[3], uint8_t* distanceMap, int w, int h) { SkScalar dist = pts[0].Distance(pts[0], pts[2]); if (dist < gCurveDistance) { (void) coverage(pts[0], pts[2], distanceMap, w, h); return; } SkPoint split[5]; SkChopQuadAt(pts, split, 0.5f); quad_coverage(&split[0], distanceMap, w, h); quad_coverage(&split[2], distanceMap, w, h); } void conic_coverage(SkPoint pts[3], SkScalar weight, uint8_t* distanceMap, int w, int h) { SkScalar dist = pts[0].Distance(pts[0], pts[2]); if (dist < gCurveDistance) { (void) coverage(pts[0], pts[2], distanceMap, w, h); return; } SkConic split[2]; SkConic conic; conic.set(pts, weight); if (conic.chopAt(0.5f, split)) { conic_coverage(split[0].fPts, split[0].fW, distanceMap, w, h); conic_coverage(split[1].fPts, split[1].fW, distanceMap, w, h); } } void cubic_coverage(SkPoint pts[4], uint8_t* distanceMap, int w, int h) { SkScalar dist = pts[0].Distance(pts[0], pts[3]); if (dist < gCurveDistance) { (void) coverage(pts[0], pts[3], distanceMap, w, h); return; } SkPoint split[7]; SkChopCubicAt(pts, split, 0.5f); cubic_coverage(&split[0], distanceMap, w, h); cubic_coverage(&split[3], distanceMap, w, h); } void path_coverage(const SkPath& path, uint8_t* distanceMap, int w, int h) { memset(distanceMap, 0, sizeof(distanceMap[0]) * w * h); SkPoint pts[4]; SkPath::Verb verb; SkPath::Iter iter(path, true); while ((verb = iter.next(pts)) != SkPath::kDone_Verb) { switch (verb) { case SkPath::kLine_Verb: (void) coverage(pts[0], pts[1], distanceMap, w, h); break; case SkPath::kQuad_Verb: quad_coverage(pts, distanceMap, w, h); break; case SkPath::kConic_Verb: conic_coverage(pts, iter.conicWeight(), distanceMap, w, h); break; case SkPath::kCubic_Verb: cubic_coverage(pts, distanceMap, w, h); break; default: break; } } } static uint8_t* set_up_dist_map(const SkImageInfo& imageInfo, SkBitmap* distMap) { distMap->setInfo(imageInfo); distMap->setIsVolatile(true); SkAssertResult(distMap->tryAllocPixels()); SkASSERT((int) distMap->rowBytes() == imageInfo.width()); return distMap->getAddr8(0, 0); } void path_stroke(int index, SkPath* inner, SkPath* outer) { #if 0 SkPathStroker stroker(fPath, fWidthControl.fValLo, 0, SkPaint::kRound_Cap, SkPaint::kRound_Join, fResControl.fValLo); SkPoint pts[4], firstPt, lastPt; SkPath::Verb verb; SkPath::Iter iter(fPath, true); int counter = -1; while ((verb = iter.next(pts)) != SkPath::kDone_Verb) { ++counter; switch (verb) { case SkPath::kMove_Verb: firstPt = pts[0]; break; case SkPath::kLine_Verb: if (counter == index) { stroker.moveTo(pts[0]); stroker.lineTo(pts[1]); goto done; } lastPt = pts[1]; break; case SkPath::kQuad_Verb: if (counter == index) { stroker.moveTo(pts[0]); stroker.quadTo(pts[1], pts[2]); goto done; } lastPt = pts[2]; break; case SkPath::kConic_Verb: if (counter == index) { stroker.moveTo(pts[0]); stroker.conicTo(pts[1], pts[2], iter.conicWeight()); goto done; } lastPt = pts[2]; break; case SkPath::kCubic_Verb: if (counter == index) { stroker.moveTo(pts[0]); stroker.cubicTo(pts[1], pts[2], pts[3]); goto done; } lastPt = pts[3]; break; case SkPath::kClose_Verb: if (counter == index) { stroker.moveTo(lastPt); stroker.lineTo(firstPt); goto done; } break; case SkPath::kDone_Verb: break; default: SkASSERT(0); } } done: *inner = stroker.fInner; *outer = stroker.fOuter; #endif } void draw_stroke(SkCanvas* canvas, int active) { SkPath inner, outer; path_stroke(active, &inner, &outer); canvas->drawPath(inner, fSkeletonPaint); canvas->drawPath(outer, fSkeletonPaint); } void gather_strokes() { fStrokes.reset(); for (int index = 0; index < fPath.countVerbs(); ++index) { Stroke& inner = fStrokes.push_back(); inner.reset(); inner.fInner = true; Stroke& outer = fStrokes.push_back(); outer.reset(); outer.fInner = false; path_stroke(index, &inner.fPath, &outer.fPath); } } void trim_strokes() { // eliminate self-itersecting loops // trim outside edges gather_strokes(); for (int index = 0; index < fStrokes.count(); ++index) { SkPath& outPath = fStrokes[index].fPath; for (int inner = 0; inner < fStrokes.count(); ++inner) { if (index == inner) { continue; } SkPath& inPath = fStrokes[inner].fPath; if (!outPath.getBounds().intersects(inPath.getBounds())) { continue; } } } } void onDrawContent(SkCanvas* canvas) override { #if 0 SkDEBUGCODE(SkDebugStrokeGlobals debugGlobals); SkOpAA aaResult(fPath, fWidthControl.fValLo, fResControl.fValLo SkDEBUGPARAMS(&debugGlobals)); #endif SkPath strokePath; // aaResult.simplify(&strokePath); canvas->drawPath(strokePath, fSkeletonPaint); SkRect bounds = fPath.getBounds(); SkScalar radius = fWidthControl.fValLo; int w = (int) (bounds.fRight + radius + 1); int h = (int) (bounds.fBottom + radius + 1); SkImageInfo imageInfo = SkImageInfo::MakeA8(w, h); SkBitmap distMap; uint8_t* distanceMap = set_up_dist_map(imageInfo, &distMap); path_coverage(fPath, distanceMap, w, h); if (fFillButton.enabled()) { canvas->drawPath(fPath, fCoveragePaint); } if (fFilterButton.fState == 2 && (0 < fFilterControl.fValLo || fFilterControl.fValHi < 255)) { SkBitmap filteredMap; uint8_t* filtered = set_up_dist_map(imageInfo, &filteredMap); filter_coverage(distanceMap, sizeof(uint8_t) * w * h, (uint8_t) fFilterControl.fValLo, (uint8_t) fFilterControl.fValHi, filtered); canvas->drawBitmap(filteredMap, 0, 0, &fCoveragePaint); } else if (fFilterButton.enabled()) { canvas->drawBitmap(distMap, 0, 0, &fCoveragePaint); } if (fSkeletonButton.enabled()) { canvas->drawPath(fPath, fActiveVerb >= 0 ? fLightSkeletonPaint : fSkeletonPaint); } if (fActiveVerb >= 0) { draw_segment(canvas); } if (fBisectButton.enabled() || fJoinButton.enabled()) { draw_bisects(canvas, fActiveVerb >= 0); } if (fInOutButton.enabled()) { if (fActiveVerb >= 0) { draw_stroke(canvas, fActiveVerb); } else { for (int index = 0; index < fPath.countVerbs(); ++index) { draw_stroke(canvas, index); } } } if (fHideAll) { return; } for (int index = 0; index < kControlCount; ++index) { kControlList[index].fControl->draw(canvas, fControlPaints); } for (int index = 0; index < kButtonCount; ++index) { kButtonList[index].fButton->draw(canvas, fButtonPaints); } if (fShowLegend) { draw_legend(canvas); } #if 0 SkPaint paint; paint.setARGB(255, 34, 31, 31); paint.setAntiAlias(true); SkPath path; path.moveTo(18,439); path.lineTo(414,439); path.lineTo(414,702); path.lineTo(18,702); path.lineTo(18,439); path.moveTo(19,701); path.lineTo(413,701); path.lineTo(413,440); path.lineTo(19,440); path.lineTo(19,701); path.close(); canvas->drawPath(path, paint); canvas->scale(1.0f, -1.0f); canvas->translate(0.0f, -800.0f); canvas->drawPath(path, paint); #endif } int hittest_pt(SkPoint pt) { for (int index = 0; index < fPath.countPoints(); ++index) { if (SkPoint::Distance(fPath.getPoint(index), pt) <= kHitToleranace * 2) { return index; } } return -1; } virtual SkView::Click* onFindClickHandler(SkScalar x, SkScalar y, unsigned modi) override { SkPoint pt = {x, y}; int ptHit = hittest_pt(pt); if (ptHit >= 0) { return new MyClick(this, MyClick::kPtType, ptHit); } SkPath::Verb verb; SkScalar weight; int verbHit = hittest_verb(pt, &verb, &weight); if (verbHit >= 0) { return new MyClick(this, MyClick::kVerbType, verbHit, verb, weight); } if (!fHideAll) { const SkRect& rectPt = SkRect::MakeXYWH(x, y, 1, 1); for (int index = 0; index < kControlCount; ++index) { if (kControlList[index].fControl->contains(rectPt)) { return new MyClick(this, MyClick::kControlType, kControlList[index].fControlType); } } for (int index = 0; index < kButtonCount; ++index) { if (kButtonList[index].fButton->contains(rectPt)) { return new MyClick(this, MyClick::kControlType, kButtonList[index].fButtonType); } } } fLineButton.fVisible = fQuadButton.fVisible = fConicButton.fVisible = fCubicButton.fVisible = fWeightControl.fVisible = fAddButton.fVisible = fDeleteButton.fVisible = false; fActiveVerb = -1; fActivePt = -1; if (fHandlePathMove) { return new MyClick(this, MyClick::kPathType, MyClick::kPathMove); } return this->INHERITED::onFindClickHandler(x, y, modi); } static SkScalar MapScreenYtoValue(int y, const UniControl& control) { return SkTMin(1.f, SkTMax(0.f, SkIntToScalar(y) - control.fBounds.fTop) / control.fBounds.height()) * (control.fMax - control.fMin) + control.fMin; } bool onClick(Click* click) override { MyClick* myClick = (MyClick*) click; switch (myClick->fType) { case MyClick::kPtType: { savePath(click->fState); fActivePt = myClick->ptHit(); SkPoint pt = fPath.getPoint((int) myClick->fControl); pt.offset(SkIntToScalar(click->fICurr.fX - click->fIPrev.fX), SkIntToScalar(click->fICurr.fY - click->fIPrev.fY)); set_path_pt(fActivePt, pt, &fPath); validatePath(); this->inval(NULL); return true; } case MyClick::kPathType: savePath(click->fState); fPath.offset(SkIntToScalar(click->fICurr.fX - click->fIPrev.fX), SkIntToScalar(click->fICurr.fY - click->fIPrev.fY)); validatePath(); this->inval(NULL); return true; case MyClick::kVerbType: { fActiveVerb = myClick->verbHit(); fLineButton.fVisible = fQuadButton.fVisible = fConicButton.fVisible = fCubicButton.fVisible = fAddButton.fVisible = fDeleteButton.fVisible = true; fLineButton.setEnabled(myClick->fVerb == SkPath::kLine_Verb); fQuadButton.setEnabled(myClick->fVerb == SkPath::kQuad_Verb); fConicButton.setEnabled(myClick->fVerb == SkPath::kConic_Verb); fCubicButton.setEnabled(myClick->fVerb == SkPath::kCubic_Verb); fWeightControl.fValLo = myClick->fWeight; fWeightControl.fVisible = myClick->fVerb == SkPath::kConic_Verb; } break; case MyClick::kControlType: { if (click->fState != Click::kDown_State && myClick->isButton()) { return true; } switch (myClick->fControl) { case MyClick::kFilterControl: { SkScalar val = MapScreenYtoValue(click->fICurr.fY, fFilterControl); if (val - fFilterControl.fValLo < fFilterControl.fValHi - val) { fFilterControl.fValLo = SkTMax(0.f, val); } else { fFilterControl.fValHi = SkTMin(255.f, val); } } break; case MyClick::kResControl: fResControl.fValLo = MapScreenYtoValue(click->fICurr.fY, fResControl); break; case MyClick::kWeightControl: { savePath(click->fState); SkScalar w = MapScreenYtoValue(click->fICurr.fY, fWeightControl); set_path_weight(fActiveVerb, w, &fPath); validatePath(); fWeightControl.fValLo = w; } break; case MyClick::kWidthControl: fWidthControl.fValLo = MapScreenYtoValue(click->fICurr.fY, fWidthControl); break; case MyClick::kLineButton: savePath(click->fState); enable_verb_button(myClick->fControl); fWeightControl.fVisible = false; set_path_verb(fActiveVerb, SkPath::kLine_Verb, &fPath, 1); validatePath(); break; case MyClick::kQuadButton: savePath(click->fState); enable_verb_button(myClick->fControl); fWeightControl.fVisible = false; set_path_verb(fActiveVerb, SkPath::kQuad_Verb, &fPath, 1); validatePath(); break; case MyClick::kConicButton: { savePath(click->fState); enable_verb_button(myClick->fControl); fWeightControl.fVisible = true; const SkScalar defaultConicWeight = 1.f / SkScalarSqrt(2); set_path_verb(fActiveVerb, SkPath::kConic_Verb, &fPath, defaultConicWeight); validatePath(); fWeightControl.fValLo = get_path_weight(fActiveVerb, fPath); } break; case MyClick::kCubicButton: savePath(click->fState); enable_verb_button(myClick->fControl); fWeightControl.fVisible = false; set_path_verb(fActiveVerb, SkPath::kCubic_Verb, &fPath, 1); validatePath(); break; case MyClick::kAddButton: savePath(click->fState); add_path_segment(fActiveVerb, &fPath); validatePath(); if (fWeightControl.fVisible) { fWeightControl.fValLo = get_path_weight(fActiveVerb, fPath); } break; case MyClick::kDeleteButton: savePath(click->fState); delete_path_segment(fActiveVerb, &fPath); validatePath(); break; case MyClick::kFillButton: fFillButton.toggle(); break; case MyClick::kSkeletonButton: fSkeletonButton.toggle(); break; case MyClick::kFilterButton: fFilterButton.toggle(); fFilterControl.fVisible = fFilterButton.fState == 2; break; case MyClick::kBisectButton: fBisectButton.toggle(); break; case MyClick::kJoinButton: fJoinButton.toggle(); break; case MyClick::kInOutButton: fInOutButton.toggle(); break; default: SkASSERT(0); break; } } break; default: SkASSERT(0); break; } setControlButtonsPos(); this->inval(NULL); return true; } private: typedef SampleView INHERITED; }; static struct KeyCommand { char fKey; char fAlternate; const char* fDescriptionL; const char* fDescriptionR; bool (AAGeometryView::*fFunction)(); } kKeyCommandList[] = { { ' ', 0, ""space"", ""center path"", &AAGeometryView::scaleToFit }, { '-', 0, ""-"", ""zoom out"", &AAGeometryView::scaleDown }, { '+', '=', ""+/="", ""zoom in"", &AAGeometryView::scaleUp }, { 'd', 0, ""d"", ""dump to console"", &AAGeometryView::pathDump }, { 'h', 0, ""h"", ""hide controls"", &AAGeometryView::hideAll }, { 'r', 0, ""r"", ""reset path"", &AAGeometryView::constructPath }, { 'z', 0, ""z"", ""undo"", &AAGeometryView::undo }, { '?', 0, ""?"", ""show legend"", &AAGeometryView::showLegend }, }; const int kKeyCommandCount = (int) SK_ARRAY_COUNT(kKeyCommandList); void AAGeometryView::draw_legend(SkCanvas* canvas) { SkScalar bottomOffset = this->height() - 10; for (int index = kKeyCommandCount - 1; index >= 0; --index) { bottomOffset -= 15; canvas->drawString(kKeyCommandList[index].fDescriptionL, this->width() - 160, bottomOffset, fLegendLeftPaint); canvas->drawString(kKeyCommandList[index].fDescriptionR, this->width() - 20, bottomOffset, fLegendRightPaint); } } // overrides from SkEventSink bool AAGeometryView::onQuery(SkEvent* evt) { if (SampleCode::TitleQ(*evt)) { SampleCode::TitleR(evt, ""AAGeometry""); return true; } SkUnichar uni; if (false) { return this->INHERITED::onQuery(evt); } if (SampleCode::CharQ(*evt, &uni)) { for (int index = 0; index < kButtonCount; ++index) { Button* button = kButtonList[index].fButton; if (button->fVisible && uni == button->fLabel) { MyClick click(this, MyClick::kControlType, kButtonList[index].fButtonType); click.fState = Click::kDown_State; (void) this->onClick(&click); return true; } } for (int index = 0; index < kKeyCommandCount; ++index) { KeyCommand& keyCommand = kKeyCommandList[index]; if (uni == keyCommand.fKey || uni == keyCommand.fAlternate) { return (this->*keyCommand.fFunction)(); } } if (('A' <= uni && uni <= 'Z') || ('a' <= uni && uni <= 'z')) { for (int index = 0; index < kButtonCount; ++index) { Button* button = kButtonList[index].fButton; if (button->fVisible && (uni & ~0x20) == (button->fLabel & ~0x20)) { MyClick click(this, MyClick::kControlType, kButtonList[index].fButtonType); click.fState = Click::kDown_State; (void) this->onClick(&click); return true; } } } } return this->INHERITED::onQuery(evt); } DEF_SAMPLE( return new AAGeometryView; ) ",16138,True,2842.897700103025,median "[[install-config-install-deploy-router]] = Configure or Deploy the Router {product-author} {product-version} :data-uri: :icons: :experimental: :toc: macro :toc-title: :prewrap!: toc::[] == Overview The {product-title} xref:../../architecture/core_concepts/routes.adoc#architecture-core-concepts-routes[router] is the ingress point for all external traffic destined for xref:../../architecture/core_concepts/pods_and_services.adoc#services[services] in your {product-title} installation. {product-title} provides and supports the following two router plug-ins: - The xref:../../architecture/core_concepts/routes.adoc#haproxy-template-router[HAProxy template router] is the default plug-in. It uses the ifdef::openshift-enterprise[] *openshift3/ose-haproxy-router* endif::[] ifdef::openshift-origin[] *openshift/origin-haproxy-router* endif::[] image to run an HAProxy instance alongside the template router plug-in inside a container on {product-title}. It currently supports HTTP(S) traffic and TLS-enabled traffic via SNI. The router's container listens on the host network interface, unlike most containers that listen only on private IPs. The router proxies external requests for route names to the IPs of actual pods identified by the service associated with the route. - The xref:../../architecture/core_concepts/routes.adoc#f5-router[F5 router] integrates with an existing *F5 BIG-IP®* system in your environment to synchronize routes. *F5 BIG-IP®* version 11.4 or newer is required in order to have the F5 iControl REST API. ifdef::openshift-enterprise[] [NOTE] ==== The F5 router plug-in is available starting in {product-title} 3.0.2. ==== endif::[] [[creating-the-router-service-account]] ifdef::openshift-enterprise[] == Router Service Account Before deploying an {product-title} cluster, you must have a service account for the router. Starting in {product-title} 3.1, a router xref:../../admin_guide/service_accounts.adoc#admin-guide-service-accounts[service account] is automatically created during a quick or advanced installation (previously, this required manual creation). This service account has permissions to a xref:../../architecture/additional_concepts/authorization.adoc#security-context-constraints[security context constraint] (SCC) that allows it to specify host ports. // See NB[1] below. endif::[] ifdef::openshift-origin[] == Creating the Router Service Account You must first create a xref:../../admin_guide/service_accounts.adoc#admin-guide-service-accounts[service account] for the router before deploying. This service account must have permissions to a xref:../../architecture/additional_concepts/authorization.adoc#security-context-constraints[security context constraint] (SCC) that allows it to specify host ports. To create a service account named *router* in the *default* namespace: ==== ---- $ oc create serviceaccount router -n default ---- ==== To add a privileged SCC to the *router* service account in the *default* namespace: ==== ---- $ oadm policy add-scc-to-user privileged system:serviceaccount:default:router ---- ==== // See NB[1] below. endif::[] // NB[1]: The following blurb+codeblock is to both: // - Creating the Router Service Account (origin) // - Router Service Account (enterprise) // and both of these have anchor ‘creating-the-router-service-account’. Use of labels (e.g., to define xref:using-router-shards[router shards]) requires `cluster-reader` permission. ---- $ oadm policy add-cluster-role-to-user \\ cluster-reader \\ system:serviceaccount:default:router ---- [[haproxy-router]] == Deploying the Default HAProxy Router The `oadm router` command is provided with the administrator CLI to simplify the tasks of setting up routers in a new installation. If you followed the xref:../../install_config/install/quick_install.adoc#install-config-install-quick-install[quick installation], then a default router was automatically created for you. The `oadm router` command creates the service and deployment configuration objects. Just about every form of communication between {product-title} components is secured by TLS and uses various certificates and authentication methods. Use the `--credentials` option to specify what credentials the router should use to contact the master. [IMPORTANT] ==== Routers directly attach to port 80 and 443 on all interfaces on a host. Restrict routers to hosts where port 80/443 is available and not being consumed by another service, and set this using node selectors and the xref:../../admin_guide/scheduler.adoc#admin-guide-scheduler[scheduler configuration]. As an example, you can achieve this by dedicating infrastructure nodes to run services such as routers. ==== [IMPORTANT] ==== It is recommended to use separate distinct *openshift-router* credentials with your router. The credentials can be provided using the `--credentials` flag to the `oadm router` command. Alternatively, the default cluster administrator credentials can be used from the `$KUBECONFIG` environment variable. ifdef::openshift-enterprise[] ---- $ oadm router --dry-run --service-account=router \\ --credentials='/etc/origin/master/openshift-router.kubeconfig' //<1> ---- endif::[] ifdef::openshift-origin[] ---- $ oadm router --dry-run --service-account=router \\ --credentials=${ROUTER_KUBECONFIG:-""$KUBECONFIG""} //<1> ---- endif::[] <1> `--credentials` is the path to the xref:../../cli_reference/manage_cli_profiles.adoc#cli-reference-manage-cli-profiles[CLI configuration file] for the *openshift-router*. ifdef::openshift-origin[] It is recommended using an *openshift-router* specific profile with appropriate permissions. endif::[] ==== [IMPORTANT] ==== Router pods created using `oadm router` have default resource requests that a node must satisfy for the router pod to be deployed. In an effort to increase the reliability of infrastructure components, the default resource requests are used to increase the QoS tier of the router pods above pods without resource requests. The default values represent the observed minimum resources required for a basic router to be deployed and can be edited in the routers deployment configuration and you may want to increase them based on the load of the router. ==== [[deploy-router-check-default]] Checking the Default Router:: ifdef::openshift-enterprise[] The default router service account, named *router*, is automatically created during quick and advanced installations. To verify that this account already exists: endif::[] ifdef::openshift-origin[] First, ensure you have xref:creating-the-router-service-account[created the router service account] before deploying a router. To check if a default router, named *router*, already exists: endif::[] ifdef::openshift-enterprise[] ---- $ oadm router --dry-run \\ --credentials='/etc/origin/master/openshift-router.kubeconfig' \\ --service-account=router ---- endif::[] ifdef::openshift-origin[] ---- $ oadm router --dry-run --service-account=router \\ --credentials=${ROUTER_KUBECONFIG:-""$KUBECONFIG""} ---- endif::[] [[deploy-router-viewing-default]] Viewing the Default Router:: To see what the default router would look like if created: ifdef::openshift-enterprise[] ---- $ oadm router -o yaml \\ --credentials='/etc/origin/master/openshift-router.kubeconfig' \\ --service-account=router ---- endif::[] ifdef::openshift-origin[] ---- $ oadm router -o yaml --service-account=router \\ --credentials=${ROUTER_KUBECONFIG:-""$KUBECONFIG""} ---- endif::[] [[deploy-router-create-router]] Creating a Router:: The xref:../../install_config/install/quick_install.adoc#install-config-install-quick-install[quick installation] process automatically creates a default router. To create a router if it does not exist: ifdef::openshift-enterprise[] ---- $ oadm router --replicas= \\ --credentials='/etc/origin/master/openshift-router.kubeconfig' \\ --service-account=router ---- endif::[] ifdef::openshift-origin[] ---- $ oadm router --replicas= \\ --credentials=${ROUTER_KUBECONFIG:-""$KUBECONFIG""} \\ --service-account=router ---- endif::[] [[deploy-router-to-labeled-nodes]] Deploying the Router to a Labeled Node:: To deploy the router to any node(s) that match a specified xref:../../admin_guide/manage_nodes.adoc#updating-labels-on-nodes[node label]: ifdef::openshift-enterprise[] ---- $ oadm router --replicas= --selector=

  • 0: SMSC Default Alphabet
  • 4: 8 bit Alphabet
  • 8: UCS2 Alphabet
| | Byte | *camel.component.smpp.configuration.data-coding* | Defines the data coding according the SMPP 3.4 specification, section 5.2.19. Example data encodings are:
  • 0: SMSC Default Alphabet
  • 3: Latin 1 (ISO-8859-1)
  • 4: Octet unspecified (8-bit binary)
  • 8: UCS2 (ISO/IEC-10646)
  • 13: Extended Kanji JIS(X 0212-1990)
| | Byte | *camel.component.smpp.configuration.dest-addr* | Defines the destination SME address. For mobile terminated messages, this is the directory number of the recipient MS. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. | 1717 | String | *camel.component.smpp.configuration.dest-addr-npi* | Defines the type of number (TON) to be used in the SME destination address parameters. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. The following NPI values are defined:
  • 0: Unknown
  • 1: ISDN (E163/E164)
  • 2: Data (X.121)
  • 3: Telex (F.69)
  • 6: Land Mobile (E.212)
  • 8: National
  • 9: Private
  • 10: ERMES
  • 13: Internet (IP)
  • 18: WAP Client Id (to be defined by WAP Forum)
| | Byte | *camel.component.smpp.configuration.dest-addr-ton* | Defines the type of number (TON) to be used in the SME destination address parameters. Only for SubmitSm, SubmitMulti, CancelSm and DataSm. The following TON values are defined:
  • 0: Unknown
  • 1: International
  • 2: National
  • 3: Network Specific
  • 4: Subscriber Number
  • 5: Alphanumeric
  • 6: Abbreviated
| | Byte | *camel.component.smpp.configuration.encoding* | Defines the encoding scheme of the short message user data. Only for SubmitSm, ReplaceSm and SubmitMulti. | ISO-8859-1 | String | *camel.component.smpp.configuration.enquire-link-timer* | Defines the interval in milliseconds between the confidence checks. The confidence check is used to test the communication path between an ESME and an SMSC. | 5000 | Integer | *camel.component.smpp.configuration.host* | Hostname for the SMSC server to use. | localhost | String | *camel.component.smpp.configuration.http-proxy-host* | If you need to tunnel SMPP through a HTTP proxy, set this attribute to the hostname or ip address of your HTTP proxy. | | String | *camel.component.smpp.configuration.http-proxy-password* | If your HTTP proxy requires basic authentication, set this attribute to the password required for your HTTP proxy. | | String | *camel.component.smpp.configuration.http-proxy-port* | If you need to tunnel SMPP through a HTTP proxy, set this attribute to the port of your HTTP proxy. | 3128 | Integer | *camel.component.smpp.configuration.http-proxy-username* | If your HTTP proxy requires basic authentication, set this attribute to the username required for your HTTP proxy. | | String | *camel.component.smpp.configuration.initial-reconnect-delay* | Defines the initial delay in milliseconds after the consumer/producer tries to reconnect to the SMSC, after the connection was lost. | 5000 | Long | *camel.component.smpp.configuration.lazy-session-creation* | Sessions can be lazily created to avoid exceptions, if the SMSC is not available when the Camel producer is started. Camel will check the in message headers 'CamelSmppSystemId' and 'CamelSmppPassword' of the first exchange. If they are present, Camel will use these data to connect to the SMSC. | false | Boolean | *camel.component.smpp.configuration.max-reconnect* | Defines the maximum number of attempts to reconnect to the SMSC, if SMSC returns a negative bind response | 2147483647 | Integer | *camel.component.smpp.configuration.numbering-plan-indicator* | Defines the numeric plan indicator (NPI) to be used in the SME. The following NPI values are defined:
  • 0: Unknown
  • 1: ISDN (E163/E164)
  • 2: Data (X.121)
  • 3: Telex (F.69)
  • 6: Land Mobile (E.212)
  • 8: National
  • 9: Private
  • 10: ERMES
  • 13: Internet (IP)
  • 18: WAP Client Id (to be defined by WAP Forum)
| | Byte | *camel.component.smpp.configuration.password* | Defines the encoding scheme of the short message user data. Only for SubmitSm, ReplaceSm and SubmitMulti. | | String | *camel.component.smpp.configuration.port* | Port number for the SMSC server to use. | 2775 | Integer | *camel.component.smpp.configuration.priority-flag* | Allows the originating SME to assign a priority level to the short message. Only for SubmitSm and SubmitMulti. Four Priority Levels are supported:
  • 0: Level 0 (lowest) priority
  • 1: Level 1 priority
  • 2: Level 2 priority
  • 3: Level 3 (highest) priority
| | Byte | *camel.component.smpp.configuration.protocol-id* | The protocol id | | Byte | *camel.component.smpp.configuration.proxy-headers* | These headers will be passed to the proxy server while establishing the connection. | | Map | *camel.component.smpp.configuration.reconnect-delay* | Defines the interval in milliseconds between the reconnect attempts, if the connection to the SMSC was lost and the previous was not succeed. | 5000 | Long | *camel.component.smpp.configuration.registered-delivery* | Is used to request an SMSC delivery receipt and/or SME originated acknowledgements. The following values are defined:
  • 0: No SMSC delivery receipt requested.
  • 1: SMSC delivery receipt requested where final delivery outcome is success or failure.
  • 2: SMSC delivery receipt requested where the final delivery outcome is delivery failure.
| | Byte | *camel.component.smpp.configuration.replace-if-present-flag* | Used to request the SMSC to replace a previously submitted message, that is still pending delivery. The SMSC will replace an existing message provided that the source address, destination address and service type match the same fields in the new message. The following replace if present flag values are defined:
  • 0: Don't replace
  • 1: Replace
| | Byte | *camel.component.smpp.configuration.service-type* | The service type parameter can be used to indicate the SMS Application service associated with the message. The following generic service_types are defined:
  • CMT: Cellular Messaging
  • CPT: Cellular Paging
  • VMN: Voice Mail Notification
  • VMA: Voice Mail Alerting
  • WAP: Wireless Application Protocol
  • USSD: Unstructured Supplementary Services Data
| | String | *camel.component.smpp.configuration.session-state-listener* | You can refer to a org.jsmpp.session.SessionStateListener in the Registry to receive callbacks when the session state changed. | | SessionStateListener | *camel.component.smpp.configuration.source-addr* | Defines the address of SME (Short Message Entity) which originated this message. | 1616 | String | *camel.component.smpp.configuration.source-addr-npi* | Defines the numeric plan indicator (NPI) to be used in the SME originator address parameters. The following NPI values are defined:
  • 0: Unknown
  • 1: ISDN (E163/E164)
  • 2: Data (X.121)
  • 3: Telex (F.69)
  • 6: Land Mobile (E.212)
  • 8: National
  • 9: Private
  • 10: ERMES
  • 13: Internet (IP)
  • 18: WAP Client Id (to be defined by WAP Forum)
| | Byte | *camel.component.smpp.configuration.source-addr-ton* | Defines the type of number (TON) to be used in the SME originator address parameters. The following TON values are defined:
  • 0: Unknown
  • 1: International
  • 2: National
  • 3: Network Specific
  • 4: Subscriber Number
  • 5: Alphanumeric
  • 6: Abbreviated
| | Byte | *camel.component.smpp.configuration.splitting-policy* | You can specify a policy for handling long messages:
  • ALLOW - the default, long messages are split to 140 bytes per message
  • TRUNCATE - long messages are split and only the first fragment will be sent to the SMSC. Some carriers drop subsequent fragments so this reduces load on the SMPP connection sending parts of a message that will never be delivered.
  • REJECT - if a message would need to be split, it is rejected with an SMPP NegativeResponseException and the reason code signifying the message is too long.
| | SmppSplittingPolicy | *camel.component.smpp.configuration.system-id* | The system id (username) for connecting to SMSC server. | smppclient | String | *camel.component.smpp.configuration.system-type* | This parameter is used to categorize the type of ESME (External Short Message Entity) that is binding to the SMSC (max. 13 characters). | | String | *camel.component.smpp.configuration.transaction-timer* | Defines the maximum period of inactivity allowed after a transaction, after which an SMPP entity may assume that the session is no longer active. This timer may be active on either communicating SMPP entity (i.e. SMSC or ESME). | 10000 | Integer | *camel.component.smpp.configuration.type-of-number* | Defines the type of number (TON) to be used in the SME. The following TON values are defined:
  • 0: Unknown
  • 1: International
  • 2: National
  • 3: Network Specific
  • 4: Subscriber Number
  • 5: Alphanumeric
  • 6: Abbreviated
| | Byte | *camel.component.smpp.configuration.using-s-s-l* | Whether using SSL with the smpps protocol | false | Boolean | *camel.component.smpp.enabled* | Whether to enable auto configuration of the smpp component. This is enabled by default. | | Boolean | *camel.component.smpp.lazy-start-producer* | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | Boolean |=== // spring-boot-auto-configure options: END You can have as many of these options as you like. [source,java] ------------------------------------------------------------------------------------------------------------------ smpp://smppclient@localhost:2775?password=password&enquireLinkTimer=3000&transactionTimer=5000&systemType=consumer ------------------------------------------------------------------------------------------------------------------ == Producer Message Headers The following message headers can be used to affect the behavior of the SMPP producer [width=""100%"",cols=""10%,10%,80%"",options=""header"",] |======================================================================= |Header |Type |Description |`CamelSmppDestAddr` |`List`/`String` |*only for SubmitSm, SubmitMulti, CancelSm and DataSm* Defines the destination SME address(es). For mobile terminated messages, this is the directory number of the recipient MS. Is must be a `List` for SubmitMulti and a `String` otherwise. |`CamelSmppDestAddrTon` |`Byte` |*only for SubmitSm, SubmitMulti, CancelSm and DataSm* Defines the type of number (TON) to be used in the SME destination address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppDestAddrNpi` |`Byte` |*only for SubmitSm, SubmitMulti, CancelSm and DataSm* Defines the numeric plan indicator (NPI) to be used in the SME destination address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppSourceAddr` |`String` |Defines the address of SME (Short Message Entity) which originated this message. |`CamelSmppSourceAddrTon` |`Byte` |Defines the type of number (TON) to be used in the SME originator address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppSourceAddrNpi` |`Byte` |Defines the numeric plan indicator (NPI) to be used in the SME originator address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppServiceType` |`String` |The service type parameter can be used to indicate the SMS Application service associated with the message. Use the URI option `serviceType` settings above. |`CamelSmppRegisteredDelivery` |`Byte` |*only for SubmitSm, ReplaceSm, SubmitMulti and DataSm* Is used to request an SMSC delivery receipt and/or SME originated acknowledgements. Use the URI option `registeredDelivery` settings above. |`CamelSmppPriorityFlag` |`Byte` |*only for SubmitSm and SubmitMulti* Allows the originating SME to assign a priority level to the short message. Use the URI option `priorityFlag` settings above. |`CamelSmppScheduleDeliveryTime` |`Date` |*only for SubmitSm, SubmitMulti and ReplaceSm* This parameter specifies the scheduled time at which the message delivery should be first attempted. It defines either the absolute date and time or relative time from the current SMSC time at which delivery of this message will be attempted by the SMSC. It can be specified in either absolute time format or relative time format. The encoding of a time format is specified in chapter 7.1.1. in the smpp specification v3.4. |`CamelSmppValidityPeriod` |`String`/`Date` |*only for SubmitSm, SubmitMulti and ReplaceSm* The validity period parameter indicates the SMSC expiration time, after which the message should be discarded if not delivered to the destination. If it's provided as `Date`, it's interpreted as absolute time or relative time format if you provide it as `String` as specified in chapter 7.1.1 in the smpp specification v3.4. |`CamelSmppReplaceIfPresentFlag` |`Byte` |*only for SubmitSm and SubmitMulti* The replace if present flag parameter is used to request the SMSC to replace a previously submitted message, that is still pending delivery. The SMSC will replace an existing message provided that the source address, destination address and service type match the same fields in the new message. The following values are defined: `0`, Don't replace and `1`, Replace |`CamelSmppAlphabet` / `CamelSmppDataCoding` |`Byte` |*For SubmitSm, SubmitMulti and ReplaceSm* The data coding according to the SMPP 3.4 specification, section 5.2.19. Use the URI option `alphabet` settings above. |`CamelSmppOptionalParameter` |`Map` |*only for SubmitSm, SubmitMulti and DataSm* The optional parameter which are send to the SMSC. The value is converted in the following way: `String` -> `org.jsmpp.bean.OptionalParameter.COctetString`, `byte[]` -> `org.jsmpp.bean.OptionalParameter.OctetString`, `Byte` -> `org.jsmpp.bean.OptionalParameter.Byte`, `Integer` -> `org.jsmpp.bean.OptionalParameter.Int`, `Short` -> `org.jsmpp.bean.OptionalParameter.Short`, `null` -> `org.jsmpp.bean.OptionalParameter.Null` |CamelSmppEncoding |String |*only for SubmitSm, SubmitMulti and DataSm*. Specifies the encoding (character set name) of the bytes in the message body. If the message body is a string then this is not relevant because Java Strings are always Unicode. If the body is a byte array then this header can be used to indicate that it is ISO-8859-1 or some other value. Default value is specified by the endpoint configuration parameter _encoding_ |CamelSmppSplittingPolicy |String |*only for SubmitSm, SubmitMulti and DataSm*. Specifies the policy for message splitting for this exchange. Possible values are described in the endpoint configuration parameter _splittingPolicy_ |======================================================================= The following message headers are used by the SMPP producer to set the response from the SMSC in the message header [width=""100%"",cols=""10%,10%,80%"",options=""header"",] |======================================================================= |Header |Type |Description |`CamelSmppId` |`List`/`String` |The id to identify the submitted short message(s) for later use. In case of a ReplaceSm, QuerySm, CancelSm and DataSm this header vaule is a `String`. In case of a SubmitSm or SubmitMultiSm this header vaule is a `List`. |`CamelSmppSentMessageCount` |`Integer` |*only for SubmitSm and SubmitMultiSm* The total number of messages which has been sent. |`CamelSmppError` |`Map>>` |*only for SubmitMultiSm* The errors which occurred by sending the short message(s) the form `Map>>` (messageID : (destAddr : address, error : errorCode)). |`CamelSmppOptionalParameter` |`Map` |*only for DataSm* The optional parameter which are returned from the SMSC by sending the message. The key is the `Short` code for the optional parameter. The value is converted in the following way: `org.jsmpp.bean.OptionalParameter.COctetString` -> `String`, `org.jsmpp.bean.OptionalParameter.OctetString` -> `byte[]`, `org.jsmpp.bean.OptionalParameter.Byte` -> `Byte`, `org.jsmpp.bean.OptionalParameter.Int` -> `Integer`, `org.jsmpp.bean.OptionalParameter.Short` -> `Short`, `org.jsmpp.bean.OptionalParameter.Null` -> `null` |======================================================================= == Consumer Message Headers The following message headers are used by the SMPP consumer to set the request data from the SMSC in the message header [width=""100%"",cols=""10%,10%,80%"",options=""header"",] |======================================================================= |Header |Type |Description |`CamelSmppSequenceNumber` |`Integer` |*only for AlertNotification, DeliverSm and DataSm* A sequence number allows a response PDU to be correlated with a request PDU. The associated SMPP response PDU must preserve this field. |`CamelSmppCommandId` |`Integer` |*only for AlertNotification, DeliverSm and DataSm* The command id field identifies the particular SMPP PDU. For the complete list of defined values see chapter 5.1.2.1 in the smpp specification v3.4. |`CamelSmppSourceAddr` |`String` |*only for AlertNotification, DeliverSm and DataSm* Defines the address of SME (Short Message Entity) which originated this message. |`CamelSmppSourceAddrNpi` |`Byte` |*only for AlertNotification and DataSm* Defines the numeric plan indicator (NPI) to be used in the SME originator address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppSourceAddrTon` |`Byte` |*only for AlertNotification and DataSm* Defines the type of number (TON) to be used in the SME originator address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppEsmeAddr` |`String` |*only for AlertNotification* Defines the destination ESME address. For mobile terminated messages, this is the directory number of the recipient MS. |`CamelSmppEsmeAddrNpi` |`Byte` |*only for AlertNotification* Defines the numeric plan indicator (NPI) to be used in the ESME originator address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppEsmeAddrTon` |`Byte` |*only for AlertNotification* Defines the type of number (TON) to be used in the ESME originator address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppId` |`String` |*only for smsc DeliveryReceipt and DataSm* The message ID allocated to the message by the SMSC when originally submitted. |`CamelSmppDelivered` |`Integer` |*only for smsc DeliveryReceipt* Number of short messages delivered. This is only relevant where the original message was submitted to a distribution list.The value is padded with leading zeros if necessary. |`CamelSmppDoneDate` |`Date` |*only for smsc DeliveryReceipt* The time and date at which the short message reached it's final state. The format is as follows: YYMMDDhhmm. |`CamelSmppStatus` |`DeliveryReceiptState` |*only for smsc DeliveryReceipt:* The final status of the message. The following values are defined: `DELIVRD`: Message is delivered to destination, `EXPIRED`: Message validity period has expired, `DELETED`: Message has been deleted, `UNDELIV`: Message is undeliverable, `ACCEPTD`: Message is in accepted state (i.e. has been manually read on behalf of the subscriber by customer service), `UNKNOWN`: Message is in invalid state, `REJECTD`: Message is in a rejected state |`CamelSmppCommandStatus` |`Integer` |*only for DataSm* The Command status of the message. |`CamelSmppError` |`String` |*only for smsc DeliveryReceipt* Where appropriate this may hold a Network specific error code or an SMSC error code for the attempted delivery of the message. These errors are Network or SMSC specific and are not included here. |`CamelSmppSubmitDate` |`Date` |*only for smsc DeliveryReceipt* The time and date at which the short message was submitted. In the case of a message which has been replaced, this is the date that the original message was replaced. The format is as follows: YYMMDDhhmm. |`CamelSmppSubmitted` |`Integer` |*only for smsc DeliveryReceipt* Number of short messages originally submitted. This is only relevant when the original message was submitted to a distribution list.The value is padded with leading zeros if necessary. |`CamelSmppDestAddr` |`String` |*only for DeliverSm and DataSm:* Defines the destination SME address. For mobile terminated messages, this is the directory number of the recipient MS. |`CamelSmppScheduleDeliveryTime` |`String` |*only for DeliverSm:* This parameter specifies the scheduled time at which the message delivery should be first attempted. It defines either the absolute date and time or relative time from the current SMSC time at which delivery of this message will be attempted by the SMSC. It can be specified in either absolute time format or relative time format. The encoding of a time format is specified in Section 7.1.1. in the smpp specification v3.4. |`CamelSmppValidityPeriod` |`String` |*only for DeliverSm* The validity period parameter indicates the SMSC expiration time, after which the message should be discarded if not delivered to the destination. It can be defined in absolute time format or relative time format. The encoding of absolute and relative time format is specified in Section 7.1.1 in the smpp specification v3.4. |`CamelSmppServiceType` |`String` |*only for DeliverSm and DataSm* The service type parameter indicates the SMS Application service associated with the message. |`CamelSmppRegisteredDelivery` |`Byte` |*only for DataSm* Is used to request an delivery receipt and/or SME originated acknowledgements. Same values as in Producer header list above. |`CamelSmppDestAddrNpi` |`Byte` |*only for DataSm* Defines the numeric plan indicator (NPI) in the destination address parameters. Use the URI option `sourceAddrNpi` values defined above. |`CamelSmppDestAddrTon` |`Byte` |*only for DataSm* Defines the type of number (TON) in the destination address parameters. Use the `sourceAddrTon` URI option values defined above. |`CamelSmppMessageType` |`String` |Identifies the type of an incoming message: `AlertNotification`: an SMSC alert notification, `DataSm`: an SMSC data short message, `DeliveryReceipt`: an SMSC delivery receipt, `DeliverSm`: an SMSC deliver short message |`CamelSmppOptionalParameter` |`Map` |*only for DeliverSm* The optional parameters send back by the SMSC. The key is the `Short` code for the optional parameter. The value is converted in the following way: `org.jsmpp.bean.OptionalParameter.COctetString` -> `String`, `org.jsmpp.bean.OptionalParameter.OctetString` -> `byte[]`, `org.jsmpp.bean.OptionalParameter.Byte` -> `Byte`, `org.jsmpp.bean.OptionalParameter.Int` -> `Integer`, `org.jsmpp.bean.OptionalParameter.Short` -> `Short`, `org.jsmpp.bean.OptionalParameter.Null` -> `null` |======================================================================= [TIP] ==== *JSMPP library* See the documentation of the http://jsmpp.org[JSMPP Library] for more details about the underlying library. ==== == Exception handling This component supports the general Camel exception handling capabilities When an error occurs sending a message with SubmitSm (the default action), the org.apache.camel.component.smpp.SmppException is thrown with a nested exception, org.jsmpp.extra.NegativeResponseException. Call NegativeResponseException.getCommandStatus() to obtain the exact SMPP negative response code, the values are explained in the SMPP specification 3.4, section 5.1.3. + When the SMPP consumer receives a `DeliverSm` or `DataSm` short message and the processing of these messages fails, you can also throw a `ProcessRequestException` instead of handle the failure. In this case, this exception is forwarded to the underlying http://jsmpp.org[JSMPP library] which will return the included error code to the SMSC. This feature is useful to e.g. instruct the SMSC to resend the short message at a later time. This could be done with the following lines of code: [source,java] -------------------------------------------------------------------------------------------------------------------------- from(""smpp://smppclient@localhost:2775?password=password&enquireLinkTimer=3000&transactionTimer=5000&systemType=consumer"") .doTry() .to(""bean:dao?method=updateSmsState"") .doCatch(Exception.class) .throwException(new ProcessRequestException(""update of sms state failed"", 100)) .end(); -------------------------------------------------------------------------------------------------------------------------- Please refer to the http://smsforum.net/SMPP_v3_4_Issue1_2.zip[SMPP specification] for the complete list of error codes and their meanings. == Samples A route which sends an SMS using the Java DSL: [source,java] ------------------------------------------------------------------------------------------ from(""direct:start"") .to(""smpp://smppclient@localhost:2775? password=password&enquireLinkTimer=3000&transactionTimer=5000&systemType=producer""); ------------------------------------------------------------------------------------------ A route which sends an SMS using the Spring XML DSL: [source,xml] ----------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------- A route which receives an SMS using the Java DSL: [source,java] -------------------------------------------------------------------------------------------------------------------------- from(""smpp://smppclient@localhost:2775?password=password&enquireLinkTimer=3000&transactionTimer=5000&systemType=consumer"") .to(""bean:foo""); -------------------------------------------------------------------------------------------------------------------------- A route which receives an SMS using the Spring XML DSL: [source,xml] ---------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------- [TIP] ==== *SMSC simulator* If you need an SMSC simulator for your test, you can use the simulator provided by http://opensmpp.logica.com/CommonPart/Download/download2.html#simulator[Logica]. ==== == Debug logging This component has log level *DEBUG*, which can be helpful in debugging problems. If you use log4j, you can add the following line to your configuration: [source,java] -------------------------------------------------- log4j.logger.org.apache.camel.component.smpp=DEBUG -------------------------------------------------- ",12128,False,2383.8960067562252,median "/* Copyright 2014 Stanford University * * 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. */ #include ""activemsg.h"" #include ""utilities.h"" #ifndef __GNUC__ #include ""atomics.h"" // for __sync_add_and_fetch #endif #include #include #include ""lowlevel_impl.h"" #define NO_DEBUG_AMREQUESTS enum { MSGID_LONG_EXTENSION = 253, MSGID_FLIP_REQ = 254, MSGID_FLIP_ACK = 255 }; #ifdef DEBUG_MEM_REUSE static int payload_count = 0; #endif static const int DEFERRED_FREE_COUNT = 128; gasnet_hsl_t deferred_free_mutex; int deferred_free_pos; void *deferred_frees[DEFERRED_FREE_COUNT]; gasnet_seginfo_t *segment_info = 0; static bool is_registered(void *ptr) { off_t offset = ((char *)ptr) - ((char *)(segment_info[gasnet_mynode()].addr)); if((offset >= 0) && (offset < segment_info[gasnet_mynode()].size)) return true; return false; } void init_deferred_frees(void) { gasnet_hsl_init(&deferred_free_mutex); deferred_free_pos = 0; for(int i = 0; i < DEFERRED_FREE_COUNT; i++) deferred_frees[i] = 0; } void deferred_free(void *ptr) { #ifdef DEBUG_MEM_REUSE printf(""%d: deferring free of %p\\n"", gasnet_mynode(), ptr); #endif gasnet_hsl_lock(&deferred_free_mutex); void *oldptr = deferred_frees[deferred_free_pos]; deferred_frees[deferred_free_pos] = ptr; deferred_free_pos = (deferred_free_pos + 1) % DEFERRED_FREE_COUNT; gasnet_hsl_unlock(&deferred_free_mutex); if(oldptr) { #ifdef DEBUG_MEM_REUSE printf(""%d: actual free of %p\\n"", gasnet_mynode(), oldptr); #endif free(oldptr); } } class PayloadSource { public: PayloadSource(void) { } virtual ~PayloadSource(void) { } public: virtual void copy_data(void *dest) = 0; virtual void *get_contig_pointer(void) { return 0; } }; class ContiguousPayload : public PayloadSource { public: ContiguousPayload(void *_srcptr, size_t _size, int _mode); virtual ~ContiguousPayload(void) { } virtual void copy_data(void *dest); virtual void *get_contig_pointer(void) { return srcptr; } protected: void *srcptr; size_t size; int mode; }; class TwoDPayload : public PayloadSource { public: TwoDPayload(const void *_srcptr, size_t _line_size, size_t _line_count, ptrdiff_t _line_stride, int _mode); virtual ~TwoDPayload(void) { } virtual void copy_data(void *dest); protected: const void *srcptr; size_t line_size, line_count; ptrdiff_t line_stride; int mode; }; class SpanPayload : public PayloadSource { public: SpanPayload(const SpanList& _spans, size_t _size, int _mode); virtual ~SpanPayload(void) { } virtual void copy_data(void *dest); protected: SpanList spans; size_t size; int mode; }; struct OutgoingMessage { OutgoingMessage(unsigned _msgid, unsigned _num_args, const void *_args); ~OutgoingMessage(void); void set_payload(PayloadSource *_payload, size_t _payload_size, int _payload_mode, void *_dstptr = 0); void reserve_srcdata(void); #if 0 void set_payload(void *_payload, size_t _payload_size, int _payload_mode, void *_dstptr = 0); void set_payload(void *_payload, size_t _line_size, off_t _line_stride, size_t _line_count, int _payload_mode, void *_dstptr = 0); void set_payload(const SpanList& spans, size_t _payload_size, int _payload_mode, void *_dstptr = 0); #endif void assign_srcdata_pointer(void *ptr); unsigned msgid; unsigned num_args; void *payload; size_t payload_size; int payload_mode; void *dstptr; PayloadSource *payload_src; int args[16]; #ifdef DEBUG_MEM_REUSE int payload_num; #endif }; LegionRuntime::Logger::Category log_sdp(""srcdatapool""); class SrcDataPool { public: SrcDataPool(void *base, size_t size); ~SrcDataPool(void); class Lock { public: Lock(SrcDataPool& _sdp) : sdp(_sdp) { gasnet_hsl_lock(&sdp.mutex); } ~Lock(void) { gasnet_hsl_unlock(&sdp.mutex); } protected: SrcDataPool& sdp; }; // allocators must already hold the lock - prove it by passing a reference void *alloc_srcptr(size_t size_needed, Lock& held_lock); // enqueuing a pending message must also hold the lock void add_pending(OutgoingMessage *msg, Lock& held_lock); // releasing memory will take the lock itself void release_srcptr(void *srcptr); static void release_srcptr_handler(gasnet_token_t token, gasnet_handlerarg_t arg0, gasnet_handlerarg_t arg1); protected: size_t round_up_size(size_t size); friend class SrcDataPool::Lock; gasnet_hsl_t mutex; size_t total_size; std::map free_list; std::queue pending_allocations; // debug std::map in_use; std::map alloc_counts; }; static SrcDataPool *srcdatapool = 0; // wrapper so we don't have to expose SrcDataPool implementation void release_srcptr(void *srcptr) { assert(srcdatapool != 0); srcdatapool->release_srcptr(srcptr); } SrcDataPool::SrcDataPool(void *base, size_t size) { gasnet_hsl_init(&mutex); free_list[(char *)base] = size; total_size = size; } SrcDataPool::~SrcDataPool(void) { size_t total = 0; size_t nonzero = 0; for(std::map::const_iterator it = alloc_counts.begin(); it != alloc_counts.end(); it++) { total++; if(it->second != 0) { printf(""HELP! srcptr %p on node %d has final count of %zd\\n"", it->first, gasnet_mynode(), it->second); nonzero++; } } printf(""SrcDataPool: node %d: %zd total srcptrs, %zd nonzero\\n"", gasnet_mynode(), total, nonzero); } size_t SrcDataPool::round_up_size(size_t size) { const size_t BLOCK_SIZE = 64; size_t remainder = size % BLOCK_SIZE; if(remainder) return size + (BLOCK_SIZE - remainder); else return size; } void *SrcDataPool::alloc_srcptr(size_t size_needed, Lock& held_lock) { // sanity check - if the requested size is larger than will ever fit, fail if(size_needed > total_size) return 0; // early out - if our pending allocation queue is non-empty, they're // first in line, so fail this allocation if(!pending_allocations.empty()) return 0; // round up size to something reasonable size_needed = round_up_size(size_needed); // walk the free list until we find something big enough // only use the a bigger chunk if we absolutely have to // in order to avoid segmentation problems. std::map::iterator it = free_list.begin(); char *smallest_upper_bound = 0; size_t smallest_upper_size = 0; while(it != free_list.end()) { if(it->second == size_needed) { // exact match log_sdp.debug(""found %p + %zd - exact"", it->first, it->second); char *srcptr = it->first; free_list.erase(it); in_use[srcptr] = size_needed; return srcptr; } if(it->second > size_needed) { // match with some left over // Check to see if it is smaller // than the largest upper bound if (smallest_upper_bound == 0) { smallest_upper_bound = it->first; smallest_upper_size = it->second; } else if (it->second < smallest_upper_size) { smallest_upper_bound = it->first; smallest_upper_size = it->second; } } // not big enough - keep looking it++; } if (smallest_upper_bound != 0) { it = free_list.find(smallest_upper_bound); char *srcptr = it->first + (it->second - size_needed); it->second -= size_needed; in_use[srcptr] = size_needed; log_sdp.debug(""found %p + %zd > %zd"", it->first, it->second, size_needed); return srcptr; } // allocation failed - let caller decide what to do (probably add it as a // pending allocation after maybe moving data) return 0; } void SrcDataPool::add_pending(OutgoingMessage *msg, Lock& held_lock) { // simple - just add to our queue log_sdp.debug(""pending allocation: %zd for %p"", msg->payload_size, msg); // sanity check - if the requested size is larger than will ever fit, // we're just dead if(msg->payload_size > total_size) { log_sdp.error(""allocation of %zd can never be satisfied! (max = %zd)"", msg->payload_size, total_size); assert(0); } pending_allocations.push(msg); } void SrcDataPool::release_srcptr(void *srcptr) { char *srcptr_c = (char *)srcptr; log_sdp.debug(""releasing srcptr = %p"", srcptr); // releasing a srcptr span may result in some pending allocations being // satisfied - keep a list so their actual copies can happen without // holding the SDP lock std::vector > satisfied; { Lock held_lock(*this); // look up the pointer to find its size std::map::iterator it = in_use.find(srcptr_c); assert(it != in_use.end()); size_t size = it->second; in_use.erase(it); // remove from in use list // we'd better not be in the free list ourselves assert(free_list.find(srcptr_c) == free_list.end()); // see if we can absorb any adjacent ranges if(!free_list.empty()) { std::map::iterator above = free_list.lower_bound(srcptr_c); // look below first while(above != free_list.begin()) { std::map::iterator below = above; below--; log_sdp.spew(""merge? %p+%zd %p+%zd NONE"", below->first, below->second, srcptr_c, size); if((below->first + below->second) != srcptr_c) break; srcptr_c = below->first; size += below->second; free_list.erase(below); } // now look above while(above != free_list.end()) { log_sdp.spew(""merge? NONE %p+%zd %p+%zd"", srcptr_c, size, above->first, above->second); if((srcptr_c + size) != above->first) break; size += above->second; std::map::iterator to_nuke(above++); free_list.erase(to_nuke); } } // is this possibly-merged span large enough to satisfy the first pending // allocation (if any)? if(!pending_allocations.empty() && (size >= pending_allocations.front()->payload_size)) { OutgoingMessage *msg = pending_allocations.front(); pending_allocations.pop(); size_t act_size = round_up_size(msg->payload_size); in_use[srcptr_c] = act_size; satisfied.push_back(std::make_pair(msg, srcptr_c)); // was anything left? if so, add it to the list of free spans if(size > act_size) free_list[srcptr_c + act_size] = size - act_size; // now see if we can satisfy any other pending allocations - use the // normal allocator routine here because there might be better choices // to use than the span we just freed (assuming any of it is left) while(!pending_allocations.empty()) { OutgoingMessage *msg = pending_allocations.front(); void *ptr = alloc_srcptr(msg->payload_size, held_lock); if(!ptr) break; satisfied.push_back(std::make_pair(msg, ptr)); pending_allocations.pop(); } } else { // no? then no other span will either, so just add this to the free list // and return free_list[srcptr_c] = size; } } // with the lock released, tell any messages that got srcptr's so they can // do their copies if(!satisfied.empty()) for(std::vector >::iterator it = satisfied.begin(); it != satisfied.end(); it++) { log_sdp.debug(""satisfying pending allocation: %p for %p"", it->second, it->first); it->first->assign_srcdata_pointer(it->second); } } OutgoingMessage::OutgoingMessage(unsigned _msgid, unsigned _num_args, const void *_args) : msgid(_msgid), num_args(_num_args), payload(0), payload_size(0), payload_mode(PAYLOAD_NONE), dstptr(0), payload_src(0) { for(unsigned i = 0; i < _num_args; i++) args[i] = ((const int *)_args)[i]; } OutgoingMessage::~OutgoingMessage(void) { if((payload_mode == PAYLOAD_COPY) || (payload_mode == PAYLOAD_FREE)) { if(payload_size > 0) { #ifdef DEBUG_MEM_REUSE for(size_t i = 0; i < payload_size >> 2; i++) ((unsigned *)payload)[i] = ((0xdc + gasnet_mynode()) << 24) + payload_num; //memset(payload, 0xdc+gasnet_mynode(), payload_size); printf(""%d: freeing payload %x = [%p, %p)\\n"", gasnet_mynode(), payload_num, payload, ((char *)payload) + payload_size); #endif deferred_free(payload); } } if (payload_src != 0) { assert(payload_mode == PAYLOAD_KEEPREG); delete payload_src; payload_src = 0; } } // these values can be overridden by command-line parameters static int num_lmbs = 2; static size_t lmb_size = 1 << 20; // 1 MB static bool force_long_messages = true; // returns the largest payload that can be sent to a node (to a non-pinned // address) size_t get_lmb_size(int target_node) { // not node specific right yet return lmb_size; } class ActiveMessageEndpoint { public: struct ChunkInfo { public: ChunkInfo(void) : base_ptr(NULL), chunks(0), total_size(0) { } ChunkInfo(void *base, int c, size_t size) : base_ptr(base), chunks(c), total_size(size) { } public: void *base_ptr; int chunks; size_t total_size; }; public: ActiveMessageEndpoint(gasnet_node_t _peer) : peer(_peer) { gasnet_hsl_init(&mutex); gasnett_cond_init(&cond); cur_write_lmb = 0; cur_write_offset = 0; cur_write_count = 0; //cur_long_ptr = 0; //cur_long_chunk_idx = 0; //cur_long_size = 0; next_outgoing_message_id = 0; lmb_w_bases = new char *[num_lmbs]; lmb_r_bases = new char *[num_lmbs]; lmb_r_counts = new int[num_lmbs]; lmb_w_avail = new bool[num_lmbs]; for(int i = 0; i < num_lmbs; i++) { lmb_w_bases[i] = ((char *)(segment_info[peer].addr)) + (segment_info[peer].size - lmb_size * (gasnet_mynode() * num_lmbs + i + 1)); lmb_r_bases[i] = ((char *)(segment_info[gasnet_mynode()].addr)) + (segment_info[peer].size - lmb_size * (peer * num_lmbs + i + 1)); lmb_r_counts[i] = 0; lmb_w_avail[i] = true; } #ifdef TRACE_MESSAGES sent_messages = 0; received_messages = 0; #endif } ~ActiveMessageEndpoint(void) { delete[] lmb_w_bases; delete[] lmb_r_bases; delete[] lmb_r_counts; delete[] lmb_w_avail; } void record_message(bool sent_reply) { #ifdef TRACE_MESSAGES __sync_fetch_and_add(&received_messages, 1); if (sent_reply) __sync_fetch_and_add(&sent_messages, 1); #endif } int push_messages(int max_to_send = 0, bool wait = false) { int count = 0; while((max_to_send == 0) || (count < max_to_send)) { // attempt to get the mutex that covers the outbound queues - do not // block int ret = gasnet_hsl_trylock(&mutex); if(ret == GASNET_ERR_NOT_READY) break; // try to send a long message, but only if we have an LMB available // on the receiving end if((out_long_hdrs.size() > 0) && lmb_w_avail[cur_write_lmb]) { OutgoingMessage *hdr; hdr = out_long_hdrs.front(); // no payload? this happens when a short/medium message needs to be ordered with long messages if(hdr->payload_size == 0) { out_long_hdrs.pop(); gasnet_hsl_unlock(&mutex); send_short(hdr); delete hdr; count++; continue; } // is the message still waiting on space in the srcdatapool? if(hdr->payload_mode == PAYLOAD_PENDING) { gasnet_hsl_unlock(&mutex); break; } // do we have a known destination pointer on the target? if so, no need to use LMB if(hdr->dstptr != 0) { //printf(""sending long message directly to %p (%zd bytes)\\n"", hdr->dstptr, hdr->payload_size); out_long_hdrs.pop(); gasnet_hsl_unlock(&mutex); send_long(hdr, hdr->dstptr); delete hdr; count++; continue; } // do we have enough room in the current LMB? assert(hdr->payload_size <= lmb_size); if((cur_write_offset + hdr->payload_size) <= lmb_size) { // we can send the message - update lmb pointers and remove the // packet from the queue, and then drop them mutex before // sending the message char *dest_ptr = lmb_w_bases[cur_write_lmb] + cur_write_offset; cur_write_offset += hdr->payload_size; // keep write offset aligned to 128B if(cur_write_offset & 0x7f) cur_write_offset = ((cur_write_offset >> 7) + 1) << 7; cur_write_count++; out_long_hdrs.pop(); gasnet_hsl_unlock(&mutex); #ifdef DEBUG_LMB printf(""LMB: sending %zd bytes %d->%d, [%p,%p)\\n"", hdr->payload_size, gasnet_mynode(), peer, dest_ptr, dest_ptr + hdr->payload_size); #endif send_long(hdr, dest_ptr); delete hdr; count++; continue; } else { // can't send the message, so flip the buffer that's now full int flip_buffer = cur_write_lmb; int flip_count = cur_write_count; lmb_w_avail[cur_write_lmb] = false; cur_write_lmb = (cur_write_lmb + 1) % num_lmbs; cur_write_offset = 0; cur_write_count = 0; // now let go of the lock and send the flip request gasnet_hsl_unlock(&mutex); #ifdef DEBUG_LMB printf(""LMB: flipping buffer %d for %d->%d, [%p,%p), count=%d\\n"", flip_buffer, gasnet_mynode(), peer, lmb_w_bases[flip_buffer], lmb_w_bases[flip_buffer]+lmb_size, flip_count); #endif CHECK_GASNET( gasnet_AMRequestShort2(peer, MSGID_FLIP_REQ, flip_buffer, flip_count) ); #ifdef TRACE_MESSAGES __sync_fetch_and_add(&sent_messages, 1); #endif continue; } } // couldn't send a long message, try a short message if(out_short_hdrs.size() > 0) { OutgoingMessage *hdr = out_short_hdrs.front(); out_short_hdrs.pop(); // now let go of lock and send message gasnet_hsl_unlock(&mutex); send_short(hdr); delete hdr; count++; continue; } // Couldn't do anything so if we were told to wait, goto sleep if (wait) { gasnett_cond_wait(&cond, &mutex.lock); } // if we get here, we didn't find anything to do, so break out of loop // after releasing the lock gasnet_hsl_unlock(&mutex); break; } return count; } void enqueue_message(OutgoingMessage *hdr, bool in_order) { // need to hold the mutex in order to push onto one of the queues gasnet_hsl_lock(&mutex); // once we have the lock, we can safely move the message's payload to // srcdatapool hdr->reserve_srcdata(); // messages that don't need space in the LMB can progress when the LMB is full // (unless they need to maintain ordering with long packets) if(!in_order && (hdr->payload_size <= gasnet_AMMaxMedium())) out_short_hdrs.push(hdr); else out_long_hdrs.push(hdr); // Signal in case there is a sleeping sender gasnett_cond_signal(&cond); gasnet_hsl_unlock(&mutex); } bool handle_long_msgptr(void *ptr) { // can figure out which buffer it is without holding lock int r_buffer = -1; for(int i = 0; i < num_lmbs; i++) if((ptr >= lmb_r_bases[i]) && (ptr < (lmb_r_bases[i] + lmb_size))) { r_buffer = i; break; } if(r_buffer < 0) { // probably a medium message? return false; } //assert(r_buffer >= 0); #ifdef DEBUG_LMB printf(""LMB: received %p for %d->%d in buffer %d, [%p, %p)\\n"", ptr, peer, gasnet_mynode(), r_buffer, lmb_r_bases[r_buffer], lmb_r_bases[r_buffer] + lmb_size); #endif // now take the lock to increment the r_count and decide if we need // to ack (can't actually send it here, so queue it up) bool message_added = false; gasnet_hsl_lock(&mutex); lmb_r_counts[r_buffer]++; if(lmb_r_counts[r_buffer] == 0) { #ifdef DEBUG_LMB printf(""LMB: acking flip of buffer %d for %d->%d, [%p,%p)\\n"", r_buffer, peer, gasnet_mynode(), lmb_r_bases[r_buffer], lmb_r_bases[r_buffer]+lmb_size); #endif OutgoingMessage *hdr = new OutgoingMessage(MSGID_FLIP_ACK, 1, &r_buffer); out_short_hdrs.push(hdr); message_added = true; // wake up a sender gasnett_cond_signal(&cond); } gasnet_hsl_unlock(&mutex); return message_added; } bool adjust_long_msgsize(void *&ptr, size_t &buffer_size, int message_id, int chunks) { // Quick out, if there was only one chunk, then we are good to go if (chunks == 1) return true; bool ready = false;; // now we need to hold the lock gasnet_hsl_lock(&mutex); // See if we've seen this message id before std::map::iterator finder = observed_messages.find(message_id); if (finder == observed_messages.end()) { // haven't seen it before, mark that we've seen the first chunk observed_messages[message_id] = ChunkInfo(ptr, 1, buffer_size); } else { // Update the pointer with the smallest one which is the base if (((unsigned long)(ptr)) < ((unsigned long)(finder->second.base_ptr))) finder->second.base_ptr = ptr; finder->second.total_size += buffer_size; finder->second.chunks++; // See if we've seen the last chunk if (finder->second.chunks == chunks) { // We've seen all the chunks, now update the pointer // and the buffer size and mark that we can handle the message ptr = finder->second.base_ptr; buffer_size = finder->second.total_size; ready = true; // Remove the entry from the map observed_messages.erase(finder); } // Otherwise we're not done yet } gasnet_hsl_unlock(&mutex); return ready; } // called when the remote side tells us that there will be no more // messages sent for a given buffer - as soon as we've received them all, // we can ack bool handle_flip_request(int buffer, int count) { #ifdef DEBUG_LMB printf(""LMB: received flip of buffer %d for %d->%d, [%p,%p), count=%d\\n"", buffer, peer, gasnet_mynode(), lmb_r_bases[buffer], lmb_r_bases[buffer]+lmb_size, count); #endif #ifdef TRACE_MESSAGES __sync_fetch_and_add(&received_messages, 1); #endif bool message_added = false; gasnet_hsl_lock(&mutex); lmb_r_counts[buffer] -= count; if(lmb_r_counts[buffer] == 0) { #ifdef DEBUG_LMB printf(""LMB: acking flip of buffer %d for %d->%d, [%p,%p)\\n"", buffer, peer, gasnet_mynode(), lmb_r_bases[buffer], lmb_r_bases[buffer]+lmb_size); #endif OutgoingMessage *hdr = new OutgoingMessage(MSGID_FLIP_ACK, 1, &buffer); out_short_hdrs.push(hdr); message_added = true; // Wake up a sender gasnett_cond_signal(&cond); } gasnet_hsl_unlock(&mutex); return message_added; } // called when the remote side says it has received all the messages in a // given buffer - we can that mark that write buffer as available again // (don't even need to take the mutex!) void handle_flip_ack(int buffer) { #ifdef DEBUG_LMB printf(""LMB: received flip ack of buffer %d for %d->%d, [%p,%p)\\n"", buffer, gasnet_mynode(), peer, lmb_w_bases[buffer], lmb_w_bases[buffer]+lmb_size); #endif #ifdef TRACE_MESSAGES __sync_fetch_and_add(&received_messages, 1); #endif lmb_w_avail[buffer] = true; // wake up a sender in case we had messages waiting for free space gasnet_hsl_lock(&mutex); gasnett_cond_signal(&cond); gasnet_hsl_unlock(&mutex); } protected: void send_short(OutgoingMessage *hdr) { LegionRuntime::LowLevel::DetailedTimer::ScopedPush sp(TIME_AM); #ifdef DEBUG_AMREQUESTS printf(""%d->%d: %s %d %d %p %zd / %x %x %x %x / %x %x %x %x / %x %x %x %x / %x %x %x %x\\n"", gasnet_mynode(), peer, ((hdr->payload_mode == PAYLOAD_NONE) ? ""SHORT"" : ""MEDIUM""), hdr->num_args, hdr->msgid, hdr->payload, hdr->payload_size, hdr->args[0], hdr->args[1], hdr->args[2], hdr->args[3], hdr->args[4], hdr->args[5], hdr->args[6], hdr->args[7], hdr->args[8], hdr->args[9], hdr->args[10], hdr->args[11], hdr->args[12], hdr->args[13], hdr->args[14], hdr->args[15]); fflush(stdout); #endif #ifdef TRACE_MESSAGES __sync_fetch_and_add(&sent_messages, 1); #endif switch(hdr->num_args) { case 1: if(hdr->payload_mode != PAYLOAD_NONE) { CHECK_GASNET( gasnet_AMRequestMedium1(peer, hdr->msgid, hdr->payload, hdr->payload_size, hdr->args[0]) ); } else { CHECK_GASNET( gasnet_AMRequestShort1(peer, hdr->msgid, hdr->args[0]) ); } break; case 2: if(hdr->payload_mode != PAYLOAD_NONE) { CHECK_GASNET( gasnet_AMRequestMedium2(peer, hdr->msgid, hdr->payload, hdr->payload_size, hdr->args[0], hdr->args[1]) ); } else { CHECK_GASNET( gasnet_AMRequestShort2(peer, hdr->msgid, hdr->args[0], hdr->args[1]) ); } break; case 3: if(hdr->payload_mode != PAYLOAD_NONE) { CHECK_GASNET( gasnet_AMRequestMedium3(peer, hdr->msgid, hdr->payload, hdr->payload_size, hdr->args[0], hdr->args[1], hdr->args[2]) ); } else { CHECK_GASNET( gasnet_AMRequestShort3(peer, hdr->msgid, hdr->args[0], hdr->args[1], hdr->args[2]) ); } break; case 4: if(hdr->payload_mode != PAYLOAD_NONE) { CHECK_GASNET( gasnet_AMRequestMedium4(peer, hdr->msgid, hdr->payload, hdr->payload_size, hdr->args[0], hdr->args[1], hdr->args[2], hdr->args[3]) ); } else { CHECK_GASNET( gasnet_AMRequestShort4(peer, hdr->msgid, hdr->args[0], hdr->args[1], hdr->args[2], hdr->args[3]) ); } break; case 5: if(hdr->payload_mode != PAYLOAD_NONE) { CHECK_GASNET( gasnet_AMRequestMedium5(peer, hdr->msgid, hdr->payload, hdr->payload_size, hdr->args[0], hdr->args[1], hdr->args[2], hdr->args[3], hdr->args[4]) ); } else { CHECK_GASNET( gasnet_AMRequestShort5(peer, hdr->msgid, hdr->args[0], hdr->args[1], hdr->args[2], hdr->args[3], hdr->args[4]) ); } break; case 6: if(hdr->payload_mode != PAYLOAD_NONE) { CHECK_GASNET( gasnet_AMRequestMedium6(peer, hdr->msgid, hdr->payload, hdr->payload_size, hdr->args[0], hdr->args[1], hdr->args[2], hdr->args[3], hdr->args[4], hdr->args[5]) ); } else { CHECK_GASNET( gasnet_AMRequestShort6(peer, hdr->msgid, hdr->args[0], hdr->args[1], hdr->args[2], hdr->args[3], hdr->args[4], hdr->args[5]) ); } break; case 8: if(hdr->payload_mode != PAYLOAD_NONE) { CHECK_GASNET( gasnet_AMRequestMedium8(peer, hdr->msgid, hdr->payload, hdr->payload_size, hdr->args[0], hdr->args[1], hdr->args[2], hdr->args[3], hdr->args[4], hdr->args[5], hdr->args[6], hdr->args[7]) ); } else { CHECK_GASNET( gasnet_AMRequestShort8(peer, hdr->msgid, hdr->args[0], hdr->args[1], hdr->args[2], hdr->args[3], hdr->args[4], hdr->args[5], hdr->args[6], hdr->args[7]) ); } break; case 10: if(hdr->payload_mode != PAYLOAD_NONE) { CHECK_GASNET( gasnet_AMRequestMedium10(peer, hdr->msgid, hdr->payload, hdr->payload_size, hdr->args[0], hdr->args[1], hdr->args[2], hdr->args[3], hdr->args[4], hdr->args[5], hdr->args[6], hdr->args[7], hdr->args[8], hdr->args[9]) ); } else { CHECK_GASNET( gasnet_AMRequestShort10(peer, hdr->msgid, hdr->args[0], hdr->args[1], hdr->args[2], hdr->args[3], hdr->args[4], hdr->args[5], hdr->args[6], hdr->args[7], hdr->args[8], hdr->args[9]) ); } break; case 12: if(hdr->payload_mode != PAYLOAD_NONE) { CHECK_GASNET( gasnet_AMRequestMedium12(peer, hdr->msgid, hdr->payload, hdr->payload_size, hdr->args[0], hdr->args[1], hdr->args[2], hdr->args[3], hdr->args[4], hdr->args[5], hdr->args[6], hdr->args[7], hdr->args[8], hdr->args[9], hdr->args[10], hdr->args[11]) ); } else { CHECK_GASNET( gasnet_AMRequestShort12(peer, hdr->msgid, hdr->args[0], hdr->args[1], hdr->args[2], hdr->args[3], hdr->args[4], hdr->args[5], hdr->args[6], hdr->args[7], hdr->args[8], hdr->args[9], hdr->args[10], hdr->args[11]) ); } break; case 16: if(hdr->payload_mode != PAYLOAD_NONE) { CHECK_GASNET( gasnet_AMRequestMedium16(peer, hdr->msgid, hdr->payload, hdr->payload_size, hdr->args[0], hdr->args[1], hdr->args[2], hdr->args[3], hdr->args[4], hdr->args[5], hdr->args[6], hdr->args[7], hdr->args[8], hdr->args[9], hdr->args[10], hdr->args[11], hdr->args[12], hdr->args[13], hdr->args[14], hdr->args[15]) ); } else { CHECK_GASNET( gasnet_AMRequestShort16(peer, hdr->msgid, hdr->args[0], hdr->args[1], hdr->args[2], hdr->args[3], hdr->args[4], hdr->args[5], hdr->args[6], hdr->args[7], hdr->args[8], hdr->args[9], hdr->args[10], hdr->args[11], hdr->args[12], hdr->args[13], hdr->args[14], hdr->args[15]) ); } break; default: fprintf(stderr, ""need to support short/medium of size=%d\\n"", hdr->num_args); assert(1==2); } } void send_long(OutgoingMessage *hdr, void *dest_ptr) { LegionRuntime::LowLevel::DetailedTimer::ScopedPush sp(TIME_AM); const size_t max_long_req = gasnet_AMMaxLongRequest(); // Get a new message ID for this message // We know that all medium and long active messages use the // BaseMedium class as their base type for sending so the first // two fields hdr->args[0] and hdr->args[1] can be used for // storing the message ID and the number of chunks int message_id_start; if(hdr->args[0] == BaseMedium::MESSAGE_ID_MAGIC) { assert(hdr->args[1] == BaseMedium::MESSAGE_CHUNKS_MAGIC); message_id_start = 0; //printf(""CASE 1\\n""); } else { assert(hdr->args[2] == BaseMedium::MESSAGE_ID_MAGIC); assert(hdr->args[3] == BaseMedium::MESSAGE_CHUNKS_MAGIC); message_id_start = 2; //printf(""CASE 2\\n""); } hdr->args[message_id_start] = next_outgoing_message_id++; int chunks = (hdr->payload_size + max_long_req - 1) / max_long_req; hdr->args[message_id_start + 1] = chunks; if(hdr->payload_mode == PAYLOAD_SRCPTR) { //srcdatapool->record_srcptr(hdr->payload); gasnet_handlerarg_t srcptr_lo = ((uint64_t)(hdr->payload)) & 0x0FFFFFFFFULL; gasnet_handlerarg_t srcptr_hi = ((uint64_t)(hdr->payload)) >> 32; hdr->args[message_id_start + 2] = srcptr_lo; hdr->args[message_id_start + 3] = srcptr_hi; } else { hdr->args[message_id_start + 2] = 0; hdr->args[message_id_start + 3] = 0; } for (int i = (chunks-1); i >= 0; i--) { // every chunk but the last is the max size - the last one is whatever // is left (which may also be the max size if it divided evenly) size_t size = ((i < (chunks - 1)) ? max_long_req : (hdr->payload_size - (chunks - 1) * max_long_req)); #ifdef DEBUG_AMREQUESTS printf(""%d->%d: LONG %d %d %p %zd %p / %x %x %x %x / %x %x %x %x / %x %x %x %x / %x %x %x %x\\n"", gasnet_mynode(), peer, hdr->num_args, hdr->msgid, ((char*)hdr->payload)+(i*max_long_req), size, ((char*)dest_ptr)+(i*max_long_req), hdr->args[0], hdr->args[1], hdr->args[2], hdr->args[3], hdr->args[4], hdr->args[5], hdr->args[6], hdr->args[7], hdr->args[8], hdr->args[9], hdr->args[10], hdr->args[11], hdr->args[12], hdr->args[13], hdr->args[14], hdr->args[15]); fflush(stdout); #endif #ifdef TRACE_MESSAGES __sync_fetch_and_add(&sent_messages, 1); #endif switch(hdr->num_args) { case 1: // should never get this case since we // should always be sending at least two args assert(false); //gasnet_AMRequestLongAsync1(peer, hdr->msgid, // hdr->payload, msg_size, dest_ptr, // hdr->args[0]); break; case 2: CHECK_GASNET( gasnet_AMRequestLongAsync2(peer, hdr->msgid, ((char*)hdr->payload)+(i*max_long_req), size, ((char*)dest_ptr)+(i*max_long_req), hdr->args[0], hdr->args[1]) ); break; case 3: CHECK_GASNET( gasnet_AMRequestLongAsync3(peer, hdr->msgid, ((char*)hdr->payload)+(i*max_long_req), size, ((char*)dest_ptr)+(i*max_long_req), hdr->args[0], hdr->args[1], hdr->args[2]) ); break; case 4: CHECK_GASNET( gasnet_AMRequestLongAsync4(peer, hdr->msgid, ((char*)hdr->payload)+(i*max_long_req), size, ((char*)dest_ptr)+(i*max_long_req), hdr->args[0], hdr->args[1], hdr->args[2], hdr->args[3]) ); break; case 5: CHECK_GASNET (gasnet_AMRequestLongAsync5(peer, hdr->msgid, ((char*)hdr->payload)+(i*max_long_req), size, ((char*)dest_ptr)+(i*max_long_req), hdr->args[0], hdr->args[1], hdr->args[2], hdr->args[3], hdr->args[4]) ); break; case 6: CHECK_GASNET( gasnet_AMRequestLongAsync6(peer, hdr->msgid, ((char*)hdr->payload)+(i*max_long_req), size, ((char*)dest_ptr)+(i*max_long_req), hdr->args[0], hdr->args[1], hdr->args[2], hdr->args[3], hdr->args[4], hdr->args[5]) ); break; case 7: CHECK_GASNET( gasnet_AMRequestLongAsync7(peer, hdr->msgid, ((char*)hdr->payload)+(i*max_long_req), size, ((char*)dest_ptr)+(i*max_long_req), hdr->args[0], hdr->args[1], hdr->args[2], hdr->args[3], hdr->args[4], hdr->args[5], hdr->args[6]) ); break; case 8: CHECK_GASNET( gasnet_AMRequestLongAsync8(peer, hdr->msgid, ((char*)hdr->payload)+(i*max_long_req), size, ((char*)dest_ptr)+(i*max_long_req), hdr->args[0], hdr->args[1], hdr->args[2], hdr->args[3], hdr->args[4], hdr->args[5], hdr->args[6], hdr->args[7]) ); break; case 9: CHECK_GASNET( gasnet_AMRequestLongAsync9(peer, hdr->msgid, ((char*)hdr->payload)+(i*max_long_req), size, ((char*)dest_ptr)+(i*max_long_req), hdr->args[0], hdr->args[1], hdr->args[2], hdr->args[3], hdr->args[4], hdr->args[5], hdr->args[6], hdr->args[7], hdr->args[8]) ); break; case 10: CHECK_GASNET( gasnet_AMRequestLongAsync10(peer, hdr->msgid, ((char*)hdr->payload)+(i*max_long_req), size, ((char*)dest_ptr)+(i*max_long_req), hdr->args[0], hdr->args[1], hdr->args[2], hdr->args[3], hdr->args[4], hdr->args[5], hdr->args[6], hdr->args[7], hdr->args[8], hdr->args[9]) ); break; case 11: CHECK_GASNET( gasnet_AMRequestLongAsync11(peer, hdr->msgid, ((char*)hdr->payload)+(i*max_long_req), size, ((char*)dest_ptr)+(i*max_long_req), hdr->args[0], hdr->args[1], hdr->args[2], hdr->args[3], hdr->args[4], hdr->args[5], hdr->args[6], hdr->args[7], hdr->args[8], hdr->args[9], hdr->args[10]) ); break; case 12: CHECK_GASNET( gasnet_AMRequestLongAsync12(peer, hdr->msgid, ((char*)hdr->payload)+(i*max_long_req), size, ((char*)dest_ptr)+(i*max_long_req), hdr->args[0], hdr->args[1], hdr->args[2], hdr->args[3], hdr->args[4], hdr->args[5], hdr->args[6], hdr->args[7], hdr->args[8], hdr->args[9], hdr->args[10], hdr->args[11]) ); break; case 13: CHECK_GASNET( gasnet_AMRequestLongAsync13(peer, hdr->msgid, ((char*)hdr->payload)+(i*max_long_req), size, ((char*)dest_ptr)+(i*max_long_req), hdr->args[0], hdr->args[1], hdr->args[2], hdr->args[3], hdr->args[4], hdr->args[5], hdr->args[6], hdr->args[7], hdr->args[8], hdr->args[9], hdr->args[10], hdr->args[11], hdr->args[12]) ); break; case 14: CHECK_GASNET( gasnet_AMRequestLongAsync14(peer, hdr->msgid, ((char*)hdr->payload)+(i*max_long_req), size, ((char*)dest_ptr)+(i*max_long_req), hdr->args[0], hdr->args[1], hdr->args[2], hdr->args[3], hdr->args[4], hdr->args[5], hdr->args[6], hdr->args[7], hdr->args[8], hdr->args[9], hdr->args[10], hdr->args[11], hdr->args[12], hdr->args[13]) ); break; case 15: CHECK_GASNET( gasnet_AMRequestLongAsync15(peer, hdr->msgid, ((char*)hdr->payload)+(i*max_long_req), size, ((char*)dest_ptr)+(i*max_long_req), hdr->args[0], hdr->args[1], hdr->args[2], hdr->args[3], hdr->args[4], hdr->args[5], hdr->args[6], hdr->args[7], hdr->args[8], hdr->args[9], hdr->args[10], hdr->args[11], hdr->args[12], hdr->args[13], hdr->args[14]) ); break; case 16: CHECK_GASNET( gasnet_AMRequestLongAsync16(peer, hdr->msgid, ((char*)hdr->payload+(i*max_long_req)), size, ((char*)dest_ptr)+(i*max_long_req), hdr->args[0], hdr->args[1], hdr->args[2], hdr->args[3], hdr->args[4], hdr->args[5], hdr->args[6], hdr->args[7], hdr->args[8], hdr->args[9], hdr->args[10], hdr->args[11], hdr->args[12], hdr->args[13], hdr->args[14], hdr->args[15]) ); break; default: fprintf(stderr, ""need to support long of size=%d\\n"", hdr->num_args); assert(3==4); } } } gasnet_node_t peer; gasnet_hsl_t mutex; gasnett_cond_t cond; public: std::queue out_short_hdrs; std::queue out_long_hdrs; int cur_write_lmb, cur_write_count; size_t cur_write_offset; char **lmb_w_bases; // [num_lmbs] char **lmb_r_bases; // [num_lmbs] int *lmb_r_counts; // [num_lmbs] bool *lmb_w_avail; // [num_lmbs] //void *cur_long_ptr; //int cur_long_chunk_idx; //size_t cur_long_size; std::map observed_messages; int next_outgoing_message_id; #ifdef TRACE_MESSAGES int sent_messages; int received_messages; #endif }; void OutgoingMessage::set_payload(PayloadSource *_payload_src, size_t _payload_size, int _payload_mode, void *_dstptr) { // die if a payload has already been attached assert(payload_mode == PAYLOAD_NONE); // no payload? easy case if(_payload_mode == PAYLOAD_NONE) return; // payload must be non-empty, and fit in the LMB unless we have a dstptr for it log_sdp.info(""setting payload (%zd, %d)"", _payload_size, _payload_mode); assert(_payload_size > 0); assert((_dstptr != 0) || (_payload_size <= lmb_size)); // just copy down everything - we won't attempt to grab a srcptr until // we have reserved our spot in an outgoing queue dstptr = _dstptr; payload = 0; payload_size = _payload_size; payload_mode = _payload_mode; payload_src = _payload_src; } // called once we have reserved a space in a given outgoing queue so that // we can't get put behind somebody who failed a srcptr allocation (and might // need us to go out the door to remove the blockage) void OutgoingMessage::reserve_srcdata(void) { // no payload case is easy if(payload_mode == PAYLOAD_NONE) return; // if the payload is stable and in registered memory AND contiguous, we can // just use it if((payload_mode == PAYLOAD_KEEPREG) && payload_src->get_contig_pointer()) { payload = payload_src->get_contig_pointer(); return; } // do we need to place this data in the srcdata pool? // for now, yes, unless we don't have a srcdata pool at all bool need_srcdata = (srcdatapool != 0); if(need_srcdata) { // try to get the needed space in the srcdata pool assert(srcdatapool); void *srcptr = 0; { // take the SDP lock SrcDataPool::Lock held_lock(*srcdatapool); srcptr = srcdatapool->alloc_srcptr(payload_size, held_lock); log_sdp.info(""got %p (%d)"", srcptr, payload_mode); if(srcptr != 0) { // allocation succeeded - update state, but do copy below, after // we've released the lock payload_mode = PAYLOAD_SRCPTR; payload = srcptr; } else { // if the allocation fails, we have to queue ourselves up // if we've been instructed to copy the data, that has to happen now if(payload_mode == PAYLOAD_COPY) { void *copy_ptr = malloc(payload_size); assert(copy_ptr != 0); payload_src->copy_data(copy_ptr); delete payload_src; payload_src = new ContiguousPayload(copy_ptr, payload_size, PAYLOAD_FREE); } payload_mode = PAYLOAD_PENDING; srcdatapool->add_pending(this, held_lock); } } // do the copy now if the allocation succeeded if(srcptr != 0) { payload_src->copy_data(srcptr); delete payload_src; payload_src = 0; } } else { // no srcdatapool needed, but might still have to copy if(payload_src->get_contig_pointer() && (payload_mode != PAYLOAD_COPY)) { payload = payload_src->get_contig_pointer(); delete payload_src; payload_src = 0; } else { // make a copy payload = malloc(payload_size); assert(payload != 0); payload_src->copy_data(payload); delete payload_src; payload_src = 0; payload_mode = PAYLOAD_FREE; } } } void OutgoingMessage::assign_srcdata_pointer(void *ptr) { assert(payload_mode == PAYLOAD_PENDING); assert(payload_src != 0); payload_src->copy_data(ptr); delete payload_src; payload_src = 0; payload = ptr; payload_mode = PAYLOAD_SRCPTR; } class EndpointManager { public: EndpointManager(int num_endpoints) : total_endpoints(num_endpoints) { endpoints = new ActiveMessageEndpoint*[num_endpoints]; outstanding_messages = (int*)malloc(num_endpoints*sizeof(int)); for (int i = 0; i < num_endpoints; i++) { if (i == gasnet_mynode()) endpoints[i] = 0; else endpoints[i] = new ActiveMessageEndpoint(i); outstanding_messages[i] = 0; } } public: void handle_flip_request(gasnet_node_t src, int flip_buffer, int flip_count) { #define TRACK_MESSAGES #ifdef TRACK_MESSAGES bool added_message = #endif endpoints[src]->handle_flip_request(flip_buffer, flip_count); #ifdef TRACK_MESSAGES if (added_message) __sync_fetch_and_add(outstanding_messages+src,1); #endif } void handle_flip_ack(gasnet_node_t src, int ack_buffer) { endpoints[src]->handle_flip_ack(ack_buffer); } void push_messages(int max_to_send = 0, bool wait = false) { #ifdef TRACK_MESSAGES if (wait) { // If we have to wait, do the normal thing and iterate // over all the end points, and update message counts for (int i = 0; i < total_endpoints; i++) { int pushed = endpoints[i]->push_messages(max_to_send, true); __sync_fetch_and_add(outstanding_messages+i, -pushed); } } else { for (int i = 0; i < total_endpoints; i++) { int messages = *((volatile int*)outstanding_messages+i); if (messages == 0) continue; int pushed = endpoints[i]->push_messages(max_to_send, false); __sync_fetch_and_add(outstanding_messages+i, -pushed); } } #else for (int i = 0; i < total_endpoints; i++) { if (endpoints[i] == 0) continue; endpoints[i]->push_messages(max_to_send, wait); } #endif } void enqueue_message(gasnet_node_t target, OutgoingMessage *hdr, bool in_order) { #ifdef TRACK_MESSAGES __sync_fetch_and_add(outstanding_messages+target,1); #endif endpoints[target]->enqueue_message(hdr, in_order); } void handle_long_msgptr(gasnet_node_t source, void *ptr) { #ifdef TRACK_MESSAGES bool message_added = #endif endpoints[source]->handle_long_msgptr(ptr); #ifdef TRACK_MESSAGES if (message_added) __sync_fetch_and_add(outstanding_messages+source,1); #endif } bool adjust_long_msgsize(gasnet_node_t source, void *&ptr, size_t &buffer_size, int message_id, int chunks) { return endpoints[source]->adjust_long_msgsize(ptr, buffer_size, message_id, chunks); } void report_activemsg_status(FILE *f) { #ifdef TRACE_MESSAGES int mynode = gasnet_mynode(); for (int i = 0; i < total_endpoints; i++) { if (endpoints[i] == 0) continue; ActiveMessageEndpoint *e = endpoints[i]; fprintf(f, ""AMS: %d<->%d: S=%d R=%d\\n"", mynode, i, e->sent_messages, e->received_messages); } fflush(f); #else // for each node, report depth of outbound queues and LMB state int mynode = gasnet_mynode(); for(int i = 0; i < total_endpoints; i++) { if (endpoints[i] == 0) continue; ActiveMessageEndpoint *e = endpoints[i]; fprintf(f, ""AMS: %d->%d: S=%zd L=%zd(%zd) W=%d,%d,%zd,%c,%c R=%d,%d\\n"", mynode, i, e->out_short_hdrs.size(), e->out_long_hdrs.size(), (e->out_long_hdrs.size() ? (e->out_long_hdrs.front())->payload_size : 0), e->cur_write_lmb, e->cur_write_count, e->cur_write_offset, (e->lmb_w_avail[0] ? 'y' : 'n'), (e->lmb_w_avail[1] ? 'y' : 'n'), e->lmb_r_counts[0], e->lmb_r_counts[1]); } fflush(f); #endif } void record_message(gasnet_node_t source, bool sent_reply) { endpoints[source]->record_message(sent_reply); } private: const int total_endpoints; ActiveMessageEndpoint **endpoints; // This vector of outstanding message counts is accessed // by atomic intrinsics and is not protected by the lock int *outstanding_messages; }; static EndpointManager *endpoint_manager; static void handle_flip_req(gasnet_token_t token, int flip_buffer, int flip_count) { gasnet_node_t src; CHECK_GASNET( gasnet_AMGetMsgSource(token, &src) ); endpoint_manager->handle_flip_request(src, flip_buffer, flip_count); } static void handle_flip_ack(gasnet_token_t token, int ack_buffer) { gasnet_node_t src; CHECK_GASNET( gasnet_AMGetMsgSource(token, &src) ); endpoint_manager->handle_flip_ack(src, ack_buffer); } void init_endpoints(gasnet_handlerentry_t *handlers, int hcount, int gasnet_mem_size_in_mb, int registered_mem_size_in_mb, int argc, const char *argv[]) { size_t srcdatapool_size = 64 << 20; for(int i = 1; i < argc; i++) { if(!strcmp(argv[i], ""-ll:numlmbs"")) { num_lmbs = atoi(argv[++i]); continue; } if(!strcmp(argv[i], ""-ll:lmbsize"")) { lmb_size = ((size_t)atoi(argv[++i])) << 10; // convert KB to bytes continue; } if(!strcmp(argv[i], ""-ll:forcelong"")) { force_long_messages = atoi(argv[++i]) != 0; continue; } if(!strcmp(argv[i], ""-ll:sdpsize"")) { srcdatapool_size = ((size_t)atoi(argv[++i])) << 20; // convert MB to bytes continue; } } size_t total_lmb_size = (gasnet_nodes() * num_lmbs * lmb_size); // add in our internal handlers and space we need for LMBs size_t attach_size = ((((size_t)gasnet_mem_size_in_mb) << 20) + (((size_t)registered_mem_size_in_mb) << 20) + srcdatapool_size + total_lmb_size); if(gasnet_mynode() == 0) printf(""Pinned Memory Usage: GASNET=%d, RMEM=%d, LMB=%zd, SDP=%zd, total=%zd\\n"", gasnet_mem_size_in_mb, registered_mem_size_in_mb, total_lmb_size >> 20, srcdatapool_size >> 20, attach_size >> 20); // Don't bother checking this here. Some GASNet conduits lie if // the GASNET_PHYSMEM_MAX variable is not set. #if 0 if (attach_size > gasnet_getMaxLocalSegmentSize()) { fprintf(stderr,""ERROR: Legion exceeded maximum GASNet segment size. "" ""Requested %ld bytes but maximum set by GASNET "" ""configuration is %ld bytes. Legion will now exit..."", attach_size, gasnet_getMaxLocalSegmentSize()); assert(false); } #endif handlers[hcount].index = MSGID_FLIP_REQ; handlers[hcount].fnptr = (void (*)())handle_flip_req; hcount++; handlers[hcount].index = MSGID_FLIP_ACK; handlers[hcount].fnptr = (void (*)())handle_flip_ack; hcount++; handlers[hcount].index = MSGID_RELEASE_SRCPTR; handlers[hcount].fnptr = (void (*)())SrcDataPool::release_srcptr_handler; hcount++; CHECK_GASNET( gasnet_attach(handlers, hcount, attach_size, 0) ); segment_info = new gasnet_seginfo_t[gasnet_nodes()]; CHECK_GASNET( gasnet_getSegmentInfo(segment_info, gasnet_nodes()) ); char *my_segment = (char *)(segment_info[gasnet_mynode()].addr); char *gasnet_mem_base = my_segment; my_segment += (gasnet_mem_size_in_mb << 20); char *reg_mem_base = my_segment; my_segment += (registered_mem_size_in_mb << 20); char *srcdatapool_base = my_segment; my_segment += srcdatapool_size; char *lmb_base = my_segment; my_segment += total_lmb_size; assert(my_segment <= ((char *)(segment_info[gasnet_mynode()].addr) + segment_info[gasnet_mynode()].size)); #ifndef NO_SRCDATAPOOL srcdatapool = new SrcDataPool(srcdatapool_base, srcdatapool_size); #endif endpoint_manager = new EndpointManager(gasnet_nodes()); init_deferred_frees(); } static int num_polling_threads = 0; static pthread_t *polling_threads = 0; static int num_sending_threads = 0; static pthread_t *sending_threads = 0; static volatile bool thread_shutdown_flag = false; // do a little bit of polling to try to move messages along, but return // to the caller rather than spinning void do_some_polling(void) { endpoint_manager->push_messages(0); CHECK_GASNET( gasnet_AMPoll() ); } static void *gasnet_poll_thread_loop(void *data) { // each polling thread basically does an endless loop of trying to send // outgoing messages and then polling while(!thread_shutdown_flag) { do_some_polling(); //usleep(10000); } return 0; } void start_polling_threads(int count) { num_polling_threads = count; polling_threads = new pthread_t[count]; for(int i = 0; i < count; i++) { pthread_attr_t attr; CHECK_PTHREAD( pthread_attr_init(&attr) ); if(LegionRuntime::LowLevel::proc_assignment) LegionRuntime::LowLevel::proc_assignment->bind_thread(-1, &attr, ""AM polling thread""); CHECK_PTHREAD( pthread_create(&polling_threads[i], 0, gasnet_poll_thread_loop, 0) ); CHECK_PTHREAD( pthread_attr_destroy(&attr) ); #ifdef DEADLOCK_TRACE LegionRuntime::LowLevel::Runtime::get_runtime()->add_thread(&polling_threads[i]); #endif } } static void* sender_thread_loop(void *index) { long idx = (long)index; while (!thread_shutdown_flag) { endpoint_manager->push_messages(10000,true); } return 0; } void start_sending_threads(void) { num_sending_threads = gasnet_nodes(); sending_threads = new pthread_t[num_sending_threads]; for (int i = 0; i < gasnet_nodes(); i++) { if (i == gasnet_mynode()) continue; pthread_attr_t attr; CHECK_PTHREAD( pthread_attr_init(&attr) ); if(LegionRuntime::LowLevel::proc_assignment) LegionRuntime::LowLevel::proc_assignment->bind_thread(-1, &attr, ""AM sender thread""); CHECK_PTHREAD( pthread_create(&sending_threads[i], 0, sender_thread_loop, (void*)long(i))); CHECK_PTHREAD( pthread_attr_destroy(&attr) ); #ifdef DEADLOCK_TRACE LegionRuntime::LowLevel::Runtime::get_runtime()->add_thread(&sending_threads[i]); #endif } } void stop_activemsg_threads(void) { thread_shutdown_flag = true; if(polling_threads) { for(int i = 0; i < num_polling_threads; i++) { void *dummy; CHECK_PTHREAD( pthread_join(polling_threads[i], &dummy) ); } num_polling_threads = 0; delete[] polling_threads; } if(sending_threads) { for(int i = 0; i < num_sending_threads; i++) { void *dummy; CHECK_PTHREAD( pthread_join(sending_threads[i], &dummy) ); } num_sending_threads = 0; delete[] sending_threads; } thread_shutdown_flag = false; } void enqueue_message(gasnet_node_t target, int msgid, const void *args, size_t arg_size, const void *payload, size_t payload_size, int payload_mode, void *dstptr) { assert(target != gasnet_mynode()); OutgoingMessage *hdr = new OutgoingMessage(msgid, (arg_size + sizeof(int) - 1) / sizeof(int), args); // if we have a contiguous payload that is in the KEEP mode, and in // registered memory, we may be able to avoid a copy if((payload_mode == PAYLOAD_KEEP) && is_registered((void *)payload)) payload_mode = PAYLOAD_KEEPREG; if (payload_mode != PAYLOAD_NONE) hdr->set_payload(new ContiguousPayload((void *)payload, payload_size, payload_mode), payload_size, payload_mode, dstptr); endpoint_manager->enqueue_message(target, hdr, true); // TODO: decide when OOO is ok? } void enqueue_message(gasnet_node_t target, int msgid, const void *args, size_t arg_size, const void *payload, size_t line_size, off_t line_stride, size_t line_count, int payload_mode, void *dstptr) { assert(target != gasnet_mynode()); OutgoingMessage *hdr = new OutgoingMessage(msgid, (arg_size + sizeof(int) - 1) / sizeof(int), args); if (payload_mode != PAYLOAD_NONE) hdr->set_payload(new TwoDPayload(payload, line_size, line_count, line_stride, payload_mode), line_size * line_count, payload_mode, dstptr); endpoint_manager->enqueue_message(target, hdr, true); // TODO: decide when OOO is ok? } void enqueue_message(gasnet_node_t target, int msgid, const void *args, size_t arg_size, const SpanList& spans, size_t payload_size, int payload_mode, void *dstptr) { assert(target != gasnet_mynode()); OutgoingMessage *hdr = new OutgoingMessage(msgid, (arg_size + sizeof(int) - 1) / sizeof(int), args); if (payload_mode != PAYLOAD_NONE) hdr->set_payload(new SpanPayload(spans, payload_size, payload_mode), payload_size, payload_mode, dstptr); endpoint_manager->enqueue_message(target, hdr, true); // TODO: decide when OOO is ok? } void handle_long_msgptr(gasnet_node_t source, void *ptr) { assert(source != gasnet_mynode()); endpoint_manager->handle_long_msgptr(source, ptr); } /*static*/ void SrcDataPool::release_srcptr_handler(gasnet_token_t token, gasnet_handlerarg_t arg0, gasnet_handlerarg_t arg1) { uintptr_t srcptr = (((uintptr_t)(unsigned)arg1) << 32) | ((uintptr_t)(unsigned)arg0); // We may get pointers which are zero because we had to send a reply // Just ignore them if (srcptr != 0) srcdatapool->release_srcptr((void *)srcptr); #ifdef TRACE_MESSAGES gasnet_node_t src; CHECK_GASNET( gasnet_AMGetMsgSource(token, &src) ); endpoint_manager->record_message(src, false/*sent reply*/); #endif } ContiguousPayload::ContiguousPayload(void *_srcptr, size_t _size, int _mode) : srcptr(_srcptr), size(_size), mode(_mode) {} void ContiguousPayload::copy_data(void *dest) { log_sdp.info(""contig copy %p <- %p (%zd bytes)"", dest, srcptr, size); memcpy(dest, srcptr, size); if(mode == PAYLOAD_FREE) free(srcptr); } TwoDPayload::TwoDPayload(const void *_srcptr, size_t _line_size, size_t _line_count, ptrdiff_t _line_stride, int _mode) : srcptr(_srcptr), line_size(_line_size), line_count(_line_count), line_stride(_line_stride), mode(_mode) {} void TwoDPayload::copy_data(void *dest) { char *dst_c = (char *)dest; const char *src_c = (const char *)srcptr; for(size_t i = 0; i < line_count; i++) { memcpy(dst_c, src_c, line_size); dst_c += line_size; src_c += line_stride; } } SpanPayload::SpanPayload(const SpanList&_spans, size_t _size, int _mode) : spans(_spans), size(_size), mode(_mode) {} void SpanPayload::copy_data(void *dest) { char *dst_c = (char *)dest; off_t bytes_left = size; for(SpanList::const_iterator it = spans.begin(); it != spans.end(); it++) { assert(it->second <= bytes_left); memcpy(dst_c, it->first, it->second); dst_c += it->second; bytes_left -= it->second; } assert(bytes_left == 0); } extern bool adjust_long_msgsize(gasnet_node_t source, void *&ptr, size_t &buffer_size, const void *args, size_t arglen) { assert(source != gasnet_mynode()); assert(arglen >= 2*sizeof(int)); const int *arg_ptr = (const int*)args; return endpoint_manager->adjust_long_msgsize(source, ptr, buffer_size, arg_ptr[0], arg_ptr[1]); } extern void report_activemsg_status(FILE *f) { endpoint_manager->report_activemsg_status(f); } extern void record_message(gasnet_node_t source, bool sent_reply) { #ifdef TRACE_MESSAGES endpoint_manager->record_message(source, sent_reply); #endif } ",16325,True,3068.1690675728923,median "/* * * Copyright (c) 2020 Project CHIP Authors * * 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. */ /* * Copyright (c) 2016-2019, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * Provides Bluez dbus implementatioon for BLE */ #include #include #include #if CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE #include #include #include #include #include #include ""CHIPBluezHelper.h"" #include using namespace ::nl; namespace chip { namespace DeviceLayer { namespace Internal { static int sBluezFD[2]; static GMainLoop * sBluezMainLoop = NULL; static pthread_t sBluezThread; static BluezConnection * GetBluezConnectionViaDevice(BluezEndpoint * apEndpoint); static gboolean BluezAdvertisingRelease(BluezLEAdvertisement1 * aAdv, GDBusMethodInvocation * aInvocation, gpointer apClosure) { bool isSuccess = false; BluezEndpoint * endpoint = static_cast(apClosure); VerifyOrExit(endpoint != NULL, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); VerifyOrExit(aAdv != NULL, ChipLogProgress(DeviceLayer, ""BluezLEAdvertisement1 is NULL in %s"", __func__)); ChipLogProgress(DeviceLayer, ""Release adv object in %s"", __func__); g_dbus_object_manager_server_unexport(endpoint->mpRoot, endpoint->mpAdvPath); endpoint->mIsAdvertising = false; isSuccess = true; exit: return isSuccess ? TRUE : FALSE; } static BluezLEAdvertisement1 * BluezAdvertisingCreate(BluezEndpoint * apEndpoint) { BluezLEAdvertisement1 * adv = NULL; BluezObjectSkeleton * object; GVariant * serviceData; gchar * localName; GVariantBuilder serviceDataBuilder; GVariantBuilder serviceUUIDsBuilder; char * debugStr; const gchar * array[1]; VerifyOrExit(apEndpoint != NULL, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); if (apEndpoint->mpAdvPath == NULL) apEndpoint->mpAdvPath = g_strdup_printf(""%s/advertising"", apEndpoint->mpRootPath); array[0] = g_strdup_printf(""%s"", apEndpoint->mpAdvertisingUUID); ChipLogProgress(DeviceLayer, ""Create adv object at %s"", apEndpoint->mpAdvPath); object = bluez_object_skeleton_new(apEndpoint->mpAdvPath); adv = bluez_leadvertisement1_skeleton_new(); g_variant_builder_init(&serviceDataBuilder, G_VARIANT_TYPE(""a{sv}"")); g_variant_builder_init(&serviceUUIDsBuilder, G_VARIANT_TYPE(""as"")); g_variant_builder_add( &serviceDataBuilder, ""{sv}"", apEndpoint->mpAdvertisingUUID, g_variant_new_fixed_array(G_VARIANT_TYPE_BYTE, apEndpoint->mpChipServiceData, sizeof(CHIPServiceData), sizeof(uint8_t))); g_variant_builder_add(&serviceUUIDsBuilder, ""s"", apEndpoint->mpAdvertisingUUID); if (apEndpoint->mpAdapterName != NULL) localName = g_strdup_printf(""%s"", apEndpoint->mpAdapterName); else localName = g_strdup_printf(""%s%04x"", CHIP_DEVICE_CONFIG_BLE_DEVICE_NAME_PREFIX, getpid() & 0xffff); serviceData = g_variant_builder_end(&serviceDataBuilder); debugStr = g_variant_print(serviceData, TRUE); ChipLogProgress(DeviceLayer, ""SET service data to %s"", debugStr); g_free(debugStr); bluez_leadvertisement1_set_type_(adv, (apEndpoint->mType & BLUEZ_ADV_TYPE_CONNECTABLE) ? ""peripheral"" : ""broadcast""); // empty manufacturer data // empty solicit UUIDs bluez_leadvertisement1_set_service_data(adv, serviceData); // empty data bluez_leadvertisement1_set_discoverable(adv, (apEndpoint->mType & BLUEZ_ADV_TYPE_SCANNABLE) ? TRUE : FALSE); // advertising name corresponding to the PID and object path, for debug purposes bluez_leadvertisement1_set_local_name(adv, localName); bluez_leadvertisement1_set_service_uuids(adv, array); // 0xffff means no appearance bluez_leadvertisement1_set_appearance(adv, 0xffff); bluez_leadvertisement1_set_duration(adv, apEndpoint->mDuration); // empty duration, we don't have a clear notion what it would mean to timeslice between toble and anyone else bluez_leadvertisement1_set_timeout(adv, 0); // empty secondary channel for now bluez_object_skeleton_set_leadvertisement1(object, adv); g_signal_connect(adv, ""handle-release"", G_CALLBACK(BluezAdvertisingRelease), apEndpoint); g_dbus_object_manager_server_export(apEndpoint->mpRoot, G_DBUS_OBJECT_SKELETON(object)); g_object_unref(object); BLEManagerImpl::NotifyBLEPeripheralAdvConfiguredComplete(true, NULL); exit: return adv; } static void BluezAdvStartDone(GObject * aObject, GAsyncResult * aResult, gpointer apClosure) { BluezLEAdvertisingManager1 * advMgr = BLUEZ_LEADVERTISING_MANAGER1(aObject); GError * error = NULL; BluezEndpoint * endpoint = static_cast(apClosure); gboolean success = FALSE; VerifyOrExit(endpoint != NULL, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); success = bluez_leadvertising_manager1_call_register_advertisement_finish(advMgr, aResult, &error); if (success == FALSE) { g_dbus_object_manager_server_unexport(endpoint->mpRoot, endpoint->mpAdvPath); } VerifyOrExit(success == TRUE, ChipLogProgress(DeviceLayer, ""FAIL: RegisterAdvertisement : %s"", error->message)); endpoint->mIsAdvertising = true; ChipLogProgress(DeviceLayer, ""RegisterAdvertisement complete""); exit: BLEManagerImpl::NotifyBLEPeripheralAdvStopComplete(success == TRUE ? true : false, NULL); if (error != NULL) g_error_free(error); } static void BluezAdvStopDone(GObject * aObject, GAsyncResult * aResult, gpointer apClosure) { BluezLEAdvertisingManager1 * advMgr = BLUEZ_LEADVERTISING_MANAGER1(aObject); BluezEndpoint * endpoint = static_cast(apClosure); GError * error = NULL; gboolean success = FALSE; VerifyOrExit(endpoint != NULL, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); success = bluez_leadvertising_manager1_call_unregister_advertisement_finish(advMgr, aResult, &error); if (success == FALSE) { g_dbus_object_manager_server_unexport(endpoint->mpRoot, endpoint->mpAdvPath); } else { endpoint->mIsAdvertising = false; } VerifyOrExit(success == TRUE, ChipLogProgress(DeviceLayer, ""FAIL: UnregisterAdvertisement : %s"", error->message)); ChipLogProgress(DeviceLayer, ""UnregisterAdvertisement complete""); exit: BLEManagerImpl::NotifyBLEPeripheralAdvStopComplete(success == TRUE ? true : false, NULL); if (error != NULL) g_error_free(error); } static gboolean BluezAdvSetup(void * apClosure) { BluezEndpoint * endpoint = static_cast(apClosure); BluezLEAdvertisement1 * adv; VerifyOrExit(endpoint != NULL, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); VerifyOrExit(endpoint->mIsAdvertising == FALSE, ChipLogProgress(DeviceLayer, ""FAIL: Advertising already enabled in %s"", __func__)); VerifyOrExit(endpoint->mpAdapter != NULL, ChipLogProgress(DeviceLayer, ""FAIL: NULL endpoint->mpAdapter in %s"", __func__)); adv = BluezAdvertisingCreate(endpoint); VerifyOrExit(adv != NULL, ChipLogProgress(DeviceLayer, ""FAIL: NULL adv in %s"", __func__)); exit: return G_SOURCE_REMOVE; } static gboolean BluezAdvStart(void * apClosure) { GDBusObject * adapter; BluezLEAdvertisingManager1 * advMgr = NULL; GVariantBuilder optionsBuilder; GVariant * options; BluezEndpoint * endpoint = static_cast(apClosure); VerifyOrExit(endpoint != NULL, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); VerifyOrExit(!endpoint->mIsAdvertising, ChipLogProgress(DeviceLayer, ""FAIL: Advertising has already been enabled in %s"", __func__)); VerifyOrExit(endpoint->mpAdapter != NULL, ChipLogProgress(DeviceLayer, ""FAIL: NULL endpoint->mpAdapter in %s"", __func__)); adapter = g_dbus_interface_get_object(G_DBUS_INTERFACE(endpoint->mpAdapter)); VerifyOrExit(adapter != NULL, ChipLogProgress(DeviceLayer, ""FAIL: NULL adapter in %s"", __func__)); advMgr = bluez_object_get_leadvertising_manager1(BLUEZ_OBJECT(adapter)); VerifyOrExit(advMgr != NULL, ChipLogProgress(DeviceLayer, ""FAIL: NULL advMgr in %s"", __func__)); g_variant_builder_init(&optionsBuilder, G_VARIANT_TYPE(""a{sv}"")); options = g_variant_builder_end(&optionsBuilder); bluez_leadvertising_manager1_call_register_advertisement(advMgr, endpoint->mpAdvPath, options, NULL, BluezAdvStartDone, apClosure); exit: return G_SOURCE_REMOVE; } static gboolean BluezAdvStop(void * apClosure) { GDBusObject * adapter; BluezEndpoint * endpoint = static_cast(apClosure); BluezLEAdvertisingManager1 * advMgr = NULL; VerifyOrExit(endpoint != NULL, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); VerifyOrExit(endpoint->mIsAdvertising, ChipLogProgress(DeviceLayer, ""FAIL: Advertising has already been disabled in %s"", __func__)); VerifyOrExit(endpoint->mpAdapter != NULL, ChipLogProgress(DeviceLayer, ""FAIL: NULL endpoint->mpAdapter in %s"", __func__)); adapter = g_dbus_interface_get_object(G_DBUS_INTERFACE(endpoint->mpAdapter)); VerifyOrExit(adapter != NULL, ChipLogProgress(DeviceLayer, ""FAIL: NULL adapter in %s"", __func__)); advMgr = bluez_object_get_leadvertising_manager1(BLUEZ_OBJECT(adapter)); VerifyOrExit(advMgr != NULL, ChipLogProgress(DeviceLayer, ""FAIL: NULL advMgr in %s"", __func__)); bluez_leadvertising_manager1_call_unregister_advertisement(advMgr, endpoint->mpAdvPath, NULL, BluezAdvStopDone, apClosure); exit: return G_SOURCE_REMOVE; } static gboolean BluezCharacteristicReadValue(BluezGattCharacteristic1 * aChar, GDBusMethodInvocation * aInvocation, GVariant * aOptions) { GVariant * val; ChipLogProgress(DeviceLayer, ""Received BluezCharacteristicReadValue""); val = (GVariant *) bluez_gatt_characteristic1_get_value(aChar); bluez_gatt_characteristic1_complete_read_value(aChar, aInvocation, val); return TRUE; } #if CHIP_BLUEZ_CHAR_WRITE_VALUE static gboolean BluezCharacteristicWriteValue(BluezGattCharacteristic1 * aChar, GDBusMethodInvocation * aInvocation, GVariant * aValue, GVariant * aOptions, gpointer apClosure) { const uint8_t * tmpBuf; uint8_t * buf; size_t len; bool isSuccess = false; BluezConnection * conn = NULL; BluezEndpoint * endpoint = static_cast(apClosure); VerifyOrExit(endpoint != NULL, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); VerifyOrExit(aValue != NULL, ChipLogProgress(DeviceLayer, ""aValue is NULL in %s"", __func__)); conn = GetBluezConnectionViaDevice(endpoint); VerifyOrExit(conn != NULL, g_dbus_method_invocation_return_dbus_error(aInvocation, ""org.bluez.Error.Failed"", ""No CHIP Bluez connection"")); bluez_gatt_characteristic1_set_value(aChar, g_variant_ref(aValue)); tmpBuf = (uint8_t *) (g_variant_get_fixed_array(aValue, &len, sizeof(uint8_t))); buf = (uint8_t *) (g_memdup(tmpBuf, len)); BLEManagerImpl::HandleRXCharWrite(conn, buf, len); bluez_gatt_characteristic1_complete_write_value(aChar, aInvocation); isSuccess = true; exit: return isSuccess ? TRUE : FALSE; } #endif static gboolean BluezCharacteristicWriteValueError(BluezGattCharacteristic1 * aChar, GDBusMethodInvocation * aInvocation, GVariant * aValue, GVariant * aOptions, gpointer apClosure) { ChipLogProgress(DeviceLayer, ""BluezCharacteristicWriteValueError""); g_dbus_method_invocation_return_dbus_error(aInvocation, ""org.bluez.Error.NotSupported"", ""Write for characteristic is unsupported""); return TRUE; } static gboolean BluezCharacteristicWriteFD(GIOChannel * aChannel, GIOCondition aCond, gpointer apClosure) { GVariant * newVal; gchar * buf; ssize_t len; int fd; bool isSuccess = false; BluezConnection * conn = static_cast(apClosure); VerifyOrExit(conn != NULL, ChipLogProgress(DeviceLayer, ""No CHIP Bluez connection in %s"", __func__)); VerifyOrExit(!(aCond & G_IO_HUP), ChipLogProgress(DeviceLayer, ""INFO: socket disconnected in %s"", __func__)); VerifyOrExit(!(aCond & (G_IO_ERR | G_IO_NVAL)), ChipLogProgress(DeviceLayer, ""INFO: socket error in %s"", __func__)); VerifyOrExit(aCond == G_IO_IN, ChipLogProgress(DeviceLayer, ""FAIL: error in %s"", __func__)); ChipLogProgress(DeviceLayer, ""c1 %s mtu, %d"", __func__, conn->mMtu); buf = (gchar *) (g_malloc(conn->mMtu)); fd = g_io_channel_unix_get_fd(aChannel); len = read(fd, buf, conn->mMtu); VerifyOrExit(len > 0, ChipLogProgress(DeviceLayer, ""FAIL: short read in %s (%d)"", __func__, len)); newVal = g_variant_new_fixed_array(G_VARIANT_TYPE_BYTE, buf, len, sizeof(uint8_t)); bluez_gatt_characteristic1_set_value(conn->mpC1, newVal); BLEManagerImpl::HandleRXCharWrite(conn, (uint8_t *) (buf), len); isSuccess = true; exit: return isSuccess ? TRUE : FALSE; } static void Bluez_gatt_characteristic1_complete_acquire_write_with_fd(GDBusMethodInvocation * invocation, int fd, guint16 mtu) { GUnixFDList * fd_list = g_unix_fd_list_new(); int index; index = g_unix_fd_list_append(fd_list, fd, NULL); g_dbus_method_invocation_return_value_with_unix_fd_list(invocation, g_variant_new(""(@hq)"", g_variant_new_handle(index), mtu), fd_list); } static gboolean bluezCharacteristicDestroyFD(GIOChannel * aChannel, GIOCondition aCond, gpointer apClosure) { return G_SOURCE_REMOVE; } static gboolean BluezCharacteristicAcquireWrite(BluezGattCharacteristic1 * aChar, GDBusMethodInvocation * aInvocation, GVariant * aOptions, gpointer apClosure) { int fds[2] = { -1, -1 }; GIOChannel * channel; char * errStr; GVariantDict options; bool isSuccess = false; BluezConnection * conn = NULL; BluezEndpoint * endpoint = static_cast(apClosure); VerifyOrExit(endpoint != NULL, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); conn = GetBluezConnectionViaDevice(endpoint); VerifyOrExit(conn != NULL, g_dbus_method_invocation_return_dbus_error(aInvocation, ""org.bluez.Error.Failed"", ""No Chipoble connection"")); ChipLogProgress(DeviceLayer, ""BluezCharacteristicAcquireWrite is called, conn: %p"", conn); if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_NONBLOCK | SOCK_CLOEXEC, 0, fds) < 0) { errStr = strerror(errno); ChipLogProgress(DeviceLayer, ""FAIL: socketpair: %s in %s"", errStr, __func__); g_dbus_method_invocation_return_dbus_error(aInvocation, ""org.bluez.Error.Failed"", ""FD creation failed""); SuccessOrExit(false); } g_variant_dict_init(&options, aOptions); if (g_variant_dict_contains(&options, ""mtu"") == TRUE) { GVariant * v = g_variant_dict_lookup_value(&options, ""mtu"", G_VARIANT_TYPE_UINT16); conn->mMtu = g_variant_get_uint16(v); } else { ChipLogProgress(DeviceLayer, ""FAIL: no MTU in options in %s"", __func__); g_dbus_method_invocation_return_dbus_error(aInvocation, ""org.bluez.Error.InvalidArguments"", ""MTU negotiation failed""); SuccessOrExit(false); } channel = g_io_channel_unix_new(fds[0]); g_io_channel_set_encoding(channel, NULL, NULL); g_io_channel_set_close_on_unref(channel, TRUE); g_io_channel_set_buffered(channel, FALSE); conn->mC1Channel.mpChannel = channel; conn->mC1Channel.mWatch = g_io_add_watch(channel, (GIOCondition)(G_IO_HUP | G_IO_IN | G_IO_ERR | G_IO_NVAL), BluezCharacteristicWriteFD, conn); bluez_gatt_characteristic1_set_write_acquired(aChar, TRUE); Bluez_gatt_characteristic1_complete_acquire_write_with_fd(aInvocation, fds[1], conn->mMtu); close(fds[1]); isSuccess = true; exit: return isSuccess ? TRUE : FALSE; } static gboolean BluezCharacteristicAcquireWriteError(BluezGattCharacteristic1 * aChar, GDBusMethodInvocation * aInvocation, GVariant * aOptions) { ChipLogProgress(DeviceLayer, ""BluezCharacteristicAcquireWriteError is called""); g_dbus_method_invocation_return_dbus_error(aInvocation, ""org.bluez.Error.NotSupported"", ""AcquireWrite for characteristic is unsupported""); return TRUE; } static gboolean BluezCharacteristicAcquireNotify(BluezGattCharacteristic1 * aChar, GDBusMethodInvocation * aInvocation, GVariant * aOptions, gpointer apClosure) { int fds[2] = { -1, -1 }; GIOChannel * channel; char * errStr; GVariantDict options; BluezConnection * conn = NULL; bool isSuccess = false; BluezEndpoint * endpoint = static_cast(apClosure); VerifyOrExit(endpoint != NULL, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); conn = GetBluezConnectionViaDevice(endpoint); VerifyOrExit(conn != NULL, g_dbus_method_invocation_return_dbus_error(aInvocation, ""org.bluez.Error.Failed"", ""No Chipoble connection"")); g_variant_dict_init(&options, aOptions); if ((g_variant_dict_contains(&options, ""mtu"") == TRUE)) { GVariant * v = g_variant_dict_lookup_value(&options, ""mtu"", G_VARIANT_TYPE_UINT16); conn->mMtu = g_variant_get_uint16(v); } if (bluez_gatt_characteristic1_get_notifying(aChar)) { g_dbus_method_invocation_return_dbus_error(aInvocation, ""org.bluez.Error.NotPermitted"", ""Already notifying""); } if (socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_NONBLOCK | SOCK_CLOEXEC, 0, fds) < 0) { errStr = strerror(errno); ChipLogProgress(DeviceLayer, ""FAIL: socketpair: %s in %s"", errStr, __func__); g_dbus_method_invocation_return_dbus_error(aInvocation, ""org.bluez.Error.Failed"", ""FD creation failed""); SuccessOrExit(false); } channel = g_io_channel_unix_new(fds[0]); g_io_channel_set_encoding(channel, NULL, NULL); g_io_channel_set_close_on_unref(channel, TRUE); g_io_channel_set_buffered(channel, FALSE); conn->mC2Channel.mpChannel = channel; conn->mC2Channel.mWatch = g_io_add_watch_full(channel, G_PRIORITY_DEFAULT_IDLE, (GIOCondition)(G_IO_HUP | G_IO_ERR | G_IO_NVAL), bluezCharacteristicDestroyFD, conn, NULL); bluez_gatt_characteristic1_set_notify_acquired(aChar, TRUE); // same reply as for AcquireWrite Bluez_gatt_characteristic1_complete_acquire_write_with_fd(aInvocation, fds[1], conn->mMtu); close(fds[1]); conn->mIsNotify = true; BLEManagerImpl::HandleTXCharCCCDWrite((void *) conn); isSuccess = true; exit: return isSuccess ? TRUE : FALSE; } static gboolean BluezCharacteristicAcquireNotifyError(BluezGattCharacteristic1 * aChar, GDBusMethodInvocation * aInvocation, GVariant * aOptions) { ChipLogProgress(DeviceLayer, ""TRACE: AcquireNotify is called""); g_dbus_method_invocation_return_dbus_error(aInvocation, ""org.bluez.Error.NotSupported"", ""AcquireNotify for characteristic is unsupported""); return TRUE; } static gboolean BluezCharacteristicStartNotify(BluezGattCharacteristic1 * aChar, GDBusMethodInvocation * aInvocation, gpointer apClosure) { bool isSuccess = false; BluezConnection * conn = NULL; BluezEndpoint * endpoint = static_cast(apClosure); VerifyOrExit(endpoint != NULL, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); conn = GetBluezConnectionViaDevice(endpoint); VerifyOrExit(conn != NULL, g_dbus_method_invocation_return_dbus_error(aInvocation, ""org.bluez.Error.Failed"", ""No Chipoble connection"")); if (bluez_gatt_characteristic1_get_notifying(aChar) == TRUE) { g_dbus_method_invocation_return_dbus_error(aInvocation, ""org.bluez.Error.Failed"", ""Characteristic is already subscribed""); } else { bluez_gatt_characteristic1_complete_start_notify(aChar, aInvocation); bluez_gatt_characteristic1_set_notifying(aChar, TRUE); conn->mIsNotify = true; BLEManagerImpl::HandleTXCharCCCDWrite(conn); } isSuccess = true; exit: return isSuccess ? TRUE : FALSE; } static gboolean BluezCharacteristicStartNotifyError(BluezGattCharacteristic1 * aChar, GDBusMethodInvocation * aInvocation) { g_dbus_method_invocation_return_dbus_error(aInvocation, ""org.bluez.Error.NotSupported"", ""Subscribing to characteristic is unsupported""); return TRUE; } static gboolean BluezCharacteristicStopNotify(BluezGattCharacteristic1 * aChar, GDBusMethodInvocation * aInvocation, gpointer apClosure) { bool isSuccess = false; BluezConnection * conn = NULL; BluezEndpoint * endpoint = static_cast(apClosure); VerifyOrExit(endpoint != NULL, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); conn = GetBluezConnectionViaDevice(endpoint); VerifyOrExit(conn != NULL, g_dbus_method_invocation_return_dbus_error(aInvocation, ""org.bluez.Error.Failed"", ""No Chipoble connection"")); if (bluez_gatt_characteristic1_get_notifying(aChar) == FALSE) { g_dbus_method_invocation_return_dbus_error(aInvocation, ""org.bluez.Error.Failed"", ""Characteristic is already unsubscribed""); } else { bluez_gatt_characteristic1_complete_start_notify(aChar, aInvocation); bluez_gatt_characteristic1_set_notifying(aChar, FALSE); } conn->mIsNotify = false; isSuccess = true; exit: return isSuccess ? TRUE : FALSE; } static gboolean BluezCharacteristicConfirm(BluezGattCharacteristic1 * aChar, GDBusMethodInvocation * aInvocation, gpointer apClosure) { BluezEndpoint * endpoint = (BluezEndpoint *) apClosure; BluezConnection * conn = GetBluezConnectionViaDevice(endpoint); ChipLogDetail(Ble, ""Indication confirmation, %p"", conn); BLEManagerImpl::HandleTXComplete(conn); return TRUE; } static gboolean BluezCharacteristicStopNotifyError(BluezGattCharacteristic1 * aChar, GDBusMethodInvocation * aInvocation) { g_dbus_method_invocation_return_dbus_error(aInvocation, ""org.bluez.Error.Failed"", ""Unsubscribing from characteristic is unsupported""); return TRUE; } static gboolean BluezCharacteristicConfirmError(BluezGattCharacteristic1 * aChar, GDBusMethodInvocation * aInvocation) { g_dbus_method_invocation_return_dbus_error(aInvocation, ""org.bluez.Error.Failed"", ""Confirm from characteristic is unsupported""); return TRUE; } // both arguments allocated, and non-null static void BluezStringAddressToCHIPAddress(const char * aAddressString, BluezAddress * apAddress) { size_t i, j = 0; for (i = 0; i < BLUEZ_ADDRESS_SIZE; i++) { apAddress->mAddress[i] = (CHAR_TO_BLUEZ(aAddressString[j]) << 4) + CHAR_TO_BLUEZ(aAddressString[j + 1]); j += 2; if (aAddressString[j] == ':') j++; } } static gboolean BluezIsDeviceOnAdapter(BluezDevice1 * aDevice, BluezAdapter1 * aAdapter) { return strcmp(bluez_device1_get_adapter(aDevice), g_dbus_proxy_get_object_path(G_DBUS_PROXY(aAdapter))) == 0 ? TRUE : FALSE; } static gboolean BluezIsServiceOnDevice(BluezGattService1 * aService, BluezDevice1 * aDevice) { return strcmp(bluez_gatt_service1_get_device(aService), g_dbus_proxy_get_object_path(G_DBUS_PROXY(aDevice))) == 0 ? TRUE : FALSE; } static gboolean BluezIsCharOnService(BluezGattCharacteristic1 * aChar, BluezGattService1 * aService) { ChipLogProgress(DeviceLayer, ""Char1 %s"", bluez_gatt_characteristic1_get_service(aChar)); ChipLogProgress(DeviceLayer, ""Char1 %s"", g_dbus_proxy_get_object_path(G_DBUS_PROXY(aService))); return strcmp(bluez_gatt_characteristic1_get_service(aChar), g_dbus_proxy_get_object_path(G_DBUS_PROXY(aService))) == 0 ? TRUE : FALSE; } static uint16_t BluezUUIDStringToShortServiceID(const char * aService) { uint32_t shortService = 0; size_t i; // check that the service is a short UUID if (strncasecmp(CHIP_BLE_BASE_SERVICE_UUID_STRING, aService + CHIP_BLE_SERVICE_PREFIX_LENGTH, sizeof(CHIP_BLE_BASE_SERVICE_UUID_STRING)) == 0) { for (i = 0; i < 4; i++) { shortService = (shortService << 8) | (CHAR_TO_BLUEZ(aService[2 * i]) << 4) | CHAR_TO_BLUEZ(aService[2 * i + 1]); } ChipLogProgress(DeviceLayer, ""TRACE: full service UUID: %s, short service %08x"", aService, shortService); if (shortService > UINT16_MAX) { shortService = 0; } } return (uint16_t) shortService; } static void BluezConnectionInit(BluezConnection * apConn) { // populate the service and the characteristics GList * objects = NULL; GList * l; BluezEndpoint * endpoint = NULL; VerifyOrExit(apConn != NULL, ChipLogProgress(DeviceLayer, ""Bluez connection is NULL in %s"", __func__)); endpoint = apConn->mpEndpoint; VerifyOrExit(endpoint != NULL, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); if (!endpoint->mIsCentral) { apConn->mpService = BLUEZ_GATT_SERVICE1(g_object_ref(apConn->mpEndpoint->mpService)); apConn->mpC1 = BLUEZ_GATT_CHARACTERISTIC1(g_object_ref(endpoint->mpC1)); apConn->mpC2 = BLUEZ_GATT_CHARACTERISTIC1(g_object_ref(endpoint->mpC2)); } else { objects = g_dbus_object_manager_get_objects(endpoint->mpObjMgr); for (l = objects; l != NULL; l = l->next) { BluezObject * object = BLUEZ_OBJECT(l->data); BluezGattService1 * service = bluez_object_get_gatt_service1(object); if (service != NULL) { if ((BluezIsServiceOnDevice(service, apConn->mpDevice)) == TRUE && (strcmp(bluez_gatt_service1_get_uuid(service), CHIP_BLE_UUID_SERVICE_STRING) == 0)) { apConn->mpService = service; break; } g_object_unref(service); } } VerifyOrExit(apConn->mpService != NULL, ChipLogProgress(DeviceLayer, ""FAIL: NULL service in %s"", __func__)); for (l = objects; l != NULL; l = l->next) { BluezObject * object = BLUEZ_OBJECT(l->data); BluezGattCharacteristic1 * char1 = bluez_object_get_gatt_characteristic1(object); if (char1 != NULL) { if ((BluezIsCharOnService(char1, apConn->mpService) == TRUE) && (strcmp(bluez_gatt_characteristic1_get_uuid(char1), CHIP_PLAT_BLE_UUID_C1_STRING) == 0)) { apConn->mpC1 = char1; } else if ((BluezIsCharOnService(char1, apConn->mpService) == TRUE) && (strcmp(bluez_gatt_characteristic1_get_uuid(char1), CHIP_PLAT_BLE_UUID_C2_STRING) == 0)) { apConn->mpC2 = char1; } else { g_object_unref(char1); } if ((apConn->mpC1 != NULL) && (apConn->mpC2 != NULL)) { break; } } } VerifyOrExit(apConn->mpC1 != NULL, ChipLogProgress(DeviceLayer, ""FAIL: NULL C1 in %s"", __func__)); VerifyOrExit(apConn->mpC2 != NULL, ChipLogProgress(DeviceLayer, ""FAIL: NULL C2 in %s"", __func__)); } exit: if (objects != NULL) g_list_free_full(objects, g_object_unref); } static gboolean BluezConnectionInitIdle(gpointer user_data) { BluezConnection * conn = (BluezConnection *) user_data; ChipLogProgress(DeviceLayer, ""%s"", __func__); BluezConnectionInit(conn); return FALSE; } static void BluezOTConnectionDestroy(BluezConnection * aConn) { if (aConn) { if (aConn->mpDevice) g_object_unref(aConn->mpDevice); if (aConn->mpService) g_object_unref(aConn->mpService); if (aConn->mpC1) g_object_unref(aConn->mpC1); if (aConn->mpC2) g_object_unref(aConn->mpC2); if (aConn->mpPeerAddress) g_free(aConn->mpPeerAddress); if (aConn->mC1Channel.mWatch > 0) g_source_remove(aConn->mC1Channel.mWatch); if (aConn->mC1Channel.mpChannel) g_io_channel_unref(aConn->mC1Channel.mpChannel); if (aConn->mC2Channel.mWatch > 0) g_source_remove(aConn->mC2Channel.mWatch); if (aConn->mC2Channel.mpChannel) g_io_channel_unref(aConn->mC2Channel.mpChannel); g_free(aConn); } } static BluezGattCharacteristic1 * BluezCharacteristicCreate(BluezGattService1 * aService, const char * aCharName, const char * aUUID, GDBusObjectManagerServer * aRoot) { char * servicePath = g_strdup(g_dbus_object_get_object_path(g_dbus_interface_get_object(G_DBUS_INTERFACE(aService)))); char * charPath = g_strdup_printf(""%s/%s"", servicePath, aCharName); BluezObjectSkeleton * object; BluezGattCharacteristic1 * characteristic; ChipLogProgress(DeviceLayer, ""Create characteristic object at %s"", charPath); object = bluez_object_skeleton_new(charPath); characteristic = bluez_gatt_characteristic1_skeleton_new(); bluez_gatt_characteristic1_set_uuid(characteristic, aUUID); bluez_gatt_characteristic1_set_service(characteristic, servicePath); bluez_object_skeleton_set_gatt_characteristic1(object, characteristic); g_dbus_object_manager_server_export(aRoot, G_DBUS_OBJECT_SKELETON(object)); g_object_unref(object); return characteristic; } static void BluezPeripheralRegisterAppDone(GObject * aObject, GAsyncResult * aResult, gpointer apClosure) { GError * error = NULL; BluezGattManager1 * gattMgr = BLUEZ_GATT_MANAGER1(aObject); gboolean success = bluez_gatt_manager1_call_register_application_finish(gattMgr, aResult, &error); VerifyOrExit(success == TRUE, ChipLogProgress(DeviceLayer, ""FAIL: RegisterApplication : %s"", error->message)); BLEManagerImpl::NotifyBLEPeripheralRegisterAppComplete(true, NULL); ChipLogProgress(DeviceLayer, ""BluezPeripheralRegisterAppDone done""); exit: if (error != NULL) { BLEManagerImpl::NotifyBLEPeripheralRegisterAppComplete(false, NULL); g_error_free(error); } return; } gboolean BluezPeripheralRegisterApp(void * apClosure) { GDBusObject * adapter; BluezGattManager1 * gattMgr; GVariantBuilder optionsBuilder; GVariant * options; BluezEndpoint * endpoint = (BluezEndpoint *) apClosure; VerifyOrExit(endpoint->mpAdapter != NULL, ChipLogProgress(DeviceLayer, ""FAIL: NULL endpoint->mpAdapter in %s"", __func__)); adapter = g_dbus_interface_get_object(G_DBUS_INTERFACE(endpoint->mpAdapter)); VerifyOrExit(adapter != NULL, ChipLogProgress(DeviceLayer, ""FAIL: NULL adapter in %s"", __func__)); gattMgr = bluez_object_get_gatt_manager1(BLUEZ_OBJECT(adapter)); VerifyOrExit(gattMgr != NULL, ChipLogProgress(DeviceLayer, ""FAIL: NULL gattMgr in %s"", __func__)); g_variant_builder_init(&optionsBuilder, G_VARIANT_TYPE(""a{sv}"")); options = g_variant_builder_end(&optionsBuilder); bluez_gatt_manager1_call_register_application(gattMgr, endpoint->mpRootPath, options, NULL, BluezPeripheralRegisterAppDone, NULL); exit: return G_SOURCE_REMOVE; } /*********************************************************************** * GATT Characteristic object ***********************************************************************/ static void BluezHandleAdvertisementFromDevice(BluezDevice1 * aDevice) { const char * address = bluez_device1_get_address(aDevice); GVariant * serviceData = bluez_device1_get_service_data(aDevice); GVariant * entry; GVariantIter iter; BluezAddress * src; const uint8_t * tmpBuf; uint8_t * buf; size_t len, dataLen; size_t i, j; uint16_t serviceId; char * debugStr; // service data is optional and may not be present SuccessOrExit(serviceData != NULL); src = g_new0(BluezAddress, 1); BluezStringAddressToCHIPAddress(address, src); debugStr = g_variant_print(serviceData, TRUE); ChipLogProgress(DeviceLayer, ""TRACE: Device %s Service data: %s"", address, debugStr); g_free(debugStr); // advertising flags ChipLogProgress(DeviceLayer, ""TRACE: Device %s Advertising flags: %s"", address, bluez_device1_get_advertising_flags(aDevice)); g_variant_iter_init(&iter, serviceData); len = 0; while ((entry = g_variant_iter_next_value(&iter)) != NULL) { GVariant * key = g_variant_get_child_value(entry, 0); GVariant * val = g_variant_get_child_value(entry, 1); GVariant * rawVal = g_variant_get_variant(val); serviceId = BluezUUIDStringToShortServiceID(g_variant_get_string(key, &dataLen)); if (serviceId != 0) { len += 1 + sizeof(uint8_t) + sizeof(serviceId) + g_variant_n_children(rawVal); } } if (len != 0) { // we only parsed services, add 3 bytes for flags len = len + 3; buf = (uint8_t *) g_malloc(len); i = 0; buf[i++] = 2; // length of flags buf[i++] = BLUEZ_ADV_TYPE_FLAGS; buf[i++] = BLUEZ_ADV_FLAGS_LE_DISCOVERABLE | BLUEZ_ADV_FLAGS_EDR_UNSUPPORTED; g_variant_iter_init(&iter, serviceData); while ((entry = g_variant_iter_next_value(&iter)) != NULL) { GVariant * key = g_variant_get_child_value(entry, 0); GVariant * val = g_variant_get_child_value(entry, 1); GVariant * rawVal = g_variant_get_variant(val); serviceId = BluezUUIDStringToShortServiceID(g_variant_get_string(key, &dataLen)); if (serviceId != 0) { buf[i++] = g_variant_n_children(rawVal) + 2 + 1; buf[i++] = BLUEZ_ADV_TYPE_SERVICE_DATA; buf[i++] = serviceId & 0xff; buf[i++] = (serviceId >> 8) & 0xff; tmpBuf = (const uint8_t *) g_variant_get_fixed_array(rawVal, &dataLen, sizeof(uint8_t)); for (j = 0; j < dataLen; j++) { buf[i++] = tmpBuf[j]; } } } } exit: return; } static void BluezSignalInterfacePropertiesChanged(GDBusObjectManagerClient * aManager, GDBusObjectProxy * aObject, GDBusProxy * aInterface, GVariant * aChangedProperties, const gchar * const * aInvalidatedProps, gpointer apClosure) { BluezEndpoint * endpoint = (BluezEndpoint *) apClosure; VerifyOrExit(endpoint != NULL, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); VerifyOrExit(endpoint->mpAdapter != NULL, ChipLogProgress(DeviceLayer, ""FAIL: NULL endpoint->mpAdapter in %s"", __func__)); if (strcmp(g_dbus_proxy_get_interface_name(aInterface), DEVICE_INTERFACE) == 0) { BluezDevice1 * device = BLUEZ_DEVICE1(aInterface); GVariantIter iter; GVariant * value; char * key; if (BluezIsDeviceOnAdapter(device, endpoint->mpAdapter)) { BluezConnection * conn = (BluezConnection *) g_hash_table_lookup(endpoint->mpConnMap, g_dbus_proxy_get_object_path(aInterface)); g_variant_iter_init(&iter, aChangedProperties); while (g_variant_iter_next(&iter, ""{&sv}"", &key, &value)) { if (strcmp(key, ""Connected"") == 0) { gboolean connected; connected = g_variant_get_boolean(value); if (connected) { ChipLogProgress(DeviceLayer, ""Bluez coonnected""); // for a central, the connection has been already allocated. For a peripheral, it has not. // todo do we need this ? we could handle all connection the same wa... if (endpoint->mIsCentral) SuccessOrExit(conn != NULL); if (!endpoint->mIsCentral) { VerifyOrExit(conn == NULL, ChipLogProgress(DeviceLayer, ""FAIL: connection already tracked: conn: %x device: %s"", conn, g_dbus_proxy_get_object_path(aInterface))); conn = g_new0(BluezConnection, 1); conn->mpPeerAddress = g_strdup(bluez_device1_get_address(device)); conn->mpDevice = (BluezDevice1 *) g_object_ref(device); conn->mpEndpoint = endpoint; BluezConnectionInit(conn); endpoint->mpPeerDevicePath = g_strdup(g_dbus_proxy_get_object_path(aInterface)); ChipLogProgress(DeviceLayer, ""coonnected, insert, conn:%p, c1:%p, c2:%p and %s"", conn, conn->mpC1, conn->mpC2, endpoint->mpPeerDevicePath); g_hash_table_insert(endpoint->mpConnMap, endpoint->mpPeerDevicePath, conn); } // for central, we do not call BluezConnectionInit until the services have been resolved BLEManagerImpl::CHIPoBluez_NewConnection(endpoint); } else { ChipLogProgress(DeviceLayer, ""Bluez disconnected""); BLEManagerImpl::CHIPoBluez_ConnectionClosed(endpoint); BluezOTConnectionDestroy(conn); g_hash_table_remove(endpoint->mpConnMap, g_dbus_proxy_get_object_path(aInterface)); } } else if (strcmp(key, ""ServicesResolved"") == 0) { gboolean resolved; resolved = g_variant_get_boolean(value); if (endpoint->mIsCentral && conn != NULL && resolved == TRUE) { /* delay to idle, this is to workaround race in handling * of interface-added and properites-changed signals * it looks like we cannot specify order of those * handlers and currently implementation assumes * that interfaces-added is called first. * * TODO figure out if we can avoid this */ g_idle_add(BluezConnectionInitIdle, conn); } } else if (strcmp(key, ""RSSI"") == 0) { /* when discovery starts we will get this one device is * found even if device object was already present */ if (endpoint->mIsCentral) { BluezHandleAdvertisementFromDevice(device); } } g_variant_unref(value); } } } exit: return; } static void BluezHandleNewDevice(BluezDevice1 * device, BluezEndpoint * apEndpoint) { VerifyOrExit(apEndpoint != NULL, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); if (apEndpoint->mIsCentral) { BluezHandleAdvertisementFromDevice(device); } else { BluezConnection * conn; SuccessOrExit(bluez_device1_get_connected(device)); conn = (BluezConnection *) g_hash_table_lookup(apEndpoint->mpConnMap, g_dbus_proxy_get_object_path(G_DBUS_PROXY(device))); VerifyOrExit(conn == NULL, ChipLogProgress(DeviceLayer, ""FAIL: connection already tracked: conn: %x new device: %s"", conn, g_dbus_proxy_get_object_path(G_DBUS_PROXY(device)))); conn = g_new0(BluezConnection, 1); conn->mpPeerAddress = g_strdup(bluez_device1_get_address(device)); conn->mpDevice = (BluezDevice1 *) g_object_ref(device); conn->mpEndpoint = apEndpoint; BluezConnectionInit(conn); g_hash_table_insert(apEndpoint->mpConnMap, g_strdup(g_dbus_proxy_get_object_path(G_DBUS_PROXY(device))), conn); } exit: return; } static void BluezSignalOnObjectAdded(GDBusObjectManager * aManager, GDBusObject * aObject, gpointer apClosure) { // TODO: right now we do not handle addition/removal of adapters // Primary focus here is to handle addition of a device BluezObject * o = BLUEZ_OBJECT(aObject); BluezDevice1 * device = bluez_object_get_device1(o); BluezEndpoint * endpoint = (BluezEndpoint *) apClosure; if (device != NULL) { if (BluezIsDeviceOnAdapter(device, endpoint->mpAdapter) == TRUE) { BluezHandleNewDevice(device, endpoint); } g_object_unref(device); } } static void BluezSignalOnObjectRemoved(GDBusObjectManager * aManager, GDBusObject * aObject, gpointer apClosure) { // TODO: for Device1, lookup connection, and call otPlatTobleHandleDisconnected // for Adapter1: unclear, crash if this pertains to our adapter? at least null out the endpoint->mpAdapter. // for Characteristic1, or GattService -- handle here via calling otPlatTobleHandleDisconnected, or ignore. } static BluezGattService1 * BluezServiceCreate(gpointer apClosure) { BluezObjectSkeleton * object; BluezGattService1 * service; BluezEndpoint * endpoint = (BluezEndpoint *) apClosure; endpoint->mpServicePath = g_strdup_printf(""%s/service"", endpoint->mpRootPath); ChipLogProgress(DeviceLayer, ""CREATE service object at %s"", endpoint->mpServicePath); object = bluez_object_skeleton_new(endpoint->mpServicePath); service = bluez_gatt_service1_skeleton_new(); bluez_gatt_service1_set_uuid(service, ""0xFEAF""); // device is only valid for remote services bluez_gatt_service1_set_primary(service, TRUE); // includes -- unclear whether required. Might be filled in later bluez_object_skeleton_set_gatt_service1(object, service); g_dbus_object_manager_server_export(endpoint->mpRoot, G_DBUS_OBJECT_SKELETON(object)); g_object_unref(object); return service; } static void bluezObjectsSetup(BluezEndpoint * apEndpoint) { GList * objects = NULL; GList * l; char * expectedPath = NULL; VerifyOrExit(apEndpoint != NULL, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); expectedPath = g_strdup_printf(""%s/hci%d"", BLUEZ_PATH, apEndpoint->mNodeId); objects = g_dbus_object_manager_get_objects(apEndpoint->mpObjMgr); for (l = objects; l != NULL && apEndpoint->mpAdapter == NULL; l = l->next) { BluezObject * object = BLUEZ_OBJECT(l->data); GList * interfaces; GList * ll; interfaces = g_dbus_object_get_interfaces(G_DBUS_OBJECT(object)); for (ll = interfaces; ll != NULL; ll = ll->next) { if (BLUEZ_IS_ADAPTER1(ll->data)) { // we found the adapter BluezAdapter1 * adapter = BLUEZ_ADAPTER1(ll->data); char * addr = (char *) bluez_adapter1_get_address(adapter); if (apEndpoint->mpAdapterAddr == NULL) // no adapter address provided, bind to the hci indicated by nodeid { if (strcmp(g_dbus_proxy_get_object_path(G_DBUS_PROXY(adapter)), expectedPath) == 0) { apEndpoint->mpAdapter = (BluezAdapter1 *) g_object_ref(adapter); } } else { if (strcmp(apEndpoint->mpAdapterAddr, addr) == 0) { apEndpoint->mpAdapter = (BluezAdapter1 *) g_object_ref(adapter); } } } } g_list_free_full(interfaces, g_object_unref); } VerifyOrExit(apEndpoint->mpAdapter != NULL, ChipLogProgress(DeviceLayer, ""FAIL: NULL apEndpoint->mpAdapter in %s"", __func__)); bluez_adapter1_set_powered(apEndpoint->mpAdapter, TRUE); // with BLE we are discoverable only when advertising so this can be // set once on init bluez_adapter1_set_discoverable_timeout(apEndpoint->mpAdapter, 0); bluez_adapter1_set_discoverable(apEndpoint->mpAdapter, TRUE); exit: g_list_free_full(objects, g_object_unref); g_free(expectedPath); } static BluezConnection * GetBluezConnectionViaDevice(BluezEndpoint * apEndpoint) { BluezConnection * retval = (BluezConnection *) g_hash_table_lookup(apEndpoint->mpConnMap, apEndpoint->mpPeerDevicePath); // ChipLogProgress(DeviceLayer, ""acquire connection object %p in (%s)"", retval, __func__); return retval; } #if CHIP_BLUEZ_CENTRAL_SUPPORT static BluezConnection * BluezCharacteristicGetBluezConnection(BluezGattCharacteristic1 * aChar, GVariant * aOptions, BluezEndpoint * apEndpoint) { BluezConnection * retval = NULL; const gchar * path = NULL; GVariantDict options; GVariant * v; VerifyOrExit(apEndpoint != NULL, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); VerifyOrExit(apEndpoint->mIsCentral, ); /* TODO Unfortunately StartNotify/StopNotify doesn't provide info about * peer device in call params so we need look this up ourselves. */ if (aOptions == NULL) { GList * objects; GList * l; GList * ll; objects = g_dbus_object_manager_get_objects(apEndpoint->mpObjMgr); for (l = objects; l != NULL; l = l->next) { BluezDevice1 * device = bluez_object_get_device1(BLUEZ_OBJECT(l->data)); if (device != NULL) { if (BluezIsDeviceOnAdapter(device, apEndpoint->mpAdapter)) { for (ll = objects; ll != NULL; ll = ll->next) { BluezGattService1 * service = bluez_object_get_gatt_service1(BLUEZ_OBJECT(ll->data)); if (service != NULL) { if (BluezIsServiceOnDevice(service, device)) { if (BluezIsCharOnService(aChar, service)) { retval = (BluezConnection *) g_hash_table_lookup( apEndpoint->mpConnMap, g_dbus_proxy_get_object_path(G_DBUS_PROXY(device))); } } g_object_unref(service); if (retval != NULL) break; } } } g_object_unref(device); if (retval != NULL) break; } } g_list_free_full(objects, g_object_unref); } else { g_variant_dict_init(&options, aOptions); v = g_variant_dict_lookup_value(&options, ""device"", G_VARIANT_TYPE_OBJECT_PATH); VerifyOrExit(v != NULL, ChipLogProgress(DeviceLayer, ""FAIL: No device option in dictionary (%s)"", __func__)); path = g_variant_get_string(v, NULL); retval = (BluezConnection *) g_hash_table_lookup(apEndpoint->mpConnMap, path); } exit: return retval; } #endif // CHIP_BLUEZ_CENTRAL_SUPPORT void EndpointCleanup(BluezEndpoint * apEndpoint) { if (apEndpoint != NULL) { if (apEndpoint->mpOwningName != NULL) { g_free(apEndpoint->mpOwningName); apEndpoint->mpOwningName = NULL; } if (apEndpoint->mpAdapterName != NULL) { g_free(apEndpoint->mpAdapterName); apEndpoint->mpAdapterName = NULL; } if (apEndpoint->mpAdapterAddr != NULL) { g_free(apEndpoint->mpAdapterAddr); apEndpoint->mpAdapterAddr = NULL; } if (apEndpoint->mpRootPath != NULL) { g_free(apEndpoint->mpRootPath); apEndpoint->mpRootPath = NULL; } if (apEndpoint->mpAdvPath != NULL) { g_free(apEndpoint->mpAdvPath); apEndpoint->mpAdvPath = NULL; } if (apEndpoint->mpServicePath != NULL) { g_free(apEndpoint->mpServicePath); apEndpoint->mpServicePath = NULL; } if (apEndpoint->mpConnMap != NULL) { g_hash_table_destroy(apEndpoint->mpConnMap); apEndpoint->mpConnMap = NULL; } if (apEndpoint->mpAdvertisingUUID != NULL) { g_free(apEndpoint->mpAdvertisingUUID); apEndpoint->mpAdvertisingUUID = NULL; } if (apEndpoint->mpChipServiceData != NULL) { g_free(apEndpoint->mpChipServiceData); apEndpoint->mpChipServiceData = NULL; } if (apEndpoint->mpPeerDevicePath != NULL) { g_free(apEndpoint->mpPeerDevicePath); apEndpoint->mpPeerDevicePath = NULL; } g_free(apEndpoint); } } void BluezObjectsCleanup(BluezEndpoint * apEndpoint) { g_object_unref(apEndpoint->mpAdapter); EndpointCleanup(apEndpoint); } static void BluezPeripheralObjectsSetup(gpointer apClosure) { static const char * const c1_flags[] = { ""write"", NULL }; static const char * const c2_flags[] = { ""read"", ""indicate"", NULL }; BluezEndpoint * endpoint = (BluezEndpoint *) apClosure; VerifyOrExit(endpoint != NULL, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); endpoint->mpService = BluezServiceCreate(apClosure); // C1 characteristic endpoint->mpC1 = BluezCharacteristicCreate(endpoint->mpService, g_strdup(""c1""), g_strdup(CHIP_PLAT_BLE_UUID_C1_STRING), endpoint->mpRoot); bluez_gatt_characteristic1_set_flags(endpoint->mpC1, c1_flags); g_signal_connect(endpoint->mpC1, ""handle-read-value"", G_CALLBACK(BluezCharacteristicReadValue), apClosure); g_signal_connect(endpoint->mpC1, ""handle-write-value"", G_CALLBACK(BluezCharacteristicWriteValueError), NULL); g_signal_connect(endpoint->mpC1, ""handle-acquire-write"", G_CALLBACK(BluezCharacteristicAcquireWrite), apClosure); g_signal_connect(endpoint->mpC1, ""handle-acquire-notify"", G_CALLBACK(BluezCharacteristicAcquireNotifyError), NULL); g_signal_connect(endpoint->mpC1, ""handle-start-notify"", G_CALLBACK(BluezCharacteristicStartNotifyError), NULL); g_signal_connect(endpoint->mpC1, ""handle-stop-notify"", G_CALLBACK(BluezCharacteristicStopNotifyError), NULL); g_signal_connect(endpoint->mpC1, ""handle-confirm"", G_CALLBACK(BluezCharacteristicConfirmError), NULL); endpoint->mpC2 = BluezCharacteristicCreate(endpoint->mpService, g_strdup(""c2""), g_strdup(CHIP_PLAT_BLE_UUID_C2_STRING), endpoint->mpRoot); bluez_gatt_characteristic1_set_flags(endpoint->mpC2, c2_flags); g_signal_connect(endpoint->mpC2, ""handle-read-value"", G_CALLBACK(BluezCharacteristicReadValue), apClosure); g_signal_connect(endpoint->mpC2, ""handle-write-value"", G_CALLBACK(BluezCharacteristicWriteValueError), NULL); g_signal_connect(endpoint->mpC2, ""handle-acquire-write"", G_CALLBACK(BluezCharacteristicAcquireWriteError), NULL); g_signal_connect(endpoint->mpC2, ""handle-acquire-notify"", G_CALLBACK(BluezCharacteristicAcquireNotify), apClosure); g_signal_connect(endpoint->mpC2, ""handle-start-notify"", G_CALLBACK(BluezCharacteristicStartNotify), apClosure); g_signal_connect(endpoint->mpC2, ""handle-stop-notify"", G_CALLBACK(BluezCharacteristicStopNotify), apClosure); g_signal_connect(endpoint->mpC2, ""handle-confirm"", G_CALLBACK(BluezCharacteristicConfirm), apClosure); ChipLogProgress(DeviceLayer, ""CHIP BTP C1 %s"", bluez_gatt_characteristic1_get_service(endpoint->mpC1)); ChipLogProgress(DeviceLayer, ""CHIP BTP C2 %s"", bluez_gatt_characteristic1_get_service(endpoint->mpC2)); exit: return; } static void BluezOnBusAcquired(GDBusConnection * aConn, const gchar * aName, gpointer apClosure) { BluezEndpoint * endpoint = (BluezEndpoint *) apClosure; VerifyOrExit(endpoint != NULL, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); ChipLogProgress(DeviceLayer, ""TRACE: Bus acquired for name %s"", aName); endpoint->mpRootPath = g_strdup_printf(""/chipoble/%04x"", getpid() & 0xffff); endpoint->mpRoot = g_dbus_object_manager_server_new(endpoint->mpRootPath); g_dbus_object_manager_server_set_connection(endpoint->mpRoot, aConn); BluezPeripheralObjectsSetup(apClosure); exit: return; } #if CHIP_BLUEZ_NAME_MONITOR static void BluezOnNameAcquired(GDBusConnection * aConn, const gchar * aName, gpointer apClosure) { ChipLogProgress(DeviceLayer, ""TRACE: Owning name: Acquired %s"", aName); } static void BluezOnNameLost(GDBusConnection * aConn, const gchar * aName, gpointer apClosure) { ChipLogProgress(DeviceLayer, ""TRACE: Owning name: lost %s"", aName); } #endif static void * BluezMainLoop(void * apClosure) { GDBusObjectManager * manager; GError * error = NULL; GDBusConnection * conn = NULL; BluezEndpoint * endpoint = (BluezEndpoint *) apClosure; VerifyOrExit(endpoint != NULL, ChipLogProgress(DeviceLayer, ""endpoint is NULL in %s"", __func__)); conn = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &error); VerifyOrExit(conn != NULL, ChipLogProgress(DeviceLayer, ""FAIL: get bus sync in %s, error: %s"", __func__, error->message)); if (endpoint->mpAdapterName != NULL) endpoint->mpOwningName = g_strdup_printf(""%s"", endpoint->mpAdapterName); else endpoint->mpOwningName = g_strdup_printf(""C-%04x"", getpid() & 0xffff); BluezOnBusAcquired(conn, endpoint->mpOwningName, apClosure); manager = g_dbus_object_manager_client_new_sync( conn, G_DBUS_OBJECT_MANAGER_CLIENT_FLAGS_NONE, BLUEZ_INTERFACE, ""/"", bluez_object_manager_client_get_proxy_type, NULL /* unused user data in the Proxy Type Func */, NULL /*destroy notify */, NULL /* cancellable */, &error); VerifyOrExit(manager != NULL, ChipLogProgress(DeviceLayer, ""FAIL: Error getting object manager client: %s"", error->message)); endpoint->mpObjMgr = manager; bluezObjectsSetup(endpoint); #if 0 // reenable if we want to handle the bluetoothd restart g_signal_connect (manager, ""notify::name-owner"", G_CALLBACK (on_notify_name_owner), NULL); #endif g_signal_connect(manager, ""object-added"", G_CALLBACK(BluezSignalOnObjectAdded), apClosure); g_signal_connect(manager, ""object-removed"", G_CALLBACK(BluezSignalOnObjectRemoved), apClosure); g_signal_connect(manager, ""interface-proxy-properties-changed"", G_CALLBACK(BluezSignalInterfacePropertiesChanged), apClosure); ChipLogProgress(DeviceLayer, ""TRACE: Bluez mainloop starting %s"", __func__); g_main_loop_run(sBluezMainLoop); ChipLogProgress(DeviceLayer, ""TRACE: Bluez mainloop stopping %s"", __func__); BluezObjectsCleanup(endpoint); exit: if (error != NULL) g_error_free(error); return NULL; } bool BluezRunOnBluezThread(int (*aCallback)(void *), void * apClosure) { GMainContext * context = NULL; const char * msg = NULL; VerifyOrExit(sBluezMainLoop != NULL, msg = ""FAIL: NULL sBluezMainLoop""); VerifyOrExit(g_main_loop_is_running(sBluezMainLoop), msg = ""FAIL: sBluezMainLoop not running""); context = g_main_loop_get_context(sBluezMainLoop); VerifyOrExit(context != NULL, msg = ""FAIL: NULL main context""); g_main_context_invoke(context, aCallback, apClosure); exit: if (msg != NULL) { ChipLogProgress(DeviceLayer, ""%s in %s"", msg, __func__); } return msg == NULL; } static gboolean BluezC2Indicate(void * apClosure) { ConnectionDataBundle * closure = NULL; BluezConnection * conn = NULL; GError * error = NULL; GIOStatus status; const char * buf; size_t len, written; closure = static_cast(apClosure); VerifyOrExit(closure != NULL, ChipLogProgress(DeviceLayer, ""ConnectionDataBundle is NULL in %s"", __func__)); conn = closure->mpConn; VerifyOrExit(conn != NULL, ChipLogProgress(DeviceLayer, ""BluezConnection is NULL in %s"", __func__)); VerifyOrExit(conn->mpC2 != NULL, ChipLogProgress(DeviceLayer, ""FAIL: C2 Indicate: %s"", ""NULL C2"")); if (bluez_gatt_characteristic1_get_notify_acquired(conn->mpC2) == TRUE) { buf = (char *) g_variant_get_fixed_array(closure->mpVal, &len, sizeof(uint8_t)); status = g_io_channel_write_chars(conn->mC2Channel.mpChannel, buf, len, &written, &error); g_variant_unref(closure->mpVal); closure->mpVal = NULL; VerifyOrExit(status == G_IO_STATUS_NORMAL, ChipLogProgress(DeviceLayer, ""FAIL: C2 Indicate: %s"", error->message)); } else { bluez_gatt_characteristic1_set_value(conn->mpC2, closure->mpVal); closure->mpVal = NULL; } exit: if (closure != NULL) { if (closure->mpVal) { g_variant_unref(closure->mpVal); } g_free(closure); } if (error != NULL) g_error_free(error); return G_SOURCE_REMOVE; } bool SendBluezIndication(void * apConn, chip::System::PacketBuffer * apBuf) { ConnectionDataBundle * closure; const char * msg = NULL; bool success = false; uint8_t * buffer = NULL; size_t len = 0; VerifyOrExit(apBuf != NULL, ChipLogProgress(DeviceLayer, ""apBuf is NULL in %s"", __func__)); buffer = apBuf->Start(); len = apBuf->DataLength(); closure = g_new(ConnectionDataBundle, 1); closure->mpConn = static_cast(apConn); closure->mpVal = g_variant_new_fixed_array(G_VARIANT_TYPE_BYTE, buffer, len * sizeof(uint8_t), sizeof(uint8_t)); success = BluezRunOnBluezThread(BluezC2Indicate, closure); exit: if (NULL != msg) { ChipLogError(Ble, msg); } if (NULL != apBuf) { chip::System::PacketBuffer::Free(apBuf); } return success; } static gboolean BluezDisconnect(void * apClosure) { BluezConnection * conn = static_cast(apClosure); GError * error = NULL; gboolean success; VerifyOrExit(conn != NULL, ChipLogProgress(DeviceLayer, ""conn is NULL in %s"", __func__)); VerifyOrExit(conn->mpDevice != NULL, ChipLogProgress(DeviceLayer, ""FAIL: Disconnect: %s"", ""NULL Device"")); ChipLogProgress(DeviceLayer, ""%s peer=%s"", __func__, bluez_device1_get_address(conn->mpDevice)); success = bluez_device1_call_disconnect_sync(conn->mpDevice, NULL, &error); VerifyOrExit(success == TRUE, ChipLogProgress(DeviceLayer, ""FAIL: Disconnect: %s"", error->message)); exit: if (error != NULL) g_error_free(error); return G_SOURCE_REMOVE; } static int CloseBleconnectionCB(void * apAppState) { BluezDisconnect(apAppState); return G_SOURCE_REMOVE; } bool CloseBluezConnection(void * apAppState) { return BluezRunOnBluezThread(CloseBleconnectionCB, apAppState); } CHIP_ERROR StartBluezAdv(void * apAppState) { CHIP_ERROR err = CHIP_NO_ERROR; if (!BluezRunOnBluezThread(BluezAdvStart, apAppState)) { err = CHIP_ERROR_INCORRECT_STATE; ChipLogError(Ble, ""Failed to schedule BluezAdvStart() on CHIPoBluez thread""); } return err; } CHIP_ERROR StopBluezAdv(void * apAppState) { CHIP_ERROR err = CHIP_NO_ERROR; if (!BluezRunOnBluezThread(BluezAdvStop, apAppState)) { err = CHIP_ERROR_INCORRECT_STATE; ChipLogError(Ble, ""Failed to schedule BluezAdvStop() on CHIPoBluez thread""); } return err; } CHIP_ERROR BluezAdvertisementSetup(void * apAppState) { CHIP_ERROR err = CHIP_NO_ERROR; if (!BluezRunOnBluezThread(BluezAdvSetup, apAppState)) { err = CHIP_ERROR_INCORRECT_STATE; ChipLogError(Ble, ""Failed to schedule BluezAdvertisementSetup() on CHIPoBluez thread""); } return err; } CHIP_ERROR BluezGattsAppRegister(void * apAppState) { CHIP_ERROR err = CHIP_NO_ERROR; if (!BluezRunOnBluezThread(BluezPeripheralRegisterApp, apAppState)) { err = CHIP_ERROR_INCORRECT_STATE; ChipLogError(Ble, ""Failed to schedule BluezPeripheralRegisterApp() on CHIPoBluez thread""); } return err; } CHIP_ERROR ConfigureBluezAdv(BLEAdvConfig & aBleAdvConfig, BluezEndpoint * apEndpoint) { const char * msg = NULL; CHIP_ERROR err = CHIP_NO_ERROR; VerifyOrExit(aBleAdvConfig.mpBleName != NULL, msg = ""FAIL: BLE name is NULL""); VerifyOrExit(aBleAdvConfig.mpAdvertisingUUID != NULL, msg = ""FAIL: BLE mpAdvertisingUUID is NULL in %s""); apEndpoint->mpAdapterName = g_strdup(aBleAdvConfig.mpBleName); apEndpoint->mpAdvertisingUUID = g_strdup(aBleAdvConfig.mpAdvertisingUUID); apEndpoint->mNodeId = aBleAdvConfig.mNodeId; apEndpoint->mType = aBleAdvConfig.mType; apEndpoint->mDuration = aBleAdvConfig.mDuration; apEndpoint->mpChipServiceData = static_cast(g_malloc(sizeof(CHIPServiceData) + 1)); apEndpoint->mpChipServiceData->mDataBlock0Len = sizeof(CHIPIdInfo) + 1; apEndpoint->mpChipServiceData->mDataBlock0Type = 1; apEndpoint->mpChipServiceData->mIdInfo.mMajor = aBleAdvConfig.mMajor; apEndpoint->mpChipServiceData->mIdInfo.mMinor = aBleAdvConfig.mMinor; apEndpoint->mpChipServiceData->mIdInfo.mVendorId = aBleAdvConfig.mVendorId; apEndpoint->mpChipServiceData->mIdInfo.mProductId = aBleAdvConfig.mProductId; apEndpoint->mpChipServiceData->mIdInfo.mDeviceId = aBleAdvConfig.mDeviceId; apEndpoint->mpChipServiceData->mIdInfo.mPairingStatus = aBleAdvConfig.mPairingStatus; apEndpoint->mDuration = aBleAdvConfig.mDuration; exit: if (NULL != msg) { ChipLogProgress(DeviceLayer, ""%s in %s"", msg, __func__); err = CHIP_ERROR_INCORRECT_STATE; if (apEndpoint->mpChipServiceData != NULL) { g_free(apEndpoint->mpChipServiceData); apEndpoint->mpChipServiceData = NULL; } } return err; } CHIP_ERROR InitBluezBleLayer(bool aIsCentral, char * apBleAddr, BLEAdvConfig & aBleAdvConfig, void *& apEndpoint) { CHIP_ERROR err = CHIP_NO_ERROR; bool retval = false; int pthreadErr = 0; int tmpErrno; BluezEndpoint * endpoint = NULL; VerifyOrExit(pipe2(sBluezFD, O_DIRECT) == 0, ChipLogProgress(DeviceLayer, ""FAIL: open pipe in %s"", __func__)); // initialize server endpoint endpoint = g_new0(BluezEndpoint, 1); VerifyOrExit(endpoint != NULL, ChipLogProgress(DeviceLayer, ""FAIL: memory allocation in %s"", __func__)); if (apBleAddr != NULL) endpoint->mpAdapterAddr = g_strdup(apBleAddr); else endpoint->mpAdapterAddr = NULL; endpoint->mpConnMap = g_hash_table_new(g_str_hash, g_str_equal); endpoint->mIsCentral = aIsCentral; err = ConfigureBluezAdv(aBleAdvConfig, endpoint); SuccessOrExit(err); sBluezMainLoop = g_main_loop_new(NULL, FALSE); VerifyOrExit(sBluezMainLoop != NULL, ChipLogProgress(DeviceLayer, ""FAIL: memory alloc in %s"", __func__)); pthreadErr = pthread_create(&sBluezThread, NULL, BluezMainLoop, endpoint); tmpErrno = errno; VerifyOrExit(pthreadErr == 0, ChipLogProgress(DeviceLayer, ""FAIL: pthread_create (%s) in %s"", strerror(tmpErrno), __func__)); sleep(1); retval = TRUE; exit: if (retval) { apEndpoint = endpoint; ChipLogProgress(DeviceLayer, ""PlatformBlueZInit init success""); } else { EndpointCleanup(endpoint); } return err; } } // namespace Internal } // namespace DeviceLayer } // namespace chip #endif // CHIP_DEVICE_CONFIG_ENABLE_CHIPOBLE ",16168,True,3070.7787355858372,median "[[flowableApps]] == Flowable applications Flowable provides several ui web applications to demonstrate and leverage the functionality provided by the Flowable project: * Flowable IDM: an Identity Management application that provides single sign-on authentication functionality for all the Flowable UI applications, and, for users with the IDM administrative privilege, it also provides functionality to manage users, groups and privileges. * Flowable Modeler: an application that allows users with modeler privileges to model processes, forms, decision tables and application definitions. * Flowable Task: a runtime task application that provides functionality to start process instances, edit task forms, complete tasks and query on tasks and process instances. * Flowable Admin: an administrative application that allows users with admin privilege to query the BPMN, DMN, form and content engines and provides several options to change process instances, tasks, jobs and so on. The admin application connects to the engines through the REST API that is deployed together with the Flowable Task app and the Flowable REST app. The Flowable IDM is required for all other apps to enable authentication. The WAR files for each app can be deployed to the same servlet container (such as Apache Tomcat), but can also be deployed on different servlet containers. Because the same cookie is used for authentication with each app, the apps need to run on the same domain. Flowable also provides the `flowable-rest.war` which contains the Flowable REST API. More about this can be read in the <> chapter. The apps are Spring Boot 2.0 based, which means that that the WAR files are actually executable and can be run as a normal standalone applications. See https://docs.spring.io/spring-boot/docs/current/reference/html/build-tool-plugins-maven-plugin.html#build-tool-plugins-maven-packaging[The Executable Jar Format] in the Spring Boot reference documentation. [[uiAppInstallation]] === Flowable UI Applications installation As mentioned before, all four UI apps can be deployed together on the same Tomcat server, and to get started this is probably the easiest approach. You can choose to only install the Modeler app, for example, but make sure the Flowable IDM app is always running/deployed as well. For this installation guide we'll describe the installation of all four apps to a Tomcat server. 1. Download a recent stable version of link:$$http://tomcat.apache.org$$[Apache Tomcat]. 2. Download the latest stable link:$$http://www.flowable.org/downloads.html$$[Flowable 6 version]. 3. Copy the flowable-admin.war, flowable-idm.war, flowable-modeler.war and flowable-task.war files from the Flowable distribution __wars__ folder to the Tomcat webapps folder. 4. Startup the Tomcat server by running the bin/startup.sh (Mac OS and Linux) or bin/startup.bat (Windows) script. 5. Open a web browser and go to link:$$http://localhost:8080/flowable-modeler$$[http://localhost:8080/flowable-modeler]. All Flowable UI apps should now be running with an H2 in-memory database and the following login screen should be shown in your web browser: image::images/flowable_idm_login_screen.png[align=""center""] By default, the Flowable IDM application will create an admin user that has privileges to all the Flowable UI apps. You can login with admin/test and the browser should redirect to the Flowable Modeler application: image::images/flowable_modeler_startup_screen.png[align=""center""] Since the UI apps are Spring Boot executable apps it is possible to run them as standalone applications without the need of an application server. Starting single application looks like: ``` java -jar flowable-idm.war ``` Usually, you will want to change the default H2 in-memory database configuration to a MySQL or Postgres (or other persistent database) configuration. You can do this per app by changing the application.properties file in the _WEB-INF/classes/_ directory of each app. However, it is easier to use the Spring Boot https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html[Externalized Configuration]. An example configuration can be found on link:$$https://github.com/flowable/flowable-engine/blob/master/modules/flowable-ui-task/flowable-ui-task-app/src/main/resources/application.properties$$[Github] To change the default configuration to MySQL the following changes are needed to the properties file: [source,linenums] ---- spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://127.0.0.1:3306/flowable?characterEncoding=UTF-8 spring.datasource.username=flowable spring.datasource.password=flowable ---- This configuration will expect a flowable database to be present in the MySQL server and the UI apps will automatically generate the necessary database tables. For Postgres the following changes are necessary: [source,linenums] ---- spring.datasource.driver-class-name=org.postgresql.Driver spring.datasource.url=jdbc:postgresql://localhost:5432/flowable spring.datasource.username=flowable spring.datasource.password=flowable ---- In addition to changing the configuration, make sure the database driver is available on the classpath. Again, you could do this for every web application separately by adding the driver JAR file to the WEB-INF/lib folder, but you can also copy the JAR file once to the Tomcat lib folder. For MySQL and Postgres the database drivers can be downloaded from: * MySQL: link:$$https://dev.mysql.com/downloads/connector/j$$[https://dev.mysql.com/downloads/connector/j] * Postgres: link:$$https://jdbc.postgresql.org/$$[https://jdbc.postgresql.org/] When running the apps as standalone applications the database driver can be added by using the `loader.path` property. ``` java -Dloader.path=/location/to/your/driverfolder -jar flowable-idm.war ``` See the https://docs.spring.io/spring-boot/docs/current/reference/html/executable-jar.html#executable-jar-property-launcher-features[`PropertiesLauncher` Features] in the Spring Boot reference documentation for more information. === Flowable UI Applications Configurations As the Flowable UI apps are Spring Boot applications you can use all the properties Spring Boot provides. In order to provide custom configuration for the apps have a look at the https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html[Externalized Configuration] section of the Spring Boot documentation. [TIP] ----- You can also use YAML based properties. ----- .Common UI App Properties [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.common.app.idm-url |idm.app.url |- |The URL to the IDM application, used for the user info and token info REST GET calls. It's also used as a fallback for the redirect url to the login page in the UI apps. |flowable.common.app.idm-redirect-url |idm.app.redirect.url |- |The redirect URL to the IDM application, used for the login redirect when the cookie isn't set or is invalid. |flowable.common.app.redirect-on-auth-success |app.redirect.url.on.authsuccess |- |The URL to which the redirect should occur after a successful authentication. |flowable.common.app.role-prefix |- |ROLE_ |The default role prefix that needs to be used by Spring Security. |flowable.common.app.tenant-id |- |- |The static tenant id used for the DefaultTenantProvider. The modeler app uses this to determine under which tenant id to store and publish models. When not provided, empty or only contains whitespace it defaults to the user's tenant id if available otherwise it uses no tenant id. |flowable.common.app.cache-login-tokens.max-age |cache.login-tokens.max.age |30 |The max age in seconds after which the entry should be invalidated. |flowable.common.app.cache-login-tokens.max-size |cache.login-tokens.max.size |2048 |The maximum number of entries that the cache should contain. |flowable.common.app.cache-login-users.max-age |cache.login-users.max.age |30 |The max age in seconds after which the entry should be invalidated. |flowable.common.app.cache-login-users.max-size |cache.login-users.max.size |2048 |The maximum number of entries that the cache should contain. |flowable.common.app.cache-users.max-age |cache.users.max.age |30 |The max age in seconds after which the entry should be invalidated. |flowable.common.app.cache-users.max-size |cache.users.max.size |2048 |The maximum number of entries that the cache should contain. |flowable.common.app.idm-admin.password |idm.admin.password |- |The password used for executing the REST calls (with basic auth) to the IDM REST services. Default is test. |flowable.common.app.idm-admin.user |idm.admin.user |admin |The username used for executing the REST calls (with basic auth) to the IDM REST services. Default is admin |flowable.rest.app.authentication-mode |rest.authentication.mode |verify-privilege |Configures the way user credentials are verified when doing a REST API call: 'any-user' : the user needs to exist and the password need to match. Any user is allowed to do the call (this is the pre 6.3.0 behavior) 'verify-privilege' : the user needs to exist, the password needs to match and the user needs to have the 'rest-api' privilege If nothing set, defaults to 'verify-privilege' |=============== Some of the old properties have been moved to be managed by the Flowable Spring Boot starter (or Spring Boot itself) .Old properties managed by the Flowable Spring Boot Starter [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.async-executor-activate |engine.process.asyncexecutor.activate |true |Whether the async executor should be activated. |flowable.database-schema-update |engine.process.schema.update |true |The strategy that should be used for the database schema. |flowable.history-level |engine.process.history.level |- |The history level that needs to be used. |flowable.process.servlet.name |flowable.rest-api-servlet-name |Flowable BPMN Rest API |The name of the Process servlet. |flowable.process.servlet.path |flowable.rest-api-mapping |/process-api |The context path for the Process rest servlet. |flowable.content.storage.create-root |contentstorage.fs.create-root |true |If the root folder doesn't exist, should it be created? |flowable.content.storage.root-folder |contentstorage.fs.root-folder |- |Root folder location where content files will be stored, for example, task attachments or form file uploads. |flowable.idm.enabled |flowable.db-identity-used |true |Whether the idm engine needs to be started. |flowable.idm.password-encoder |security.passwordencoder |- |The type of the password encoder that needs to be used. |flowable.idm.ldap.base-dn |ldap.basedn |- |The base 'distinguished name' (DN) from which the searches for users and groups are started. Use 'user-base-dn' or 'group-base-dn' when needing to differentiate between user and group base DN. |flowable.idm.ldap.enabled |ldap.enabled |false |Whether to enable LDAP IDM Service. |flowable.idm.ldap.password |ldap.password |- |The password that is used to connect to the LDAP system. |flowable.idm.ldap.port |ldap.port |-1 |The port on which the LDAP system is running. |flowable.idm.ldap.server |ldap.server |- |The server host on which the LDAP system can be reached. For example 'ldap://localhost'. |flowable.idm.ldap.user |ldap.user |- |The user id that is used to connect to the LDAP system. |flowable.idm.ldap.attribute.email |ldap.attribute.email |- |Name of the attribute that matches the user email. This property is used when looking for an 'org.flowable.idm.api.User' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.User' object is done. |flowable.idm.ldap.attribute.first-name |ldap.attribute.firstname |- |Name of the attribute that matches the user first name. This property is used when looking for a 'org.flowable.idm.api.User' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.User' object is done. |flowable.idm.ldap.attribute.group-id |ldap.attribute.groupid |- |Name of the attribute that matches the group id. This property is used when looking for a 'org.flowable.idm.api.Group' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.Group' object is done. |flowable.idm.ldap.attribute.group-name |ldap.attribute.groupname |- |Name of the attribute that matches the group name. This property is used when looking for a 'org.flowable.idm.api.Group' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.Group' object is done. |flowable.idm.ldap.attribute.last-name |ldap.attribute.lastname |- |Name of the attribute that matches the user last name. This property is used when looking for a 'org.flowable.idm.api.User' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.User' object is done. |flowable.idm.ldap.attribute.user-id |ldap.attribute.userid |- |Name of the attribute that matches the user id. This property is used when looking for a 'org.flowable.idm.api.User' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.User' object is done. This property is optional and is only needed if searching for 'org.flowable.idm.api.User' objects using the Flowable API. |flowable.idm.ldap.cache.group-size |ldap.cache.groupsize |-1 |Allows to set the size of the 'org.flowable.ldap.LDAPGroupCache'. This is an LRU cache that caches groups for users and thus avoids hitting the LDAP system each time the groups of a user needs to be known. The cache will not be instantiated if the value is less then zero. By default set to -1, so no caching is done. Note that the group cache is instantiated on the 'org.flowable.ldap.LDAPIdentityServiceImpl'. As such, if you have a custom implementation of the 'org.flowable.ldap.LDAPIdentityServiceImpl', do not forget to add the group cache functionality. |flowable.idm.ldap.query.all-groups |ldap.query.groupall |- |The query that is executed when searching for all groups. |flowable.idm.ldap.query.all-users |ldap.query.userall |- |The query that is executed when searching for all users. |flowable.idm.ldap.query.groups-for-user |ldap.query.groupsforuser |- |The query that is executed when searching for the groups of a specific user. For example: `(&(objectClass=groupOfUniqueNames)(uniqueMember={0}))` Here, all the objects in LDAP with the class 'groupOfUniqueNames' and where the provided DN is a 'uniqueMember' are returned. As shown in the example, the user id is injected by the typical {@link java.text.MessageFormat}, ie by using _{0}_ If setting the query alone is insufficient for your specific LDAP setup, you can alternatively plug in a different `org.flowable.ldap.LDAPQueryBuilder`, which allows for more customization than only the query. |flowable.idm.ldap.query.user-by-full-name-like |ldap.query.userbyname |- |The query that is executed when searching for a user by full name. For example: `(&(objectClass=inetOrgPerson)(\\|({0}=**{1}**)({2}={3})))` Here, all the objects in LDAP with the class 'inetOrgPerson' and who have the matching first name or last name will be returned Several things will be injected in the expression: {0} : the first name attribute {1} : the search text {2} : the last name attribute {3} : the search text If setting the query alone is insufficient for your specific LDAP setup, you can alternatively plug in a different 'org.flowable.ldap.LDAPQueryBuilder', which allows for more customization than only the query. |flowable.idm.ldap.query.user-by-id |ldap.query.userbyid |- |The query that is executed when searching for a user by userId. For example: `(&(objectClass=inetOrgPerson)(uid={0}))` Here, all the objects in LDAP with the class 'inetOrgPerson' and who have the matching 'uid' attribute value will be returned. As shown in the example, the user id is injected by the typical {@link java.text.MessageFormat}, ie by using _{0}_ If setting the query alone is insufficient for your specific LDAP setup, you can alternatively plug in a different 'org.flowable.ldap.LDAPQueryBuilder', which allows for more customization than only the query. |flowable.mail.server.host |email.host |localhost |The host of the mail server. |flowable.mail.server.password |email.password |- |The password for the mail server authentication. |flowable.mail.server.port |email.port |1025 |The port of the mail server. |flowable.mail.server.use-ssl |email.use-ssl |false |Sets whether SSL/TLS encryption should be enabled for the SMTP transport upon connection (SMTPS/POPS). |flowable.mail.server.use-tls |email.use-tls |false |Set or disable the STARTTLS encryption. |flowable.mail.server.username |email.username |- |The username that needs to be used for the mail server authentication. If empty no authentication would be used. |flowable.process.definition-cache-limit |flowable.process-definitions.cache.max |-1 |The maximum amount of process definitions available in the process definition cache. Per default it is 1 (all process definitions) |=============== .Old properties managed by Spring Boot [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |spring.datasource.driver-class-name |datasource.driver |- |Fully qualified name of the JDBC driver. Auto-detected based on the URL by default. |spring.datasource.jndi-name |datasource.jndi.name |- |JNDI location of the datasource. Class, url, username & password are ignored when set. |spring.datasource.password |datasource.password |- |Login password of the database. |spring.datasource.url |datasource.url |- |JDBC URL of the database. |spring.datasource.username |datasource.username |- |Login username of the database. |spring.datasource.hikari.connection-test-query |datasource.preferred-test-query |- |The SQL query to be executed to test the validity of connections. |spring.datasource.hikari.connection-timeout |datasource.connection.timeout |- |The maximum number of milliseconds that a client will wait for a connection from the pool. If this time is exceeded without a connection becoming available, a SQLException will be thrown when getting a connection. |spring.datasource.hikari.idle-timeout |datasource.connection.idletimeout |- |The maximum amount of time (in milliseconds) that a connection is allowed to sit idle in the pool. Whether a connection is retired as idle or not is subject to a maximum variation of +30 seconds, and average variation of +15 seconds. A connection will never be retired as idle before this timeout. A value of 0 means that idle connections are never removed from the pool. |spring.datasource.hikari.max-lifetime |datasource.connection.maxlifetime |- |This property controls the maximum lifetime of a connection in the pool. When a connection reaches this timeout, even if recently used, it will be retired from the pool. An in-use connection will never be retired, only when it is idle will it be removed. |spring.datasource.hikari.maximum-pool-size |datasource.connection.maxpoolsize |- |The property controls the maximum size that the pool is allowed to reach, including both idle and in-use connections. Basically this value will determine the maximum number of actual connections to the database backend. When the pool reaches this size, and no idle connections are available, calls to getConnection() will block for up to connectionTimeout milliseconds before timing out. |spring.datasource.hikari.minimum-idle |datasource.connection.minidle |- |The property controls the minimum number of idle connections that HikariCP tries to maintain in the pool, including both idle and in-use connections. If the idle connections dip below this value, HikariCP will make a best effort to restore them quickly and efficiently. |spring.servlet.multipart.max-file-size |file.upload.max.size |10MB |Max file size. Values can use the suffixes ""MB"" or ""KB"" to indicate megabytes or kilobytes, respectively. |=============== .Not used old properties [cols=""2*"",options=""header""] |=============== |Old property |Description |datasource.jndi.resource-ref |Spring Boot does not support configuring JNDI resourceRef. Use entire resource reference in the name. |email.use-credentials |In case you don't want to use credentials, set the password and user to empty. |=============== [[flowableIDMApp]] === Flowable IDM application The Flowable IDM application is used by all other three Flowable web applications for authentication and authorization and is therefore required to be available when you want to run the Modeler, Task or Admin application. The Flowable IDM application is a simple identity management application and is targeted at providing single sign-on capabilities to the Flowable web applications, including providing a central place to define users, groups and privileges. The IDM application boots the IDM engine at startup and will create the identity tables as defined in the IDM engine in the datasource defined in the properties configuration. When the Flowable IDM application is deployed and started, it will check if there's a user available in the ACT_ID_USER table, and if not it will use the `flowable.common.app.idm-admin.user` property to create a new default admin user in this table. It will also add all available privileges in the Flowable project to the newly created admin user: * access-idm: provides the privilege to manage users, groups and privileges * access-admin: allows the user to login to the Flowable Admin application, manage the Flowable engines and access the Actuator endpoints of all the applications * access-modeler: enables access to the Flowable Modeler application * access-task: provides the privilege to login to the Flowable Task application * access-rest-api: allows the user to do call the REST API. Otherwise a 403 (forbidden) http status will be returned. Note that _flowable.rest.app.authentication-mode_ nees to be set to _verify-privilege_, which is the default. When logging in to link:$$http://localhost:8080/flowable-idm$$[http://localhost:8080/flowable-idm] with admin/test for the first time the following user overview screen is shown: image::images/flowable_idm_startup_screen.png[align=""center""] In this screen users can be added, removed and updated. The groups section can be used to create, delete and update groups. In the group details view you can also add and remove users to and from the group. The privilege screen allows you to add and remove privileges from users and groups: image::images/flowable_idm_privilege_screen.png[align=""center""] There's no option to define new privileges yet, but you can add and remove users and groups for the existing four privileges. This are the IDM UI App specific properties. .IDM UI App Properties [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.idm.app.bootstrap |idm.bootstrap.enabled |true |Whether the IDM App needs to be bootstrapped. |flowable.idm.app.rest-enabled |rest.idm-app.enabled |true |Enables the REST API (this is not the REST api used by the UI, but an api that's available over basic auth authentication). |flowable.idm.app.admin.email |admin.email |- |The email of the admin user. |flowable.idm.app.admin.first-name |admin.firstname |- |The first name of the admin user. |flowable.idm.app.admin.last-name |admin.lastname |- |The last name of the admin user. |flowable.idm.app.admin.password |admin.password |- |The password for the admin user. |flowable.idm.app.admin.user-id |admin.userid |- |The id of the admin user. |flowable.idm.app.security.remember-me-key |security.rememberme.key |testKey |The hash key that is used by Spring Security to hash the password values in the applications. Make sure that you change the value of this property. |flowable.idm.app.security.user-validity-period |cache.users.recheck.period |30000 |How long should a user be cached before invalidating it in the cache for the cacheable CustomUserDetailsService. |flowable.idm.app.security.cookie.domain |security.cookie.domain |- |The domain for the cookie. |flowable.idm.app.security.cookie.max-age |security.cookie.max-age |2678400 |The max age of the security cookie in seconds. Default is 31 days. |flowable.idm.app.security.cookie.refresh-age |security.cookie.refresh-age |86400 |The refresh age of the cookie in seconds. Default is 1 day. |=============== In addition to the default identity tables, the IDM application can also be configured to use an LDAP server. To connect to a LDAP server, additional properties in the application.properties file (or any other way of configuring the application) are needed: [source,linenums] ---- # # LDAP # flowable.idm.ldap.enabled=true flowable.idm.ldap.server=ldap://localhost flowable.idm.ldap.port=10389 flowable.idm.ldap.user=uid=admin, ou=system flowable.idm.ldap.password=secret flowable.idm.ldap.base-dn=o=flowable flowable.idm.ldap.query.user-by-id=(&(objectClass=inetOrgPerson)(uid={0})) flowable.idm.ldap.query.user-by-full-name-like=(&(objectClass=inetOrgPerson)(|({0}=*{1}*)({2}=*{3}*))) flowable.idm.ldap.query.all-users=(objectClass=inetOrgPerson) flowable.idm.ldap.query.groups-for-user=(&(objectClass=groupOfUniqueNames)(uniqueMember={0})) flowable.idm.ldap.query.all-groups=(objectClass=groupOfUniqueNames) flowable.idm.ldap.query.group-by-id=(&(objectClass=groupOfUniqueNames)(uniqueId={0})) flowable.idm.ldap.attribute.user-id=uid flowable.idm.ldap.attribute.first-name=cn flowable.idm.ldap.attribute.last-name=sn flowable.idm.ldap.attribute.group-id=cn flowable.idm.ldap.attribute.group-name=cn flowable.idm.ldap.cache.group-size=10000 flowable.idm.ldap.cache.group-expiration=180000 ---- When the `flowable.idm.ldap.enabled` property is set to true, the IDM app will expect the other LDAP properties to have been filled-in. In this example configuration the server configuration + LDAP queries for the Apache Directory Server are provided. For other LDAP servers, like Active Directory, other configuration values are needed. When LDAP is configured, authentication and group retrieval for a user will be done through the LDAP server. Only privileges will still be retrieved from the Flowable identity tables. So make sure each LDAP user has the correct privileges defined in the IDM application. If the IDM application is booted with LDAP configuration the bootstrap logic will check if there are already privileges present in the Flowable identity tables. If there are no privileges (only when booting the first time), the 4 default privileges will be created and the `flowable.idm.app.admin.user-id` property value (from application.properties or configured in the environment) will be used as the user id to get all 4 privileges. So make sure that the `flowable.idm.app.admin.user-id` property value is set to a valid LDAP user, otherwise nobody will be able to login to any of the Flowable UI apps. [[flowableModelerApp]] === Flowable Modeler application The Flowable Modeler application can be used to model BPMN processes, DMN decision table, Form definitions and create app definitions. The BPMN modeler uses the same Oryx and Angular foundation as in Flowable 5, but the functionality has now been moved into a separate Modeler application. When using the Flowable Modeler application, make sure the Flowable IDM application is deployed and running as well (for authentication and authorization purposes). When you login to the Modeler application (link:$$http://localhost:8080/flowable-modeler$$[http://localhost:8080/flowable-modeler]) with your user (or the default admin/test user), you will see the process overview screen. From here you can start creating new BPMN process models by clicking on the Create Process or Import Process button. image::images/flowable_modeler_createmodel_popup.png[align=""center"", width=""600""] When creating a process model (but also any other model), it's important to think carefully about the model key value. The model key is a unique identifier for the model across the full model repository. If you choose a model key that already exists in the model repository, an error message is shown and the model is not saved. After creating the model with the popup, the BPMN modeling canvas is shown. The BPMN editor is very similar to the Flowable 5 BPMN editor that was part of the Explorer application. All BPMN elements supported by the Flowable engine are available to be used in the design of a process model. image::images/flowable_modeler_design_screen.png[align=""center""] The BPMN editor is divided into 4 parts: * Palette: the palette of BPMN elements available to design a process model * Toolbar: actions to change the model canvas, such as zooming, layout and saving a model * Model canvas: the modeling canvas on which to drag and drop BPMN elements and design the process model * Properties panel: the properties for the main process model if no element is select and otherwise the properties of the selected BPMN element For a User task element there's a _Referenced form_ property in the properties panel. If you select this property, a popup is opened where you can select a form definition from the repository or create a new form. When creating a new form, a similar create dialog to the process model create dialog is presented. After filling in the name and form model key, the form editor is opened. image::images/flowable_modeler_formdesign_screen.png[align=""center""] Form fields can be dragged from the form palette on to the form canvas. In this example, a name textfield, two date fields and a remarks multiline textfield are added to the form canvas. When editing a form field, the label, id, required status and placeholder can be filled in. image::images/flowable_modeler_editfield_popup.png[align=""center"", width=""600""] The id field is an important value, because a process variable will be created with the form field value using the id property value. When filling in the label property, the id property is automatically filled. If needed, you can also provide the id property value yourself by checking the override id checkbox. After saving the form model and closing the form editor, you are automatically navigated back to the process model (when the form editor was opened via the BPMN editor). When selecting the User task element again and clicking on the _Referenced form_ property you will see that the newly created form definition is now attached to the User task. When clicking on the _Form_ tab in the header of the Modeler application, all form definitions available in the model repository are shown. image::images/flowable_modeler_formoverview_screen.png[align=""center""] You can preview every form definition by opening the details view of a form definition. In the details view, the form name, key and description can be edited and the history of form models is available. You can also duplicate the form definition to create a new form definition with the same form fields. Now let's open the vacation request process model in the BPMN editor again and add a Script task to the process model, that will calculate the number of days between the vacation start and end dates. Click on the _Script format_ property and fill in a value of _groovy_ to instruct the Flowable engine to use the Groovy scripting engine. Now click on the _Script_ property and fill in the script that calculates the number of days. image::images/flowable_modeler_script_popup.png[align=""center"", width=""600""] Now we have a _amountOfVacationDays_ process variable we can add a Decision task to the process model. A decision task can be used to execute a DMN decision table in the Flowable DMN engine. Through the _Decision table reference_ property, a new decision table model can be created and the DMN editor is opened. image::images/flowable_modeler_dmneditor_screen.png[align=""center""] The DMN editor provides a table editor with input columns, where input conditions can be defined with the process variables available in the process context, and output columns, where output variable values can be defined. In this very simple example there's one input column using the _amountOfVacationDays_ variable that checks if it's less than 10 or higher or equal to 10. When the amount of days is less than 10, an output variable _managerApprovalNeeded_ is returned with value false, and otherwise a value of true is returned. You can define multiple input columns and have multiple input conditions per rule. It's also possible to leave an input column empty, which means that it's evaluated to true for that part of the rule. You can define one or multiple output variables. Another important part of the DMN decision table definition is the hit policy. Currently, Flowable supports the First and Any hit policy. With the First hit policy, when the first rule is found that evaluates to true the DMN execution will stop and its output variables are returned. For the Any hit policy, all rules will be executed and the output variables for the last rule that evaluates to true are returned. When the DMN editor is saved and closed, the Modeler application navigates back to the BPMN editor and the newly created DMN decision table is now attached to the Decision task. The decision task will be generated in the BPMN XML like; [source,xml,linenums] ---- ---- With the _managerApprovalNeeded_ variable available in the process instance context, we can now create an exclusive gateway with a sequence flow condition that evaluates the calculated value of the DMN Engine. image::images/flowable_modeler_sequenceflowcondition_popup.png[align=""center"", width=""500""] The full BPMN process model now looks like this: image::images/flowable_modeler_vacationrequest_screen.png[align=""center""] With the process model completed, we can now create an app definition that combines one or more process models with all their associated models (for example, decision tables and form definitions) into a single artifact. An app definition can be exported as a BAR file (zip format) that can be deployed on the Flowable engine. When creating a vacation request app definition, the app editor will look something like the screen below. image::images/flowable_modeler_appeditor_screen.png[align=""center""] In the app editor, an icon and a theme color can be selected that will be used in the Flowable Task application to show the application in the dashboard. The important step is to add the vacation request process model, and by selecting the process model, automatically include any form definitions and DMN decision tables. image::images/flowable_modeler_modelselection_popup.png[align=""center""] A process model can be selected by clicking on the model thumbnail. When one or more models are selected, you can close the popup, save the app definition and close it. When navigating to the details view of the newly created vacation request app definition, the following details screen is shown: image::images/flowable_modeler_appdetails_screen.png[align=""center""] From this view, you can download the app definition in two different formats. The first download button (with the arrow pointing downwards) can be used to download the app definition with the JSON model files for each included model. This makes it easy to share app definitions between different Flowable Modeler applications. The second download button (with the arrow point to upper right) will provide a BAR file of the app definition models, which can be deployed on the Flowable engine. In the BAR file, only the deployable artifacts are included, such as the BPMN 2.0 XML file and the DMN XML file, and not the JSON model files. All files in a BAR file deployed on a Flowable engine are stored in the database, so therefore only the deployable files are included. From the app definition details view, you can also _Publish_ the app definition directly to the Flowable engine. The Flowable Modeler uses the URL defined in the application.properties file with the _flowable.modeler.app.deployment-api-url_ property key. By default, the deployment URL is configured so the app definition will be deployed on the Flowable Task application when it's running. However, this can be changed to use the Flowable REST application, for example. Make sure the Flowable Task application is running and click on the _Publish_ button. The app definition is now deployed as a BAR file to the Flowable Task application. This are the Modeler UI App specific properties. .Modeler UI App Properties [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.modeler.app.data-source-prefix |datasource.prefix |- |The prefix for the database tables. |flowable.modeler.app.deployment-api-url |deployment.api.url |http://localhost:8080/flowable-task/app-api |The root URI to the REST services of the Flowable engine, used by the Flowable Modeler application to deploy the application definition BAR file to the engine. Default url for the Flowable Task application is http://localhost:8080/flowable-task/app-api |flowable.modeler.app.rest-enabled |rest.modeler-app.enabled |true |Enables the REST API (this is not the REST api used by the UI, but an api that's available over basic auth authentication). |=============== [[flowableTaskApp]] === Flowable Task application The Flowable Task application is the runtime application of the Flowable project and includes the Flowable BPMN, DMN, Form and Content engines by default. With the Flowable Task application, new process instances can be started, tasks can be completed, task forms can be rendered and so on. In the previous section, the vacation request app definition was deployed on the Flowable Task application REST API, and through that deployed on the Flowable engine. If you look in the Flowable database, you can see a new deployment entry has been added to the ACT_RE_DEPLOYMENT table for the BPMN Engine. Also, new entries haven been created in the ACT_DMN_DEPLOYMENT and ACT_FO_FORM_DEPLOYMENT tables for the DMN and Form engines. On the dashboard on link:$$http://localhost:8080/flowable-task$$[http://localhost:8080/flowable-task], you can see a vacation request app in addition to the default Task app, and any other apps that have been deployed to the Flowable engine already. image::images/flowable_task_dashboard_screen.png[align=""center""] When clicking on the vacation request app, the task list for the logged-in user is shown (which is probably empty for now). image::images/flowable_task_tasklist_screen.png[align=""center""] When clicking on the _Processes_ tab you can choose to start a new process instance by clicking on the _Start a process_ button. The list of available process definitions within the context of this app definition is now displayed. In the general Task app this works in a similar way, but in the Task app, all process definitions deployed on the Flowable engine are shown. After selecting the vacation request process definition, the _Start process_ button can be clicked to start a new vacation request process instance. The Flowable Task application automatically navigates to the process instance details view. You can see the _Provide vacation information_ task is active and, for example, comments can be added and the process instance state can be shown diagrammatically using the _Show diagram_ button. image::images/flowable_task_processdetails_screen.png[align=""center""] When navigating to the task list, you can also see the _Provide vacation information_ task listed there as well. The task details are shown in this view, with the vacation info form being rendered. You can also switch to the details view by clicking on the _Show details_ button. In the details view, comments can be added, users can involved in the task and attachments can be added to the task. You can also change the due date and the assignee of a task. image::images/flowable_task_taskdetails_screen.png[align=""center""] Let's fill in the form and complete the task. First, select a start date and end date that have more than 10 days in between, so we can validate that a _Manager approval_ task is being generated. After filling in the vacation info form and clicking the _Complete_ button, the Flowable task app navigates directly to the _Manager approval_ task view. When you also complete this task (without a task form), the process instance is completed. When navigating to the _Processes_ tab and clicking on the _Showing running processes_ section, you can select an option to show completed process instances. The list of completed process instances is now shown and when clicking on the just completed vacation request process you can see the two completed tasks. image::images/flowable_task_processhistory_screen.png[align=""center""] The completed form of each task is stored in the ACT_FO_FORM_INSTANCE table of the Flowable Form engine. So it's possible to look at the values of each completed form when you navigate to the completed task. image::images/flowable_task_completedform_screen.png[align=""center""] Make sure to switch back to showing running processes instead of the completed ones, otherwise you won't see newly started process instances. You can also filter tasks in the task list view. There are options to search on the name of a task, the task state, only tasks for a specific process definition and change the assignment filter. image::images/flowable_task_taskfilter_screen.png[align=""center"", width=""400""] By default, the assignment filter is set to _Tasks where I am involved_. This doesn't show the tasks where you are a candidate, such as tasks that are available to a specific candidate group before they are assigned to a specific person. To show candidate tasks you can select the _Tasks where I am one of the candidates_ assignment filter option. This are the Task UI App specific properties. .Task UI App Properties [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.experimental.debugger.enabled |debugger.enabled |false |Whether the process debugger should be enabled. |flowable.task.app.rest-enabled |rest.task-app.enabled |true |Enables the REST API (this is not the REST api used by the UI, but an api that's available over basic auth authentication). |=============== [[flowableAdminApp]] === Flowable Admin application The fourth UI application the Flowable project provides is the Flowable Admin application. This application provides ways to, for example, query deployments in the BPMN, DMN and Form Engines, but also shows the active state of a process instance with its active tasks and process variables. It also provides actions to assign a task to a different assignee and to complete an active task. The Flowable Admin application uses the REST API to communicate with the Flowable engines. By default, it is configured to connect to the Flowable Task REST API, but you can easily change this to use the Flowable REST app REST API instead. When going to link:$$http://localhost:8080/flowable-admin$$[http://localhost:8080/flowable-admin], the configuration screen is shown (which is also available by clicking on the arrow at the top right near the Flowable logo). image:images/flowable_admin_configuration_screen.png[align=""center""] For each engine, the REST endpoint can be configured with the basic authentication values. The configuration is done per engine, because it's possible to, for example, deploy the DMN Engine on a separate server from the BPMN Engine. When the configuration is defined with the correct values, the _Process Engine_ can be selected to administer the Flowable BPMN engine. By default, the deployments of the Flowable BPMN engine are shown. image::images/flowable_admin_deployments_screen.png[align=""center""] You can filter the deployments based on name and tenant identifier. In this view, it's also possible to deploy a new BPMN XML file or BAR file to the Flowable engine. When clicking on one of the deployments, the deployment details view is shown. image::images/flowable_admin_deploymentdetails_screen.png[align=""center""] More details of a deployment are shown here and also the process definitions that are part of this deployment on which you click to get more details. It's also possible to delete a deployment here. When you want to delete a deployed app definition, this is also the way to delete the app definition from the Flowable Task app dashboard. When clicking on one of the process definitions, the process definition details view is shown. image::images/flowable_admin_processdefinitiondetails_screen.png[align=""center""] In the process definition details view, the first page of process instances is shown, together with optional decision table definitions and form definitions that are used in the process definition. For the vacation request process definition, there's one connected decision table and one connected form definition. Clicking on the decision table definition navigates the Flowable Admin application to the DMN engine. You can always navigate back to the Process engine by clicking on the _Parent Deployment ID_ link. In addition to the deployments and definitions, you can also query on process instances, tasks, jobs and event subscriptions in the Process engine. The views all work in a similar way to what's already been described. This are the Admin UI App specific properties .Admin UI App Properties [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.admin.app.data-source-prefix |datasource.prefix | |The prefix for the database tables. |flowable.admin.app.security.encryption.credentials-i-v-spec |security.encryption.credentials-i-v-spec |- |The string that needs to be used to create an IvParameterSpec object using it's the bytes. |flowable.admin.app.security.encryption.credentials-secret-spec |security.encryption.credentials-secret-spec |- |The string that needs to be used to create a SecretKeySpec using it's bytes. |flowable.admin.app.security.preemptive-basic-authentication | |false |Perform a preemptive basic authentication when issuing requests to the flowable REST API. **NB:** This is an experimental property and might be removed without notice. |=============== In addition to these properties, the Flowable admin application has a few more properties. The full content of the properties file can be viewed on {sc-flowable-ui-admin}/flowable-ui-admin-app/src/main/resources/application.properties[Github]. The additional properties are mainly used for defining the initial values for the REST endpoints for the different engines. The Admin application uses the initial values to make a connection to the Flowable engines, but the values can be overridden in the Admin application configuration view and these values are stored in the __ACT\\_ADM\\_SERVER\\_CONFIG__ table. An example of the BPMN Engine REST properties is shown below: [source,linenums] ---- flowable.admin.app.server-config.process.name=Flowable Process app flowable.admin.app.server-config.process.description=Flowable Process REST config flowable.admin.app.server-config.process.server-address=http://localhost flowable.admin.app.server-config.process.port=8080 flowable.admin.app.server-config.process.context-root=flowable-task flowable.admin.app.server-config.process.rest-root=process-api flowable.admin.app.server-config.process.user-name=admin flowable.admin.app.server-config.process.password=test ---- These values can be used when the Flowable Task app (with all the Flowable engines included) is managed by the Flowable Admin application. .Admin UI App Properties managed by Spring Boot [cols=""2*"",options=""header""] |=============== |Old property |Description |message.reloading.enabled |Using Spring Boot MessageSourceAutoConfiguration. Set the duration with `spring.messages.cache-duration`. |=============== === Internationalization The Flowable UI apps support internationalization (i18n). The project maintains the English translations. It is however possible to provide your own translation files in order to support other languages. The link:$$https://github.com/angular-translate/angular-translate[Angular Translate] library tries to load a specific translation file based on the browser's locale located in the _i18n_ folder (present in each UI module). When a matching translation file cannot be loaded the framework will fallback to the English translation. Mapping multiple browser locale keys to specific translations additional configuration can be provided (located in the Angular app config); [source,linenums] ---- // Initialize angular-translate $translateProvider.useStaticFilesLoader({ prefix: './i18n/', suffix: '.json' }) /* This can be used to map multiple browser language keys to a angular translate language key. */ // .registerAvailableLanguageKeys(['en'], { // 'en-*': 'en' // }) .useCookieStorage() .useSanitizeValueStrategy('sanitizeParameters') .uniformLanguageTag('bcp47') .determinePreferredLanguage(); ---- For example; your browser is configured for English (United States) and provides the language key _en-US_. Without the mapping Angular Translate will try to fetch the corresponding translation file _en-US.json_. (If this is not available it will fallback to 'en' and load the _en.json_ translation file) By uncommenting the _.registerAvailableLanguageKeys_ block you can map _en-US_ (and all other _en_ language keys) to the _en.json_ language file. === Production ready endpoints The https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html[Production ready endpoints] from Spring Boot are present for all applications. To have an overview of all the available Endpoints have a look at the https://docs.spring.io/spring-boot/docs/current/actuator-api/html/[Actuator Web API Documentation]. This properties are set per default: [source,linenums] ----- # Expose all actuator endpoints to the web # They are exposed, but only authenticated users can see /info and /health abd users with access-admin can see the others management.endpoints.web.exposure.include=* # Full health details should only be displayed when a user is authorized management.endpoint.health.show-details=when_authorized # Only users with role access-admin can access full health details management.endpoint.health.roles=access-admin ----- The security is configured in such way that the `info` and `health` endpoint are exposed to all authenticated users. Full details of the `health` endpoint can only be seen by users with the privilege `access-admin`. In case you want to change that you need to configure `management.endpoint.health.show-details`. All the rest of the endpoints are accessing only to users with the `access-admin` privilege. [[custom-bean-deployment]] === Custom bean deployment There are multiple ways of providing custom beans to the Flowable applications. [[custom-bean-deployment-spring-boot-auto]] ==== Using Spring Boot auto configuration The Flowable applications are Spring Boot 2 applications. Which means that normal Spring Boot auto configuration can be used to make the beans to Flowable. This can be done in the following manner ``` package com.your.own.package.configuration; @Configuration @AutoConfigureOrder(Ordered.LOWEST_PRECEDENCE) // Makes sure that this configuration will be processed last by Spring Boot @ConditionalOnBean(type = ""org.flowable.engine.ProcessEngine"") // The configuration will only be used when the ProcessEngine bean is present public class YourOwnConfiguration { @Configuration @ComponentScan (""com.your.own.package.beans"") public static class ComponentScanConfiguration { // This class is needed in order to conditionally perform the component scan (i.e. when the ProcessEngine bean is present) // It is an optional class, in case you don't need component scanning then you don't need to do this } @Bean public CustomBean customBean() { // create your bean } @Bean public EngineConfigurationConfigurer customProcessEngineConfigurationConfigurer() { return engineConfiguration -> { // You can use this to add extra configuration to the process engine } } } ``` Note that when using Spring Boot the configuration class can be under your own package and not under some Flowable package. In order to make this class an auto configuration class a file named `spring.factories` should be created in the `META-INF` folder of your jar. In this file you should add ``` org.springframework.boot.autoconfigure.EnableAutoConfiguration=\\ com.your.own.package.configuration.YourOwnCustomConfiguration ``` In order to use this approach you would need to include your jar in the `WEB-INF/lib` folder of the exploded war. Placing this jar in the lib folder of the servlet container (e.g. Tomcat) is not going to work due to the way Spring proxies the `@Configuration` classes. [[custom-bean-deployment-component-scan]] ==== Component scan Another way to provide custom Spring beans to the Flowable engine is to put them under a certain package and have the Flowable application component scan that package. Based on the used application this package is different: * `org.flowable.rest.app` for the `flowable-rest.war` * `org.flowable.ui.task.application` for the `flowable-task.war` The custom beans can be located in a single JAR and this jar should be present on the classpath when the applications are starting up. Depending where there JAR is placed, the lib folder of the servlet container (e.g. Tomcat) or the `WEB-INF/lib` folder of the exploded war, there are different possibilities. When using the lib folder of the servlet container then the created classes should be self contained, i.e. they should only use classes from within the jar. You can use any of the Spring `@Component` annotations (with the exception of `@Configuration`). The reason for not being able to use `@Configuration` classes is the fact that each configuration class is proxied by Spring with the help of the `ConfigurationClassPostProcessor`. However, the classloader loading the `@Configuration` class does not have access to the needed classes by Spring. When including the jar in the `WEB-INF/lib` folder of the exploded war then `@Configuration` classes and dependencies to other jars is possible. [[custom-bean-deployment-own-spring-boot]] ==== Creating your own Spring Boot application This approach is the most flexible and most powerful approach of all. In order to follow this approach have a look at the <> section of this documentation.",12226,False,2062.221492465571,median "// // Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2021 // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include ""td/utils/algorithm.h"" #include ""td/utils/as.h"" #include ""td/utils/base64.h"" #include ""td/utils/BigNum.h"" #include ""td/utils/bits.h"" #include ""td/utils/CancellationToken.h"" #include ""td/utils/common.h"" #include ""td/utils/ExitGuard.h"" #include ""td/utils/Hash.h"" #include ""td/utils/HashMap.h"" #include ""td/utils/HashSet.h"" #include ""td/utils/HttpUrl.h"" #include ""td/utils/invoke.h"" #include ""td/utils/logging.h"" #include ""td/utils/misc.h"" #include ""td/utils/port/EventFd.h"" #include ""td/utils/port/FileFd.h"" #include ""td/utils/port/IPAddress.h"" #include ""td/utils/port/path.h"" #include ""td/utils/port/sleep.h"" #include ""td/utils/port/Stat.h"" #include ""td/utils/port/thread.h"" #include ""td/utils/port/uname.h"" #include ""td/utils/port/wstring_convert.h"" #include ""td/utils/Random.h"" #include ""td/utils/Slice.h"" #include ""td/utils/Status.h"" #include ""td/utils/StringBuilder.h"" #include ""td/utils/tests.h"" #include ""td/utils/Time.h"" #include ""td/utils/translit.h"" #include ""td/utils/uint128.h"" #include ""td/utils/unicode.h"" #include ""td/utils/utf8.h"" #include #include #include #include #include #include #include #if TD_HAVE_ABSL #include #endif struct CheckExitGuard { explicit CheckExitGuard(bool expected_value) : expected_value_(expected_value) { } CheckExitGuard(CheckExitGuard &&) = delete; CheckExitGuard &operator=(CheckExitGuard &&) = delete; CheckExitGuard(const CheckExitGuard &) = delete; CheckExitGuard &operator=(const CheckExitGuard &) = delete; ~CheckExitGuard() { ASSERT_EQ(expected_value_, td::ExitGuard::is_exited()); } bool expected_value_; }; static CheckExitGuard check_exit_guard_true{true}; static td::ExitGuard exit_guard; static CheckExitGuard check_exit_guard_false{false}; #if TD_LINUX || TD_DARWIN TEST(Misc, update_atime_saves_mtime) { SET_VERBOSITY_LEVEL(VERBOSITY_NAME(ERROR)); td::string name = ""test_file""; td::unlink(name).ignore(); auto r_file = td::FileFd::open(name, td::FileFd::Read | td::FileFd::Flags::Create | td::FileFd::Flags::Truncate); LOG_IF(ERROR, r_file.is_error()) << r_file.error(); ASSERT_TRUE(r_file.is_ok()); r_file.move_as_ok().close(); auto info = td::stat(name).ok(); td::int32 tests_ok = 0; td::int32 tests_wa = 0; for (int i = 0; i < 10000; i++) { td::update_atime(name).ensure(); auto new_info = td::stat(name).ok(); if (info.mtime_nsec_ == new_info.mtime_nsec_) { tests_ok++; } else { tests_wa++; info.mtime_nsec_ = new_info.mtime_nsec_; } ASSERT_EQ(info.mtime_nsec_, new_info.mtime_nsec_); td::usleep_for(td::Random::fast(0, 1000)); } if (tests_wa > 0) { LOG(ERROR) << ""Access time was unexpectedly updated "" << tests_wa << "" times""; } td::unlink(name).ensure(); } TEST(Misc, update_atime_change_atime) { SET_VERBOSITY_LEVEL(VERBOSITY_NAME(ERROR)); td::string name = ""test_file""; td::unlink(name).ignore(); auto r_file = td::FileFd::open(name, td::FileFd::Read | td::FileFd::Flags::Create | td::FileFd::Flags::Truncate); LOG_IF(ERROR, r_file.is_error()) << r_file.error(); ASSERT_TRUE(r_file.is_ok()); r_file.move_as_ok().close(); auto info = td::stat(name).ok(); // not enough for fat and e.t.c. td::usleep_for(5000000); td::update_atime(name).ensure(); auto new_info = td::stat(name).ok(); if (info.atime_nsec_ == new_info.atime_nsec_) { LOG(ERROR) << ""Access time was unexpectedly not changed""; } td::unlink(name).ensure(); } #endif TEST(Misc, errno_tls_bug) { // That's a problem that should be avoided // errno = 0; // impl_.alloc(123); // CHECK(errno == 0); #if !TD_THREAD_UNSUPPORTED && !TD_EVENTFD_UNSUPPORTED td::EventFd test_event_fd; test_event_fd.init(); std::atomic s{0}; s = 1; td::thread th([&] { while (s != 1) { } test_event_fd.acquire(); }); th.join(); for (int i = 0; i < 1000; i++) { td::vector events(10); td::vector threads; for (auto &event : events) { event.init(); event.release(); } for (auto &event : events) { threads.emplace_back([&] { { td::EventFd tmp; tmp.init(); tmp.acquire(); } event.acquire(); }); } for (auto &thread : threads) { thread.join(); } } #endif } TEST(Misc, get_last_argument) { auto a = td::make_unique(5); ASSERT_EQ(*td::get_last_argument(std::move(a)), 5); ASSERT_EQ(*td::get_last_argument(1, 2, 3, 4, a), 5); ASSERT_EQ(*td::get_last_argument(a), 5); auto b = td::get_last_argument(1, 2, 3, std::move(a)); ASSERT_TRUE(!a); ASSERT_EQ(*b, 5); } TEST(Misc, call_n_arguments) { auto f = [](int, int) { }; td::call_n_arguments<2>(f, 1, 3, 4); } TEST(Misc, base64) { ASSERT_TRUE(td::is_base64(""dGVzdA=="") == true); ASSERT_TRUE(td::is_base64(""dGVzdB=="") == false); ASSERT_TRUE(td::is_base64(""dGVzdA="") == false); ASSERT_TRUE(td::is_base64(""dGVzdA"") == false); ASSERT_TRUE(td::is_base64(""dGVzd"") == false); ASSERT_TRUE(td::is_base64(""dGVz"") == true); ASSERT_TRUE(td::is_base64(""dGVz===="") == false); ASSERT_TRUE(td::is_base64("""") == true); ASSERT_TRUE(td::is_base64(""ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"") == true); ASSERT_TRUE(td::is_base64(""ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="") == false); ASSERT_TRUE(td::is_base64(""ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-/"") == false); ASSERT_TRUE(td::is_base64(""ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"") == false); ASSERT_TRUE(td::is_base64(""===="") == false); ASSERT_TRUE(td::is_base64url(""dGVzdA=="") == true); ASSERT_TRUE(td::is_base64url(""dGVzdB=="") == false); ASSERT_TRUE(td::is_base64url(""dGVzdA="") == false); ASSERT_TRUE(td::is_base64url(""dGVzdA"") == true); ASSERT_TRUE(td::is_base64url(""dGVzd"") == false); ASSERT_TRUE(td::is_base64url(""dGVz"") == true); ASSERT_TRUE(td::is_base64url(""dGVz===="") == false); ASSERT_TRUE(td::is_base64url("""") == true); ASSERT_TRUE(td::is_base64url(""ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"") == true); ASSERT_TRUE(td::is_base64url(""ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_="") == false); ASSERT_TRUE(td::is_base64url(""ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-/"") == false); ASSERT_TRUE(td::is_base64url(""ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"") == false); ASSERT_TRUE(td::is_base64url(""===="") == false); ASSERT_TRUE(td::is_base64_characters(""dGVzdA=="") == false); ASSERT_TRUE(td::is_base64_characters(""dGVzdB=="") == false); ASSERT_TRUE(td::is_base64_characters(""dGVzdA="") == false); ASSERT_TRUE(td::is_base64_characters(""dGVzdA"") == true); ASSERT_TRUE(td::is_base64_characters(""dGVz"") == true); ASSERT_TRUE(td::is_base64_characters("""") == true); ASSERT_TRUE(td::is_base64_characters(""ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"") == true); ASSERT_TRUE(td::is_base64_characters(""ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="") == false); ASSERT_TRUE(td::is_base64_characters(""ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-/"") == false); ASSERT_TRUE(td::is_base64_characters(""ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"") == false); ASSERT_TRUE(td::is_base64_characters(""===="") == false); ASSERT_TRUE(td::is_base64url_characters(""dGVzdA=="") == false); ASSERT_TRUE(td::is_base64url_characters(""dGVzdB=="") == false); ASSERT_TRUE(td::is_base64url_characters(""dGVzdA="") == false); ASSERT_TRUE(td::is_base64url_characters(""dGVzdA"") == true); ASSERT_TRUE(td::is_base64url_characters(""dGVz"") == true); ASSERT_TRUE(td::is_base64url_characters("""") == true); ASSERT_TRUE(td::is_base64url_characters(""ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"") == true); ASSERT_TRUE(td::is_base64url_characters(""ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_="") == false); ASSERT_TRUE(td::is_base64url_characters(""ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-/"") == false); ASSERT_TRUE(td::is_base64url_characters(""ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"") == false); ASSERT_TRUE(td::is_base64url_characters(""===="") == false); for (int l = 0; l < 300000; l += l / 20 + l / 1000 * 500 + 1) { for (int t = 0; t < 10; t++) { auto s = td::rand_string(std::numeric_limits::min(), std::numeric_limits::max(), l); auto encoded = td::base64url_encode(s); auto decoded = td::base64url_decode(encoded); ASSERT_TRUE(decoded.is_ok()); ASSERT_TRUE(decoded.ok() == s); encoded = td::base64_encode(s); decoded = td::base64_decode(encoded); ASSERT_TRUE(decoded.is_ok()); ASSERT_TRUE(decoded.ok() == s); auto decoded_secure = td::base64_decode_secure(encoded); ASSERT_TRUE(decoded_secure.is_ok()); ASSERT_TRUE(decoded_secure.ok().as_slice() == s); } } ASSERT_TRUE(td::base64url_decode(""dGVzdA"").is_ok()); ASSERT_TRUE(td::base64url_decode(""dGVzdB"").is_error()); ASSERT_TRUE(td::base64_encode(td::base64url_decode(""dGVzdA"").ok()) == ""dGVzdA==""); ASSERT_TRUE(td::base64_encode(""any carnal pleas"") == ""YW55IGNhcm5hbCBwbGVhcw==""); ASSERT_TRUE(td::base64_encode(""any carnal pleasu"") == ""YW55IGNhcm5hbCBwbGVhc3U=""); ASSERT_TRUE(td::base64_encode(""any carnal pleasur"") == ""YW55IGNhcm5hbCBwbGVhc3Vy""); ASSERT_TRUE(td::base64_encode("" /'.;.';≤.];,].',[.;/,.;/]/..;!@#!*(%?::;!%\\"";"") == ""ICAgICAgLycuOy4nO+KJpC5dOyxdLicsWy47LywuOy9dLy4uOyFAIyEqKCU/Ojo7ISUiOw==""); ASSERT_TRUE(td::base64url_encode(""ab><"") == ""YWI-PA""); ASSERT_TRUE(td::base64url_encode(""ab> static void test_remove_if(td::vector v, const T &func, td::vector expected) { td::remove_if(v, func); if (expected != v) { LOG(FATAL) << ""Receive "" << v << "", expected "" << expected << "" in remove_if""; } } TEST(Misc, remove_if) { auto odd = [](int x) { return x % 2 == 1; }; auto even = [](int x) { return x % 2 == 0; }; auto all = [](int x) { return true; }; auto none = [](int x) { return false; }; td::vector v{1, 2, 3, 4, 5, 6}; test_remove_if(v, odd, {2, 4, 6}); test_remove_if(v, even, {1, 3, 5}); test_remove_if(v, all, {}); test_remove_if(v, none, v); v = td::vector{1, 3, 5, 2, 4, 6}; test_remove_if(v, odd, {2, 4, 6}); test_remove_if(v, even, {1, 3, 5}); test_remove_if(v, all, {}); test_remove_if(v, none, v); v.clear(); test_remove_if(v, odd, v); test_remove_if(v, even, v); test_remove_if(v, all, v); test_remove_if(v, none, v); v.push_back(-1); test_remove_if(v, odd, v); test_remove_if(v, even, v); test_remove_if(v, all, {}); test_remove_if(v, none, v); v[0] = 1; test_remove_if(v, odd, {}); test_remove_if(v, even, v); test_remove_if(v, all, {}); test_remove_if(v, none, v); v[0] = 2; test_remove_if(v, odd, v); test_remove_if(v, even, {}); test_remove_if(v, all, {}); test_remove_if(v, none, v); } static void test_remove(td::vector v, int value, td::vector expected) { bool is_found = expected != v; ASSERT_EQ(is_found, td::remove(v, value)); if (expected != v) { LOG(FATAL) << ""Receive "" << v << "", expected "" << expected << "" in remove""; } } TEST(Misc, remove) { td::vector v{1, 2, 3, 4, 5, 6}; test_remove(v, 0, {1, 2, 3, 4, 5, 6}); test_remove(v, 1, {2, 3, 4, 5, 6}); test_remove(v, 2, {1, 3, 4, 5, 6}); test_remove(v, 3, {1, 2, 4, 5, 6}); test_remove(v, 4, {1, 2, 3, 5, 6}); test_remove(v, 5, {1, 2, 3, 4, 6}); test_remove(v, 6, {1, 2, 3, 4, 5}); test_remove(v, 7, {1, 2, 3, 4, 5, 6}); v.clear(); test_remove(v, -1, v); test_remove(v, 0, v); test_remove(v, 1, v); } static void test_unique(td::vector v, td::vector expected) { td::unique(v); ASSERT_EQ(expected, v); } TEST(Misc, unique) { test_unique({1, 2, 3, 4, 5, 6}, {1, 2, 3, 4, 5, 6}); test_unique({5, 2, 1, 6, 3, 4}, {1, 2, 3, 4, 5, 6}); test_unique({}, {}); test_unique({0}, {0}); test_unique({0, 0}, {0}); test_unique({0, 1}, {0, 1}); test_unique({1, 0}, {0, 1}); test_unique({1, 1}, {1}); test_unique({3, 3, 3, 3, 3, 2, 2, 2, 1, 1, 0}, {0, 1, 2, 3}); test_unique({3, 3, 3, 3, 3}, {3}); test_unique({3, 3, -1, 3, 3}, {-1, 3}); } TEST(Misc, contains) { td::vector v{1, 3, 5, 7, 4, 2}; for (int i = -10; i < 20; i++) { ASSERT_EQ(td::contains(v, i), (1 <= i && i <= 5) || i == 7); } v.clear(); ASSERT_TRUE(!td::contains(v, 0)); ASSERT_TRUE(!td::contains(v, 1)); td::string str = ""abacaba""; ASSERT_TRUE(!td::contains(str, '0')); ASSERT_TRUE(!td::contains(str, 0)); ASSERT_TRUE(!td::contains(str, 'd')); ASSERT_TRUE(td::contains(str, 'a')); ASSERT_TRUE(td::contains(str, 'b')); ASSERT_TRUE(td::contains(str, 'c')); } TEST(Misc, base32) { ASSERT_EQ("""", td::base32_encode("""")); ASSERT_EQ(""me"", td::base32_encode(""a"")); td::base32_decode(""me"").ensure(); ASSERT_EQ(""mfra"", td::base32_encode(""ab"")); ASSERT_EQ(""mfrgg"", td::base32_encode(""abc"")); ASSERT_EQ(""mfrggza"", td::base32_encode(""abcd"")); ASSERT_EQ(""mfrggzdg"", td::base32_encode(""abcdf"")); ASSERT_EQ(""mfrggzdgm4"", td::base32_encode(""abcdfg"")); for (int l = 0; l < 300000; l += l / 20 + l / 1000 * 500 + 1) { for (int t = 0; t < 10; t++) { auto s = td::rand_string(std::numeric_limits::min(), std::numeric_limits::max(), l); auto encoded = td::base32_encode(s); auto decoded = td::base32_decode(encoded); ASSERT_TRUE(decoded.is_ok()); ASSERT_TRUE(decoded.ok() == s); } } } TEST(Misc, to_integer) { ASSERT_EQ(td::to_integer(""-1234567""), -1234567); ASSERT_EQ(td::to_integer(""-1234567""), -1234567); ASSERT_EQ(td::to_integer(""-1234567""), 0u); ASSERT_EQ(td::to_integer(""-1234567""), 10617); ASSERT_EQ(td::to_integer(""-1234567""), 0u); ASSERT_EQ(td::to_integer(""-1254567""), -9383); ASSERT_EQ(td::to_integer(""1254567""), 9383u); ASSERT_EQ(td::to_integer(""-12345678910111213""), -12345678910111213); ASSERT_EQ(td::to_integer(""12345678910111213""), 12345678910111213ull); ASSERT_EQ(td::to_integer_safe(""-1234567"").ok(), -1234567); ASSERT_EQ(td::to_integer_safe(""-1234567"").ok(), -1234567); ASSERT_TRUE(td::to_integer_safe(""-1234567"").is_error()); ASSERT_TRUE(td::to_integer_safe(""-1234567"").is_error()); ASSERT_TRUE(td::to_integer_safe(""-1234567"").is_error()); ASSERT_TRUE(td::to_integer_safe(""-1254567"").is_error()); ASSERT_TRUE(td::to_integer_safe(""1254567"").is_error()); ASSERT_EQ(td::to_integer_safe(""-12345678910111213"").ok(), -12345678910111213); ASSERT_EQ(td::to_integer_safe(""12345678910111213"").ok(), 12345678910111213ull); ASSERT_TRUE(td::to_integer_safe(""-12345678910111213"").is_error()); } static void test_to_double_one(td::CSlice str, td::Slice expected, int precision = 6) { auto result = PSTRING() << td::StringBuilder::FixedDouble(to_double(str), precision); if (expected != result) { LOG(ERROR) << ""To double conversion failed: have "" << str << "", expected "" << expected << "", parsed "" << to_double(str) << "", got "" << result; } } static void test_to_double() { test_to_double_one(""0"", ""0.000000""); test_to_double_one(""1"", ""1.000000""); test_to_double_one(""-10"", ""-10.000000""); test_to_double_one(""1.234"", ""1.234000""); test_to_double_one(""-1.234e2"", ""-123.400000""); test_to_double_one(""inf"", ""inf""); test_to_double_one("" inF asdasd"", ""inf""); test_to_double_one("" inFasdasd"", ""0.000000""); test_to_double_one("" NaN"", ""nan""); test_to_double_one("" 12345678910111213141516171819 asdasd"", ""12345678910111213670658736128.000000""); test_to_double_one(""1.234567891011121314E123"", ""1234567891011121363209105003376291141757777526749278953577304234065881343284952489418916814035346"" ""625663604561924259911303168.000000""); test_to_double_one(""1.234567891011121314E-9"", ""0.000000""); test_to_double_one(""123456789"", ""123456789.000000""); test_to_double_one(""-1,234567891011121314E123"", ""-1.000000""); test_to_double_one(""123456789"", ""123456789"", 0); test_to_double_one(""1.23456789"", ""1"", 0); test_to_double_one(""1.23456789"", ""1.2"", 1); test_to_double_one(""1.23456789"", ""1.23"", 2); test_to_double_one(""1.23456789"", ""1.235"", 3); test_to_double_one(""1.23456789"", ""1.2346"", 4); test_to_double_one(""1.23456789"", ""1.23457"", 5); test_to_double_one(""1.23456789"", ""1.234568"", 6); test_to_double_one(""1.23456789"", ""1.2345679"", 7); test_to_double_one(""1.23456789"", ""1.23456789"", 8); test_to_double_one(""1.23456789"", ""1.234567890"", 9); test_to_double_one(""1.23456789"", ""1.2345678900"", 10); } TEST(Misc, to_double) { test_to_double(); const char *locale_name = (std::setlocale(LC_ALL, ""fr-FR"") == nullptr ? ""C"" : ""fr-FR""); std::locale new_locale(locale_name); auto host_locale = std::locale::global(new_locale); test_to_double(); new_locale = std::locale::global(std::locale::classic()); test_to_double(); auto classic_locale = std::locale::global(host_locale); test_to_double(); } TEST(Misc, print_int) { ASSERT_STREQ(""-9223372036854775808"", PSLICE() << -9223372036854775807 - 1); ASSERT_STREQ(""-2147483649"", PSLICE() << -2147483649ll); ASSERT_STREQ(""-2147483648"", PSLICE() << -2147483647 - 1); ASSERT_STREQ(""-2147483647"", PSLICE() << -2147483647); ASSERT_STREQ(""-123456789"", PSLICE() << -123456789); ASSERT_STREQ(""-1"", PSLICE() << -1); ASSERT_STREQ(""0"", PSLICE() << 0); ASSERT_STREQ(""1"", PSLICE() << 1); ASSERT_STREQ(""9"", PSLICE() << 9); ASSERT_STREQ(""10"", PSLICE() << 10); ASSERT_STREQ(""2147483647"", PSLICE() << 2147483647); ASSERT_STREQ(""2147483648"", PSLICE() << 2147483648ll); ASSERT_STREQ(""2147483649"", PSLICE() << 2147483649ll); ASSERT_STREQ(""9223372036854775807"", PSLICE() << 9223372036854775807ll); } TEST(Misc, print_uint) { ASSERT_STREQ(""0"", PSLICE() << 0u); ASSERT_STREQ(""1"", PSLICE() << 1u); ASSERT_STREQ(""9"", PSLICE() << 9u); ASSERT_STREQ(""10"", PSLICE() << 10u); ASSERT_STREQ(""2147483647"", PSLICE() << 2147483647u); ASSERT_STREQ(""2147483648"", PSLICE() << 2147483648u); ASSERT_STREQ(""2147483649"", PSLICE() << 2147483649u); ASSERT_STREQ(""9223372036854775807"", PSLICE() << 9223372036854775807u); } static void test_get_url_query_file_name_one(const char *prefix, const char *suffix, const char *file_name) { auto path = td::string(prefix) + td::string(file_name) + td::string(suffix); ASSERT_STREQ(file_name, td::get_url_query_file_name(path)); ASSERT_STREQ(file_name, td::get_url_file_name(""http://telegram.org"" + path)); ASSERT_STREQ(file_name, td::get_url_file_name(""http://telegram.org:80"" + path)); ASSERT_STREQ(file_name, td::get_url_file_name(""telegram.org"" + path)); } TEST(Misc, get_url_query_file_name) { for (auto suffix : {""?t=1#test"", ""#test?t=1"", ""#?t=1"", ""?t=1#"", ""#test"", ""?t=1"", ""#"", ""?"", """"}) { test_get_url_query_file_name_one("""", suffix, """"); test_get_url_query_file_name_one(""/"", suffix, """"); test_get_url_query_file_name_one(""/a/adasd/"", suffix, """"); test_get_url_query_file_name_one(""/a/lklrjetn/"", suffix, ""adasd.asdas""); test_get_url_query_file_name_one(""/"", suffix, ""a123asadas""); test_get_url_query_file_name_one(""/"", suffix, ""\\\\a\\\\1\\\\2\\\\3\\\\a\\\\s\\\\a\\\\das""); } } static void test_idn_to_ascii_one(td::string host, td::string result) { if (result != td::idn_to_ascii(host).ok()) { LOG(ERROR) << ""Failed to convert "" << host << "" to "" << result << "", got \\"""" << td::idn_to_ascii(host).ok() << ""\\""""; } } TEST(Misc, idn_to_ascii) { test_idn_to_ascii_one(""::::::::::::::::::::::::::::::::::::::@/"", ""::::::::::::::::::::::::::::::::::::::@/""); test_idn_to_ascii_one("""", """"); test_idn_to_ascii_one(""%30"", ""%30""); test_idn_to_ascii_one(""127.0.0.1"", ""127.0.0.1""); test_idn_to_ascii_one(""fe80::"", ""fe80::""); test_idn_to_ascii_one(""fe80:0:0:0:200:f8ff:fe21:67cf"", ""fe80:0:0:0:200:f8ff:fe21:67cf""); test_idn_to_ascii_one(""2001:0db8:11a3:09d7:1f34:8a2e:07a0:765d"", ""2001:0db8:11a3:09d7:1f34:8a2e:07a0:765d""); test_idn_to_ascii_one(""::ffff:192.0.2.1"", ""::ffff:192.0.2.1""); test_idn_to_ascii_one(""ABCDEF"", ""abcdef""); test_idn_to_ascii_one(""abcdef"", ""abcdef""); test_idn_to_ascii_one(""abæcdöef"", ""xn--abcdef-qua4k""); test_idn_to_ascii_one(""schön"", ""xn--schn-7qa""); test_idn_to_ascii_one(""ยจฆฟคฏข"", ""xn--22cdfh1b8fsa""); test_idn_to_ascii_one(""☺"", ""xn--74h""); test_idn_to_ascii_one(""правда"", ""xn--80aafi6cg""); test_idn_to_ascii_one(""büücher"", ""xn--bcher-kvaa""); test_idn_to_ascii_one(""BüüCHER"", ""xn--bcher-kvaa""); test_idn_to_ascii_one(""bücüher"", ""xn--bcher-kvab""); test_idn_to_ascii_one(""bücherü"", ""xn--bcher-kvae""); test_idn_to_ascii_one(""ýbücher"", ""xn--bcher-kvaf""); test_idn_to_ascii_one(""übücher"", ""xn--bcher-jvab""); test_idn_to_ascii_one(""bücher.tld"", ""xn--bcher-kva.tld""); test_idn_to_ascii_one(""кто.рф"", ""xn--j1ail.xn--p1ai""); test_idn_to_ascii_one(""wіkіреdіа.org"", ""xn--wkd-8cdx9d7hbd.org""); test_idn_to_ascii_one(""cnwin2k8中国.avol.com"", ""xn--cnwin2k8-sd0mx14e.avol.com""); test_idn_to_ascii_one(""win-2k12r2-addc.阿伯测阿伯测ad.hai.com"", ""win-2k12r2-addc.xn--ad-tl3ca3569aba8944eca.hai.com""); test_idn_to_ascii_one(""✌.ws"", ""xn--7bi.ws""); // test_idn_to_ascii_one(""✌️.ws"", ""xn--7bi.ws""); // needs nameprep to succeed test_idn_to_ascii_one(""⛧"", ""xn--59h""); test_idn_to_ascii_one(""--рф.рф"", ""xn-----mmcq.xn--p1ai""); ASSERT_TRUE(td::idn_to_ascii(""\\xc0"").is_error()); } #if TD_WINDOWS static void test_to_wstring_one(td::string str) { ASSERT_STREQ(str, td::from_wstring(td::to_wstring(str).ok()).ok()); } TEST(Misc, to_wstring) { test_to_wstring_one(""""); for (int i = 0; i < 10; i++) { test_to_wstring_one(""test""); test_to_wstring_one(""тест""); } td::string str; for (td::uint32 i = 0; i <= 0xD7FF; i++) { td::append_utf8_character(str, i); } for (td::uint32 i = 0xE000; i <= 0x10FFFF; i++) { td::append_utf8_character(str, i); } test_to_wstring_one(str); ASSERT_TRUE(td::to_wstring(""\\xc0"").is_error()); auto emoji = td::to_wstring(""🏟"").ok(); ASSERT_TRUE(td::from_wstring(emoji).ok() == ""🏟""); ASSERT_TRUE(emoji.size() == 2); auto emoji2 = emoji; emoji[0] = emoji[1]; emoji2[1] = emoji2[0]; ASSERT_TRUE(td::from_wstring(emoji).is_error()); ASSERT_TRUE(td::from_wstring(emoji2).is_error()); emoji2[0] = emoji[0]; ASSERT_TRUE(td::from_wstring(emoji2).is_error()); } #endif static void test_translit(td::string word, td::vector result, bool allow_partial = true) { ASSERT_EQ(result, td::get_word_transliterations(word, allow_partial)); } TEST(Misc, translit) { test_translit(""word"", {""word"", ""ворд""}); test_translit("""", {}); test_translit(""ььььььььь"", {""ььььььььь""}); test_translit(""крыло"", {""krylo"", ""крыло""}); test_translit(""krylo"", {""krylo"", ""крило""}); test_translit(""crylo"", {""crylo"", ""крило""}); test_translit(""cheiia"", {""cheiia"", ""кхеииа"", ""чейия""}); test_translit(""cheii"", {""cheii"", ""кхеии"", ""чейи"", ""чейий"", ""чейия""}); test_translit(""s"", {""s"", ""с"", ""ш"", ""щ""}); test_translit(""y"", {""e"", ""y"", ""е"", ""и"", ""ю"", ""я""}); test_translit(""j"", {""e"", ""j"", ""е"", ""й"", ""ю"", ""я""}); test_translit(""yo"", {""e"", ""yo"", ""е"", ""ио""}); test_translit(""artjom"", {""artem"", ""artjom"", ""артем"", ""артйом""}); test_translit(""artyom"", {""artem"", ""artyom"", ""артем"", ""артиом""}); test_translit(""arty"", {""arte"", ""arty"", ""арте"", ""арти"", ""артю"", ""артя""}); test_translit(""льи"", {""li"", ""lia"", ""ly"", ""льи""}); test_translit(""y"", {""y"", ""и""}, false); test_translit(""yo"", {""e"", ""yo"", ""е"", ""ио""}, false); } static void test_unicode(td::uint32 (*func)(td::uint32)) { for (td::uint32 i = 0; i <= 0x110000; i++) { auto res = func(i); CHECK(res <= 0x10ffff); } } TEST(Misc, unicode) { test_unicode(td::prepare_search_character); test_unicode(td::unicode_to_lower); test_unicode(td::remove_diacritics); } TEST(BigNum, from_decimal) { ASSERT_TRUE(td::BigNum::from_decimal("""").is_error()); ASSERT_TRUE(td::BigNum::from_decimal(""a"").is_error()); ASSERT_TRUE(td::BigNum::from_decimal(""123a"").is_error()); ASSERT_TRUE(td::BigNum::from_decimal(""-123a"").is_error()); // ASSERT_TRUE(td::BigNum::from_decimal(""-"").is_error()); ASSERT_TRUE(td::BigNum::from_decimal(""123"").is_ok()); ASSERT_TRUE(td::BigNum::from_decimal(""-123"").is_ok()); ASSERT_TRUE(td::BigNum::from_decimal(""0"").is_ok()); ASSERT_TRUE(td::BigNum::from_decimal(""-0"").is_ok()); ASSERT_TRUE(td::BigNum::from_decimal(""-999999999999999999999999999999999999999999999999"").is_ok()); ASSERT_TRUE(td::BigNum::from_decimal(""999999999999999999999999999999999999999999999999"").is_ok()); } TEST(BigNum, from_binary) { ASSERT_STREQ(td::BigNum::from_binary("""").to_decimal(), ""0""); ASSERT_STREQ(td::BigNum::from_binary(""a"").to_decimal(), ""97""); ASSERT_STREQ(td::BigNum::from_binary(""\\x00\\xff"").to_decimal(), ""255""); ASSERT_STREQ(td::BigNum::from_binary(""\\x00\\x01\\x00\\x00"").to_decimal(), ""65536""); ASSERT_STREQ(td::BigNum::from_le_binary("""").to_decimal(), ""0""); ASSERT_STREQ(td::BigNum::from_le_binary(""a"").to_decimal(), ""97""); ASSERT_STREQ(td::BigNum::from_le_binary(""\\x00\\xff"").to_decimal(), ""65280""); ASSERT_STREQ(td::BigNum::from_le_binary(""\\x00\\x01\\x00\\x00"").to_decimal(), ""256""); ASSERT_STREQ(td::BigNum::from_decimal(""255"").move_as_ok().to_binary(), ""\\xff""); ASSERT_STREQ(td::BigNum::from_decimal(""255"").move_as_ok().to_le_binary(), ""\\xff""); ASSERT_STREQ(td::BigNum::from_decimal(""255"").move_as_ok().to_binary(2), ""\\x00\\xff""); ASSERT_STREQ(td::BigNum::from_decimal(""255"").move_as_ok().to_le_binary(2), ""\\xff\\x00""); ASSERT_STREQ(td::BigNum::from_decimal(""65280"").move_as_ok().to_binary(), ""\\xff\\x00""); ASSERT_STREQ(td::BigNum::from_decimal(""65280"").move_as_ok().to_le_binary(), ""\\x00\\xff""); ASSERT_STREQ(td::BigNum::from_decimal(""65280"").move_as_ok().to_binary(2), ""\\xff\\x00""); ASSERT_STREQ(td::BigNum::from_decimal(""65280"").move_as_ok().to_le_binary(2), ""\\x00\\xff""); ASSERT_STREQ(td::BigNum::from_decimal(""65536"").move_as_ok().to_binary(), ""\\x01\\x00\\x00""); ASSERT_STREQ(td::BigNum::from_decimal(""65536"").move_as_ok().to_le_binary(), ""\\x00\\x00\\x01""); ASSERT_STREQ(td::BigNum::from_decimal(""65536"").move_as_ok().to_binary(4), ""\\x00\\x01\\x00\\x00""); ASSERT_STREQ(td::BigNum::from_decimal(""65536"").move_as_ok().to_le_binary(4), ""\\x00\\x00\\x01\\x00""); } static void test_get_ipv4(td::uint32 ip) { td::IPAddress ip_address; ip_address.init_ipv4_port(td::IPAddress::ipv4_to_str(ip), 80).ensure(); ASSERT_EQ(ip_address.get_ipv4(), ip); } TEST(Misc, IPAddress_get_ipv4) { test_get_ipv4(0x00000000); test_get_ipv4(0x010000FF); test_get_ipv4(0xFF000001); test_get_ipv4(0x01020304); test_get_ipv4(0x04030201); test_get_ipv4(0xFFFFFFFF); } static void test_is_reserved(td::string ip, bool is_reserved) { td::IPAddress ip_address; ip_address.init_ipv4_port(ip, 80).ensure(); ASSERT_EQ(is_reserved, ip_address.is_reserved()); } TEST(Misc, IPAddress_is_reserved) { test_is_reserved(""0.0.0.0"", true); test_is_reserved(""0.255.255.255"", true); test_is_reserved(""1.0.0.0"", false); test_is_reserved(""5.0.0.0"", false); test_is_reserved(""9.255.255.255"", false); test_is_reserved(""10.0.0.0"", true); test_is_reserved(""10.255.255.255"", true); test_is_reserved(""11.0.0.0"", false); test_is_reserved(""100.63.255.255"", false); test_is_reserved(""100.64.0.0"", true); test_is_reserved(""100.127.255.255"", true); test_is_reserved(""100.128.0.0"", false); test_is_reserved(""126.255.255.255"", false); test_is_reserved(""127.0.0.0"", true); test_is_reserved(""127.255.255.255"", true); test_is_reserved(""128.0.0.0"", false); test_is_reserved(""169.253.255.255"", false); test_is_reserved(""169.254.0.0"", true); test_is_reserved(""169.254.255.255"", true); test_is_reserved(""169.255.0.0"", false); test_is_reserved(""172.15.255.255"", false); test_is_reserved(""172.16.0.0"", true); test_is_reserved(""172.31.255.255"", true); test_is_reserved(""172.32.0.0"", false); test_is_reserved(""191.255.255.255"", false); test_is_reserved(""192.0.0.0"", true); test_is_reserved(""192.0.0.255"", true); test_is_reserved(""192.0.1.0"", false); test_is_reserved(""192.0.1.255"", false); test_is_reserved(""192.0.2.0"", true); test_is_reserved(""192.0.2.255"", true); test_is_reserved(""192.0.3.0"", false); test_is_reserved(""192.88.98.255"", false); test_is_reserved(""192.88.99.0"", true); test_is_reserved(""192.88.99.255"", true); test_is_reserved(""192.88.100.0"", false); test_is_reserved(""192.167.255.255"", false); test_is_reserved(""192.168.0.0"", true); test_is_reserved(""192.168.255.255"", true); test_is_reserved(""192.169.0.0"", false); test_is_reserved(""198.17.255.255"", false); test_is_reserved(""198.18.0.0"", true); test_is_reserved(""198.19.255.255"", true); test_is_reserved(""198.20.0.0"", false); test_is_reserved(""198.51.99.255"", false); test_is_reserved(""198.51.100.0"", true); test_is_reserved(""198.51.100.255"", true); test_is_reserved(""198.51.101.0"", false); test_is_reserved(""203.0.112.255"", false); test_is_reserved(""203.0.113.0"", true); test_is_reserved(""203.0.113.255"", true); test_is_reserved(""203.0.114.0"", false); test_is_reserved(""223.255.255.255"", false); test_is_reserved(""224.0.0.0"", true); test_is_reserved(""239.255.255.255"", true); test_is_reserved(""240.0.0.0"", true); test_is_reserved(""255.255.255.254"", true); test_is_reserved(""255.255.255.255"", true); } TEST(Misc, ipv6_clear) { td::IPAddress ip_address; ip_address.init_host_port(""2001:0db8:85a3:0000:0000:8a2e:0370:7334"", 123).ensure(); ASSERT_EQ(""2001:db8:85a3::8a2e:370:7334"", ip_address.get_ip_str()); ip_address.clear_ipv6_interface(); ASSERT_EQ(""2001:db8:85a3::"", ip_address.get_ip_str()); } static void test_split(td::Slice str, std::pair expected) { ASSERT_EQ(expected, td::split(str)); } TEST(Misc, split) { test_split("""", {"""", """"}); test_split("" "", {"""", """"}); test_split(""abcdef"", {""abcdef"", """"}); test_split(""abc def"", {""abc"", ""def""}); test_split(""a bcdef"", {""a"", ""bcdef""}); test_split("" abcdef"", {"""", ""abcdef""}); test_split(""abcdef "", {""abcdef"", """"}); test_split(""ab cd ef"", {""ab"", ""cd ef""}); test_split(""ab cdef "", {""ab"", ""cdef ""}); test_split("" abcd ef"", {"""", ""abcd ef""}); test_split("" abcdef "", {"""", ""abcdef ""}); } static void test_full_split(td::Slice str, td::vector expected) { ASSERT_EQ(expected, td::full_split(str)); } static void test_full_split(td::Slice str, char c, std::size_t max_parts, td::vector expected) { ASSERT_EQ(expected, td::full_split(str, c, max_parts)); } TEST(Misc, full_split) { test_full_split("""", {}); test_full_split("" "", {"""", """"}); test_full_split("" "", {"""", """", """"}); test_full_split(""abcdef"", {""abcdef""}); test_full_split(""abc def"", {""abc"", ""def""}); test_full_split(""a bcdef"", {""a"", ""bcdef""}); test_full_split("" abcdef"", {"""", ""abcdef""}); test_full_split(""abcdef "", {""abcdef"", """"}); test_full_split(""ab cd ef"", {""ab"", ""cd"", ""ef""}); test_full_split(""ab cdef "", {""ab"", ""cdef"", """"}); test_full_split("" abcd ef"", {"""", ""abcd"", ""ef""}); test_full_split("" abcdef "", {"""", ""abcdef"", """"}); test_full_split("" ab cd ef "", {"""", ""ab"", ""cd"", ""ef"", """"}); test_full_split("" ab cd ef "", {"""", """", ""ab"", """", ""cd"", """", ""ef"", """", """"}); test_full_split(""ab cd ef gh"", ' ', 3, {""ab"", ""cd"", ""ef gh""}); } TEST(Misc, StringBuilder) { auto small_str = td::string{""abcdefghij""}; auto big_str = td::string(1000, 'a'); using V = td::vector; for (auto use_buf : {false, true}) { for (std::size_t initial_buffer_size : {0, 1, 5, 10, 100, 1000, 2000}) { for (auto test : {V{small_str}, V{small_str, big_str, big_str, small_str}, V{big_str, small_str, big_str}}) { td::string buf(initial_buffer_size, '\\0'); td::StringBuilder sb(buf, use_buf); td::string res; for (auto x : test) { res += x; sb << x; } if (use_buf) { ASSERT_EQ(res, sb.as_cslice()); } else { auto got = sb.as_cslice(); res.resize(got.size()); ASSERT_EQ(res, got); } } } } } TEST(Misc, As) { char buf[100]; td::as(buf) = 123; ASSERT_EQ(123, td::as(static_cast(buf))); ASSERT_EQ(123, td::as(static_cast(buf))); char buf2[100]; td::as(buf2) = td::as(buf); ASSERT_EQ(123, td::as(static_cast(buf2))); ASSERT_EQ(123, td::as(static_cast(buf2))); } TEST(Misc, Regression) { td::string name = ""regression_db""; td::RegressionTester::destroy(name); { auto tester = td::RegressionTester::create(name); tester->save_db(); tester->verify_test(""one_plus_one"", ""two"").ensure(); tester->verify_test(""one_plus_one"", ""two"").ensure(); tester->verify_test(""two_plus_one"", ""three"").ensure(); tester->verify_test(""one_plus_one"", ""two"").ensure(); tester->verify_test(""two_plus_one"", ""three"").ensure(); tester->save_db(); } { auto tester = td::RegressionTester::create(name); tester->save_db(); tester->verify_test(""one_plus_one"", ""two"").ensure(); tester->verify_test(""one_plus_one"", ""two"").ensure(); tester->verify_test(""two_plus_one"", ""three"").ensure(); tester->verify_test(""one_plus_one"", ""two"").ensure(); tester->verify_test(""two_plus_one"", ""three"").ensure(); tester->save_db(); tester->verify_test(""one_plus_one"", ""three"").ensure_error(); tester->verify_test(""two_plus_one"", ""two"").ensure_error(); } { auto tester = td::RegressionTester::create(name); tester->verify_test(""one_plus_one"", ""three"").ensure_error(); tester->verify_test(""two_plus_one"", ""two"").ensure_error(); } } TEST(Misc, Bits) { ASSERT_EQ(32, td::count_leading_zeroes32(0)); ASSERT_EQ(64, td::count_leading_zeroes64(0)); ASSERT_EQ(32, td::count_trailing_zeroes32(0)); ASSERT_EQ(64, td::count_trailing_zeroes64(0)); for (int i = 0; i < 32; i++) { ASSERT_EQ(31 - i, td::count_leading_zeroes32(1u << i)); ASSERT_EQ(i, td::count_trailing_zeroes32(1u << i)); ASSERT_EQ(31 - i, td::count_leading_zeroes_non_zero32(1u << i)); ASSERT_EQ(i, td::count_trailing_zeroes_non_zero32(1u << i)); } for (int i = 0; i < 64; i++) { ASSERT_EQ(63 - i, td::count_leading_zeroes64(1ull << i)); ASSERT_EQ(i, td::count_trailing_zeroes64(1ull << i)); ASSERT_EQ(63 - i, td::count_leading_zeroes_non_zero64(1ull << i)); ASSERT_EQ(i, td::count_trailing_zeroes_non_zero64(1ull << i)); } ASSERT_EQ(0x12345678u, td::bswap32(0x78563412u)); ASSERT_EQ(0x12345678abcdef67ull, td::bswap64(0x67efcdab78563412ull)); td::uint8 buf[8] = {1, 90, 2, 18, 129, 255, 0, 2}; td::uint64 num2 = td::bswap64(td::as(buf)); td::uint64 num = (static_cast(buf[0]) << 56) | (static_cast(buf[1]) << 48) | (static_cast(buf[2]) << 40) | (static_cast(buf[3]) << 32) | (static_cast(buf[4]) << 24) | (static_cast(buf[5]) << 16) | (static_cast(buf[6]) << 8) | (static_cast(buf[7])); ASSERT_EQ(num, num2); ASSERT_EQ(0, td::count_bits32(0)); ASSERT_EQ(0, td::count_bits64(0)); ASSERT_EQ(4, td::count_bits32((1u << 31) | 7)); ASSERT_EQ(4, td::count_bits64((1ull << 63) | 7)); } TEST(Misc, BitsRange) { auto to_vec_a = [](td::uint64 x) { td::vector bits; for (auto i : td::BitsRange(x)) { bits.push_back(i); } return bits; }; auto to_vec_b = [](td::uint64 x) { td::vector bits; td::int32 pos = 0; while (x != 0) { if ((x & 1) != 0) { bits.push_back(pos); } x >>= 1; pos++; } return bits; }; auto do_check = [](const td::vector &a, const td::vector &b) { ASSERT_EQ(b, a); }; auto check = [&](td::uint64 x) { do_check(to_vec_a(x), to_vec_b(x)); }; do_check(to_vec_a(21), {0, 2, 4}); for (int x = 0; x < 100; x++) { check(x); check(std::numeric_limits::max() - x); check(std::numeric_limits::max() - x); } } #if !TD_THREAD_UNSUPPORTED TEST(Misc, Time) { td::Stage run; td::Stage check; td::Stage finish; std::size_t threads_n = 3; td::vector threads; td::vector> ts(threads_n); for (std::size_t i = 0; i < threads_n; i++) { threads.emplace_back([&, thread_id = i] { for (td::uint64 round = 1; round < 10000; round++) { ts[thread_id] = 0; run.wait(round * threads_n); ts[thread_id] = td::Time::now(); check.wait(round * threads_n); for (auto &ts_ref : ts) { auto other_ts = ts_ref.load(); if (other_ts != 0) { ASSERT_TRUE(other_ts <= td::Time::now_cached()); } } finish.wait(round * threads_n); } }); } for (auto &thread : threads) { thread.join(); } } #endif TEST(Misc, uint128) { td::vector parts = {0, 1, 2000, 2001, std::numeric_limits::max(), std::numeric_limits::max() - 1, std::numeric_limits::max(), static_cast(std::numeric_limits::max()) + 1}; td::vector signed_parts = {0, 1, 2000, 2001, -1, -2000, -2001, std::numeric_limits::max(), std::numeric_limits::max() - 1, std::numeric_limits::min(), std::numeric_limits::min() + 1, std::numeric_limits::max(), static_cast(std::numeric_limits::max()) + 1, std::numeric_limits::max() - 1, std::numeric_limits::min(), std::numeric_limits::min() + 1, static_cast(std::numeric_limits::min()) - 1}; #if TD_HAVE_INT128 auto to_intrinsic = [](td::uint128_emulated num) { return td::uint128_intrinsic(num.hi(), num.lo()); }; auto eq = [](td::uint128_emulated a, td::uint128_intrinsic b) { return a.hi() == b.hi() && a.lo() == b.lo(); }; auto ensure_eq = [&](td::uint128_emulated a, td::uint128_intrinsic b) { if (!eq(a, b)) { LOG(FATAL) << ""["" << a.hi() << "";"" << a.lo() << ""] vs ["" << b.hi() << "";"" << b.lo() << ""]""; } }; #endif td::vector nums; for (auto hi : parts) { for (auto lo : parts) { auto a = td::uint128_emulated(hi, lo); #if TD_HAVE_INT128 auto ia = td::uint128_intrinsic(hi, lo); ensure_eq(a, ia); #endif nums.push_back(a); nums.pop_back(); nums.push_back({hi, lo}); } } #if TD_HAVE_INT128 for (auto a : nums) { auto ia = to_intrinsic(a); ensure_eq(a, ia); CHECK(a.is_zero() == ia.is_zero()); for (int i = 0; i <= 130; i++) { ensure_eq(a.shl(i), ia.shl(i)); ensure_eq(a.shr(i), ia.shr(i)); } for (auto b : parts) { ensure_eq(a.mult(b), ia.mult(b)); } for (auto b : signed_parts) { ensure_eq(a.mult_signed(b), ia.mult_signed(b)); if (b == 0) { continue; } td::int64 q, r; a.divmod_signed(b, &q, &r); td::int64 iq, ir; ia.divmod_signed(b, &iq, &ir); ASSERT_EQ(q, iq); ASSERT_EQ(r, ir); } for (auto b : nums) { auto ib = to_intrinsic(b); //LOG(ERROR) << ia.hi() << "";"" << ia.lo() << "" "" << ib.hi() << "";"" << ib.lo(); ensure_eq(a.mult(b), ia.mult(ib)); ensure_eq(a.add(b), ia.add(ib)); ensure_eq(a.sub(b), ia.sub(ib)); if (!b.is_zero()) { ensure_eq(a.div(b), ia.div(ib)); ensure_eq(a.mod(b), ia.mod(ib)); } } } for (auto signed_part : signed_parts) { auto a = td::uint128_emulated::from_signed(signed_part); auto ia = td::uint128_intrinsic::from_signed(signed_part); ensure_eq(a, ia); } #endif } template