1// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
2// See LICENSE.txt for license information.
3
4package model
5
6import (
7	"net/http"
8	"os"
9)
10
11const (
12	CDSOfflineAfterMillis = 1000 * 60 * 30 // 30 minutes
13	CDSTypeApp            = "mattermost_app"
14)
15
16type ClusterDiscovery struct {
17	Id          string `json:"id"`
18	Type        string `json:"type"`
19	ClusterName string `json:"cluster_name"`
20	Hostname    string `json:"hostname"`
21	GossipPort  int32  `json:"gossip_port"`
22	Port        int32  `json:"port"`
23	CreateAt    int64  `json:"create_at"`
24	LastPingAt  int64  `json:"last_ping_at"`
25}
26
27func (o *ClusterDiscovery) PreSave() {
28	if o.Id == "" {
29		o.Id = NewId()
30	}
31
32	if o.CreateAt == 0 {
33		o.CreateAt = GetMillis()
34		o.LastPingAt = o.CreateAt
35	}
36}
37
38func (o *ClusterDiscovery) AutoFillHostname() {
39	// attempt to set the hostname from the OS
40	if o.Hostname == "" {
41		if hn, err := os.Hostname(); err == nil {
42			o.Hostname = hn
43		}
44	}
45}
46
47func (o *ClusterDiscovery) AutoFillIPAddress(iface string, ipAddress string) {
48	// attempt to set the hostname to the first non-local IP address
49	if o.Hostname == "" {
50		if ipAddress != "" {
51			o.Hostname = ipAddress
52		} else {
53			o.Hostname = GetServerIPAddress(iface)
54		}
55	}
56}
57
58func (o *ClusterDiscovery) IsEqual(in *ClusterDiscovery) bool {
59	if in == nil {
60		return false
61	}
62
63	if o.Type != in.Type {
64		return false
65	}
66
67	if o.ClusterName != in.ClusterName {
68		return false
69	}
70
71	if o.Hostname != in.Hostname {
72		return false
73	}
74
75	return true
76}
77
78func FilterClusterDiscovery(vs []*ClusterDiscovery, f func(*ClusterDiscovery) bool) []*ClusterDiscovery {
79	copy := make([]*ClusterDiscovery, 0)
80	for _, v := range vs {
81		if f(v) {
82			copy = append(copy, v)
83		}
84	}
85
86	return copy
87}
88
89func (o *ClusterDiscovery) IsValid() *AppError {
90	if !IsValidId(o.Id) {
91		return NewAppError("ClusterDiscovery.IsValid", "model.cluster.is_valid.id.app_error", nil, "", http.StatusBadRequest)
92	}
93
94	if o.ClusterName == "" {
95		return NewAppError("ClusterDiscovery.IsValid", "model.cluster.is_valid.name.app_error", nil, "", http.StatusBadRequest)
96	}
97
98	if o.Type == "" {
99		return NewAppError("ClusterDiscovery.IsValid", "model.cluster.is_valid.type.app_error", nil, "", http.StatusBadRequest)
100	}
101
102	if o.Hostname == "" {
103		return NewAppError("ClusterDiscovery.IsValid", "model.cluster.is_valid.hostname.app_error", nil, "", http.StatusBadRequest)
104	}
105
106	if o.CreateAt == 0 {
107		return NewAppError("ClusterDiscovery.IsValid", "model.cluster.is_valid.create_at.app_error", nil, "", http.StatusBadRequest)
108	}
109
110	if o.LastPingAt == 0 {
111		return NewAppError("ClusterDiscovery.IsValid", "model.cluster.is_valid.last_ping_at.app_error", nil, "", http.StatusBadRequest)
112	}
113
114	return nil
115}
116